Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines34567816 unmodified lines252627282930313233188 unmodified lines2222232242252262272285 unmodified lines23423523623723823924024139 unmodified lines2812822832842852862872882892902912922932942952962972982993002 unmodified lines# Single-tab app for cost-equivalent HF, LF, and MF comparison# + Budget sweep panel# + 2D DoE visualization of the trained data# ------------------------------------------------------------import sys, os, warningsfrom dataclasses import dataclass16 unmodified linessys.path.insert(0, CURRENT_DIR)# --- Project imports ----------------------------------------from data import get_simulation_data, get_prediction_modelfrom estimator import MultiFidelityKriging_dev# --- Constants ----------------------------------------------PARAMETER_OPTIONS = [2, 5, 10]FIDELITY_LOW_OPTIONS = ['medium', 'low', 'high'] # default medium188 unmodified linesyL_hat_HF = np.asarray(lf_model.predict(Xh)).ravel()yL_hat_RF = np.asarray(lf_model.predict(X_ref)).ravel()else:# degenerate LF -> constantm = float(np.mean(yl)) if len(yl) else 0.0yL_hat_HF = np.full((len(Xh),), m, dtype=float)yL_hat_RF = np.full((len(X_ref),), m, dtype=float)5 unmodified linesmu = float(np.mean(yH)) if len(yH) else 0.0return np.full((len(X_ref),), mu, dtype=float), (mu, 1.0)# ---- If too few HF or LF feature is (near) constant -> affine-onlyif len(Xh) < 3 or np.std(yL_hat_HF) < 1e-8:a = float(np.mean(yH) - np.mean(yL_hat_HF))b = 1.0return (a + b * yL_hat_RF).astype(float), (a, b)39 unmodified lines# --- Budgeting logic ----------------------------------------def mf_counts_from_share(budget_ncc: float, hf_share: float, c_lf: float, dim: int) -> tuple[int, int, float]:"""MF = HF baseline + LF fill. Enforce a minimum HF to make the fusion identifiable.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))# desired HF from the sharen_hf = int(round(B * s))# minimum HF anchors: max(8, 3*dim) but never exceed budgethf_floor = min(int(B), max(8, 3 * max(1, dim)))n_hf = max(n_hf, hf_floor)# LF fills the rest (never exceed budget)remain = max(0.0, B - n_hf)n_lf = int(np.floor(remain / c_lf)) if c_lf > 0 else 02 unmodified lines34567891016 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263188 unmodified lines2522532542552562572585 unmodified lines26426526626726826927027127227327427527627727827928028128228328428539 unmodified lines3253263273283293303313323333343353363373383393403413422 unmodified lines# 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, warningsfrom dataclasses import dataclass16 unmodified linessys.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_datafrom estimator import MultiFidelityKriging_devtry:from data import get_prediction_model as _vipre_get_prediction_modeldef 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 GaussianProcessRegressorfrom sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel as Cey = 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 appreturn _KrigingFactory(model_parameters)# --- Constants ----------------------------------------------PARAMETER_OPTIONS = [2, 5, 10]FIDELITY_LOW_OPTIONS = ['medium', 'low', 'high'] # default medium188 unmodified linesyL_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 variationm = float(np.mean(yl)) if len(yl) else 0.0yL_hat_HF = np.full((len(Xh),), m, dtype=float)yL_hat_RF = np.full((len(X_ref),), m, dtype=float)5 unmodified linesmu = float(np.mean(yH)) if len(yH) else 0.0return 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 predictionsif 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.0return np.full((len(X_ref),), mu, dtype=float), (0.0, 1.0)# ---- If too few HF -> simple affine using LFif len(Xh) < 3:a = float(np.mean(yH) - np.mean(yL_hat_HF))b = 1.0return (a + b * yL_hat_RF).astype(float), (a, b)39 unmodified lines# --- 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 NCCReturns (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
app.py+54-12