Spaces:
Sleeping
Sleeping
Download app.py from kode24/Usecase_3_Active_Learn: direct link, hf CLI and curl.
- Browser
- Download file 74 kB
-
https://huggingface.co/spaces/kode24/Usecase_3_Active_Learn/resolve/main/app.py
- Command line
-
hf download hf://spaces/kode24/Usecase_3_Active_Learn/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kode24/Usecase_3_Active_Learn/resolve/main/app.py
74 kB
#!/usr/bin/env python3
"""
Combined Active Learning Application
====================================
This application combines both single-objective and multi-objective
Bayesian optimization by importing and running the original scripts
in separate tabs without any simplifications.
Features:
- 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)
- Tab 3: Complete Propeller multi-objecitve optimization (from main_case1_multi_objective_propeller.ipynb)
"""
import os
import sys
import warnings
import numpy as np
import pandas as pd
from pathlib import Path
import joblib
from scipy.stats import qmc
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import gradio as gr
from typing import Dict, List, Any, Tuple, Optional
from dataclasses import dataclass
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel as C
from scipy.optimize import minimize
from scipy.stats import norm
# --- Project paths ------------------------------------------
CURRENT_DIR = os.path.dirname(__file__)
if CURRENT_DIR not in sys.path:
sys.path.insert(0, CURRENT_DIR)
# Import project modules
from L1interface import EvaluateL1
# Import hypervolume calculation
try:
from hypervolume import hypervolume
except ImportError:
# Fallback hypervolume implementation
def hypervolume(points, ref):
"""Simple hypervolume calculation for 2D case."""
if len(points) == 0:
return 0.0
# Sort points by first objective
sorted_points = points[np.argsort(points[:, 0])]
hv = 0.0
for i, point in enumerate(sorted_points):
if i == 0:
hv += (ref[0] - point[0]) * (ref[1] - point[1])
else:
prev_point = sorted_points[i-1]
hv += (ref[0] - point[0]) * (ref[1] - point[1]) - (ref[0] - point[0]) * (ref[1] - prev_point[1])
return max(0.0, hv)
# Suppress warnings
warnings.filterwarnings("ignore")
np.seterr(all="ignore")
# ============================================================================
# SINGLE-OBJECTIVE CODE (from app_active_learning_single.py)
# ============================================================================
# --- Problems registry --------------------------------------
SINGLE_PROBLEMS: Dict[str, Dict[str, Any]] = {
"1D Forrester": {"InfoCase": "1DFORRESTER", "dim": 1, "fids": [1,2,3,4]},
"1D Sasena": {"InfoCase": "1DSASENA", "dim": 1, "fids": [1,2]},
"2D Rosenbrock": {"InfoCase": "2DROSENBROCK", "dim": 2, "fids": [1,2,3]},
"2D Rastrigin": {"InfoCase": "2DRASTRIGIN", "dim": 2, "fids": [1,2,3]},
"2D ALOS": {"InfoCase": "2DALOS", "dim": 2, "fids": [1,2]},
}
# --- Single-objective Utils ---------------------------------------------------
def unit_grid_1d(n: int) -> np.ndarray:
return np.linspace(0.0, 1.0, n).reshape(-1, 1)
def unit_grid_2d(n_per_axis: int) -> np.ndarray:
g = np.linspace(0.0, 1.0, n_per_axis)
X1, X2 = np.meshgrid(g, g, indexing="xy")
return np.c_[X1.ravel(), X2.ravel()]
def eval_batch(x_unit: np.ndarray, info: str, fidelity: int, noise_std: float) -> np.ndarray:
"""Evaluate benchmark via EvaluateL1 (unit inputs are accepted by your interface)."""
y = EvaluateL1(x_unit, info, FidelityLevel=fidelity, noise=noise_std)
return np.asarray(y).reshape(-1)
# Single-objective Acquisition functions
def expected_improvement(mu, sigma, f_best, xi=0.01):
sigma = np.maximum(sigma, 1e-12)
z = (f_best - mu - xi) / sigma
return (f_best - mu - xi) * norm.cdf(z) + sigma * norm.pdf(z)
def compute_acq_values(mu: np.ndarray, std: np.ndarray, f_best: float, xi: float) -> np.ndarray:
return expected_improvement(mu, std, f_best, xi=xi)
# Single-objective GP model
def make_gp_single(noise_level: float, nu: float = 2.5, length_scale: float = 0.2) -> GaussianProcessRegressor:
kernel = C(1.0, (1e-3, 1e3)) * Matern(length_scale=length_scale, nu=nu) \
+ WhiteKernel(noise_level=max(noise_level**2, 1e-10))
return GaussianProcessRegressor(kernel=kernel, normalize_y=True, n_restarts_optimizer=3, random_state=0)
# --- Single-objective True process & LHS -------------------------------------
def _eval_true_process(info: str, X: np.ndarray, fidelity_level: int = 1) -> np.ndarray:
"""
Return noiseless true process value for a given InfoCase and unit-space X.
Uses EvaluateL1 with specified FidelityLevel and noise=0.
Args:
info: Problem identifier (InfoCase)
X: Input points in unit space
fidelity_level: Fidelity level to use (default=1 for highest fidelity)
"""
try:
y = EvaluateL1(X, info, FidelityLevel=fidelity_level, noise=0.0)
return np.asarray(y).reshape(-1)
except Exception as e:
print(f"[warn] True process eval failed for {info} at fidelity {fidelity_level}: {e}")
return np.zeros(X.shape[0])
def _lhs_ref(dim: int, n: int, seed: int = 0):
rng = np.random.default_rng(seed)
return rng.random((n, dim))
# --- Single-objective Plotting ------------------------------------------------
def plot_model_1d(X, y, Xc, mu, std, it, info_text: str, info: str,
best_xy: Tuple[float, float], last_x: Optional[float],
show_truth=True, show_lhs=True, fidelity_level=1):
fig, ax = plt.subplots(figsize=(8.0, 4.2))
if show_truth:
y_true = _eval_true_process(info, Xc, fidelity_level)
ax.plot(Xc[:, 0], y_true, "k--", lw=1.8, label="True process")
# GP mean & band
ax.plot(Xc[:, 0], mu, lw=2.0, color="tab:blue", label="GP mean")
ax.fill_between(Xc[:, 0], mu - 2*std, mu + 2*std, alpha=0.25, color="tab:blue", label="Β±2Ο")
# Observations
ax.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:
ax.scatter([last_x], [np.interp(last_x, Xc[:,0], mu)], s=90, marker="+", c="red", zorder=6, label="Last x")
if show_lhs:
Xlhs = _lhs_ref(1, 8)
ylhs = _eval_true_process(info, Xlhs, fidelity_level)
ax.scatter(Xlhs[:, 0], ylhs, c="gray", marker="x", s=40, label="LHS ref")
ax.set_xlim(0, 1); ax.set_xlabel("x"); ax.set_ylabel("f(x)")
ax.set_title(f"{info_text} β iteration {it}")
ax.grid(alpha=0.3); ax.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_model_2d(X, y, Xc, mu, std, it, info_text: str, info: str, n_axis: int,
best_xy: Tuple[float, float], last_xy: Optional[Tuple[float, float]],
show_truth=True, show_lhs=True, fidelity_level=1):
fig, ax = plt.subplots(figsize=(6.8, 5.6))
g = np.linspace(0.0, 1.0, n_axis)
if show_truth:
y_true = _eval_true_process(info, Xc, fidelity_level)
Zt = y_true.reshape(n_axis, n_axis)
cs = ax.contourf(g, g, Zt, levels=25, cmap="Greys", alpha=0.40)
plt.colorbar(cs, ax=ax, label="True f(x)")
Z = mu.reshape(n_axis, n_axis)
cs2 = ax.contourf(g, g, Z, levels=25, cmap="viridis", alpha=0.80)
plt.colorbar(cs2, ax=ax, label="GP mean")
ax.scatter(X[:, 0], X[:, 1], c="tab:orange", edgecolor="k", s=52, label="Samples", zorder=5)
if best_xy is not None:
ax.scatter([best_xy[0]], [best_xy[1]], s=130, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")
if last_xy is not None:
ax.scatter([last_xy[0]], [last_xy[1]], s=90, marker="+", c="red", zorder=6, label="Last x")
if show_lhs:
Xlhs = _lhs_ref(2, 20)
ax.scatter(Xlhs[:, 0], Xlhs[:, 1], c="gray", s=25, marker="x", label="LHS ref")
ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal", adjustable="box")
ax.set_xlabel("x1"); ax.set_ylabel("x2")
ax.set_title(f"{info_text} β iteration {it}")
ax.grid(alpha=0.3); ax.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_convergence(best_hist: List[float]):
fig, ax = plt.subplots(figsize=(6.8, 3.8))
ax.plot(np.arange(1, len(best_hist)+1), best_hist, "-o")
ax.set_xlabel("Iteration"); ax.set_ylabel("Best-so-far f(x)")
ax.set_title("Convergence (minimization)")
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def plot_acquisition_1d(Xc, acq_vals, picked_x):
fig, ax = plt.subplots(figsize=(8.0, 2.8))
ax.plot(Xc[:, 0], acq_vals, lw=2, label="Acquisition")
if picked_x is not None:
ax.axvline(picked_x, color="r", ls="--", lw=1.5, label="Sampled x this iter")
ax.set_xlabel("x"); ax.set_ylabel("acq(x)")
ax.set_title("Acquisition (selected iteration)")
ax.grid(alpha=0.3); ax.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_acquisition_2d(Xc, acq_vals, n_axis, picked_xy):
fig, ax = plt.subplots(figsize=(6.8, 4.8))
g = np.linspace(0.0, 1.0, n_axis)
Z = acq_vals.reshape(n_axis, n_axis)
cs = ax.contourf(g, g, Z, levels=25, cmap="magma")
plt.colorbar(cs, ax=ax, label="Acquisition value")
if picked_xy is not None:
ax.scatter([picked_xy[0]], [picked_xy[1]], s=90, marker="+", c="cyan", label="Sampled x this iter", zorder=5)
ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal", adjustable="box")
ax.set_xlabel("x1"); ax.set_ylabel("x2")
ax.set_title("Acquisition (selected iteration)")
ax.grid(alpha=0.3); ax.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_combined_model_acq_1d(X, y, Xc, mu, std, acq_vals, it, info_text: str, info: str,
best_xy: Tuple[float, float], last_x: Optional[float],
show_truth=True, show_lhs=True, fidelity_level=1):
"""Combined plot showing GP model and acquisition function side by side."""
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8.0, 6.5), height_ratios=[2, 1])
# Top plot: GP model
if show_truth:
y_true = _eval_true_process(info, Xc, fidelity_level)
ax1.plot(Xc[:, 0], y_true, "k--", lw=1.8, label="True process")
# GP mean & band
ax1.plot(Xc[:, 0], mu, lw=2.0, color="tab:blue", label="GP mean")
ax1.fill_between(Xc[:, 0], mu - 2*std, mu + 2*std, alpha=0.25, color="tab:blue", label="Β±2Ο")
# Observations
ax1.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:
ax1.scatter([last_x], [np.interp(last_x, Xc[:,0], mu)], s=90, marker="+", c="red", zorder=6, label="Last x")
if show_lhs:
Xlhs = _lhs_ref(1, 8)
ylhs = _eval_true_process(info, Xlhs, fidelity_level)
ax1.scatter(Xlhs[:, 0], ylhs, c="gray", marker="x", s=40, label="LHS ref")
ax1.set_xlim(0, 1); ax1.set_xlabel("x"); ax1.set_ylabel("f(x)")
ax1.set_title(f"{info_text} β iteration {it}")
ax1.grid(alpha=0.3); ax1.legend(loc="upper left")
# Bottom plot: Acquisition function
ax2.plot(Xc[:, 0], acq_vals, lw=2, color="tab:purple", label="Acquisition")
if last_x is not None:
ax2.axvline(last_x, color="r", ls="--", lw=1.5, label="Sampled x this iter")
ax2.set_xlim(0, 1); ax2.set_xlabel("x"); ax2.set_ylabel("acq(x)")
ax2.set_title("Acquisition Function")
ax2.grid(alpha=0.3); ax2.legend(loc="upper left")
fig.tight_layout()
return fig
def plot_combined_model_acq_2d(X, y, Xc, mu, std, acq_vals, it, info_text: str, info: str, n_axis: int,
best_xy: Tuple[float, float], last_xy: Optional[Tuple[float, float]],
show_truth=True, show_lhs=True, fidelity_level=1):
"""Combined plot showing GP model and acquisition function side by side."""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13.6, 5.6))
g = np.linspace(0.0, 1.0, n_axis)
# Left plot: GP model
if show_truth:
y_true = _eval_true_process(info, Xc, fidelity_level)
Zt = y_true.reshape(n_axis, n_axis)
cs = ax1.contourf(g, g, Zt, levels=25, cmap="Greys", alpha=0.40)
plt.colorbar(cs, ax=ax1, label="True f(x)")
Z = mu.reshape(n_axis, n_axis)
cs2 = ax1.contourf(g, g, Z, levels=25, cmap="viridis", alpha=0.80)
plt.colorbar(cs2, ax=ax1, label="GP mean")
ax1.scatter(X[:, 0], X[:, 1], c="tab:orange", edgecolor="k", s=52, label="Samples", zorder=5)
if best_xy is not None:
ax1.scatter([best_xy[0]], [best_xy[1]], s=130, marker="*", c="gold", edgecolors="k", zorder=6, label="Best sample")
if last_xy is not None:
ax1.scatter([last_xy[0]], [last_xy[1]], s=90, marker="+", c="red", zorder=6, label="Last x")
if show_lhs:
Xlhs = _lhs_ref(2, 20)
ax1.scatter(Xlhs[:, 0], Xlhs[:, 1], c="gray", s=25, marker="x", label="LHS ref")
ax1.set_xlim(0, 1); ax1.set_ylim(0, 1); ax1.set_aspect("equal", adjustable="box")
ax1.set_xlabel("x1"); ax1.set_ylabel("x2")
ax1.set_title(f"{info_text} β iteration {it}")
ax1.grid(alpha=0.3); ax1.legend(loc="upper left")
# Right plot: Acquisition function
Z_acq = acq_vals.reshape(n_axis, n_axis)
cs3 = ax2.contourf(g, g, Z_acq, levels=25, cmap="magma")
plt.colorbar(cs3, ax=ax2, label="Acquisition value")
if last_xy is not None:
ax2.scatter([last_xy[0]], [last_xy[1]], s=90, marker="+", c="cyan", label="Sampled x this iter", zorder=5)
ax2.set_xlim(0, 1); ax2.set_ylim(0, 1); ax2.set_aspect("equal", adjustable="box")
ax2.set_xlabel("x1"); ax2.set_ylabel("x2")
ax2.set_title("Acquisition Function")
ax2.grid(alpha=0.3); ax2.legend(loc="upper left")
fig.tight_layout()
return fig
# --- Single-objective Core BO loop -------------------------------------------
@dataclass
class SingleRunCfg:
problem_key: str
fidelity: int
noise_std: float
n_init: int
n_iter: int
acq_xi: float
grid_1d: int
grid_2d: int
seed: int
show_truth: bool
show_lhs: bool
def run_single_bo(cfg: SingleRunCfg):
pr = SINGLE_PROBLEMS[cfg.problem_key]
info, dim = pr["InfoCase"], pr["dim"]
rng = np.random.default_rng(cfg.seed)
# Initial design
X = rng.random((cfg.n_init, dim))
y = eval_batch(X, info, cfg.fidelity, cfg.noise_std)
# Candidate set
if dim == 1:
Xcand = unit_grid_1d(cfg.grid_1d)
elif dim == 2:
Xcand = unit_grid_2d(cfg.grid_2d)
else:
Xcand = rng.random((5000, dim))
best_hist = [float(np.min(y))]
gp = make_gp_single(noise_level=cfg.noise_std)
# --- History containers (for playback) ---
acq_hist: List[np.ndarray] = []
pick_idx_hist: List[int] = []
pick_xy_hist: List[np.ndarray] = []
gp_mu_hist: List[np.ndarray] = []
gp_std_hist: List[np.ndarray] = []
X_hist: List[np.ndarray] = []
y_hist: List[np.ndarray] = []
last_x_new = None
# Iterate BO
for _it in range(1, cfg.n_iter + 1):
gp.fit(X, y)
mu, std = gp.predict(Xcand, return_std=True)
f_best = float(np.min(y))
acq_vals = compute_acq_values(mu, std, f_best, cfg.acq_xi)
j = int(np.argmax(acq_vals))
x_new = Xcand[j:j+1, :]
y_new = eval_batch(x_new, info, cfg.fidelity, cfg.noise_std)
# record history BEFORE updating f_best for next iter
acq_hist.append(acq_vals.copy())
pick_idx_hist.append(j)
pick_xy_hist.append(x_new[0].copy())
gp_mu_hist.append(mu.copy())
gp_std_hist.append(std.copy())
X_hist.append(X.copy())
y_hist.append(y.copy())
X = np.vstack([X, x_new])
y = np.r_[y, y_new]
best_hist.append(float(np.min(y)))
last_x_new = x_new[0]
# Final model
gp.fit(X, y)
mu_cand, std_cand = gp.predict(Xcand, return_std=True)
# Best-so-far star
i_best = int(np.argmin(y))
x_best = X[i_best]
y_best = float(y[i_best])
info_text = f"{cfg.problem_key} | Fid {cfg.fidelity} | noise Ο={cfg.noise_std:g}"
# Model plot (last iteration state)
if dim == 1:
fig_model = plot_model_1d(
X, y, Xcand, mu_cand, std_cand, cfg.n_iter, info_text, info,
best_xy=(x_best[0], y_best),
last_x=float(last_x_new[0]) if last_x_new is not None else None,
show_truth=cfg.show_truth, show_lhs=cfg.show_lhs, fidelity_level=cfg.fidelity
)
elif dim == 2:
fig_model = plot_model_2d(
X, y, Xcand, mu_cand, std_cand, cfg.n_iter, info_text, info, cfg.grid_2d,
best_xy=(x_best[0], x_best[1]),
last_xy=(float(last_x_new[0]), float(last_x_new[1])) if last_x_new is not None else None,
show_truth=cfg.show_truth, show_lhs=cfg.show_lhs, fidelity_level=cfg.fidelity
)
else:
fig_model = plt.figure(figsize=(5,3))
ax = fig_model.add_subplot(111); ax.axis("off")
ax.text(0.5, 0.5, f"No model plot for dim={dim}", ha="center", va="center")
fig_model.tight_layout()
fig_conv = plot_convergence(best_hist)
# Markdown table
rows = [f"| {k+1} | {v:.6g} |" for k, v in enumerate(best_hist)]
table_md = (
f"**Best found**: `f(x*) = {y_best:.6g}` at `x* = {np.array2string(x_best, precision=4)}`\n\n"
"| Iter | Best-so-far |\n|---:|---:|\n" + "\n".join(rows)
)
# Pack history for UI playback
history_payload = dict(
dim=dim,
Xcand=Xcand,
n_axis=(cfg.grid_2d if dim == 2 else None),
acq_hist=acq_hist,
pick_idx_hist=pick_idx_hist,
pick_xy_hist=pick_xy_hist,
gp_mu_hist=gp_mu_hist,
gp_std_hist=gp_std_hist,
X_hist=X_hist,
y_hist=y_hist,
info=info,
fidelity_level=cfg.fidelity,
show_truth=cfg.show_truth,
show_lhs=cfg.show_lhs,
)
# Return last-iter acquisition too (for initial display)
last_iter = len(acq_hist)
if last_iter > 0:
acq_vals_last = acq_hist[-1]
pick_xy_last = pick_xy_hist[-1]
if dim == 1:
fig_acq = plot_acquisition_1d(Xcand, acq_vals_last, picked_x=float(pick_xy_last[0]))
elif dim == 2:
fig_acq = plot_acquisition_2d(Xcand, acq_vals_last, cfg.grid_2d, picked_xy=(float(pick_xy_last[0]), float(pick_xy_last[1])))
else:
fig_acq = plt.figure(figsize=(5,3))
ax2 = fig_acq.add_subplot(111); ax2.axis("off")
ax2.text(0.5, 0.5, "No acquisition plot for dim>2", ha="center", va="center")
fig_acq.tight_layout()
else:
fig_acq = plt.figure()
return fig_model, fig_acq, fig_conv, table_md, history_payload
# ============================================================================
# MULTI-OBJECTIVE CODE (from app_active_learning_multi_objective.py)
# ============================================================================
# --- Multi-objective Problems Registry ---------------------
MO_PROBLEMS: Dict[str, Dict[str, Any]] = {
"2D Spring-Mass": {
"objectives": ["2DSPRING", "2DMASS"],
"dim": 2,
"fids": [1, 2],
"constraints": [],
"description": "Spring stiffness vs Mass optimization"
},
"2D Spring-Mass-ALOS": {
"objectives": ["2DSPRING", "2DALOS"],
"dim": 2,
"fids": [1, 2],
"constraints": [],
"description": "Spring stiffness vs ALOS function"
},
"3D Rosenbrock-Rastrigin": {
"objectives": ["2DROSENBROCK", "2DRASTRIGIN"],
"dim": 2,
"fids": [1, 2, 3],
"constraints": [],
"description": "Rosenbrock vs Rastrigin functions"
}
}
# --- Multi-objective Utils ---------------------------------------------------
def unit_grid_2d_mo(n_per_axis: int) -> np.ndarray:
g = np.linspace(0.0, 1.0, n_per_axis)
X1, X2 = np.meshgrid(g, g, indexing="xy")
return np.c_[X1.ravel(), X2.ravel()]
def eval_objectives(x_unit: np.ndarray, objectives: List[str], fidelity: int, noise_std: float) -> np.ndarray:
"""Evaluate multiple objectives via EvaluateL1."""
results = []
for obj_name in objectives:
y = EvaluateL1(x_unit, obj_name, FidelityLevel=fidelity, noise=noise_std)
results.append(np.asarray(y).reshape(-1))
return np.column_stack(results)
def eval_constraints(x_unit: np.ndarray, constraints: List[str], fidelity: int) -> np.ndarray:
"""Evaluate constraints (if any)."""
if not constraints:
return np.zeros((x_unit.shape[0], 0))
results = []
for con_name in constraints:
# For now, we'll use simple constraint functions
# In practice, you'd implement proper constraint evaluation
y = EvaluateL1(x_unit, con_name, FidelityLevel=fidelity, noise=0.0)
results.append(np.asarray(y).reshape(-1))
return np.column_stack(results)
def is_feasible(constraints: np.ndarray) -> np.ndarray:
"""Check constraint feasibility (constraints <= 0)."""
if constraints.shape[1] == 0:
return np.ones(constraints.shape[0], dtype=bool)
return np.all(constraints <= 0, axis=1)
def compute_pareto_front(objectives: np.ndarray, constraints: np.ndarray) -> np.ndarray:
"""Compute Pareto front considering constraints."""
feasible_mask = is_feasible(constraints)
if not np.any(feasible_mask):
return np.array([])
feasible_obj = objectives[feasible_mask]
feasible_indices = np.where(feasible_mask)[0]
if len(feasible_obj) == 0:
return np.array([])
# Simple Pareto front computation
pareto_mask = np.ones(len(feasible_obj), dtype=bool)
for i in range(len(feasible_obj)):
for j in range(len(feasible_obj)):
if i != j:
# Check if point j dominates point i
if np.all(feasible_obj[j] <= feasible_obj[i]) and np.any(feasible_obj[j] < feasible_obj[i]):
pareto_mask[i] = False
break
return feasible_indices[pareto_mask]
# --- Multi-objective GP Models for Multi-objective --------------------------
def make_gp_mo(noise_level: float, nu: float = 2.5, length_scale: float = 0.2) -> GaussianProcessRegressor:
kernel = C(1.0, (1e-3, 1e3)) * Matern(length_scale=length_scale, nu=nu) \
+ WhiteKernel(noise_level=max(noise_level**2, 1e-10))
return GaussianProcessRegressor(kernel=kernel, normalize_y=True, n_restarts_optimizer=5, random_state=0)
# --- Multi-objective Acquisition Functions -----------------
def expected_hypervolume_improvement(mu_list: List[np.ndarray], std_list: List[np.ndarray],
current_obj: np.ndarray, ref_point: np.ndarray,
n_samples: int = 50) -> np.ndarray:
"""Expected Hypervolume Improvement acquisition function."""
n_obj = len(mu_list)
n_candidates = len(mu_list[0])
ehi_values = np.zeros(n_candidates)
for i in range(n_candidates):
# Sample from GP predictions
samples = []
for j in range(n_obj):
samples.append(np.random.normal(mu_list[j][i], std_list[j][i], n_samples))
# Compute hypervolume for each sample
hv_improvements = []
for s in range(n_samples):
sample_obj = np.array([samples[j][s] for j in range(n_obj)])
new_obj = np.vstack([current_obj, sample_obj])
hv_new = hypervolume(new_obj, ref_point)
hv_current = hypervolume(current_obj, ref_point)
hv_improvements.append(max(0, hv_new - hv_current))
ehi_values[i] = np.mean(hv_improvements)
return ehi_values
def probability_of_improvement(mu_list: List[np.ndarray], std_list: List[np.ndarray],
current_obj: np.ndarray, ref_point: np.ndarray) -> np.ndarray:
"""Probability of Hypervolume Improvement."""
n_obj = len(mu_list)
n_candidates = len(mu_list[0])
poi_values = np.zeros(n_candidates)
for i in range(n_candidates):
# Check if this point could improve hypervolume
sample_obj = np.array([mu_list[j][i] for j in range(n_obj)])
new_obj = np.vstack([current_obj, sample_obj])
hv_new = hypervolume(new_obj, ref_point)
hv_current = hypervolume(current_obj, ref_point)
if hv_new > hv_current:
# Probability that this point is non-dominated
prob_non_dominated = 1.0
for j in range(n_obj):
# Probability that this objective is better than current best
current_best = np.min(current_obj[:, j])
prob_better = norm.cdf((current_best - mu_list[j][i]) / std_list[j][i])
prob_non_dominated *= prob_better
poi_values[i] = prob_non_dominated
return poi_values
# --- Multi-objective Visualization Functions --------------------------------
def plot_objectives_3d(X_ref: np.ndarray, obj1_ref: np.ndarray, obj2_ref: np.ndarray,
X_samples: np.ndarray, obj_samples: np.ndarray,
title: str = "Objective Functions"):
"""Create 3D surface plots of objective functions."""
fig = make_subplots(
rows=1, cols=2,
specs=[[{'type': 'surface'}, {'type': 'surface'}]],
subplot_titles=("Objective 1", "Objective 2")
)
n_axis = int(np.sqrt(len(X_ref)))
X_grid = X_ref[:, 0].reshape(n_axis, n_axis)
Y_grid = X_ref[:, 1].reshape(n_axis, n_axis)
Z1_grid = obj1_ref.reshape(n_axis, n_axis)
Z2_grid = obj2_ref.reshape(n_axis, n_axis)
# Add surfaces with distinct colorscales and proper colorbar positioning
fig.add_trace(go.Surface(
x=X_grid, y=Y_grid, z=Z1_grid,
colorscale='Viridis',
colorbar=dict(x=0.45, len=0.4) # Position colorbar for first surface
), row=1, col=1)
fig.add_trace(go.Surface(
x=X_grid, y=Y_grid, z=Z2_grid,
colorscale='Plasma',
colorbar=dict(x=1.0, len=0.4) # Position colorbar for second surface
), row=1, col=2)
# Add sample points
fig.add_trace(go.Scatter3d(
x=X_samples[:, 0], y=X_samples[:, 1], z=obj_samples[:, 0],
mode='markers', marker=dict(size=4, color='red'),
name='Samples Obj1'
), row=1, col=1)
fig.add_trace(go.Scatter3d(
x=X_samples[:, 0], y=X_samples[:, 1], z=obj_samples[:, 1],
mode='markers', marker=dict(size=4, color='red'),
name='Samples Obj2'
), row=1, col=2)
# Update layout with better spacing
fig.update_layout(
title=title,
height=500,
width=1200, # Increased width to accommodate both colorbars
scene=dict(
xaxis_title="X1",
yaxis_title="X2",
zaxis_title="Objective 1"
),
scene2=dict(
xaxis_title="X1",
yaxis_title="X2",
zaxis_title="Objective 2"
)
)
return fig
def plot_pareto_front_2d(objectives: np.ndarray, pareto_indices: np.ndarray,
ref_point: np.ndarray, title: str = "Pareto Front"):
"""Plot 2D Pareto front."""
fig, ax = plt.subplots(figsize=(8, 6))
# Plot all points
ax.scatter(objectives[:, 0], objectives[:, 1], c='lightblue', alpha=0.6, label='All points')
# Plot Pareto front
if len(pareto_indices) > 0:
pareto_obj = objectives[pareto_indices]
ax.scatter(pareto_obj[:, 0], pareto_obj[:, 1], c='red', s=50, label='Pareto front')
# Sort Pareto points for line plot
sorted_indices = np.argsort(pareto_obj[:, 0])
sorted_pareto = pareto_obj[sorted_indices]
ax.plot(sorted_pareto[:, 0], sorted_pareto[:, 1], 'r-', alpha=0.7)
# Plot reference point
ax.scatter(ref_point[0], ref_point[1], c='magenta', s=100, marker='*', label='Reference point')
ax.set_xlabel('Objective 1')
ax.set_ylabel('Objective 2')
ax.set_title(title)
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_hypervolume_progress(hypervolume_history: List[float]):
"""Plot hypervolume convergence."""
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(np.arange(1, len(hypervolume_history) + 1), hypervolume_history, 'o-')
ax.set_xlabel('Iteration')
ax.set_ylabel('Hypervolume')
ax.set_title('Hypervolume Convergence')
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_acquisition_2d_mo(Xc: np.ndarray, acq_vals: np.ndarray, n_axis: int,
picked_xy: Optional[Tuple[float, float]] = None):
"""Plot 2D acquisition function."""
fig, ax = plt.subplots(figsize=(6, 5))
g = np.linspace(0.0, 1.0, n_axis)
Z = acq_vals.reshape(n_axis, n_axis)
cs = ax.contourf(g, g, Z, levels=25, cmap="magma")
plt.colorbar(cs, ax=ax, label="Acquisition value")
if picked_xy is not None:
ax.scatter([picked_xy[0]], [picked_xy[1]], s=90, marker="+", c="cyan",
label="Sampled x this iter", zorder=5)
ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal", adjustable="box")
ax.set_xlabel("x1"); ax.set_ylabel("x2")
ax.set_title("Multi-objective Acquisition Function")
ax.grid(alpha=0.3); ax.legend(loc="upper left")
fig.tight_layout()
return fig
# --- Multi-objective Core BO loop ---------------------------
@dataclass
class MORunCfg:
problem_key: str
fidelity: int
noise_std: float
n_init: int
n_iter: int
acq_name: str
grid_2d: int
seed: int
ref_point: Tuple[float, float]
def run_multi_objective_bo(cfg: MORunCfg):
pr = MO_PROBLEMS[cfg.problem_key]
objectives = pr["objectives"]
constraints = pr["constraints"]
dim = pr["dim"]
rng = np.random.default_rng(cfg.seed)
# Initial design
X = rng.random((cfg.n_init, dim))
obj_vals = eval_objectives(X, objectives, cfg.fidelity, cfg.noise_std)
con_vals = eval_constraints(X, constraints, cfg.fidelity)
# Candidate set
Xcand = unit_grid_2d_mo(cfg.grid_2d)
# Initialize GP models for each objective
gp_models = [make_gp_mo(noise_level=cfg.noise_std) for _ in objectives]
# History containers
hv_history = []
pareto_history = []
acq_history = []
pick_history = []
X_history = []
obj_history = []
con_history = []
# Initial hypervolume
initial_pareto = compute_pareto_front(obj_vals, con_vals)
initial_hv = hypervolume(obj_vals[initial_pareto], cfg.ref_point) if len(initial_pareto) > 0 else 0.0
# Store initial state in all history arrays
hv_history.append(initial_hv)
pareto_history.append(initial_pareto)
X_history.append(X.copy())
obj_history.append(obj_vals.copy())
con_history.append(con_vals.copy())
# Multi-objective optimization loop
for iteration in range(cfg.n_iter):
print(f"Multi-objective BO iteration {iteration + 1}/{cfg.n_iter}")
# Train GP models
for i, gp in enumerate(gp_models):
gp.fit(X, obj_vals[:, i])
# Predict on candidates
mu_list = []
std_list = []
for gp in gp_models:
mu, std = gp.predict(Xcand, return_std=True)
mu_list.append(mu)
std_list.append(std)
# Compute acquisition function
current_pareto_indices = pareto_history[-1]
current_obj = obj_vals[current_pareto_indices] if len(current_pareto_indices) > 0 else obj_vals
if cfg.acq_name == "EHI":
acq_vals = expected_hypervolume_improvement(mu_list, std_list, current_obj, cfg.ref_point)
else: # POI
acq_vals = probability_of_improvement(mu_list, std_list, current_obj, cfg.ref_point)
# Select next point
j = int(np.argmax(acq_vals))
x_new = Xcand[j:j+1, :]
# Evaluate new point
obj_new = eval_objectives(x_new, objectives, cfg.fidelity, cfg.noise_std)
con_new = eval_constraints(x_new, constraints, cfg.fidelity)
# Update data
X = np.vstack([X, x_new])
obj_vals = np.vstack([obj_vals, obj_new])
con_vals = np.vstack([con_vals, con_new])
# Update Pareto front and hypervolume
new_pareto = compute_pareto_front(obj_vals, con_vals)
new_hv = hypervolume(obj_vals[new_pareto], cfg.ref_point) if len(new_pareto) > 0 else 0.0
# Store history
hv_history.append(new_hv)
pareto_history.append(new_pareto)
acq_history.append(acq_vals.copy())
pick_history.append(x_new[0].copy())
X_history.append(X.copy())
obj_history.append(obj_vals.copy())
con_history.append(con_vals.copy())
# Final results
final_pareto = pareto_history[-1]
final_obj = obj_history[-1]
final_X = X_history[-1]
info_text = f"{cfg.problem_key} | Fid {cfg.fidelity} | noise Ο={cfg.noise_std:g}"
# Create visualizations
fig_pareto = plot_pareto_front_2d(final_obj, final_pareto, cfg.ref_point,
f"{info_text} β Final Pareto Front")
fig_hv = plot_hypervolume_progress(hv_history)
# Create 3D objective plots (use smaller grid to reduce printouts)
X_ref = unit_grid_2d_mo(10) # Even smaller reference grid for 3D plots
obj1_ref = eval_objectives(X_ref, [objectives[0]], cfg.fidelity, 0.0)[:, 0]
obj2_ref = eval_objectives(X_ref, [objectives[1]], cfg.fidelity, 0.0)[:, 0]
fig_3d = plot_objectives_3d(X_ref, obj1_ref, obj2_ref, final_X, final_obj,
f"{info_text} β Objective Functions")
# Markdown summary
n_pareto = len(final_pareto)
final_hv = hv_history[-1]
summary_md = f"""
**Multi-objective Optimization Results:**
- **Problem**: {cfg.problem_key}
- **Fidelity Level**: {cfg.fidelity}
- **Total Evaluations**: {len(final_X)}
- **Pareto Front Size**: {n_pareto} points
- **Final Hypervolume**: {final_hv:.6f}
- **Reference Point**: {cfg.ref_point}
**Objectives**: {', '.join(objectives)}
"""
# Pack history for playback
history_payload = dict(
Xcand=Xcand,
n_axis=cfg.grid_2d,
acq_history=acq_history,
pick_history=pick_history,
X_history=X_history,
obj_history=obj_history,
con_history=con_history,
pareto_history=pareto_history,
hv_history=hv_history,
objectives=objectives,
ref_point=cfg.ref_point,
)
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 = None
HV_REF_PAD_REL = 0.02 # 2% relative padding
HV_REF_PAD_ABS = 1e-3 # absolute fallback padding
def load_propeller_surrogates(noise_level: float = 1e-3):
"""
Load cached propeller surrogates if available; otherwise train them
from the DoE file and cache them.
"""
global _prop_surrogate_power, _prop_surrogate_cav
global _prop_x_ref, _prop_obj1_ref, _prop_obj2_ref
# If already loaded, just return
if _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_ref
if not PROP_DOE_PATH.exists():
raise FileNotFoundError(f"Propeller DoE file not found at {PROP_DOE_PATH}")
# Load DoE table
table_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 = None
surrogate_cav = None
if 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_ref
return surrogate_power, surrogate_cav, x_ref, obj1_at_x_ref, obj2_at_x_ref
def _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.ndarray
Reference 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
@dataclass
class PropRunCfg:
n_init: int # initial LHS samples
n_iter: int # active learning iterations
n_restarts: int # restarts for inner optimization
seed: int = 42 # RNG seed
noise_level: float = 1e-3 # GP noise for acquisition surrogate
def 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 notebook
def objective_1(x):
return surrogate_power.predict(np.atleast_2d(x)) # power
def objective_2(x):
return surrogate_cav.predict(np.atleast_2d(x)) # cavitation
# 2. Initial LHS design in unit box [0,1]^4
rng = 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 1000
objective_2(np.array([xi])).item()] # cavitation objective
for xi in x
]) # shape (n_init, 2)
# 4. Build acquisition surrogates (GPs) on initial data
model_list = []
noise_level = cfg.noise_level
for 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 settings
doe_objectives = np.hstack([obj1_ref / 1000.0, obj2_ref])
hv_ref = _compute_hv_reference(np.vstack([obj_at_x, doe_objectives]))
ndim = 4
bounds = tuple((0.0, 1.0) for _ in range(ndim))
# Starting points for inner optimization
x_start = rng.random((cfg.n_restarts, ndim))
y = obj_at_x.copy()
iterations = cfg.n_iter
hypervolume_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 restarts
opt_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 results
if len(opt_success) == 0:
opt_success = opt_results
obj_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 optimization
x_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 datasets
x = np.vstack([x, x_new])
y = np.vstack([y, y_new])
# Record true hypervolume
hypervolume_list.append(hypervolume(y, hv_ref))
# Retrain acquisition surrogates on enriched data
for 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 scatter
ax[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 evolution
it_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 markdown
final_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 UI
history_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 APPLICATION
# ============================================================================
def create_combined_app():
"""Create the combined Gradio application with tabs."""
with gr.Blocks(title="Active Learning App") as demo:
with gr.Row():
with gr.Column(scale=1): # 1/3 of the row
gr.Image(
"marin_logo.png",
show_label=False,
show_download_button=False,
show_fullscreen_button=False,
height=100, # you can tweak this
elem_id="app-logo"
)
with gr.Column(scale=3): # 2/3 of the row
gr.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.
### **Key Concepts:**
#### **π― Surrogate Model (Gaussian Process)**
- **Purpose**: Approximates the expensive function
- **Advantage**: Provides both predictions AND uncertainty estimates
- **Learning**: Updates beliefs as new data arrives
#### **π Acquisition Function**
- **Purpose**: Balances exploration vs exploitation
- **Exploration**: Try uncertain regions (high variance)
- **Exploitation**: Focus on promising regions (low mean)
- **Smart Sampling**: Automatically finds the best trade-off
#### **β‘ Efficiency Benefits**
- **Fewer Evaluations**: Find optima with minimal function calls
- **Global Search**: Avoids getting stuck in local optima
- **Uncertainty Quantification**: Know how confident predictions are
- **Adaptive**: Learns the function's complexity automatically
### **Available Applications:**
- **Single-Objective**: Find the best design for one goal
- **Multi-Objective**: Balance competing objectives (Pareto optimization)
""")
# gr.Image("../marin_logo.png", elem_id="app-logo", scale=0.15, show_label=False, show_download_button=False)
# gr.Markdown("# Active Learning Application")
# gr.Markdown("Single-objective and multi-objective Bayesian optimization with interactive visualization")
with 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.
### **How Bayesian Optimization Works:**
#### **π The Iterative Process:**
1. **Start**: Begin with a few random samples
2. **Learn**: Fit a Gaussian Process to the data
3. **Decide**: Use acquisition function to pick next sample
4. **Evaluate**: Run expensive simulation at chosen point
5. **Repeat**: Continue until budget exhausted
#### **π§ Acquisition Function (EI):**
- **Expected Improvement** balances improvement potential with uncertainty.
### **Interactive Features:**
- **Live Visualization**: Watch the optimization progress
- **Model Evolution**: See how the surrogate learns
- **Acquisition Plots**: Understand sampling decisions
- **Convergence Tracking**: Monitor optimization progress
### **π‘ Pro Tips:**
- EI already balances exploration vs. exploitation
- Higher observation noise benefits from a slightly larger ΞΎ
- More iterations = better results (up to a point)
""")
# State to keep acquisition history for playback
state_history_single = gr.State(value=None)
with gr.Row():
with gr.Column(scale=1):
problem_single = gr.Dropdown(list(SINGLE_PROBLEMS.keys()), value="1D Forrester", label="Benchmark problem")
fidelity_single = gr.Dropdown([1,2,3,4], value=1, label="Benchmark complexity (per problem)")
noise_single = gr.Slider(0.0, 0.2, value=0.00, step=0.01, label="Observation noise Ο")
n_init_single = gr.Slider(2, 20, value=5, step=1, label="Initial random samples")
n_iter_single = gr.Slider(1, 50, value=15, step=1, label="BO iterations (budget)")
acq_xi_single = gr.Slider(0.0, 0.2, value=0.01, step=0.005, label="ΞΎ (EI)")
with gr.Accordion("Advanced options", open=False):
grid_1d_single = gr.Slider(50, 2000, value=500, step=10, label="1D candidate points")
grid_2d_single = gr.Slider(20, 150, value=60, step=2, label="2D candidate points per axis")
seed_single = gr.Slider(0, 10_000, value=42, step=1, label="Random seed")
show_truth_single = gr.Checkbox(True, label="Show true process")
show_lhs_single = gr.Checkbox(True, label="Show LHS reference points")
def _sync_fids_single(pname):
fids = SINGLE_PROBLEMS[pname]["fids"]
return gr.update(choices=fids, value=fids[0])
problem_single.change(_sync_fids_single, inputs=[problem_single], outputs=[fidelity_single])
run_single = gr.Button("Run active learning", variant="primary")
# Playback slider (enabled after a run)
acq_iter_single = gr.Slider(1, 1, value=1, step=1, interactive=True, label="View model + acquisition at iteration")
with gr.Column(scale=2):
out_model_single = gr.Plot(label="Model view (GP + true process + samples)")
out_acq_single = gr.Plot(label="Model + Acquisition (selected iteration)")
out_conv_single = gr.Plot(label="Convergence (best-so-far)")
out_table_single = gr.Markdown()
def _go_single(problem, fidelity, noise, n_init, n_iter, acq_xi,
grid_1d, grid_2d, seed, show_truth, show_lhs):
cfg = SingleRunCfg(
problem_key=problem,
fidelity=int(fidelity),
noise_std=float(noise),
n_init=int(n_init),
n_iter=int(n_iter),
acq_xi=float(acq_xi),
grid_1d=int(grid_1d),
grid_2d=int(grid_2d),
seed=int(seed),
show_truth=bool(show_truth),
show_lhs=bool(show_lhs),
)
fig_model, fig_acq, fig_conv, table_md, hist = run_single_bo(cfg)
# Set slider range to number of iterations and default to the last
total = len(hist["acq_hist"]) if hist is not None else 1
acq_slider_update = gr.update(minimum=1, maximum=max(1, total), value=max(1, total), step=1, interactive=True)
return fig_model, fig_acq, fig_conv, table_md, hist, acq_slider_update
run_single.click(
_go_single,
inputs=[problem_single, fidelity_single, noise_single, n_init_single, n_iter_single, acq_xi_single,
grid_1d_single, grid_2d_single, seed_single, show_truth_single, show_lhs_single],
outputs=[out_model_single, out_acq_single, out_conv_single, out_table_single, state_history_single, acq_iter_single]
)
# --- Playback handler: render combined model+acquisition at selected iteration ---
def _render_acq_at_iter_single(hist, iter_idx: int):
if not hist or "acq_hist" not in hist:
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111); ax.axis("off")
ax.text(0.5, 0.5, "No acquisition history available.", ha="center", va="center")
fig.tight_layout()
return fig
acq_hist = hist["acq_hist"]
pick_idx_hist = hist["pick_idx_hist"]
pick_xy_hist = hist["pick_xy_hist"]
gp_mu_hist = hist["gp_mu_hist"]
gp_std_hist = hist["gp_std_hist"]
X_hist = hist["X_hist"]
y_hist = hist["y_hist"]
Xcand = np.asarray(hist["Xcand"])
dim = int(hist["dim"])
n_axis = hist.get("n_axis", None)
info = hist["info"]
fidelity_level = hist["fidelity_level"]
show_truth = hist["show_truth"]
show_lhs = hist["show_lhs"]
k = int(np.clip(iter_idx, 1, len(acq_hist))) - 1
acq_vals = np.asarray(acq_hist[k])
picked_xy = np.asarray(pick_xy_hist[k])
mu = np.asarray(gp_mu_hist[k])
std = np.asarray(gp_std_hist[k])
X = np.asarray(X_hist[k])
y = np.asarray(y_hist[k])
# Find best sample up to this iteration
i_best = int(np.argmin(y))
x_best = X[i_best]
y_best = float(y[i_best])
info_text = f"Iteration {iter_idx}"
if dim == 1:
return plot_combined_model_acq_1d(
X, y, Xcand, mu, std, acq_vals, iter_idx, info_text, info,
best_xy=(x_best[0], y_best),
last_x=float(picked_xy[0]),
show_truth=show_truth, show_lhs=show_lhs, fidelity_level=fidelity_level
)
elif dim == 2:
return plot_combined_model_acq_2d(
X, y, Xcand, mu, std, acq_vals, iter_idx, info_text, info, int(n_axis),
best_xy=(x_best[0], x_best[1]),
last_xy=(float(picked_xy[0]), float(picked_xy[1])),
show_truth=show_truth, show_lhs=show_lhs, fidelity_level=fidelity_level
)
else:
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111); ax.axis("off")
ax.text(0.5, 0.5, "No combined plot for dim>2", ha="center", va="center")
fig.tight_layout()
return fig
acq_iter_single.change(_render_acq_at_iter_single, inputs=[state_history_single, acq_iter_single], outputs=[out_acq_single])
# Tab 2: Multi-Objective (from app_active_learning_multi_objective.py)
with gr.Tab("Multi-Objective Optimization"):
with gr.Accordion("Multi-Objective Active Learning", open=False):
gr.Markdown("""
### **What is Multi-Objective Optimization?**
Real engineering problems often involve **competing objectives** that can't all be optimized simultaneously. Multi-objective optimization finds the **Pareto front** - the set of optimal trade-offs between objectives.
### **Key Concepts:**
#### **π Pareto Optimality**
- **Definition**: A solution is Pareto optimal if no other solution is better in ALL objectives
- **Trade-offs**: Improving one objective worsens another
- **Pareto Front**: The curve/surface of all Pareto optimal solutions
#### **π Hypervolume Metric**
- **Purpose**: Measures the "volume" of dominated space
- **Higher is Better**: Larger hypervolume = better Pareto front
- **Convergence**: Tracks optimization progress over time
#### **π― Multi-Objective Acquisition Functions**
- **EHI (Expected Hypervolume Improvement)**: Maximizes expected hypervolume gain
### **Visualization Features:**
- **3D Objective Surfaces**: See how objectives vary with parameters
- **Pareto Front Evolution**: Watch the front improve over iterations
- **Hypervolume Convergence**: Track optimization progress
- **Interactive Exploration**: Examine different trade-offs
### **π‘ Pro Tips:**
- **Reference Point**: Set appropriately for hypervolume calculation
- **More Objectives**: Harder to visualize but same principles apply
- **Decision Making**: Use Pareto front to make informed trade-offs
""")
# State for history
state_history_mo = gr.State(value=None)
with gr.Row():
with gr.Column(scale=1):
problem_mo = gr.Dropdown(list(MO_PROBLEMS.keys()), value="2D Spring-Mass",
label="Multi-objective Problem")
fidelity_mo = gr.Dropdown([1, 2], value=1, label="Fidelity level")
noise_mo = gr.Slider(0.0, 0.2, value=0.00, step=0.01, label="Observation noise Ο")
n_init_mo = gr.Slider(3, 20, value=5, step=1, label="Initial random samples")
n_iter_mo = gr.Slider(1, 50, value=15, step=1, label="BO iterations")
acq_mo = gr.Radio(["EHI"], value="EHI",
label="Acquisition Function")
with gr.Accordion("Reference Point", open=False):
ref_x_mo = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Reference Point X")
ref_y_mo = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Reference Point Y")
with gr.Accordion("Advanced options", open=False):
grid_2d_mo = gr.Slider(20, 100, value=40, step=5, label="2D candidate points per axis")
seed_mo = gr.Slider(0, 10_000, value=42, step=1, label="Random seed")
run_mo = gr.Button("Run Multi-objective Optimization", variant="primary")
# Playback slider
mo_iter = gr.Slider(1, 1, value=1, step=1, interactive=True,
label="View optimization at iteration")
with gr.Column(scale=2):
out_3d_mo = gr.Plot(label="3D Objective Functions")
out_pareto_mo = gr.Plot(label="Pareto Front Evolution")
out_hv_mo = gr.Plot(label="Hypervolume Convergence")
out_summary_mo = gr.Markdown()
def _run_mo_optimization(problem, fidelity, noise, n_init, n_iter, acq, ref_x, ref_y,
grid_2d, seed):
cfg = MORunCfg(
problem_key=problem,
fidelity=int(fidelity),
noise_std=float(noise),
n_init=int(n_init),
n_iter=int(n_iter),
acq_name=str(acq),
grid_2d=int(grid_2d),
seed=int(seed),
ref_point=(float(ref_x), float(ref_y)),
)
fig_3d, fig_pareto, fig_hv, summary_md, hist = run_multi_objective_bo(cfg)
# Update slider range
total = len(hist["hv_history"]) if hist is not None else 1
slider_update = gr.update(minimum=1, maximum=max(1, total), value=max(1, total),
step=1, interactive=True)
return fig_3d, fig_pareto, fig_hv, summary_md, hist, slider_update
run_mo.click(
_run_mo_optimization,
inputs=[problem_mo, fidelity_mo, noise_mo, n_init_mo, n_iter_mo, acq_mo, ref_x_mo, ref_y_mo, grid_2d_mo, seed_mo],
outputs=[out_3d_mo, out_pareto_mo, out_hv_mo, out_summary_mo, state_history_mo, mo_iter]
)
# Playback handler
def _render_mo_at_iter(hist, iter_idx: int):
if not hist or "hv_history" not in hist or "obj_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 fig
# Ensure we don't go out of bounds
max_iter = len(hist["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 fig
k = int(np.clip(iter_idx, 1, max_iter)) - 1
# Get data at iteration k
obj_vals = hist["obj_history"][k]
pareto_indices = hist["pareto_history"][k]
ref_point = hist["ref_point"]
# Create Pareto front plot for this iteration
fig = plot_pareto_front_2d(obj_vals, pareto_indices, ref_point,
f"Iteration {iter_idx} - Pareto Front")
return fig
mo_iter.change(_render_mo_at_iter, inputs=[state_history_mo, mo_iter], outputs=[out_pareto_mo])
# Function to update fidelity options based on problem
def update_fidelity_options_mo(problem_name):
available_fids = MO_PROBLEMS[problem_name]["fids"]
return gr.Dropdown(available_fids, value=available_fids[0], label="Fidelity level")
# Connect problem dropdown to fidelity dropdown
problem_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 Optimization
In this tab we use **pre-trained surrogate models** of a propeller to
perform **multi-objective active learning**. The objectives are:
- **Objective 1**: Power (scaled by 1/1000)
- **Objective 2**: Cavitation objective
The underlying CFD or experimental model is **not** called directly here;
instead, we use surrogates (Gaussian Process / Kriging) that you provide
as `.joblib` files.
The acquisition strategy is based on **hypervolume improvement**:
at each iteration, we choose a new propeller design that is expected
to maximally improve the Pareto front in terms of dominated volume.
""")
# State for history / playback
state_history_prop = gr.State(value=None)
with gr.Row():
with gr.Column(scale=1):
n_init_prop = gr.Slider(
10, 30, value=20, step=1,
label="Initial LHS samples"
)
n_iter_prop = gr.Slider(
1, 30, value=15, step=1,
label="Active learning iterations"
)
n_restarts_prop = gr.Slider(
10, 50, value=25, 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_iter
total = cfg.n_iter if hist is not None else 1
slider_update = gr.update(
minimum=1,
maximum=max(1, total),
value=max(1, total),
step=1,
interactive=True,
)
return fig, summary_md, hist, slider_update
run_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 fig
hv_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 fig
k = int(np.clip(iter_idx, 1, max_iter))
# Reuse the plotting logic from run_propeller_bo
fig, ax = plt.subplots(1, 2, figsize=(13, 5))
# Objectives scatter
ax[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 evolution
it_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 fig
iter_prop.change(
_render_prop_at_iter,
inputs=[state_history_prop, iter_prop],
outputs=[out_prop_plot],
)
return demo
# --- Main ------------------------------------------------------
if __name__ == "__main__":
demo = create_combined_app()
demo.launch(share=True, debug=True)
#!/usr/bin/env python3
"""
Combined Active Learning Application
====================================
This application combines both single-objective and multi-objective
Bayesian optimization by importing and running the original scripts
in separate tabs without any simplifications.
Features:
- 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)
- Tab 3: Complete Propeller multi-objecitve optimization (from main_case1_multi_objective_propeller.ipynb)
"""
import os
import sys
import warnings
import numpy as np
import pandas as pd
from pathlib import Path
import joblib
from scipy.stats import qmc
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import gradio as gr
from typing import Dict, List, Any, Tuple, Optional
from dataclasses import dataclass
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel as C
from scipy.optimize import minimize
from scipy.stats import norm
# --- Project paths ------------------------------------------
CURRENT_DIR = os.path.dirname(__file__)
if CURRENT_DIR not in sys.path:
sys.path.insert(0, CURRENT_DIR)
# Import project modules
from L1interface import EvaluateL1
# Import hypervolume calculation
try:
from hypervolume import hypervolume
except ImportError:
# Fallback hypervolume implementation
def hypervolume(points, ref):
"""Simple hypervolume calculation for 2D case."""
if len(points) == 0:
return 0.0
# Sort points by first objective
sorted_points = points[np.argsort(points[:, 0])]
hv = 0.0
for i, point in enumerate(sorted_points):
if i == 0:
hv += (ref[0] - point[0]) * (ref[1] - point[1])
else:
prev_point = sorted_points[i-1]
hv += (ref[0] - point[0]) * (ref[1] - point[1]) - (ref[0] - point[0]) * (ref[1] - prev_point[1])
return max(0.0, hv)
# Suppress warnings
warnings.filterwarnings("ignore")
np.seterr(all="ignore")
# ============================================================================
# SINGLE-OBJECTIVE CODE (from app_active_learning_single.py)
# ============================================================================
# --- Problems registry --------------------------------------
SINGLE_PROBLEMS: Dict[str, Dict[str, Any]] = {
"1D Forrester": {"InfoCase": "1DFORRESTER", "dim": 1, "fids": [1,2,3,4]},
"1D Sasena": {"InfoCase": "1DSASENA", "dim": 1, "fids": [1,2]},
"2D Rosenbrock": {"InfoCase": "2DROSENBROCK", "dim": 2, "fids": [1,2,3]},
"2D Rastrigin": {"InfoCase": "2DRASTRIGIN", "dim": 2, "fids": [1,2,3]},
"2D ALOS": {"InfoCase": "2DALOS", "dim": 2, "fids": [1,2]},
}
# --- Single-objective Utils ---------------------------------------------------
def unit_grid_1d(n: int) -> np.ndarray:
return np.linspace(0.0, 1.0, n).reshape(-1, 1)
def unit_grid_2d(n_per_axis: int) -> np.ndarray:
g = np.linspace(0.0, 1.0, n_per_axis)
X1, X2 = np.meshgrid(g, g, indexing="xy")
return np.c_[X1.ravel(), X2.ravel()]
def eval_batch(x_unit: np.ndarray, info: str, fidelity: int, noise_std: float) -> np.ndarray:
"""Evaluate benchmark via EvaluateL1 (unit inputs are accepted by your interface)."""
y = EvaluateL1(x_unit, info, FidelityLevel=fidelity, noise=noise_std)
return np.asarray(y).reshape(-1)
# Single-objective Acquisition functions
def expected_improvement(mu, sigma, f_best, xi=0.01):
sigma = np.maximum(sigma, 1e-12)