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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pip install torch botorch gpytorch pyro-ppl pandas numpy scikit-learn matplotlib gradio
|
| 2 |
+
import torch, pandas as pd, numpy as np
|
| 3 |
+
from botorch.models import SaasFullyBayesianSingleTaskGP
|
| 4 |
+
from botorch.fit import fit_fully_bayesian_model_nuts
|
| 5 |
+
from botorch.acquisition import qExpectedImprovement, qLogExpectedImprovement
|
| 6 |
+
from botorch.optim import optimize_acqf
|
| 7 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
from typing import List, Tuple, Optional, Dict
|
| 10 |
+
import os
|
| 11 |
+
import gradio as gr
|
| 12 |
+
import tempfile
|
| 13 |
+
import io
|
| 14 |
+
from matplotlib.figure import Figure
|
| 15 |
+
|
| 16 |
+
class CustomizableBayesianOptimizer:
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
data_file: str,
|
| 20 |
+
input_features: List[str],
|
| 21 |
+
output_features: List[str],
|
| 22 |
+
objective_weights: Dict[str, float],
|
| 23 |
+
input_bounds: Dict[str, Tuple[float, float]] = None,
|
| 24 |
+
output_bounds: Dict[str, Tuple[float, float]] = None,
|
| 25 |
+
num_samples: int = 512,
|
| 26 |
+
warmup_steps: int = 128,
|
| 27 |
+
thinning: int = 16,
|
| 28 |
+
use_gpu: bool = True
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Initialize the Bayesian optimizer with customizable parameters.
|
| 32 |
+
"""
|
| 33 |
+
# Check for GPU availability
|
| 34 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() and use_gpu else "cpu")
|
| 35 |
+
print(f"Using device: {self.device}")
|
| 36 |
+
|
| 37 |
+
self.data_file = data_file
|
| 38 |
+
self.input_features = input_features
|
| 39 |
+
self.output_features = output_features
|
| 40 |
+
self.objective_weights = objective_weights
|
| 41 |
+
self.input_bounds = input_bounds
|
| 42 |
+
self.output_bounds = output_bounds
|
| 43 |
+
self.mcmc_settings = {
|
| 44 |
+
"num_samples": num_samples,
|
| 45 |
+
"warmup_steps": warmup_steps,
|
| 46 |
+
"thinning": thinning
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Load data
|
| 50 |
+
self.df = pd.read_csv(self.data_file)
|
| 51 |
+
print(f"Loaded data with columns: {list(self.df.columns)}")
|
| 52 |
+
|
| 53 |
+
# Initialize scalers
|
| 54 |
+
self.scaler_x = MinMaxScaler(feature_range=(0, 1))
|
| 55 |
+
self.scalers_y = {feat: MinMaxScaler(feature_range=(0, 1)) for feat in output_features}
|
| 56 |
+
|
| 57 |
+
# Process data
|
| 58 |
+
self.process_data()
|
| 59 |
+
|
| 60 |
+
def process_data(self):
|
| 61 |
+
"""Load and normalize data from CSV file."""
|
| 62 |
+
# Verify input features exist
|
| 63 |
+
for feat in self.input_features:
|
| 64 |
+
if feat not in self.df.columns:
|
| 65 |
+
raise KeyError(f"Input feature '{feat}' not found in data file. Available columns: {list(self.df.columns)}")
|
| 66 |
+
|
| 67 |
+
# Normalize input features
|
| 68 |
+
self.X = torch.as_tensor(
|
| 69 |
+
self.scaler_x.fit_transform(self.df[self.input_features].values),
|
| 70 |
+
dtype=torch.double,
|
| 71 |
+
device=self.device
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Normalize each output feature separately
|
| 75 |
+
self.Y_dict = {}
|
| 76 |
+
for feat in self.output_features:
|
| 77 |
+
self.Y_dict[feat] = torch.as_tensor(
|
| 78 |
+
self.scalers_y[feat].fit_transform(self.df[feat].values.reshape(-1, 1)),
|
| 79 |
+
dtype=torch.double,
|
| 80 |
+
device=self.device
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Calculate the composite score based on weights
|
| 84 |
+
score = np.zeros(len(self.df))
|
| 85 |
+
for feat, weight in self.objective_weights.items():
|
| 86 |
+
if feat in self.df.columns:
|
| 87 |
+
score += weight * self.df[feat].values
|
| 88 |
+
|
| 89 |
+
self.score = score
|
| 90 |
+
self.score_scaler = MinMaxScaler(feature_range=(0, 1))
|
| 91 |
+
self.Y_score = torch.as_tensor(
|
| 92 |
+
self.score_scaler.fit_transform(score.reshape(-1, 1)),
|
| 93 |
+
dtype=torch.double,
|
| 94 |
+
device=self.device
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def build_models(self):
|
| 98 |
+
"""Build individual models for each output and a model for the score."""
|
| 99 |
+
# Individual models for each output feature
|
| 100 |
+
self.individual_models = {}
|
| 101 |
+
for feat in self.output_features:
|
| 102 |
+
print(f"Building model for {feat}...")
|
| 103 |
+
model = SaasFullyBayesianSingleTaskGP(
|
| 104 |
+
self.X,
|
| 105 |
+
self.Y_dict[feat]
|
| 106 |
+
)
|
| 107 |
+
fit_fully_bayesian_model_nuts(
|
| 108 |
+
model,
|
| 109 |
+
num_samples=self.mcmc_settings["num_samples"],
|
| 110 |
+
warmup_steps=self.mcmc_settings["warmup_steps"],
|
| 111 |
+
thinning=self.mcmc_settings["thinning"]
|
| 112 |
+
)
|
| 113 |
+
self.individual_models[feat] = model
|
| 114 |
+
|
| 115 |
+
# Model for overall score
|
| 116 |
+
print("Building model for combined score...")
|
| 117 |
+
self.score_model = SaasFullyBayesianSingleTaskGP(
|
| 118 |
+
self.X,
|
| 119 |
+
self.Y_score
|
| 120 |
+
)
|
| 121 |
+
fit_fully_bayesian_model_nuts(
|
| 122 |
+
self.score_model,
|
| 123 |
+
num_samples=self.mcmc_settings["num_samples"],
|
| 124 |
+
warmup_steps=self.mcmc_settings["warmup_steps"],
|
| 125 |
+
thinning=self.mcmc_settings["thinning"]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def optimize(self, bounds: List[Tuple[float, float]] = None):
|
| 129 |
+
"""Run Bayesian optimization to find next experimental point."""
|
| 130 |
+
if bounds is None:
|
| 131 |
+
# Default normalized bounds [0,1] for all features
|
| 132 |
+
bounds = torch.tensor([[0.0] * len(self.input_features),
|
| 133 |
+
[1.0] * len(self.input_features)],
|
| 134 |
+
dtype=torch.double,
|
| 135 |
+
device=self.device)
|
| 136 |
+
else:
|
| 137 |
+
# Normalize user-provided bounds
|
| 138 |
+
bounds_min = [b[0] for b in bounds]
|
| 139 |
+
bounds_max = [b[1] for b in bounds]
|
| 140 |
+
bounds_min_norm = self.scaler_x.transform(np.array([bounds_min]))[0]
|
| 141 |
+
bounds_max_norm = self.scaler_x.transform(np.array([bounds_max]))[0]
|
| 142 |
+
bounds = torch.tensor([bounds_min_norm, bounds_max_norm], dtype=torch.double, device=self.device)
|
| 143 |
+
|
| 144 |
+
# Create acquisition function
|
| 145 |
+
acq = qLogExpectedImprovement(model=self.score_model, best_f=self.Y_score.max())
|
| 146 |
+
|
| 147 |
+
# Optimize acquisition function
|
| 148 |
+
cand, _ = optimize_acqf(
|
| 149 |
+
acq_function=acq,
|
| 150 |
+
bounds=bounds,
|
| 151 |
+
q=1,
|
| 152 |
+
num_restarts=25,
|
| 153 |
+
raw_samples=512,
|
| 154 |
+
options={"batch_limit": 5, "maxiter": 200},
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Denormalize next point
|
| 158 |
+
next_point = self.scaler_x.inverse_transform(cand.cpu().detach().numpy())[0]
|
| 159 |
+
self.next_point = next_point
|
| 160 |
+
|
| 161 |
+
# Apply bounds if provided
|
| 162 |
+
if self.input_bounds:
|
| 163 |
+
for i, feat in enumerate(self.input_features):
|
| 164 |
+
if feat in self.input_bounds:
|
| 165 |
+
self.next_point[i] = np.clip(
|
| 166 |
+
self.next_point[i],
|
| 167 |
+
self.input_bounds[feat][0],
|
| 168 |
+
self.input_bounds[feat][1]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Predict values and uncertainties for next point
|
| 172 |
+
self.predict_for_next_point()
|
| 173 |
+
|
| 174 |
+
return self.next_point
|
| 175 |
+
|
| 176 |
+
def predict_for_next_point(self):
|
| 177 |
+
"""Predict values and uncertainties for the next experimental point."""
|
| 178 |
+
# Normalize the next point
|
| 179 |
+
next_point_norm = torch.tensor(
|
| 180 |
+
self.scaler_x.transform(self.next_point.reshape(1, -1)),
|
| 181 |
+
dtype=torch.double,
|
| 182 |
+
device=self.device
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# Predict for each property
|
| 186 |
+
self.predictions = {}
|
| 187 |
+
for feat, model in self.individual_models.items():
|
| 188 |
+
posterior = model.posterior(next_point_norm)
|
| 189 |
+
|
| 190 |
+
# Get mean and standard deviation
|
| 191 |
+
mean = posterior.mean.cpu().detach().numpy().flatten()[0]
|
| 192 |
+
std = np.sqrt(posterior.variance.cpu().detach().numpy().flatten()[0])
|
| 193 |
+
|
| 194 |
+
# Denormalize predictions
|
| 195 |
+
mean_denorm = self.scalers_y[feat].inverse_transform([[mean]])[0, 0]
|
| 196 |
+
# Scale the std by the same factor used in denormalizing the mean
|
| 197 |
+
std_denorm = std * (self.scalers_y[feat].data_max_[0] - self.scalers_y[feat].data_min_[0])
|
| 198 |
+
|
| 199 |
+
# Apply output bounds if provided
|
| 200 |
+
if self.output_bounds and feat in self.output_bounds:
|
| 201 |
+
mean_denorm = np.clip(mean_denorm, self.output_bounds[feat][0], self.output_bounds[feat][1])
|
| 202 |
+
|
| 203 |
+
self.predictions[feat] = {
|
| 204 |
+
"mean": mean_denorm,
|
| 205 |
+
"std": std_denorm,
|
| 206 |
+
"uncertainty_percent": (std_denorm / abs(mean_denorm) * 100) if mean_denorm != 0 else 0
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
def get_results(self):
|
| 210 |
+
"""Return the next point and predictions."""
|
| 211 |
+
result = {
|
| 212 |
+
"next_point": {feat: val for feat, val in zip(self.input_features, self.next_point)},
|
| 213 |
+
"predictions": self.predictions,
|
| 214 |
+
"objective_weights": self.objective_weights
|
| 215 |
+
}
|
| 216 |
+
return result
|
| 217 |
+
|
| 218 |
+
def visualize(self):
|
| 219 |
+
"""Visualize the results and return figure."""
|
| 220 |
+
if len(self.input_features) == 2:
|
| 221 |
+
# For 2D input space
|
| 222 |
+
fig = Figure(figsize=(10, 8))
|
| 223 |
+
ax = fig.add_subplot(111)
|
| 224 |
+
|
| 225 |
+
scatter = ax.scatter(
|
| 226 |
+
self.df[self.input_features[0]],
|
| 227 |
+
self.df[self.input_features[1]],
|
| 228 |
+
c=self.score,
|
| 229 |
+
cmap="viridis",
|
| 230 |
+
s=50
|
| 231 |
+
)
|
| 232 |
+
ax.scatter(
|
| 233 |
+
self.next_point[0],
|
| 234 |
+
self.next_point[1],
|
| 235 |
+
c="red",
|
| 236 |
+
s=150,
|
| 237 |
+
edgecolors="black",
|
| 238 |
+
marker="*",
|
| 239 |
+
label="Next Suggested Point"
|
| 240 |
+
)
|
| 241 |
+
ax.set_xlabel(self.input_features[0])
|
| 242 |
+
ax.set_ylabel(self.input_features[1])
|
| 243 |
+
ax.set_title("Bayesian Optimization: Next Suggested Experiment")
|
| 244 |
+
fig.colorbar(scatter, ax=ax, label="Objective Score")
|
| 245 |
+
ax.legend()
|
| 246 |
+
ax.grid(True)
|
| 247 |
+
|
| 248 |
+
# Add prediction information as text
|
| 249 |
+
info_text = "Predictions:\n"
|
| 250 |
+
for feat, pred in self.predictions.items():
|
| 251 |
+
info_text += f"{feat}: {pred['mean']:.3f} ± {pred['std']:.3f}\n"
|
| 252 |
+
|
| 253 |
+
ax.text(0.02, 0.02, info_text, transform=ax.transAxes, fontsize=10,
|
| 254 |
+
bbox={"facecolor": "white", "alpha": 0.8, "pad": 5})
|
| 255 |
+
|
| 256 |
+
fig.tight_layout()
|
| 257 |
+
return fig
|
| 258 |
+
else:
|
| 259 |
+
print("Visualization only supported for 2D input space")
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
# Gradio interface function
|
| 263 |
+
def run_optimization(
|
| 264 |
+
csv_file,
|
| 265 |
+
input_features,
|
| 266 |
+
output_features,
|
| 267 |
+
input_bounds_min,
|
| 268 |
+
input_bounds_max,
|
| 269 |
+
output_bounds_min,
|
| 270 |
+
output_bounds_max,
|
| 271 |
+
objective_weights,
|
| 272 |
+
use_gpu,
|
| 273 |
+
num_samples,
|
| 274 |
+
warmup_steps,
|
| 275 |
+
progress=gr.Progress()
|
| 276 |
+
):
|
| 277 |
+
# Save uploaded file temporarily
|
| 278 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
|
| 279 |
+
|
| 280 |
+
# Fix for handling Gradio file upload
|
| 281 |
+
if hasattr(csv_file, 'name'):
|
| 282 |
+
# This is a NamedString object from Gradio
|
| 283 |
+
with open(csv_file.name, 'rb') as f:
|
| 284 |
+
file_content = f.read()
|
| 285 |
+
temp_file.write(file_content)
|
| 286 |
+
else:
|
| 287 |
+
# Fallback for direct bytes content
|
| 288 |
+
temp_file.write(csv_file)
|
| 289 |
+
|
| 290 |
+
temp_file.close()
|
| 291 |
+
|
| 292 |
+
# Parse input fields
|
| 293 |
+
input_features = [x.strip() for x in input_features.split(",")]
|
| 294 |
+
output_features = [x.strip() for x in output_features.split(",")]
|
| 295 |
+
|
| 296 |
+
# Parse bounds
|
| 297 |
+
input_bounds = {}
|
| 298 |
+
if input_bounds_min and input_bounds_max:
|
| 299 |
+
input_mins = [float(x.strip()) for x in input_bounds_min.split(",")]
|
| 300 |
+
input_maxs = [float(x.strip()) for x in input_bounds_max.split(",")]
|
| 301 |
+
if len(input_mins) == len(input_features) and len(input_maxs) == len(input_features):
|
| 302 |
+
for i, feat in enumerate(input_features):
|
| 303 |
+
input_bounds[feat] = (input_mins[i], input_maxs[i])
|
| 304 |
+
|
| 305 |
+
output_bounds = {}
|
| 306 |
+
if output_bounds_min and output_bounds_max:
|
| 307 |
+
output_mins = [float(x.strip()) for x in output_bounds_min.split(",")]
|
| 308 |
+
output_maxs = [float(x.strip()) for x in output_bounds_max.split(",")]
|
| 309 |
+
if len(output_mins) == len(output_features) and len(output_maxs) == len(output_features):
|
| 310 |
+
for i, feat in enumerate(output_features):
|
| 311 |
+
output_bounds[feat] = (output_mins[i], output_maxs[i])
|
| 312 |
+
|
| 313 |
+
# Parse weights
|
| 314 |
+
weight_values = [float(x.strip()) for x in objective_weights.split(",")]
|
| 315 |
+
weights = {}
|
| 316 |
+
if len(weight_values) == len(output_features):
|
| 317 |
+
for i, feat in enumerate(output_features):
|
| 318 |
+
weights[feat] = weight_values[i]
|
| 319 |
+
else:
|
| 320 |
+
return "Error: Number of weights must match number of output features", None, None
|
| 321 |
+
|
| 322 |
+
progress(0.1, "Initializing optimizer...")
|
| 323 |
+
|
| 324 |
+
# Initialize and run optimizer
|
| 325 |
+
try:
|
| 326 |
+
optimizer = CustomizableBayesianOptimizer(
|
| 327 |
+
data_file=temp_file.name,
|
| 328 |
+
input_features=input_features,
|
| 329 |
+
output_features=output_features,
|
| 330 |
+
objective_weights=weights,
|
| 331 |
+
input_bounds=input_bounds,
|
| 332 |
+
output_bounds=output_bounds,
|
| 333 |
+
num_samples=int(num_samples),
|
| 334 |
+
warmup_steps=int(warmup_steps),
|
| 335 |
+
use_gpu=use_gpu
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
progress(0.3, "Building models...")
|
| 339 |
+
optimizer.build_models()
|
| 340 |
+
|
| 341 |
+
progress(0.7, "Running optimization...")
|
| 342 |
+
optimizer.optimize()
|
| 343 |
+
|
| 344 |
+
progress(0.9, "Generating results...")
|
| 345 |
+
results = optimizer.get_results()
|
| 346 |
+
|
| 347 |
+
# Prepare results text
|
| 348 |
+
result_text = "=== Next Experimental Point ===\n"
|
| 349 |
+
for feat, val in results["next_point"].items():
|
| 350 |
+
result_text += f"{feat}: {val:.4f}\n"
|
| 351 |
+
|
| 352 |
+
result_text += "\n=== Predictions with Uncertainty ===\n"
|
| 353 |
+
for feat, pred in results["predictions"].items():
|
| 354 |
+
result_text += f"{feat}: {pred['mean']:.4f} ± {pred['std']:.4f} ({pred['uncertainty_percent']:.2f}% uncertainty)\n"
|
| 355 |
+
|
| 356 |
+
# Generate visualization
|
| 357 |
+
fig = optimizer.visualize()
|
| 358 |
+
|
| 359 |
+
# Clean up temp file
|
| 360 |
+
os.unlink(temp_file.name)
|
| 361 |
+
|
| 362 |
+
return result_text, fig, None
|
| 363 |
+
|
| 364 |
+
except Exception as e:
|
| 365 |
+
import traceback
|
| 366 |
+
error_message = f"Error: {str(e)}\n\n{traceback.format_exc()}"
|
| 367 |
+
return None, None, error_message
|
| 368 |
+
|
| 369 |
+
# Create Gradio interface
|
| 370 |
+
with gr.Blocks(title="Bayesian Optimization for Electrolyte Optimization") as demo:
|
| 371 |
+
gr.Markdown("# Bayesian Optimization for Electrolytes")
|
| 372 |
+
gr.Markdown("Upload your CSV file and configure the optimization settings.")
|
| 373 |
+
|
| 374 |
+
with gr.Row():
|
| 375 |
+
with gr.Column(scale=1):
|
| 376 |
+
# Input section
|
| 377 |
+
file_input = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 378 |
+
input_features = gr.Textbox(label="Input Features (comma-separated)", placeholder="x1, x2")
|
| 379 |
+
output_features = gr.Textbox(label="Output Features (comma-separated)", placeholder="CE (%), LCE, Overpotential (V)")
|
| 380 |
+
|
| 381 |
+
input_bounds_min = gr.Textbox(label="Input Min Bounds (comma-separated, match order of features)", placeholder="1, 1")
|
| 382 |
+
input_bounds_max = gr.Textbox(label="Input Max Bounds (comma-separated, match order of features)", placeholder="6, 6")
|
| 383 |
+
|
| 384 |
+
output_bounds_min = gr.Textbox(label="Output Min Bounds (comma-separated, match order of features)", placeholder="0, 0, 0")
|
| 385 |
+
output_bounds_max = gr.Textbox(label="Output Max Bounds (comma-separated, match order of features)", placeholder="100, 100, 10")
|
| 386 |
+
|
| 387 |
+
objective_weights = gr.Textbox(
|
| 388 |
+
label="Objective Weights (comma-separated, match order of output features, use negative for minimization)",
|
| 389 |
+
placeholder="0.25, 0.25, -0.5"
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
with gr.Row():
|
| 393 |
+
use_gpu = gr.Checkbox(label="Use GPU (if available)", value=True)
|
| 394 |
+
num_samples = gr.Number(label="MCMC Samples", value=512, precision=0)
|
| 395 |
+
warmup_steps = gr.Number(label="Warmup Steps", value=128, precision=0)
|
| 396 |
+
|
| 397 |
+
submit_btn = gr.Button("Run Optimization")
|
| 398 |
+
|
| 399 |
+
with gr.Column(scale=1):
|
| 400 |
+
# Output section
|
| 401 |
+
results_text = gr.Textbox(label="Results", lines=10)
|
| 402 |
+
plot_output = gr.Plot(label="Optimization Plot")
|
| 403 |
+
error_output = gr.Textbox(label="Errors (if any)", visible=True)
|
| 404 |
+
|
| 405 |
+
# Connect the interface to the optimization function
|
| 406 |
+
submit_btn.click(
|
| 407 |
+
fn=run_optimization,
|
| 408 |
+
inputs=[
|
| 409 |
+
file_input,
|
| 410 |
+
input_features,
|
| 411 |
+
output_features,
|
| 412 |
+
input_bounds_min,
|
| 413 |
+
input_bounds_max,
|
| 414 |
+
output_bounds_min,
|
| 415 |
+
output_bounds_max,
|
| 416 |
+
objective_weights,
|
| 417 |
+
use_gpu,
|
| 418 |
+
num_samples,
|
| 419 |
+
warmup_steps
|
| 420 |
+
],
|
| 421 |
+
outputs=[results_text, plot_output, error_output]
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
gr.Markdown("""
|
| 425 |
+
## Instructions:
|
| 426 |
+
1. Upload your CSV file with experimental data
|
| 427 |
+
2. Specify input features (e.g., "x1, x2")
|
| 428 |
+
3. Specify output features (e.g., "CE (%), LCE, Overpotential (V)")
|
| 429 |
+
4. Set bounds for inputs and outputs (comma-separated, matching the order of features)
|
| 430 |
+
5. Specify weights for each output (positive for maximization, negative for minimization)
|
| 431 |
+
6. Click "Run Optimization"
|
| 432 |
+
|
| 433 |
+
The default settings optimize with weights: 0.25 for CE, 0.25 for LCE, -0.5 for Overpotential
|
| 434 |
+
""")
|
| 435 |
+
|
| 436 |
+
# Launch the interface
|
| 437 |
+
if __name__ == "__main__":
|
| 438 |
+
demo.launch(share=True)
|
grid_experiment.csv
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
x1,x2,CE (%),Overpotential (V),LCE
|
| 2 |
+
1.0,1.0,98.12362035654209,0.013457210425540768,2.049422152308001
|
| 3 |
+
1.5555555555555556,1.0,99.85214291922975,0.08000514523901583,1.6588979754965343
|
| 4 |
+
2.111111111111111,1.0,99.19598182543422,0.04457915791839594,1.7131400998662296
|
| 5 |
+
2.666666666666667,1.0,98.79597545259111,0.06594277602811731,2.2289879319689554
|
| 6 |
+
3.2222222222222223,1.0,97.4680559213273,0.10983231213187022,2.024500341761713
|
| 7 |
+
3.7777777777777777,1.0,97.46798356100861,0.037422145206376246,1.6064379361316408
|
| 8 |
+
4.333333333333334,1.0,97.1742508365046,0.05514212153391927,1.6710300800062226
|
| 9 |
+
4.888888888888889,1.0,99.5985284373248,0.09311062523973535,2.064451238375639
|
| 10 |
+
5.444444444444445,1.0,98.80334503522963,0.03516779820407847,1.603543108692353
|
| 11 |
+
6.0,1.0,99.12421773338814,0.01846779008116723,1.7125656359922492
|
| 12 |
+
1.0,1.5555555555555556,97.06175348288741,0.04187265982051448,1.9841136525566103
|
| 13 |
+
1.5555555555555556,1.5555555555555556,99.90972955648598,0.027734341597940484,2.0843266383848853
|
| 14 |
+
2.111111111111111,1.5555555555555556,99.49732792240127,0.11226674175768303,2.0563728816518205
|
| 15 |
+
2.666666666666667,1.5555555555555556,97.63701733203483,0.09889324175208586,1.756988516622392
|
| 16 |
+
3.2222222222222223,1.5555555555555556,97.5454749016213,0.07967441321614657,2.098525454943275
|
| 17 |
+
3.7777777777777777,1.5555555555555556,97.5502135295603,0.10586066492064894,1.76607436124776
|
| 18 |
+
4.333333333333334,1.5555555555555556,97.91272672887861,0.09840392845890258,1.8277797887114875
|
| 19 |
+
4.888888888888889,1.5555555555555556,98.57426929489671,0.03052270647746394,2.1225439835826165
|
| 20 |
+
5.444444444444445,1.5555555555555556,98.29583505592635,0.10818148983389755,2.05474302933305
|
| 21 |
+
6.0,1.5555555555555556,97.87368742059412,0.06932764661072158,2.1944563873459244
|
| 22 |
+
1.0,2.111111111111111,98.83555868416714,0.09881841706804688,2.0603290246102404
|
| 23 |
+
1.5555555555555556,2.111111111111111,97.41848158195613,0.10857004299158425,1.99781602233483
|
| 24 |
+
2.111111111111111,2.111111111111111,97.87643394560565,0.04498038224690503,1.6655723374796647
|
| 25 |
+
2.666666666666667,2.111111111111111,98.09908552988108,0.022105711698044442,1.8574010621416035
|
| 26 |
+
3.2222222222222223,2.111111111111111,98.36820995265111,0.035072867879613584,1.7856416573772078
|
| 27 |
+
3.7777777777777777,2.111111111111111,99.35552788417904,0.0569818567488882,1.7707927503653584
|
| 28 |
+
4.333333333333334,2.111111111111111,97.59902134647508,0.09998162425147424,2.2811073883267117
|
| 29 |
+
4.888888888888889,2.111111111111111,98.54270331524083,0.10468036415819777,1.8751684072667323
|
| 30 |
+
5.444444444444445,2.111111111111111,98.77724370658613,0.010764734358430977,2.224432588623979
|
| 31 |
+
6.0,2.111111111111111,97.13935123815999,0.06618220328353223,2.041797038198084
|
| 32 |
+
1.0,2.666666666666667,98.82263455570431,0.05591521034636569,2.156367912479154
|
| 33 |
+
1.5555555555555556,2.666666666666667,97.51157237106187,0.03443185915178033,1.9518459651736344
|
| 34 |
+
2.111111111111111,2.666666666666667,97.19515477895584,0.02318519040670511,2.003832719238451
|
| 35 |
+
2.666666666666667,2.666666666666667,99.84665661176,0.04713766885439908,1.9447623856732048
|
| 36 |
+
3.2222222222222223,2.666666666666667,99.89689609922368,0.1137200674303771,1.7366700914586313
|
| 37 |
+
3.7777777777777777,2.666666666666667,99.42519204434939,0.04555232252228308,2.1057164806830535
|
| 38 |
+
4.333333333333334,2.666666666666667,97.91384130752012,0.06706696839177027,1.796540653708599
|
| 39 |
+
4.888888888888889,2.666666666666667,97.29301634201916,0.08733208547846956,1.6170211765020177
|
| 40 |
+
5.444444444444445,2.666666666666667,99.05269907953647,0.04999925626172234,2.0518306071350176
|
| 41 |
+
6.0,2.666666666666667,98.32045748121881,0.11689602909930567,1.7239774755849342
|
| 42 |
+
1.0,3.2222222222222223,97.36611470453434,0.11586920244363223,2.25832100904704
|
| 43 |
+
1.5555555555555556,3.2222222222222223,98.4855307303338,0.03769605254079006,2.267750003901811
|
| 44 |
+
2.111111111111111,3.2222222222222223,97.10316556334566,0.0646973356481624,2.2404050731543137
|
| 45 |
+
2.666666666666667,3.2222222222222223,99.72796120623634,0.043096614079844664,1.859111090178811
|
| 46 |
+
3.2222222222222223,3.2222222222222223,97.77633994480006,0.04133245438152144,1.6108196315702072
|
| 47 |
+
3.7777777777777777,3.2222222222222223,98.98756685306195,0.014057564208998608,2.2498229938114074
|
| 48 |
+
4.333333333333334,3.2222222222222223,97.93513322826823,0.07705207673778865,1.89972890382212
|
| 49 |
+
4.888888888888889,3.2222222222222223,98.56020406353343,0.06529469255517477,2.2766583733305685
|
| 50 |
+
5.444444444444445,3.2222222222222223,98.64013083802983,0.01566266263749883,2.2745339839624767
|
| 51 |
+
6.0,3.2222222222222223,97.55456336657659,0.04065111106602726,2.197106618827152
|
| 52 |
+
1.0,3.7777777777777777,99.90875388329367,0.1099092474563319,1.80611422444871
|
| 53 |
+
1.5555555555555556,3.7777777777777777,99.32539847008334,0.03635180797336696,1.8695684100213477
|
| 54 |
+
2.111111111111111,3.7777777777777777,99.81849682469257,0.025938435930034538,2.1957956700617998
|
| 55 |
+
2.666666666666667,3.7777777777777777,99.68448205128294,0.06383980363053193,1.8218454036093943
|
| 56 |
+
3.2222222222222223,3.7777777777777777,98.79369993643326,0.11842154995216607,1.7186449226802647
|
| 57 |
+
3.7777777777777777,3.7777777777777777,99.76562270506935,0.036626079866265045,1.989760883720845
|
| 58 |
+
4.333333333333334,3.7777777777777777,97.26547750615576,0.08393491021464664,2.2553083419125466
|
| 59 |
+
4.888888888888889,3.7777777777777777,97.58794858725743,0.09377815768615894,2.087220857672481
|
| 60 |
+
5.444444444444445,3.7777777777777777,97.13568186673162,0.03614012983916396,1.9990428190625553
|
| 61 |
+
6.0,3.7777777777777777,97.9759909922898,0.09010379834730455,1.668023545639538
|
| 62 |
+
1.0,4.333333333333334,98.16603186906845,0.050456144599117854,2.030505058689419
|
| 63 |
+
1.5555555555555556,4.333333333333334,97.81404709532168,0.07955364136529373,2.293037695072984
|
| 64 |
+
2.111111111111111,4.333333333333334,99.48621252745579,0.07968826818369841,1.698058810665567
|
| 65 |
+
2.666666666666667,4.333333333333334,98.07025998008076,0.06893521524822344,1.9628307566546157
|
| 66 |
+
3.2222222222222223,4.333333333333334,97.84280352906214,0.01993187470598491,2.2141611503495686
|
| 67 |
+
3.7777777777777777,4.333333333333334,98.62808824947474,0.10188327451481617,2.118538032427943
|
| 68 |
+
4.333333333333334,4.333333333333334,97.42277267492429,0.04528580714689094,2.0879110186966874
|
| 69 |
+
4.888888888888889,4.333333333333334,99.40659094226211,0.030517036143983968,2.0917388587909764
|
| 70 |
+
5.444444444444445,4.333333333333334,97.22365193103931,0.01448526557102403,1.8516438058538287
|
| 71 |
+
6.0,4.333333333333334,99.96066080980155,0.0749982237507066,1.8055142909851454
|
| 72 |
+
1.0,4.888888888888889,99.31673430788997,0.08453207980265107,2.1665528088349593
|
| 73 |
+
1.5555555555555556,4.888888888888889,97.59614704460252,0.011824661182064176,2.167079376275426
|
| 74 |
+
2.111111111111111,4.888888888888889,97.01656635137081,0.0663302364129209,2.2069506230060725
|
| 75 |
+
2.666666666666667,4.888888888888889,99.4463842853645,0.03491453527177318,2.2392683867895298
|
| 76 |
+
3.2222222222222223,4.888888888888889,99.12057203154285,0.08096900694503947,1.9579396792026564
|
| 77 |
+
3.7777777777777777,4.888888888888889,99.18702150412297,0.029180307190549058,1.9510614062810396
|
| 78 |
+
4.333333333333334,4.888888888888889,99.31381104005784,0.08600315119127125,2.1588066252767426
|
| 79 |
+
4.888888888888889,4.888888888888889,97.22213395520227,0.05254088809305912,2.0549747515444357
|
| 80 |
+
5.444444444444445,4.888888888888889,98.07539718563282,0.1130402987610408,2.0913768140803923
|
| 81 |
+
6.0,4.888888888888889,97.34760717857539,0.02512730385605926,2.157054868605271
|
| 82 |
+
1.0,5.444444444444445,99.58931027762678,0.04751729861552844,2.223003739272296
|
| 83 |
+
1.5555555555555556,5.444444444444445,98.86989438048268,0.0224820873364648,1.836596609796075
|
| 84 |
+
2.111111111111111,5.444444444444445,97.99269407455795,0.1117162980106419,1.8629080668479607
|
| 85 |
+
2.666666666666667,5.444444444444445,97.19067505085808,0.1065073288719079,1.6657873578886084
|
| 86 |
+
3.2222222222222223,5.444444444444445,97.93294696514698,0.03837357904866712,2.0047960986973217
|
| 87 |
+
3.7777777777777777,5.444444444444445,97.97554996608024,0.08259824506375969,1.6251595916577195
|
| 88 |
+
4.333333333333334,5.444444444444445,99.18881853501419,0.09989444202213374,1.9259186126927221
|
| 89 |
+
4.888888888888889,5.444444444444445,98.91267241406564,0.07107208927594086,1.9798512442953036
|
| 90 |
+
5.444444444444445,5.444444444444445,99.66163822772899,0.0682615636191607,1.8005788764897992
|
| 91 |
+
6.0,5.444444444444445,98.41664477548585,0.03660375199904969,2.0135832823983075
|
| 92 |
+
1.0,6.0,97.3587827378149,0.020241304458648912,1.6213501749573347
|
| 93 |
+
1.5555555555555556,6.0,99.13973436166899,0.10869373337486594,1.62614373212445
|
| 94 |
+
2.111111111111111,6.0,99.28235514585069,0.10904598628796634,2.1758203924617607
|
| 95 |
+
2.666666666666667,6.0,98.68383159270849,0.07964116030005947,1.852133448987884
|
| 96 |
+
3.2222222222222223,6.0,99.31290153986369,0.04729327701535708,1.6889423588563195
|
| 97 |
+
3.7777777777777777,6.0,98.48138678909318,0.0484130532073927,1.965570282038363
|
| 98 |
+
4.333333333333334,6.0,98.56819848814598,0.08985512467572633,2.1389954871690273
|
| 99 |
+
4.888888888888889,6.0,98.28262305507565,0.10868212859478348,1.7510747192477902
|
| 100 |
+
5.444444444444445,6.0,97.07625738023229,0.1075795066691629,2.0360233330733
|
| 101 |
+
6.0,6.0,97.32367428097992,0.09578631004433862,1.6597432254956377
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=1.11.0
|
| 2 |
+
botorch>=0.6.6
|
| 3 |
+
gpytorch>=1.6.0
|
| 4 |
+
pyro-ppl>=1.8.2
|
| 5 |
+
pandas>=1.4.2
|
| 6 |
+
numpy>=1.22.3
|
| 7 |
+
scikit-learn>=1.0.2
|
| 8 |
+
matplotlib>=3.5.1
|
| 9 |
+
gradio>=3.0.0
|