Spaces:
Sleeping
Sleeping
Download inference.py from SPINBDO/spinbilstm: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/SPINBDO/spinbilstm/resolve/main/inference.py
- Command line
-
hf download hf://spaces/SPINBDO/spinbilstm/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/SPINBDO/spinbilstm/resolve/main/inference.py
16.4 kB
| # inference.py | |
| import numpy as np | |
| import pandas as pd | |
| # ---- Recommendation eligibility (trend-based) ---- | |
| START_HOURS = 12.0 | |
| START_BDO = 20.0 | |
| # ---- Feeding rule ---- | |
| CC_THRESHOLD = 20.0 | |
| DEFAULT_FEED_VALUE = 50.0 # g/L | |
| # ---- RPM search: CURRENT RPM ± 200 only ---- | |
| RPM_DELTAS = (-200, -150, -100, -50, 50, 100, 150, 200) | |
| CLAMP_RPM_RANGE = (150.0, 650.0) | |
| FORBID_BOUNDARY = True | |
| # ============================================================ | |
| # Smoothing / constraints | |
| # ============================================================ | |
| MAX_RATE_PER_H = 2.0 | |
| SLOPE_MULT = 1.5 | |
| SLOPE_ADD = 0.2 | |
| EMA_ALPHA = 0.0 # keep off by default | |
| def _prepare_window(win_raw: np.ndarray, L: int) -> np.ndarray: | |
| if win_raw.shape[0] < L: | |
| pad = np.repeat(win_raw[:1], L - win_raw.shape[0], axis=0) | |
| return np.vstack([pad, win_raw]).astype(np.float32) | |
| return win_raw[-L:].astype(np.float32) | |
| def _apply_scaling(scaler, X_np: np.ndarray, feature_cols: list) -> np.ndarray: | |
| if scaler is None: | |
| return X_np.astype(np.float32) | |
| if hasattr(scaler, "transform"): | |
| X_df = pd.DataFrame(X_np, columns=feature_cols) | |
| return scaler.transform(X_df).astype(np.float32) | |
| mean_ = getattr(scaler, "mean_", None) | |
| scale_ = getattr(scaler, "scale_", None) | |
| if mean_ is not None and scale_ is not None: | |
| mean_ = np.asarray(mean_, dtype=np.float32) | |
| scale_ = np.asarray(scale_, dtype=np.float32) | |
| if mean_.shape[0] != X_np.shape[1] or scale_.shape[0] != X_np.shape[1]: | |
| raise ValueError( | |
| f"Scaler mean_/scale_ dim mismatch. mean={mean_.shape}, scale={scale_.shape}, X={X_np.shape}" | |
| ) | |
| scale_safe = np.where(scale_ == 0, 1.0, scale_) | |
| return ((X_np.astype(np.float32) - mean_) / scale_safe).astype(np.float32) | |
| return X_np.astype(np.float32) | |
| def build_window_matrix( | |
| timepoints: list, | |
| feature_cols: list, | |
| gene_cols: list, | |
| gene_vec: list, | |
| medium_cols: list, | |
| medium_vec: list, | |
| ) -> np.ndarray: | |
| if len(timepoints) == 0: | |
| raise ValueError("No timepoints given") | |
| df = pd.DataFrame(timepoints).copy() | |
| required = ["Time", "BDO", "OD", "rpm", "Feed", "CarbonContents"] | |
| for c in required: | |
| if c not in df.columns: | |
| raise ValueError(f"Missing required field: {c}") | |
| for c in required: | |
| df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0.0) | |
| for c in df.columns: | |
| if c not in required: | |
| df[c] = pd.to_numeric(df[c], errors="coerce") | |
| df = df.sort_values("Time").reset_index(drop=True) | |
| t = df["Time"].to_numpy(dtype=float) | |
| delta_t = np.zeros_like(t, dtype=float) | |
| if len(t) >= 2: | |
| delta_t[1:] = np.maximum(0.0, t[1:] - t[:-1]) | |
| df["delta_t"] = delta_t | |
| gene_map = {gene_cols[i]: float(gene_vec[i]) for i in range(len(gene_cols))} | |
| med_map = {medium_cols[i]: float(medium_vec[i]) for i in range(len(medium_cols))} | |
| rows = [] | |
| for _, r in df.iterrows(): | |
| row_dict = {c: 0.0 for c in feature_cols} | |
| # required dynamic | |
| row_dict["BDO"] = float(r.get("BDO", 0.0)) | |
| row_dict["CarbonContents"] = float(r.get("CarbonContents", 0.0)) | |
| row_dict["Time"] = float(r.get("Time", 0.0)) | |
| row_dict["rpm"] = float(r.get("rpm", 0.0)) | |
| row_dict["Feed"] = float(r.get("Feed", 0.0)) | |
| row_dict["delta_t"] = float(r.get("delta_t", 0.0)) | |
| row_dict["OD"] = float(r.get("OD", 0.0)) | |
| # optional dynamic | |
| for opt in ["Acetoin", "Ethanol", "pH", "DO", "Temp", "Air", "Succinate", "Lactate", "Formate", "Acetate"]: | |
| if opt in feature_cols and opt in df.columns and pd.notna(r.get(opt)): | |
| row_dict[opt] = float(r.get(opt)) | |
| row_dict.update(gene_map) | |
| row_dict.update(med_map) | |
| rows.append([row_dict[c] for c in feature_cols]) | |
| return np.asarray(rows, dtype=np.float32) | |
| def _predict_one_step_bdo( | |
| timepoints: list, | |
| gene_vec: list, | |
| medium_vec: list, | |
| model, | |
| scaler, | |
| feature_cols: list, | |
| gene_cols: list, | |
| medium_cols: list, | |
| seq_len: int, | |
| override_last: dict | None = None, | |
| ) -> float: | |
| df_tp = pd.DataFrame(timepoints).copy().sort_values("Time").reset_index(drop=True) | |
| required = ["Time", "BDO", "OD", "rpm", "Feed", "CarbonContents"] | |
| for c in required: | |
| if c not in df_tp.columns: | |
| raise ValueError(f"Missing required field: {c}") | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce").fillna(0.0) | |
| for c in df_tp.columns: | |
| if c not in required: | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce") | |
| if override_last is not None and len(df_tp) > 0: | |
| for k, v in override_last.items(): | |
| if k in df_tp.columns: | |
| df_tp.loc[len(df_tp) - 1, k] = float(v) | |
| win = build_window_matrix( | |
| timepoints=df_tp.to_dict(orient="records"), | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| gene_vec=gene_vec, | |
| medium_cols=medium_cols, | |
| medium_vec=medium_vec, | |
| ) | |
| win = _prepare_window(win, int(seq_len)) | |
| X = _apply_scaling(scaler, win, feature_cols) | |
| pred = model.predict(X[None, :, :], verbose=0)[0] | |
| pred = np.asarray(pred).reshape(-1) | |
| return float(pred[0]) | |
| def _apply_rollout_constraints( | |
| bdo_prev: float, | |
| bdo_pred: float, | |
| step_h: float, | |
| prev_step_delta: float | None, | |
| ema_prev: float | None, | |
| ) -> tuple[float, float, float]: | |
| bdo_prev = float(bdo_prev) | |
| bdo_pred = float(bdo_pred) | |
| step_h = max(1e-9, float(step_h)) | |
| # non-decrease | |
| if bdo_pred < bdo_prev: | |
| bdo_pred = bdo_prev | |
| # rate cap | |
| max_inc = float(MAX_RATE_PER_H) * step_h | |
| delta = bdo_pred - bdo_prev | |
| if delta > max_inc: | |
| bdo_pred = bdo_prev + max_inc | |
| delta = max_inc | |
| # slope cap | |
| if prev_step_delta is not None: | |
| cap = float(SLOPE_MULT) * float(prev_step_delta) + float(SLOPE_ADD) | |
| if delta > cap: | |
| bdo_pred = bdo_prev + cap | |
| delta = cap | |
| # EMA optional | |
| if float(EMA_ALPHA) > 0.0: | |
| a = float(EMA_ALPHA) | |
| if ema_prev is None: | |
| ema_prev = bdo_prev | |
| ema_now = a * bdo_pred + (1.0 - a) * ema_prev | |
| if ema_now < bdo_prev: | |
| ema_now = bdo_prev | |
| bdo_new = float(ema_now) | |
| delta_used = bdo_new - bdo_prev | |
| return bdo_new, float(delta_used), float(ema_now) | |
| return float(bdo_pred), float(delta), (float(ema_prev) if ema_prev is not None else float(bdo_pred)) | |
| def _rollout_knots_only( | |
| timepoints: list, | |
| gene_vec: list, | |
| medium_vec: list, | |
| model, | |
| scaler, | |
| feature_cols: list, | |
| gene_cols: list, | |
| medium_cols: list, | |
| seq_len: int, | |
| knot_hours=(0.0, 2.0, 4.0, 6.0), | |
| base_step_h: float = 2.0, | |
| override_last: dict | None = None, | |
| ) -> dict: | |
| """ | |
| Predict only at knots (0,2,4,6) using repeated 2h steps. | |
| This avoids odd-hour rem-step artifacts. | |
| """ | |
| df_tp = pd.DataFrame(timepoints).copy() | |
| if df_tp.empty: | |
| raise ValueError("No timepoints given") | |
| required = ["Time", "BDO", "OD", "rpm", "Feed", "CarbonContents"] | |
| for c in required: | |
| if c not in df_tp.columns: | |
| raise ValueError(f"Missing required field: {c}") | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce").fillna(0.0) | |
| for c in df_tp.columns: | |
| if c not in required: | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce") | |
| df_tp = df_tp.sort_values("Time").reset_index(drop=True) | |
| sim = df_tp.to_dict(orient="records") | |
| base_step_h = float(base_step_h) | |
| if base_step_h <= 0: | |
| raise ValueError("base_step_h must be > 0") | |
| # We will advance in 2h increments only | |
| out = {0.0: float(sim[-1]["BDO"])} | |
| prev_step_delta = None | |
| ema_state = None | |
| first_override = override_last | |
| # We assume knots include 0 and are multiples of base_step_h | |
| curr_h = 0.0 | |
| for h in knot_hours: | |
| h = float(h) | |
| if h <= 0: | |
| continue | |
| step = h - curr_h | |
| if step <= 0: | |
| continue | |
| # enforce step == base_step_h for stability (knot design) | |
| # if not, we'll still do a single step of that size, but usually not needed. | |
| step_h = float(step) | |
| pred_next = _predict_one_step_bdo( | |
| timepoints=sim, | |
| gene_vec=gene_vec, | |
| medium_vec=medium_vec, | |
| model=model, | |
| scaler=scaler, | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| medium_cols=medium_cols, | |
| seq_len=int(seq_len), | |
| override_last=first_override, | |
| ) | |
| first_override = None | |
| last = sim[-1].copy() | |
| bdo_now = float(last["BDO"]) | |
| bdo_new, used_delta, ema_state = _apply_rollout_constraints( | |
| bdo_prev=bdo_now, | |
| bdo_pred=float(pred_next), | |
| step_h=step_h, | |
| prev_step_delta=prev_step_delta, | |
| ema_prev=ema_state, | |
| ) | |
| prev_step_delta = float(used_delta) | |
| new_tp = last.copy() | |
| new_tp["Time"] = float(last["Time"]) + step_h | |
| new_tp["BDO"] = float(bdo_new) | |
| sim.append(new_tp) | |
| curr_h = float(h) | |
| out[float(h)] = float(bdo_new) | |
| return out | |
| def _interp_between_knots(knot_map: dict, horizon_h: float) -> float: | |
| h = float(horizon_h) | |
| if h <= 0: | |
| return float(knot_map.get(0.0, 0.0)) | |
| ks = sorted([float(x) for x in knot_map.keys()]) | |
| if h >= ks[-1]: | |
| return float(knot_map[ks[-1]]) | |
| lo = ks[0] | |
| hi = ks[-1] | |
| for i in range(len(ks) - 1): | |
| if ks[i] <= h <= ks[i + 1]: | |
| lo = ks[i] | |
| hi = ks[i + 1] | |
| break | |
| y0 = float(knot_map[lo]) | |
| y1 = float(knot_map[hi]) | |
| if abs(hi - lo) < 1e-9: | |
| return y0 | |
| w = (h - lo) / (hi - lo) | |
| y = (1 - w) * y0 + w * y1 | |
| # monotonic safeguard | |
| if y < y0: | |
| y = y0 | |
| if y > y1 and y1 >= y0: | |
| y = y1 | |
| return float(y) | |
| def _rollout_bdo_horizon( | |
| timepoints: list, | |
| gene_vec: list, | |
| medium_vec: list, | |
| model, | |
| scaler, | |
| feature_cols: list, | |
| gene_cols: list, | |
| medium_cols: list, | |
| seq_len: int, | |
| horizon_h: float, | |
| base_step_h: float, | |
| override_last: dict | None = None, | |
| ) -> float: | |
| """ | |
| New behavior: | |
| - Predict only at 0/2/4/6 using model (2h steps) | |
| - Interpolate for odd horizons (1/3/5) | |
| """ | |
| horizon_h = float(horizon_h) | |
| if horizon_h <= 0: | |
| df_tp = pd.DataFrame(timepoints).sort_values("Time").reset_index(drop=True) | |
| return float(pd.to_numeric(df_tp.iloc[-1]["BDO"], errors="coerce") or 0.0) | |
| # knots fixed to 0/2/4/6 | |
| knots = (0.0, 2.0, 4.0, 6.0) | |
| knot_map = _rollout_knots_only( | |
| timepoints=timepoints, | |
| gene_vec=gene_vec, | |
| medium_vec=medium_vec, | |
| model=model, | |
| scaler=scaler, | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| medium_cols=medium_cols, | |
| seq_len=int(seq_len), | |
| knot_hours=knots, | |
| base_step_h=float(base_step_h), | |
| override_last=override_last, | |
| ) | |
| return _interp_between_knots(knot_map, horizon_h) | |
| def predict_next_bdo_and_suggest_actions( | |
| timepoints: list, | |
| gene_vec: list, | |
| medium_vec: list, | |
| model, | |
| scaler, | |
| feature_cols: list, | |
| gene_cols: list, | |
| medium_cols: list, | |
| seq_len: int = 4, | |
| min_gain_pred: float = 0.5, | |
| feed_value: float = DEFAULT_FEED_VALUE, | |
| horizon_h: float = 4.0, | |
| base_step_h: float = 2.0, | |
| ): | |
| df_tp = pd.DataFrame(timepoints).copy() | |
| if df_tp.empty: | |
| raise ValueError("No timepoints given") | |
| for c in ["Time", "BDO", "OD", "rpm", "Feed", "CarbonContents"]: | |
| if c not in df_tp.columns: | |
| raise ValueError(f"Missing required field: {c}") | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce").fillna(0.0) | |
| for c in df_tp.columns: | |
| if c not in ["Time", "BDO", "OD", "rpm", "Feed", "CarbonContents"]: | |
| df_tp[c] = pd.to_numeric(df_tp[c], errors="coerce") | |
| df_tp = df_tp.sort_values("Time").reset_index(drop=True) | |
| t_last = float(df_tp.iloc[-1]["Time"]) | |
| bdo_last = float(df_tp.iloc[-1]["BDO"]) | |
| cc_last = float(df_tp.iloc[-1]["CarbonContents"]) | |
| feed_last = float(df_tp.iloc[-1]["Feed"]) | |
| rpm_last = float(df_tp.iloc[-1]["rpm"]) | |
| notice_messages = [] | |
| if cc_last < CC_THRESHOLD: | |
| notice_messages.append("주의: CarbonContents가 20 g/L 미만입니다. Feeding을 고려하세요.") | |
| eligible_for_reco = (t_last >= START_HOURS) and (bdo_last >= START_BDO) | |
| pred_keep = _rollout_bdo_horizon( | |
| timepoints=df_tp.to_dict(orient="records"), | |
| gene_vec=gene_vec, | |
| medium_vec=medium_vec, | |
| model=model, | |
| scaler=scaler, | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| medium_cols=medium_cols, | |
| seq_len=int(seq_len), | |
| horizon_h=float(horizon_h), | |
| base_step_h=float(base_step_h), | |
| override_last=None, | |
| ) | |
| if not eligible_for_reco: | |
| return { | |
| "notice_messages": notice_messages, | |
| "decision": "KEEP", | |
| "predicted_next_keep": round(float(pred_keep), 2), | |
| "predicted_next_after": round(float(pred_keep), 2), | |
| "gain": round(0.0, 2), | |
| "recommended_rpm": round(rpm_last, 0), | |
| "rpm_delta": round(0.0, 0), | |
| "recommended_feed": None, | |
| } | |
| best_decision = "KEEP" | |
| best_after = float(pred_keep) | |
| best_gain = 0.0 | |
| best_feed = None | |
| # Candidate 1, FEED | |
| if (cc_last < CC_THRESHOLD) and (abs(feed_last) < 1e-9): | |
| pred_feed = _rollout_bdo_horizon( | |
| timepoints=df_tp.to_dict(orient="records"), | |
| gene_vec=gene_vec, | |
| medium_vec=medium_vec, | |
| model=model, | |
| scaler=scaler, | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| medium_cols=medium_cols, | |
| seq_len=int(seq_len), | |
| horizon_h=float(horizon_h), | |
| base_step_h=float(base_step_h), | |
| override_last={"Feed": float(feed_value)}, | |
| ) | |
| gain_feed = float(pred_feed - pred_keep) | |
| if gain_feed >= float(min_gain_pred) and float(pred_feed) > best_after: | |
| best_decision = "FEED" | |
| best_after = float(pred_feed) | |
| best_gain = float(gain_feed) | |
| best_feed = float(feed_value) | |
| # Candidate 2, RPM search | |
| best_rpm = float(rpm_last) | |
| best_rpm_pred = float(pred_keep) | |
| for d in RPM_DELTAS: | |
| cand_rpm = float(rpm_last) + float(d) | |
| lo, hi = CLAMP_RPM_RANGE | |
| if cand_rpm < lo or cand_rpm > hi: | |
| continue | |
| if FORBID_BOUNDARY and (abs(cand_rpm - lo) < 1e-6 or abs(cand_rpm - hi) < 1e-6): | |
| continue | |
| pred_try = _rollout_bdo_horizon( | |
| timepoints=df_tp.to_dict(orient="records"), | |
| gene_vec=gene_vec, | |
| medium_vec=medium_vec, | |
| model=model, | |
| scaler=scaler, | |
| feature_cols=feature_cols, | |
| gene_cols=gene_cols, | |
| medium_cols=medium_cols, | |
| seq_len=int(seq_len), | |
| horizon_h=float(horizon_h), | |
| base_step_h=float(base_step_h), | |
| override_last={"rpm": float(cand_rpm)}, | |
| ) | |
| if float(pred_try) > best_rpm_pred: | |
| best_rpm_pred = float(pred_try) | |
| best_rpm = float(cand_rpm) | |
| gain_rpm = float(best_rpm_pred - pred_keep) | |
| rpm_changed = abs(best_rpm - float(rpm_last)) > 1e-6 | |
| if rpm_changed and (gain_rpm >= float(min_gain_pred)): | |
| if best_rpm_pred > best_after: | |
| best_decision = "CHANGE_RPM" | |
| best_after = float(best_rpm_pred) | |
| best_gain = float(gain_rpm) | |
| best_feed = None | |
| out = { | |
| "notice_messages": notice_messages, | |
| "decision": best_decision, | |
| "predicted_next_keep": round(float(pred_keep), 2), | |
| "predicted_next_after": round(float(best_after), 2), | |
| "gain": round(float(best_gain), 2), | |
| "recommended_rpm": round(float(best_rpm if best_decision == "CHANGE_RPM" else rpm_last), 0), | |
| "rpm_delta": round(float((best_rpm - rpm_last) if best_decision == "CHANGE_RPM" else 0.0), 0), | |
| "recommended_feed": (round(float(best_feed), 2) if best_decision == "FEED" else None), | |
| } | |
| return out | |