Spaces:
Runtime error
Runtime error
Download app.py from kode24/Usecase_2_MF: direct link, hf CLI and curl.
- Browser
- Download file 29.2 kB
-
https://huggingface.co/spaces/kode24/Usecase_2_MF/resolve/main/app.py
- Command line
-
hf download hf://spaces/kode24/Usecase_2_MF/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kode24/Usecase_2_MF/resolve/main/app.py
29.2 kB
| # app_multifidelity_tab2_only.py | |
| # ------------------------------------------------------------ | |
| # Single-tab app for cost-equivalent HF, LF, and MF comparison | |
| # + Budget sweep panel | |
| # + 2D DoE visualization of the trained data | |
| # Author: Kirsten Odendaal | |
| # ------------------------------------------------------------ | |
| import sys, os, warnings | |
| from dataclasses import dataclass | |
| from typing import Tuple, Dict, Any, Optional, List | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| from sklearn.pipeline import make_pipeline | |
| from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures | |
| from sklearn.metrics import root_mean_squared_error as sk_root_mse | |
| from sklearn.base import BaseEstimator | |
| # --- Project paths ------------------------------------------ | |
| CURRENT_DIR = os.path.dirname(__file__) | |
| MAIN_CASE2_DIR = os.path.join(CURRENT_DIR, 'main_case2') | |
| if os.path.isdir(MAIN_CASE2_DIR) and MAIN_CASE2_DIR not in sys.path: | |
| sys.path.insert(0, MAIN_CASE2_DIR) | |
| if CURRENT_DIR not in sys.path: | |
| sys.path.insert(0, CURRENT_DIR) | |
| # --- Project imports ---------------------------------------- | |
| # Only replace the model factory if VIPRE's get_prediction_model is unavailable. | |
| from data import get_simulation_data | |
| from estimator import MultiFidelityKriging_dev | |
| try: | |
| from data import get_prediction_model as _vipre_get_prediction_model | |
| def get_prediction_model(name: str, model_parameters: Optional[Dict[str, Any]] = None): | |
| return _vipre_get_prediction_model(name, model_parameters) | |
| except Exception: | |
| # Fallback: Kriging-like model using scikit-learn Gaussian Process (Matern) | |
| class _KrigingFactory: | |
| def __init__(self, model_parameters: Optional[Dict[str, Any]] = None): | |
| self.model_parameters = model_parameters or {} | |
| def _construct_model(self): | |
| from sklearn.gaussian_process import GaussianProcessRegressor | |
| from sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel as C | |
| ey = float(self.model_parameters.get('ey', 0.1)) | |
| kernel = C(1.0, (1e-3, 1e3)) * Matern(length_scale=0.5, nu=2.5) + \ | |
| WhiteKernel(noise_level=max(ey**2, 1e-10)) | |
| return GaussianProcessRegressor( | |
| kernel=kernel, | |
| normalize_y=True, | |
| n_restarts_optimizer=5, | |
| random_state=RANDOM_STATE | |
| ) | |
| def get_prediction_model(name: str, model_parameters: Optional[Dict[str, Any]] = None): | |
| # Always honor the KrigingModel name expected by the app | |
| return _KrigingFactory(model_parameters) | |
| # --- Constants ---------------------------------------------- | |
| PARAMETER_OPTIONS = [2, 5] | |
| FIDELITY_LOW_OPTIONS = ['medium', 'low'] # default medium | |
| INITIAL_SPAN_OPTIONS = ['1e-5,1'] | |
| LF_UNIT_COST = {'high': 1.00, 'medium': 0.30, 'low': 0.11} | |
| RANDOM_STATE = 42 # not used for get_simulation_data (no seed arg) | |
| # --- Utils --------------------------------------------------- | |
| class WorkingDir: | |
| def __init__(self, target_dir): | |
| self.target_dir = target_dir | |
| self.prev_dir = None | |
| def __enter__(self): | |
| self.prev_dir = os.getcwd() | |
| if self.target_dir is not None and os.path.isdir(self.target_dir): | |
| os.chdir(self.target_dir) | |
| return self | |
| def __exit__(self, exc_type, exc, tb): | |
| if self.prev_dir is not None: | |
| os.chdir(self.prev_dir) | |
| class MFKCompat(MultiFidelityKriging_dev, BaseEstimator): | |
| def _validate_data(self, X, accept_sparse=False, reset=True, **kwargs): | |
| return np.asarray(X) | |
| def _has_valid_reference(x_ref, y_ref) -> bool: | |
| try: | |
| return ( | |
| isinstance(x_ref, np.ndarray) and x_ref.ndim == 2 and x_ref.size > 0 and | |
| isinstance(y_ref, np.ndarray) and y_ref.ndim >= 1 and y_ref.size > 0 and | |
| len(x_ref) == len(y_ref) | |
| ) | |
| except Exception: | |
| return False | |
| # --- Data & models ------------------------------------------ | |
| class Config: | |
| dim: int | |
| lf_fid: str # 'medium' | 'low' | 'high' | |
| initial_span: str # MF initial span (e.g., '1e-5,1') | |
| poly_deg: int = 1 # baseline HF-only pipeline polynomial degree (optional) | |
| def load_reference(dim: int, lf_fid: str): | |
| """Grab a consistent reference set from the package (no unbounded gen).""" | |
| with WorkingDir(MAIN_CASE2_DIR): | |
| X_hf, y_hf, X_ref, y_ref, _ = get_simulation_data( | |
| parameters=dim, LHS_level=1, fidelity='high', NCC=[1, 0.30, 0.11] | |
| ) | |
| # A quick LF call just to sanity-check lf_fid exists (not used otherwise) | |
| with WorkingDir(MAIN_CASE2_DIR): | |
| get_simulation_data(parameters=dim, LHS_level=3, fidelity=lf_fid, NCC=[1, 0.30, 0.11]) | |
| return X_ref, y_ref | |
| def make_hf_only_model(poly_deg: int): | |
| base = get_prediction_model('KrigingModel', model_parameters={'ey': 0.1}) | |
| steps = [MinMaxScaler((0, 1))] | |
| if poly_deg > 0: | |
| steps.append(PolynomialFeatures(degree=poly_deg)) | |
| steps.append(base._construct_model()) | |
| return make_pipeline(*steps) | |
| def gen_samples_unbounded(dim: int, fidelity: str, n: int): | |
| """Generate exactly n samples at the requested fidelity; return arrays as-is.""" | |
| if n <= 0: | |
| return np.empty((0, dim)), np.empty((0,), dtype=float) | |
| with WorkingDir(MAIN_CASE2_DIR): | |
| X, y, _, _, _ = get_simulation_data( | |
| parameters=dim, | |
| LHS_level=1, | |
| fidelity=fidelity, | |
| NCC=[1, 0.30, 0.11], | |
| N_samples=int(n) | |
| ) | |
| return np.asarray(X), np.asarray(y) | |
| from functools import lru_cache | |
| def gen_samples_unbounded_cached(dim: int, fidelity: str, n: int): | |
| # cache by (dim, fidelity, n) so sliding the share doesnβt regenerate | |
| if n <= 0: | |
| return np.empty((0, dim)), np.empty((0,), dtype=float) | |
| with WorkingDir(MAIN_CASE2_DIR): | |
| X, y, _, _, _ = get_simulation_data( | |
| parameters=int(dim), | |
| LHS_level=1, | |
| fidelity=str(fidelity), | |
| NCC=[1, 0.30, 0.11], | |
| N_samples=int(n) | |
| ) | |
| return np.asarray(X), np.asarray(y) | |
| # --- Diagnostics (r, b, BPB, tau) --------------------------- | |
| from scipy.stats import kendalltau | |
| def _safe_corr(x, y): | |
| x = np.asarray(x).ravel(); y = np.asarray(y).ravel() | |
| if x.size < 2 or y.size < 2: return np.nan | |
| if np.std(x) < 1e-12 or np.std(y) < 1e-12: return np.nan | |
| return float(np.corrcoef(x, y)[0, 1]) | |
| def _affine_fit(yL_hat, yH): | |
| """Stable affine link yH ~ a + b*yL_hat (ridge) -> a,b.""" | |
| from sklearn.linear_model import Ridge | |
| z = np.asarray(yL_hat).ravel(); t = np.asarray(yH).ravel() | |
| if z.size < 2: return 0.0, 1.0 | |
| A = np.c_[np.ones_like(z), z] | |
| try: | |
| ridge = Ridge(alpha=1e-6, fit_intercept=False) | |
| ridge.fit(A, t) | |
| a, b = float(ridge.coef_[0]), float(ridge.coef_[1]) | |
| except Exception: | |
| a = float(np.mean(t) - np.mean(z)); b = 1.0 | |
| return a, b | |
| def compute_mf_diagnostics(Xh_mf, yh_mf, Xl_mf, yl_mf, c_lf, poly_deg_link=1): | |
| """ | |
| Fit LF surrogate on (Xl_mf, yl_mf), predict at HF points (Xh_mf), | |
| and compute r, slope b, BPB, Kendall tau, plus a recommendation. | |
| """ | |
| # 1) LF surrogate -> yL_hat on HF points | |
| lf_model = make_hf_only_model(poly_deg_link) | |
| if len(Xl_mf) >= 2: | |
| lf_model.fit(Xl_mf, yl_mf) | |
| yL_hat_HF = np.asarray(lf_model.predict(Xh_mf)).ravel() | |
| else: | |
| m = float(np.mean(yl_mf)) if len(yl_mf) else 0.0 | |
| yL_hat_HF = np.full((len(Xh_mf),), m, dtype=float) | |
| yH = np.asarray(yh_mf).ravel() | |
| # 2) Metrics | |
| r = _safe_corr(yL_hat_HF, yH) | |
| try: | |
| tau, _ = kendalltau(yL_hat_HF, yH) | |
| tau = float(tau) if tau is not None else np.nan | |
| except Exception: | |
| tau = np.nan | |
| a, b = _affine_fit(yL_hat_HF, yH) | |
| bpb = (r**2 / max(c_lf, 1e-12)) if np.isfinite(r) else np.nan | |
| # 3) Recommendation per your rules | |
| def _finite(x): return (x is not None) and np.isfinite(x) | |
| if _finite(r) and _finite(bpb) and _finite(tau): | |
| if (r >= 0.7 and bpb >= 5 and 0.3 <= b <= 3 and tau >= 0.6): | |
| rec = "MF" | |
| elif (r >= 0.4 and bpb >= 2): | |
| rec = "Borderline" | |
| else: | |
| rec = "HF-only" | |
| else: | |
| rec = "HF-only" | |
| # 4) Markdown summary | |
| md = ( | |
| "### Multi-Fidelity Diagnostics (from current MF split)\n" | |
| f"- **Pearson r** (LFβHF alignment): **{r:.3f}**\n" | |
| f"- **Slope b** (y_H β a + bΒ·Ε·_L): **{b:.3f}**\n" | |
| f"- **BPB** (rΒ² / c_L): **{bpb:.3f}** _(c_L = {c_lf:.3f})_\n" | |
| f"- **Kendall Ο** (ranking agreement): **{tau:.3f}**\n" | |
| f"- **Recommendation**: **{rec}** " | |
| + ("(strong candidate for MF)" if rec=="MF" else ("(borderline β try & verify)" if rec=="Borderline" else "(HF-only safer)")) | |
| ) | |
| return dict(r=r, b=b, bpb=bpb, tau=tau, rec=rec, markdown=md) | |
| # --- MF two-stage predictor --------------------------------- | |
| def _finite(arr): | |
| return np.all(np.isfinite(arr)) | |
| from sklearn.linear_model import Ridge | |
| from sklearn.preprocessing import PolynomialFeatures | |
| def mf_predict_two_stage(X_ref, Xh, yh, Xl, yl, dim, poly_deg_link: int = 1, poly_deg_delta: int = 2): | |
| """ | |
| Two-stage MF (robust): | |
| 1) LF surrogate on (Xl, yl) -> yL_hat | |
| 2) Affine link: yH ~ a + b * yL_hat at HF points (Ridge regularized) | |
| 3) Discrepancy: delta(x) on HF residuals via PolynomialFeatures + Ridge | |
| 4) Predict: a + b*yL_hat_ref + delta_hat_ref | |
| Falls back to affine-only if data is too small or unstable. | |
| """ | |
| # ---- 1) LF surrogate | |
| lf_model = make_hf_only_model(poly_deg_link) | |
| if len(Xl) >= 2: | |
| lf_model.fit(Xl, yl) | |
| yL_hat_HF = np.asarray(lf_model.predict(Xh)).ravel() | |
| yL_hat_RF = np.asarray(lf_model.predict(X_ref)).ravel() | |
| else: | |
| # Degenerate LF: avoid constant MF by falling back to HF-only surrogate for variation | |
| m = float(np.mean(yl)) if len(yl) else 0.0 | |
| yL_hat_HF = np.full((len(Xh),), m, dtype=float) | |
| yL_hat_RF = np.full((len(X_ref),), m, dtype=float) | |
| yH = np.asarray(yh).ravel() | |
| # sanitize | |
| if not (_finite(yL_hat_HF) and _finite(yH)): | |
| mu = float(np.mean(yH)) if len(yH) else 0.0 | |
| return np.full((len(X_ref),), mu, dtype=float), (mu, 1.0) | |
| # ---- If LF feature is (near) constant: fit quick HF-only discrepancy to avoid flat predictions | |
| if np.std(yL_hat_HF) < 1e-8: | |
| try: | |
| DeltaModel = make_pipeline( | |
| PolynomialFeatures(degree=max(1, poly_deg_delta), include_bias=False), | |
| Ridge(alpha=1e-3) | |
| ) | |
| DeltaModel.fit(Xh, yH) | |
| y_pred = np.asarray(DeltaModel.predict(X_ref)).ravel().astype(float) | |
| return y_pred, (0.0, 1.0) | |
| except Exception: | |
| mu = float(np.mean(yH)) if len(yH) else 0.0 | |
| return np.full((len(X_ref),), mu, dtype=float), (0.0, 1.0) | |
| # ---- If too few HF -> simple affine using LF | |
| if len(Xh) < 3: | |
| a = float(np.mean(yH) - np.mean(yL_hat_HF)) | |
| b = 1.0 | |
| return (a + b * yL_hat_RF).astype(float), (a, b) | |
| # ---- 2) Affine link via Ridge (stable) | |
| A = np.c_[np.ones_like(yL_hat_HF), yL_hat_HF] # (n_hf, 2) | |
| if not _finite(A): | |
| a = float(np.mean(yH) - np.mean(yL_hat_HF)); b = 1.0 | |
| return (a + b * yL_hat_RF).astype(float), (a, b) | |
| try: | |
| ridge = Ridge(alpha=1e-6, fit_intercept=False, positive=False) | |
| ridge.fit(A, yH) | |
| a, b = float(ridge.coef_[0]), float(ridge.coef_[1]) | |
| except Exception: | |
| a = float(np.mean(yH) - np.mean(yL_hat_HF)); b = 1.0 | |
| return (a + b * yL_hat_RF).astype(float), (a, b) | |
| # ---- 3) Discrepancy via polynomial Ridge (fast & robust) | |
| delta = (yH - (a + b * yL_hat_HF)).astype(float) | |
| if len(Xh) < max(5, dim + 2) or np.allclose(delta.std(), 0.0, atol=1e-10): | |
| return (a + b * yL_hat_RF).astype(float), (a, b) | |
| try: | |
| DeltaModel = make_pipeline( | |
| PolynomialFeatures(degree=poly_deg_delta, include_bias=False), | |
| Ridge(alpha=1e-3) | |
| ) | |
| DeltaModel.fit(Xh, delta) | |
| delta_hat_RF = np.asarray(DeltaModel.predict(X_ref)).ravel() | |
| if not _finite(delta_hat_RF): | |
| delta_hat_RF = np.zeros(len(X_ref), dtype=float) | |
| except Exception: | |
| delta_hat_RF = np.zeros(len(X_ref), dtype=float) | |
| # ---- 4) Predict | |
| y_pred = (a + b * yL_hat_RF + delta_hat_RF).astype(float) | |
| if not _finite(y_pred): | |
| y_pred = (a + b * yL_hat_RF).astype(float) | |
| return y_pred, (a, b) | |
| # --- Budgeting logic ---------------------------------------- | |
| def mf_counts_from_share(budget_ncc: float, hf_share: float, c_lf: float, dim: int) -> tuple[int, int, float]: | |
| """ | |
| Interpret the HF-share slider as a proportion of the HF-only baseline. | |
| - Baseline HF count = round(NCC target) | |
| - HF = max(2, round(baseline * share)) | |
| - LF fills the remaining budget up to NCC | |
| Returns (n_hf, n_lf, realized_cost) with cost <= budget_ncc. | |
| """ | |
| B = max(1.0, float(budget_ncc)) | |
| s = float(np.clip(hf_share, 0.0, 1.0)) | |
| baseline_hf = int(round(B)) | |
| n_hf = max(2, min(baseline_hf, int(round(baseline_hf * s)))) | |
| remain = max(0.0, B - n_hf) | |
| n_lf = int(np.floor(remain / c_lf)) if c_lf > 0 else 0 | |
| realized = float(n_hf + n_lf * c_lf) | |
| return n_hf, n_lf, realized | |
| # --- Plots --------------------------------------------------- | |
| def plot_bar(rmse_mf, rmse_hf, rmse_lf, budget): | |
| fig, ax = plt.subplots(figsize=(7, 4)) | |
| labels = ['Multi-fidelity', 'HF-only', 'LF-only'] | |
| vals = [rmse_mf, rmse_hf, rmse_lf] | |
| ax.bar(labels, vals) | |
| ax.set_title(f'RMSE at NCC target β {budget:.0f}') | |
| ax.set_ylabel('RMSE vs reference') | |
| for i,v in enumerate(vals): | |
| ax.text(i, v + 0.02*max(0.1, max(vals)), f'{v:.4f}', ha='center', va='bottom') | |
| ax.grid(True, axis='y', linestyle='--', alpha=0.4) | |
| fig.tight_layout() | |
| return fig | |
| def plot_scatter_all(y_true, y_mf, y_hf, y_lf, budget, | |
| n_ref=None, | |
| n_hf_mf=None, n_lf_mf=None, | |
| n_hf_hf=None, n_lf_lf=None, | |
| max_points: int = 15): | |
| """ | |
| Scatter parity plot using a random subset of reference points (default 15) | |
| for clarity. Keeps scales equal. | |
| """ | |
| n_ref = len(y_true) if n_ref is None else n_ref | |
| idx = np.arange(n_ref) | |
| if n_ref > max_points: | |
| np.random.seed(0) | |
| idx = np.random.choice(idx, size=max_points, replace=False) | |
| y_true_s = np.asarray(y_true)[idx] | |
| y_mf_s = np.asarray(y_mf)[idx] | |
| y_hf_s = np.asarray(y_hf)[idx] | |
| y_lf_s = np.asarray(y_lf)[idx] | |
| fig, ax = plt.subplots(figsize=(7, 5)) | |
| ax.scatter(y_mf_s, y_true_s, s=60, alpha=0.8, | |
| label=f'Multi-fidelity ({n_hf_mf} HF + {n_lf_mf} LF)', marker='o') | |
| ax.scatter(y_hf_s, y_true_s, s=60, alpha=0.8, | |
| label=f'HF-only ({n_hf_hf} HF)', marker='^') | |
| ax.scatter(y_lf_s, y_true_s, s=60, alpha=0.8, | |
| label=f'LF-only ({n_lf_lf} LF)', marker='s') | |
| lo = min(y_true_s.min(), y_mf_s.min(), y_hf_s.min(), y_lf_s.min()) | |
| hi = max(y_true_s.max(), y_mf_s.max(), y_hf_s.max(), y_lf_s.max()) | |
| ax.plot([lo, hi], [lo, hi], 'k--', lw=2, label='Perfect prediction') | |
| ax.set_xlabel('Predicted') | |
| ax.set_ylabel('Actual (reference)') | |
| ax.set_title(f'Model comparison at NCC β {budget:.0f} (showing {len(idx)} / {n_ref} points)') | |
| ax.legend() | |
| ax.grid(True, alpha=0.3) | |
| ax.set_aspect('equal', adjustable='box') | |
| fig.tight_layout() | |
| return fig | |
| def plot_doe_trained_2d(Xh, Xl, X_ref, dim, max_ref_pts: int = 200): | |
| """ | |
| Show the training points actually used at the selected budget. | |
| - Blue = HF training samples used | |
| - Orange = LF training samples used | |
| - Gray = (subsampled) reference points for context | |
| Only renders for dim==2; returns an empty figure otherwise. | |
| """ | |
| if dim != 2 or X_ref is None or len(X_ref) == 0: | |
| fig = plt.figure() | |
| ax = fig.add_subplot(111) | |
| ax.text(0.5, 0.5, '2D DoE view only (dim=2).', ha='center', va='center') | |
| ax.axis('off') | |
| fig.tight_layout() | |
| return fig | |
| # Subsample reference for clarity | |
| idx = np.arange(len(X_ref)) | |
| if len(idx) > max_ref_pts: | |
| rng = np.random.default_rng(0) | |
| idx = rng.choice(idx, size=max_ref_pts, replace=False) | |
| Xr = X_ref[idx] | |
| fig, ax = plt.subplots(figsize=(6.5, 5.5)) | |
| if len(Xr): | |
| ax.scatter(Xr[:, 0], Xr[:, 1], c='lightgray', s=18, alpha=0.35, label='Reference (subset)') | |
| if len(Xl): | |
| ax.scatter(Xl[:, 0], Xl[:, 1], c='orange', s=46, alpha=0.70, label='LF train') | |
| if len(Xh): | |
| ax.scatter(Xh[:, 0], Xh[:, 1], c='royalblue', edgecolor='k', s=56, alpha=0.95, label='HF train') | |
| ax.set_xlabel('x1'); ax.set_ylabel('x2') | |
| ax.set_xlim(-1.1, 1.1); ax.set_ylim(-1.1, 1.1) | |
| ax.set_aspect('equal', adjustable='box') | |
| ax.set_title('Training DoE at current budget (2D)') | |
| ax.grid(True, linestyle='--', alpha=0.4) | |
| ax.legend() | |
| fig.tight_layout() | |
| return fig | |
| # --- Core handler ------------------------------------------- | |
| def run_comparison(dim: int, lf_fid: str, budget_ncc: float, hf_share: float, | |
| initial_span: str, poly_deg: int, viz_points: int, lf_cost_val: float): | |
| # reference set (fixed) | |
| X_ref, y_ref = load_reference(dim, lf_fid) | |
| if not _has_valid_reference(X_ref, y_ref): | |
| return plt.figure(), plt.figure(), "Reference set unavailable for this configuration.", "β", "β", plt.figure() | |
| c_lf = float(lf_cost_val) | |
| # HF-only | |
| n_hf_hf = max(1, int(round(budget_ncc))) | |
| Xh_hf, yh_hf = gen_samples_unbounded(dim, 'high', n_hf_hf) | |
| hf_only_ncc = float(n_hf_hf) | |
| hf_model = make_hf_only_model(poly_deg) | |
| hf_model.fit(Xh_hf, yh_hf) | |
| y_hf = hf_model.predict(X_ref).reshape(-1) | |
| rmse_hf = float(sk_root_mse(y_ref, y_hf)) | |
| # LF-only | |
| n_lf_lf = max(1, int(np.floor(budget_ncc / c_lf))) | |
| Xl_lf, yl_lf = gen_samples_unbounded(dim, lf_fid, n_lf_lf) | |
| lf_only_ncc = float(n_lf_lf * c_lf) | |
| lf_model = make_hf_only_model(poly_deg) # reuse pipeline on LF data | |
| lf_model.fit(Xl_lf, yl_lf) | |
| y_lf = lf_model.predict(X_ref).reshape(-1) | |
| rmse_lf = float(sk_root_mse(y_ref, y_lf)) | |
| # --- MF (HF share + LF fills remainder) | |
| n_hf_mf, n_lf_mf, mf_realized = mf_counts_from_share(budget_ncc, hf_share, c_lf, dim) | |
| Xh_mf, yh_mf = gen_samples_unbounded(dim, 'high', n_hf_mf) | |
| Xl_mf, yl_mf = gen_samples_unbounded(dim, lf_fid, n_lf_mf) | |
| try: | |
| y_mf, (a_hat, b_hat) = mf_predict_two_stage(X_ref, Xh_mf, yh_mf, Xl_mf, yl_mf, dim) | |
| except Exception as e: | |
| print("Two-stage MF failed; fallback to HF-only predictions:", e) | |
| y_mf = y_hf | |
| rmse_mf = float(sk_root_mse(y_ref, y_mf)) | |
| # Diagnostics computed on the *current* MF allocation | |
| diag = compute_mf_diagnostics(Xh_mf, yh_mf, Xl_mf, yl_mf, c_lf, poly_deg_link=poly_deg) | |
| diag_md = diag["markdown"] | |
| # Plots + table | |
| fig_bar = plot_bar(rmse_mf, rmse_hf, rmse_lf, budget_ncc) | |
| fig_sc = plot_scatter_all( | |
| y_ref.ravel(), y_mf, y_hf, y_lf, budget_ncc, | |
| n_ref=len(X_ref), | |
| n_hf_mf=n_hf_mf, n_lf_mf=n_lf_mf, | |
| n_hf_hf=n_hf_hf, n_lf_lf=n_lf_lf, | |
| max_points=viz_points | |
| ) | |
| table = f""" | |
| | Model | RMSE | NCC (spent) | Training Points | | |
| |---|---:|---:|---:| | |
| | Multi-fidelity | {rmse_mf:.4f} | {mf_realized:.1f} | {n_hf_mf} HF + {n_lf_mf} LF | | |
| | HF-only | {rmse_hf:.4f} | {hf_only_ncc:.1f} | {n_hf_hf} HF | | |
| | LF-only | {rmse_lf:.4f} | {lf_only_ncc:.1f} | {n_lf_lf} LF | | |
| """ | |
| takeaway = f"**Target NCC:** {budget_ncc:.1f} Β· **LF cost:** {c_lf:.2f} Β· **MF HF-share:** {hf_share:.2f}" | |
| # 2D DoE plot (only meaningful for dim==2) | |
| fig_doe = plot_doe_trained_2d(Xh_mf, Xl_mf, X_ref, dim) | |
| return fig_bar, fig_sc, takeaway, table, diag_md, fig_doe | |
| # --- Budget sweep (learning curve) -------------------------- | |
| def _parse_budgets_csv(csv_text: str) -> List[float]: | |
| try: | |
| vals = [float(tok.strip()) for tok in csv_text.split(",") if tok.strip()] | |
| vals = [v for v in vals if v > 0] | |
| vals = sorted(set(vals)) | |
| return vals[:12] if len(vals) > 12 else vals | |
| except Exception: | |
| return [5, 10, 15, 20, 25, 30] | |
| def compute_rmse_for_budget(dim: int, lf_fid: str, budget_ncc: float, | |
| hf_share: float, poly_deg: int, lf_cost_val: float) -> Tuple[float,float,float]: | |
| """Lightweight RMSE computation (no plots), used for the sweep.""" | |
| X_ref, y_ref = load_reference(dim, lf_fid) | |
| c_lf = float(lf_cost_val) | |
| # HF-only | |
| n_hf_hf = max(1, int(round(budget_ncc))) | |
| Xh_hf, yh_hf = gen_samples_unbounded(dim, 'high', n_hf_hf) | |
| hf_model = make_hf_only_model(poly_deg) | |
| hf_model.fit(Xh_hf, yh_hf) | |
| rmse_hf = float(sk_root_mse(y_ref, hf_model.predict(X_ref).reshape(-1))) | |
| # LF-only | |
| n_lf_lf = max(1, int(np.floor(budget_ncc / c_lf))) | |
| Xl_lf, yl_lf = gen_samples_unbounded(dim, lf_fid, n_lf_lf) | |
| lf_model = make_hf_only_model(poly_deg) | |
| lf_model.fit(Xl_lf, yl_lf) | |
| rmse_lf = float(sk_root_mse(y_ref, lf_model.predict(X_ref).reshape(-1))) | |
| # MF | |
| n_hf_mf, n_lf_mf, _ = mf_counts_from_share(budget_ncc, hf_share, c_lf, dim) | |
| Xh_mf, yh_mf = gen_samples_unbounded(dim, 'high', n_hf_mf) | |
| Xl_mf, yl_mf = gen_samples_unbounded(dim, lf_fid, n_lf_mf) | |
| try: | |
| y_mf, _ = mf_predict_two_stage(X_ref, Xh_mf, yh_mf, Xl_mf, yl_mf, dim) | |
| except Exception: | |
| # fallback to HF-only prediction if MF fails | |
| y_mf = hf_model.predict(X_ref).reshape(-1) | |
| rmse_mf = float(sk_root_mse(y_ref, y_mf)) | |
| return rmse_mf, rmse_hf, rmse_lf | |
| def run_budget_sweep(dim: int, lf_fid: str, initial_span: str, poly_deg: int, | |
| hf_share: float, lf_cost_val: float, budgets: List[float]): | |
| mf_vals, hf_vals, lf_vals = [], [], [] | |
| for B in budgets: | |
| rmse_mf, rmse_hf, rmse_lf = compute_rmse_for_budget( | |
| dim, lf_fid, B, hf_share, poly_deg, lf_cost_val | |
| ) | |
| mf_vals.append(rmse_mf); hf_vals.append(rmse_hf); lf_vals.append(rmse_lf) | |
| fig, ax = plt.subplots(figsize=(7.5, 4.5)) | |
| ax.plot(budgets, mf_vals, 'o-', label='Multi-fidelity') | |
| ax.plot(budgets, hf_vals, 's--', label='HF-only') | |
| ax.plot(budgets, lf_vals, 'd--', label='LF-only') | |
| ax.set_xlabel('Compute budget (NCC)') | |
| ax.set_ylabel('RMSE vs reference') | |
| ax.set_title('Learning curve: MF vs HF vs LF') | |
| ax.legend() | |
| ax.grid(True, alpha=0.3) | |
| fig.tight_layout() | |
| return fig | |
| # --- Gradio UI ---------------------------------------------- | |
| with gr.Blocks() as demo: # theme=gr.themes.Soft() | |
| with gr .Row(): | |
| with gr.Column(scale=1): # 1/4 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): # 3/4 of the row | |
| gr.Markdown("# Multi-Fidelity Surrogate Trade-off Explorer") | |
| with gr.Accordion("What is Multi-Fidelity Modeling?", open=False): | |
| gr.Markdown(""" | |
| **Multi-fidelity modeling** combines data from simulations of different accuracy levels (fidelities) to create more accurate predictions than using high-fidelity data alone. It's like using both rough sketches and detailed blueprints to design a building! | |
| ### **Fidelity Levels Explained:** | |
| #### **π΄ High-Fidelity (HF)** | |
| - **Accuracy**: Most accurate, closest to reality | |
| - **Cost**: Most expensive (computational time/money) | |
| - **Use**: Critical for final validation | |
| - **Example**: Full CFD simulation with fine mesh | |
| #### **π‘ Medium-Fidelity (MF)** | |
| - **Accuracy**: Moderate accuracy | |
| - **Cost**: Moderate cost | |
| - **Use**: Good balance for many applications | |
| - **Example**: CFD with coarser mesh | |
| #### **π’ Low-Fidelity (LF)** | |
| - **Accuracy**: Lower accuracy but captures main trends | |
| - **Cost**: Very cheap (fast computation) | |
| - **Use**: Quick exploration, trend identification | |
| - **Example**: Potential flow theory, empirical correlations | |
| ### **The Multi-Fidelity Advantage:** | |
| - π° **Cost Efficiency**: Get better accuracy per dollar spent | |
| - β‘ **Speed**: Faster than high-fidelity only | |
| - π― **Smart Allocation**: Use expensive simulations where they matter most | |
| - π **Better Predictions**: Often outperforms single-fidelity approaches | |
| ### **Key Concepts You'll Explore:** | |
| - **Budget Allocation**: How to split your computational budget | |
| - **Fidelity Selection**: Which fidelity levels to use | |
| - **Cost-Benefit Analysis**: When multi-fidelity pays off | |
| - **Diagnostic Metrics**: How to assess multi-fidelity suitability | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown(""" | |
| ## βοΈ **Experiment Configuration** | |
| ### **Problem Setup:** | |
| """) | |
| dim = gr.Dropdown(PARAMETER_OPTIONS, value=2, label="Number of parameters (dim)") | |
| lf_fid = gr.Dropdown(FIDELITY_LOW_OPTIONS, value='medium', label="Low-fidelity type") | |
| gr.Markdown(""" | |
| ### **Budget & Allocation:** | |
| """) | |
| budget = gr.Slider(5, 30, value=15, step=1, label="Target compute (NCC)") | |
| hf_share = gr.Slider(0.0, 1.0, value=0.5, step=0.01, | |
| label="MF: HF share of budget (LF fills the rest)") | |
| with gr.Accordion("Advanced", open=False): | |
| gr.Markdown(""" | |
| ### **Advanced Settings:** | |
| """) | |
| initial_span = gr.Dropdown(INITIAL_SPAN_OPTIONS, value='1e-5,1', label="MF initial span") | |
| poly_deg = gr.Dropdown([1], value=1, label="Baseline polynomial degree (HF/LF models)") | |
| viz_points = gr.Slider(5, 200, value=50, step=1, label="Number of visualization points (for scatter plot)") | |
| lf_cost = gr.Slider(0.11, 0.99, value=0.30, step=0.01, label="LF unit cost (HF fixed at 1.00)") | |
| # --- Sync LF cost default with chosen LF fidelity --- | |
| def _update_lf_cost(lf_fid_val): | |
| default = LF_UNIT_COST.get(str(lf_fid_val), 0.30) | |
| return gr.update(value=default) | |
| lf_fid.change(_update_lf_cost, inputs=[lf_fid], outputs=[lf_cost]) | |
| # Budget sweep controls | |
| gr.Markdown(""" | |
| ### **Budget Sweep Analysis:** | |
| """) | |
| budgets_csv = gr.Textbox(value="5,10,15,20", label="Budgets (NCC, comma-separated)") | |
| run_sweep = gr.Button("Run budget sweep") | |
| run = gr.Button("Run comparison", variant="primary") | |
| with gr.Column(scale=3): | |
| # with gr.Accordion("π **Results & Analysis**", open=False): | |
| # gr.Markdown(""" | |
| # ### **What You'll See:** | |
| # """) | |
| out_bar = gr.Plot(label='RMSE Comparison (lower is better)') | |
| out_sc = gr.Plot(label='Predicted vs Reference (Parity Plot)') | |
| out_top = gr.Markdown() | |
| out_tbl = gr.Markdown() | |
| out_diag = gr.Markdown(label='Multi-Fidelity Diagnostics') | |
| out_doe = gr.Plot(label='Design-of-Experiments (2D Training Points)') | |
| out_sweep = gr.Plot(label='Budget Sweep (Learning Curve)') | |
| def _go(dim, lf_fid, budget, hf_share, initial_span, poly_deg, viz_points, lf_cost): | |
| return run_comparison( | |
| int(dim), str(lf_fid), float(budget), float(hf_share), | |
| str(initial_span), int(poly_deg), | |
| int(viz_points), float(lf_cost) | |
| ) | |
| run.click( | |
| _go, | |
| inputs=[dim, lf_fid, budget, hf_share, initial_span, poly_deg, viz_points, lf_cost], | |
| outputs=[out_bar, out_sc, out_top, out_tbl, out_diag, out_doe] | |
| ) | |
| def _go_sweep(dim, lf_fid, hf_share, initial_span, poly_deg, lf_cost, budgets_csv_text): | |
| budgets = _parse_budgets_csv(budgets_csv_text) | |
| return run_budget_sweep( | |
| int(dim), str(lf_fid), str(initial_span), int(poly_deg), | |
| float(hf_share), float(lf_cost), budgets | |
| ) | |
| run_sweep.click( | |
| _go_sweep, | |
| inputs=[dim, lf_fid, hf_share, initial_span, poly_deg, lf_cost, budgets_csv], | |
| outputs=[out_sweep] | |
| ) | |
| # --- Main ---------------------------------------------------- | |
| if __name__ == '__main__': | |
| warnings.filterwarnings('ignore') | |
| np.seterr(all='ignore') | |
| demo.launch(share=True, debug=True) | |