| from __future__ import annotations |
|
|
| from dataclasses import dataclass |
| from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple |
|
|
| import numpy as np |
| import pandas as pd |
|
|
|
|
| @dataclass(frozen=True) |
| class StoppingControls: |
| target_rank_percentile: float = 1.0 |
| peak_patience: int = 32 |
| min_improvement_delta: float = 0.02 |
|
|
|
|
| @dataclass(frozen=True) |
| class ExplorationControls: |
| stagnation_patience: int = 24 |
| diversity_boost_strength: float = 0.4 |
| dominant_window: int = 128 |
|
|
|
|
| @dataclass(frozen=True) |
| class UncertaintyControls: |
| uncertainty_low_threshold: float = 0.35 |
| uncertainty_patience: int = 32 |
| expected_gain_threshold: float = 0.03 |
|
|
|
|
| def enforce_control_limits(cfg: Mapping[str, Any]) -> None: |
| """Enforce compact control surface to prevent parameter explosion.""" |
|
|
| groups = { |
| "stopping": set((cfg.get("stopping") or {}).keys()), |
| "exploration": set((cfg.get("exploration") or {}).keys()), |
| "uncertainty": set((cfg.get("uncertainty") or {}).keys()), |
| } |
| for name, keys in groups.items(): |
| if len(keys) > 3: |
| raise ValueError(f"{name} parameter count exceeds limit (3): {sorted(keys)}") |
|
|
|
|
| def controls_from_config(cfg: Mapping[str, Any]) -> tuple[StoppingControls, ExplorationControls, UncertaintyControls]: |
| stop_cfg = cfg.get("stopping") or {} |
| exp_cfg = cfg.get("exploration") or {} |
| unc_cfg = cfg.get("uncertainty") or {} |
| return ( |
| StoppingControls( |
| target_rank_percentile=float(stop_cfg.get("target_rank_percentile", 1.0)), |
| peak_patience=int(stop_cfg.get("peak_patience", 32)), |
| min_improvement_delta=float(stop_cfg.get("min_improvement_delta", 0.02)), |
| ), |
| ExplorationControls( |
| stagnation_patience=int(exp_cfg.get("stagnation_patience", 24)), |
| diversity_boost_strength=float(exp_cfg.get("diversity_boost_strength", 0.4)), |
| dominant_window=int(exp_cfg.get("dominant_window", 128)), |
| ), |
| UncertaintyControls( |
| uncertainty_low_threshold=float(unc_cfg.get("uncertainty_low_threshold", 0.35)), |
| uncertainty_patience=int(unc_cfg.get("uncertainty_patience", 32)), |
| expected_gain_threshold=float(unc_cfg.get("expected_gain_threshold", 0.03)), |
| ), |
| ) |
|
|
|
|
| def _safe_float(value: Any, default: float = np.nan) -> float: |
| try: |
| x = float(value) |
| return x if np.isfinite(x) else float(default) |
| except Exception: |
| return float(default) |
|
|
|
|
| def _best_rank_percentile(selected_ids: Sequence[str], truth_map: Mapping[str, Mapping[str, float]]) -> float: |
| values: List[float] = [] |
| for lid in selected_ids: |
| info = truth_map.get(str(lid)) |
| if info is None: |
| continue |
| values.append(float(info.get("rank_percentile", 100.0))) |
| if not values: |
| return 100.0 |
| return float(np.min(np.asarray(values, dtype=float))) |
|
|
|
|
| def _dominant_cluster_from_recent(selected_rows: Sequence[dict[str, Any]], window: int) -> int | None: |
| if not selected_rows: |
| return None |
| recent = selected_rows[-max(1, int(window)) :] |
| cnt: Dict[int, int] = {} |
| for row in recent: |
| cid = int(_safe_float(row.get("cluster_id", -1), default=-1)) |
| if cid < 0: |
| continue |
| cnt[cid] = cnt.get(cid, 0) + 1 |
| if not cnt: |
| return None |
| return int(max(cnt.items(), key=lambda kv: kv[1])[0]) |
|
|
|
|
| def _expected_gain_proxy(remaining: pd.DataFrame, incumbent_best: float) -> float: |
| pred = pd.to_numeric(remaining.get("predicted_score_prebatch", np.nan), errors="coerce").dropna() |
| if pred.empty: |
| return 0.0 |
| optimistic = float(np.quantile(pred.to_numpy(dtype=float), 0.05)) |
| |
| return float(max(0.0, incumbent_best - optimistic)) |
|
|
|
|
| def simulate_multifidelity_policy( |
| order_df: pd.DataFrame, |
| *, |
| truth_map: Mapping[str, Mapping[str, float]], |
| budget: int, |
| min_budget: int, |
| max_budget: int, |
| wall_time_per_dock: float, |
| max_wall_time_seconds: float | None, |
| stopping: StoppingControls, |
| exploration: ExplorationControls, |
| uncertainty: UncertaintyControls, |
| ) -> tuple[pd.DataFrame, pd.DataFrame]: |
| """Run compact multifidelity policy simulation on a pre-ranked candidate order. |
| |
| Default mode exploits dominant cluster. Diversity fallback is enabled only under |
| dominant-cluster stagnation, then automatically disabled. |
| """ |
|
|
| if order_df.empty: |
| return order_df.copy(), pd.DataFrame() |
|
|
| cap = int(max(1, min(int(budget), int(max_budget), int(order_df.shape[0])))) |
| remaining = order_df.sort_values("step").head(cap).copy().reset_index(drop=True) |
|
|
| selected_rows: List[dict[str, Any]] = [] |
| selected_ids: List[str] = [] |
| trace_rows: List[dict[str, Any]] = [] |
|
|
| cluster_selected_counts: Dict[int, int] = {} |
| dominant_cluster: int | None = None |
| dominant_best_score = np.inf |
| dominant_stagnant_rounds = 0 |
| diversity_steps_left = 0 |
|
|
| rank_history: List[float] = [] |
| uncertainty_history: List[float] = [] |
|
|
| stop_reason = "budget_cap_reached" |
| for i in range(cap): |
| if remaining.empty: |
| stop_reason = "pool_exhausted" |
| break |
|
|
| if diversity_steps_left > 0: |
| cluster_counts_now = { |
| int(_safe_float(c, -1)): int(v) for c, v in cluster_selected_counts.items() if int(c) >= 0 |
| } |
| min_seen = min(cluster_counts_now.values()) if cluster_counts_now else 0 |
| candidate_clusters = {cid for cid, v in cluster_counts_now.items() if v <= min_seen} |
| cand = remaining[remaining["cluster_id"].isin(candidate_clusters)].head(1) |
| if cand.empty: |
| cand = remaining.head(1) |
| selection_mode = "diversity_fallback" |
| diversity_steps_left -= 1 |
| else: |
| dominant_cluster = _dominant_cluster_from_recent(selected_rows, exploration.dominant_window) |
| if dominant_cluster is not None: |
| cand = remaining[remaining["cluster_id"] == dominant_cluster].head(1) |
| if cand.empty: |
| cand = remaining.head(1) |
| selection_mode = "dominant_unavailable" |
| else: |
| selection_mode = "dominant_exploit" |
| else: |
| cand = remaining.head(1) |
| selection_mode = "initial_explore" |
|
|
| row = cand.iloc[0].to_dict() |
| remaining = remaining.drop(index=int(cand.index[0])).reset_index(drop=True) |
|
|
| lid = str(row.get("ligand_id")) |
| cid = int(_safe_float(row.get("cluster_id", -1), -1)) |
| dscore = _safe_float(row.get("docking_score", np.nan), np.nan) |
| unc = _safe_float(row.get("predicted_uncertainty_prebatch", np.nan), np.nan) |
|
|
| selected_rows.append(row) |
| selected_ids.append(lid) |
| cluster_selected_counts[cid] = int(cluster_selected_counts.get(cid, 0) + 1) |
| if np.isfinite(unc): |
| uncertainty_history.append(float(unc)) |
|
|
| if dominant_cluster is not None and cid == dominant_cluster: |
| if np.isfinite(dscore) and (dscore < dominant_best_score - stopping.min_improvement_delta): |
| dominant_best_score = float(dscore) |
| dominant_stagnant_rounds = 0 |
| else: |
| dominant_stagnant_rounds += 1 |
|
|
| best_rank_pct = _best_rank_percentile(selected_ids, truth_map) |
| rank_history.append(best_rank_pct) |
|
|
| patience = max(2, int(stopping.peak_patience)) |
| if len(rank_history) >= patience: |
| slope = float(rank_history[-patience] - rank_history[-1]) |
| else: |
| slope = np.nan |
|
|
| incumbent_best = float(np.nanmin(pd.to_numeric(pd.DataFrame(selected_rows)["docking_score"], errors="coerce").to_numpy(dtype=float))) |
| expected_gain = _expected_gain_proxy(remaining, incumbent_best) |
|
|
| u_pat = max(2, int(uncertainty.uncertainty_patience)) |
| recent_unc = uncertainty_history[-u_pat:] if uncertainty_history else [] |
| mean_unc = float(np.mean(np.asarray(recent_unc, dtype=float))) if recent_unc else np.nan |
|
|
| est_wall = float((i + 1) * wall_time_per_dock) |
| rank_target_hit = bool(best_rank_pct <= float(stopping.target_rank_percentile)) |
| slope_stagnation = bool(np.isfinite(slope) and abs(float(slope)) <= float(stopping.min_improvement_delta)) |
| uncertainty_low = bool(np.isfinite(mean_unc) and mean_unc <= float(uncertainty.uncertainty_low_threshold)) |
| gain_low = bool(float(expected_gain) <= float(uncertainty.expected_gain_threshold)) |
| dominant_plateau = bool(dominant_stagnant_rounds >= int(exploration.stagnation_patience)) |
|
|
| allow_stop = bool((i + 1) >= int(min_budget)) |
| stop_now = False |
|
|
| if allow_stop and rank_target_hit and slope_stagnation and gain_low and uncertainty_low: |
| stop_now = True |
| stop_reason = "early_peak_dynamic_stop" |
| elif max_wall_time_seconds is not None and np.isfinite(float(max_wall_time_seconds)) and est_wall >= float(max_wall_time_seconds): |
| stop_now = True |
| stop_reason = "max_wall_time_reached" |
|
|
| |
| fallback_triggered = False |
| if ( |
| not stop_now |
| and diversity_steps_left <= 0 |
| and dominant_plateau |
| and (i + 1) >= int(min_budget) |
| and not rank_target_hit |
| ): |
| diversity_steps_left = max(1, int(round(8.0 * float(exploration.diversity_boost_strength)))) |
| fallback_triggered = True |
|
|
| trace_rows.append( |
| { |
| "step": int(i), |
| "ligand_id": lid, |
| "selection_mode": selection_mode, |
| "stop_reason": stop_reason if stop_now else "", |
| "best_rank_percentile": float(best_rank_pct), |
| "rank_improvement_slope": float(slope) if np.isfinite(slope) else np.nan, |
| "expected_gain_proxy": float(expected_gain), |
| "mean_uncertainty": float(mean_unc) if np.isfinite(mean_unc) else np.nan, |
| "rank_target_hit": bool(rank_target_hit), |
| "slope_stagnation": bool(slope_stagnation), |
| "uncertainty_low": bool(uncertainty_low), |
| "dominant_plateau": bool(dominant_plateau), |
| "fallback_triggered": bool(fallback_triggered), |
| "diversity_steps_left": int(diversity_steps_left), |
| "dominant_cluster": int(dominant_cluster) if dominant_cluster is not None else -1, |
| "dynamic_budget_cap": int(cap), |
| "estimated_wall_seconds": float(est_wall), |
| } |
| ) |
|
|
| if stop_now: |
| break |
|
|
| selected_df = pd.DataFrame(selected_rows).reset_index(drop=True) |
| if not selected_df.empty: |
| selected_df = selected_df.copy() |
| selected_df["step"] = np.arange(selected_df.shape[0], dtype=int) |
| trace_df = pd.DataFrame(trace_rows) |
| return selected_df, trace_df |
|
|