Spaces:
Sleeping
Sleeping
included real propeller surrogate model.
Browse files10 unmodified lines111213141516171819202122232425136 unmodified lines16216316416516616716897 unmodified lines266267268269270271272644 unmodified lines9179189199209219226 unmodified lines9299309319329339349352 unmodified lines93893994094194294394428 unmodified lines973974975976977978979295 unmodified lines12751276127712781279128010 unmodified lines- Tab 1: Complete single-objective optimization (from app_active_learning_single.py)- Tab 2: Complete multi-objective optimization (from app_active_learning_multi_objective.py)- No simplifications - uses original code exactly as written# Author: Kirsten Odendaal"""import osimport sysimport warningsimport numpy as npimport matplotlib.pyplot as pltimport plotly.graph_objects as gofrom plotly.subplots import make_subplots136 unmodified lines# Observationsax.scatter(X[:, 0], y, c="tab:orange", s=42, zorder=5, label="Samples")# Best-so-far (star) and last sampled (+)if best_xy is not None:ax.scatter([best_xy[0]], [best_xy[1]], s=120, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")if last_x is not None:97 unmodified lines# Observationsax1.scatter(X[:, 0], y, c="tab:orange", s=42, zorder=5, label="Samples")# Best-so-far (star) and last sampled (+)if best_xy is not None:ax1.scatter([best_xy[0]], [best_xy[1]], s=120, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")if last_x is not None:644 unmodified lines)return fig_3d, fig_pareto, fig_hv, summary_md, history_payload# ============================================================================# GRADIO UI - COMBINED APPLICATION6 unmodified lineswith gr.Row():with gr.Column(scale=1): # 1/3 of the rowgr.Image("marin_logo.png",show_label=False,show_download_button=False,show_fullscreen_button=False,2 unmodified lines)with gr.Column(scale=3): # 2/3 of the rowgr.Markdown("# Active Learning Application")with gr.Accordion("What is Active Learning (Bayesian Optimization)?", open=False):gr.Markdown("""**Active Learning** is an intelligent approach to optimization that learns from previous evaluations to decide where to sample next. Instead of random sampling, it uses **Bayesian optimization** to make smart decisions about which designs to test.28 unmodified lineswith gr.Tabs():# Tab 1: Single-Objective (from app_active_learning_single.py)with gr.Tab("Single-Objective Optimization"):with gr.Accordion("Single-Objective Active Learning", open=False):gr.Markdown("""### **What is Single-Objective Optimization?**Find the **best design** that minimizes (or maximizes) one specific goal. This is the most common optimization scenario in engineering.295 unmodified lines# Connect problem dropdown to fidelity dropdownproblem_mo.change(update_fidelity_options_mo, inputs=[problem_mo], outputs=[fidelity_mo])return demo# --- Main ------------------------------------------------------10 unmodified lines1112131415161718192021222324252627136 unmodified lines16416516616716816917097 unmodified lines268269270271272273274644 unmodified lines91992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512466 unmodified lines12531254125512561257125812592 unmodified lines126212631264126512661267126828 unmodified lines1297129812991300130113021303295 unmodified lines159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177310 unmodified lines- Tab 1: Complete single-objective optimization (from app_active_learning_single.py)- Tab 2: Complete multi-objective optimization (from app_active_learning_multi_objective.py)- No simplifications - uses original code exactly as written"""import osimport sysimport warningsimport numpy as npimport pandas as pdfrom pathlib import Pathimport joblibfrom scipy.stats import qmcimport matplotlib.pyplot as pltimport plotly.graph_objects as gofrom plotly.subplots import make_subplots136 unmodified lines# Observationsax.scatter(X[:, 0], y, c="tab:orange", s=42, zorder=5, label="Samples")# Best-so-far (⭐) and last sampled (✚)if best_xy is not None:ax.scatter([best_xy[0]], [best_xy[1]], s=120, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")if last_x is not None:97 unmodified lines# Observationsax1.scatter(X[:, 0], y, c="tab:orange", s=42, zorder=5, label="Samples")# Best-so-far (⭐) and last sampled (✚)if best_xy is not None:ax1.scatter([best_xy[0]], [best_xy[1]], s=120, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")if last_x is not None:644 unmodified lines)return fig_3d, fig_pareto, fig_hv, summary_md, history_payload# ============================================================================# PROPELLER REAL USE-CASE (Multi-objective with Surrogates)# ============================================================================# Paths for propeller data and surrogates (relative to this file)PROP_MODEL_DIR = Path(CURRENT_DIR) / "trained_surrogates"PROP_MODEL_DIR.mkdir(exist_ok=True)POWER_MODEL_PATH = PROP_MODEL_DIR / "surrogate_power.joblib"CAVITATION_MODEL_PATH = PROP_MODEL_DIR / "surrogate_cavitation.joblib"PROP_DOE_PATH = Path(CURRENT_DIR) / "results_DoE_globalsurrogate.dat"# Globals to cache loaded data / models between runs_prop_surrogate_power = None_prop_surrogate_cav = None_prop_x_ref = None_prop_obj1_ref = None_prop_obj2_ref = NoneHV_REF_PAD_REL = 0.02 # 2% relative paddingHV_REF_PAD_ABS = 1e-3 # absolute fallback paddingdef load_propeller_surrogates(noise_level: float = 1e-3):"""Load cached propeller surrogates if available; otherwise train themfrom the DoE file and cache them."""global _prop_surrogate_power, _prop_surrogate_cavglobal _prop_x_ref, _prop_obj1_ref, _prop_obj2_ref# If already loaded, just returnif _prop_surrogate_power is not None and _prop_surrogate_cav is not None:return _prop_surrogate_power, _prop_surrogate_cav, _prop_x_ref, _prop_obj1_ref, _prop_obj2_refif not PROP_DOE_PATH.exists():raise FileNotFoundError(f"Propeller DoE file not found at {PROP_DOE_PATH}")# Load DoE tabletable_df = pd.read_csv(PROP_DOE_PATH,delim_whitespace=True,comment="#",header=0)# Use up to N rows (as in the notebook)N = min(len(table_df), 640)x_ref = table_df[["x1", "x2", "x3", "x4"]].to_numpy()[:N]obj1_at_x_ref = table_df["power_NATO"].to_numpy()[:N].reshape(-1, 1)obj2_at_x_ref = table_df["cavitationobjective_NATO"].to_numpy()[:N].reshape(-1, 1)surrogate_power = Nonesurrogate_cav = Noneif POWER_MODEL_PATH.exists() and CAVITATION_MODEL_PATH.exists():surrogate_power = joblib.load(POWER_MODEL_PATH)surrogate_cav = joblib.load(CAVITATION_MODEL_PATH)print(f"[Propeller] Loaded cached surrogates from {PROP_MODEL_DIR.resolve()}")else:print("[Propeller] Cached surrogates not found; training new models...")surrogate_power = make_gp_mo(noise_level=noise_level)surrogate_power.fit(x_ref, obj1_at_x_ref)surrogate_cav = make_gp_mo(noise_level=noise_level)surrogate_cav.fit(x_ref, obj2_at_x_ref)joblib.dump(surrogate_power, POWER_MODEL_PATH)joblib.dump(surrogate_cav, CAVITATION_MODEL_PATH)print(f"[Propeller] Trained and saved surrogates to {PROP_MODEL_DIR.resolve()}")_prop_surrogate_power = surrogate_power_prop_surrogate_cav = surrogate_cav_prop_x_ref = x_ref_prop_obj1_ref = obj1_at_x_ref_prop_obj2_ref = obj2_at_x_refreturn surrogate_power, surrogate_cav, x_ref, obj1_at_x_ref, obj2_at_x_refdef _hv_propeller_acq(x, y, model_list, hv_ref):"""Hypervolume-based acquisition for the propeller case.x: candidate (1D or 2D array)y: current objective values (N x 2)model_list: list [model_obj1, model_obj2]hv_ref: reference point for hypervolume"""x = np.atleast_2d(x)obj_pred_list = [m.predict(x) for m in model_list]obj_pred = np.array([[obj_pred_list[0].item(), obj_pred_list[1].item()]])y_pred = np.concatenate((y, obj_pred))return hypervolume(y_pred, hv_ref)def _compute_hv_reference(y_samples: np.ndarray) -> np.ndarray:"""Ensure that the hypervolume reference point strictly dominates all samples.Parameters----------y_samples : array-like, shape (n_samples, n_obj)Objective values that the reference point must dominate.Returns-------np.ndarrayReference point padded away from the samples."""if y_samples.size == 0:raise ValueError("Cannot infer hypervolume reference from empty samples.")hv_base = np.max(y_samples, axis=0)scale = np.maximum(np.abs(hv_base), 1.0)padding = np.maximum(HV_REF_PAD_ABS, HV_REF_PAD_REL * scale)return hv_base + padding@dataclassclass PropRunCfg:n_init: int # initial LHS samplesn_iter: int # active learning iterationsn_restarts: int # restarts for inner optimizationseed: int = 42 # RNG seednoise_level: float = 1e-3 # GP noise for acquisition surrogatedef run_propeller_bo(cfg: PropRunCfg):"""Multi-objective active learning on the propeller surrogate.Objectives:- Obj1: power_NATO / 1000 (minimize)- Obj2: cavitationobjective_NATO (minimize)Acquisition:- Hypervolume-based (like in your notebook)"""# 1. Load or train the global surrogates (power + cavitation)surrogate_power, surrogate_cav, x_ref, obj1_ref, obj2_ref = load_propeller_surrogates(noise_level=cfg.noise_level)# Objective functions as in the notebookdef objective_1(x):return surrogate_power.predict(np.atleast_2d(x)) # powerdef objective_2(x):return surrogate_cav.predict(np.atleast_2d(x)) # cavitation# 2. Initial LHS design in unit box [0,1]^4rng = np.random.default_rng(cfg.seed)sampler = qmc.LatinHypercube(d=4, seed=rng.integers(0, 1_000_000))sample = sampler.random(n=cfg.n_init)l_bounds = [0.0, 0.0, 0.0, 0.0]u_bounds = [1.0, 1.0, 1.0, 1.0]x = qmc.scale(sample, l_bounds, u_bounds) # (n_init, 4)# 3. Evaluate objectives using surrogates (as in notebook)obj_at_x = np.array([[objective_1(np.array([xi])).item() / 1000.0, # power scaled by 1000objective_2(np.array([xi])).item()] # cavitation objectivefor xi in x]) # shape (n_init, 2)# 4. Build acquisition surrogates (GPs) on initial datamodel_list = []noise_level = cfg.noise_levelfor i in range(obj_at_x.shape[1]):model = make_gp_mo(noise_level=noise_level)model.fit(x, obj_at_x[:, i].reshape(-1, 1))model_list.append(model)# 5. Hypervolume reference and optimization settingsdoe_objectives = np.hstack([obj1_ref / 1000.0, obj2_ref])hv_ref = _compute_hv_reference(np.vstack([obj_at_x, doe_objectives]))ndim = 4bounds = tuple((0.0, 1.0) for _ in range(ndim))# Starting points for inner optimizationx_start = rng.random((cfg.n_restarts, ndim))y = obj_at_x.copy()iterations = cfg.n_iterhypervolume_list = []hypervolume_list_pred = []# 6. Active learning loop (as in notebook)for it in range(iterations):print(f"[Propeller] Iteration {it+1}/{iterations}")# Acquisition objective: negative hypervolume (we minimize)def acq_obj(x_local):return -1.0 * _hv_propeller_acq(x_local, y, model_list, hv_ref)# Optimize acquisition from multiple random restartsopt_results = [minimize(acq_obj,x0=x0,method="L-BFGS-B",bounds=bounds,options={"maxiter": 1000})for x0 in x_start]opt_success = [res for res in opt_results if res.success]# Fallback: if no success, just use all resultsif len(opt_success) == 0:opt_success = opt_resultsobj_success = np.array([res.fun for res in opt_success])best_idx = int(np.argmin(obj_success))result = opt_success[best_idx]# New point from optimizationx_new = np.atleast_2d(result.x)obj1_new = objective_1(x_new)obj2_new = objective_2(x_new)y_new = np.array([[obj1_new.item() / 1000.0, obj2_new.item()]]) # same scaling# Predicted hypervolume gain (remember: result.fun = -HV_pred)hypervolume_list_pred.append(-1.0 * result.fun)# Update datasetsx = np.vstack([x, x_new])y = np.vstack([y, y_new])# Record true hypervolumehypervolume_list.append(hypervolume(y, hv_ref))# Retrain acquisition surrogates on enriched datafor i in range(y.shape[1]):model_list[i].fit(x, y[:, i].reshape(-1, 1))# 7. Plot results (similar to your notebook)n_initial = obj_at_x.shape[0]def _plot_propeller_progress(k: int):"""Plot objectives and hypervolume up to iteration k (1-based)."""fig, ax = plt.subplots(1, 2, figsize=(13, 5))# Objectives scatterax[0].scatter(hv_ref[0], hv_ref[1], color="m", label="HV reference")ax[0].scatter(obj_at_x[:, 0], obj_at_x[:, 1], color="C0", label="Initial design")if k > 0:new_points = y[n_initial : n_initial + k, :]ax[0].scatter(new_points[:, 0],new_points[:, 1],color="red",label="Active learning (Kriging)")ax[0].set_xlabel("Objective 1 (Power / 1000)")ax[0].set_ylabel("Objective 2 (Cavitation)")ax[0].legend()ax[0].set_title(f"Propeller Pareto Front (up to iter {k})")# Hypervolume evolutionit_range = np.arange(1, k + 1)if k > 0:ax[1].plot(it_range, hypervolume_list[:k], "-x", label="truth", color="red")ax[1].plot(it_range, hypervolume_list_pred[:k], "-x", label="prediction", color="k")ax[1].set_xlabel("Iterations")ax[1].set_ylabel("Hypervolume")ax[1].legend()ax[1].set_title("Hypervolume Convergence")fig.tight_layout()return fig# Final figure (all iterations)final_fig = _plot_propeller_progress(iterations)# Summary markdownfinal_hv = hypervolume_list[-1] if len(hypervolume_list) > 0 else float("nan")summary_md = f"""**Propeller Multi-objective Optimization (Surrogate-based)**- Initial design size: {n_initial}- Active learning iterations: {iterations}- Final hypervolume: `{final_hv:.6g}`- Hypervolume reference point: `{hv_ref}`- Best (min) power/1000: `{y[:, 0].min():.4g}`- Best cavitation objective: `{y[:, 1].min():.4g}`"""# History payload for playback in the UIhistory_payload = dict(hv_ref=hv_ref,y_init=obj_at_x,y_final=y,hv_history=hypervolume_list,hv_pred_history=hypervolume_list_pred,n_initial=n_initial,)return final_fig, summary_md, history_payload# ============================================================================# GRADIO UI - COMBINED APPLICATION6 unmodified lineswith gr.Row():with gr.Column(scale=1): # 1/3 of the rowgr.Image("../marin_logo.png",show_label=False,show_download_button=False,show_fullscreen_button=False,2 unmodified lines)with gr.Column(scale=3): # 2/3 of the rowgr.Markdown("# Active Learning Application")with gr.Accordion("🧠 What is Active Learning (Bayesian Optimization)?", open=False):gr.Markdown("""**Active Learning** is an intelligent approach to optimization that learns from previous evaluations to decide where to sample next. Instead of random sampling, it uses **Bayesian optimization** to make smart decisions about which designs to test.28 unmodified lineswith gr.Tabs():# Tab 1: Single-Objective (from app_active_learning_single.py)with gr.Tab("Single-Objective Optimization"):with gr.Accordion("🎯 Single-Objective Active Learning", open=False):gr.Markdown("""### **What is Single-Objective Optimization?**Find the **best design** that minimizes (or maximizes) one specific goal. This is the most common optimization scenario in engineering.295 unmodified lines# Connect problem dropdown to fidelity dropdownproblem_mo.change(update_fidelity_options_mo, inputs=[problem_mo], outputs=[fidelity_mo])# Tab 3: Propeller Real Use-Case (multi-objective with surrogates)with gr.Tab("Propeller Optimization (Real Use Case)"):with gr.Accordion("Propeller Active Learning", open=False):gr.Markdown("""### Real Use-Case: Propeller OptimizationIn this tab we use **pre-trained surrogate models** of a propeller toperform **multi-objective active learning**. The objectives are:- **Objective 1**: Power (scaled by 1/1000)- **Objective 2**: Cavitation objectiveThe underlying CFD or experimental model is **not** called directly here;instead, we use surrogates (Gaussian Process / Kriging) that you provideas `.joblib` files.The acquisition strategy is based on **hypervolume improvement**:at each iteration, we choose a new propeller design that is expectedto maximally improve the Pareto front in terms of dominated volume.""")# State for history / playbackstate_history_prop = gr.State(value=None)with gr.Row():with gr.Column(scale=1):n_init_prop = gr.Slider(10, 60, value=24, step=1,label="Initial LHS samples")n_iter_prop = gr.Slider(1, 60, value=24, step=1,label="Active learning iterations")n_restarts_prop = gr.Slider(50, 400, value=200, step=10,label="Optimization restarts per iteration")seed_prop = gr.Slider(0, 10_000, value=42, step=1,label="Random seed")run_prop = gr.Button("Run Propeller Optimization",variant="primary")iter_prop = gr.Slider(1, 1, value=1, step=1, interactive=True,label="View results up to iteration")with gr.Column(scale=2):out_prop_plot = gr.Plot(label="Objectives & Hypervolume")out_prop_summary = gr.Markdown()# --- Callback to run the propeller optimization ---def _run_propeller(n_init, n_iter, n_restarts, seed):cfg = PropRunCfg(n_init=int(n_init),n_iter=int(n_iter),n_restarts=int(n_restarts),seed=int(seed),)fig, summary_md, hist = run_propeller_bo(cfg)# Slider range update: 1..n_itertotal = cfg.n_iter if hist is not None else 1slider_update = gr.update(minimum=1,maximum=max(1, total),value=max(1, total),step=1,interactive=True,)return fig, summary_md, hist, slider_updaterun_prop.click(_run_propeller,inputs=[n_init_prop, n_iter_prop, n_restarts_prop, seed_prop],outputs=[out_prop_plot, out_prop_summary, state_history_prop, iter_prop],)# --- Playback handler: show partial progress up to selected iteration ---def _render_prop_at_iter(hist, iter_idx: int):if not hist or "hv_history" not in hist:fig = plt.figure(figsize=(5, 3))ax = fig.add_subplot(111)ax.axis("off")ax.text(0.5,0.5,"No optimization history available.",ha="center",va="center",)fig.tight_layout()return fighv_ref = np.asarray(hist["hv_ref"])y_init = np.asarray(hist["y_init"])y_final = np.asarray(hist["y_final"])hv_history = list(hist["hv_history"])hv_pred = list(hist["hv_pred_history"])n_initial = int(hist["n_initial"])max_iter = len(hv_history)if max_iter == 0:fig = plt.figure(figsize=(5, 3))ax = fig.add_subplot(111)ax.axis("off")ax.text(0.5,0.5,"No optimization history available.",ha="center",va="center",)fig.tight_layout()return figk = int(np.clip(iter_idx, 1, max_iter))# Reuse the plotting logic from run_propeller_bofig, ax = plt.subplots(1, 2, figsize=(13, 5))# Objectives scatterax[0].scatter(hv_ref[0], hv_ref[1], color="m", label="HV reference")ax[0].scatter(y_init[:, 0], y_init[:, 1], color="C0", label="Initial design")if k > 0:new_points = y_final[n_initial : n_initial + k, :]ax[0].scatter(new_points[:, 0],new_points[:, 1],color="red",label="Active learning (Kriging)",)ax[0].set_xlabel("Objective 1 (Power / 1000)")ax[0].set_ylabel("Objective 2 (Cavitation)")ax[0].legend()ax[0].set_title(f"Propeller Pareto Front (up to iter {k})")# Hypervolume evolutionit_range = np.arange(1, k + 1)if k > 0:ax[1].plot(it_range, hv_history[:k], "-x", label="truth", color="red")ax[1].plot(it_range, hv_pred[:k], "-x", label="prediction", color="k")ax[1].set_xlabel("Iterations")ax[1].set_ylabel("Hypervolume")ax[1].legend()ax[1].set_title("Hypervolume Convergence")fig.tight_layout()return figiter_prop.change(_render_prop_at_iter,inputs=[state_history_prop, iter_prop],outputs=[out_prop_plot],)return demo# --- Main ------------------------------------------------------
app.py+501-8