Docking_project / libs /benchmark /overnight_stop.py
QPromaQ's picture
Upload folder using huggingface_hub
c289d87 verified
Raw
History Blame Contribute Delete
11.7 kB
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, Mapping, Sequence
import numpy as np
import pandas as pd
STOP_MODELS = (
"percentile_target",
"regret_constrained",
"utility_maximizing",
"hybrid",
)
OBJECTIVES = (
"quality_per_time",
"quality_per_docking",
"rank_percentile_minimization",
"regret_constrained_utility",
"target_percentile_attainment",
"hybrid_objective",
)
@dataclass(frozen=True)
class StopModelParams:
target_percentile: float = 1.0
probability_threshold: float = 0.80
epsilon_quality: float = 0.10
min_budget: int = 100
max_budget: int = 10000
gain_threshold: float = 0.03
utility_lambda: float = 0.001
utility_threshold: float = 0.0
uncertainty_threshold: float = 0.35
confirmation_window: int = 24
min_improvement_delta: float = 0.02
def _sigmoid(x: float) -> float:
z = float(np.clip(x, -50.0, 50.0))
return float(1.0 / (1.0 + np.exp(-z)))
def _safe_float(v: Any, default: float = np.nan) -> float:
try:
x = float(v)
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:
vals = []
for lid in selected_ids:
info = truth_map.get(str(lid))
if info is None:
continue
vals.append(_safe_float(info.get("rank_percentile"), 100.0))
if not vals:
return 100.0
return float(np.nanmin(np.asarray(vals, dtype=float)))
def estimate_marginal_expected_gain(
*,
remaining_df: pd.DataFrame,
incumbent_best_score: float,
uncertainty_weight: float = 0.5,
) -> float:
pred = pd.to_numeric(remaining_df.get("predicted_score_prebatch", np.nan), errors="coerce").dropna().to_numpy(dtype=float)
if pred.size == 0:
return 0.0
unc = pd.to_numeric(remaining_df.get("predicted_uncertainty_prebatch", np.nan), errors="coerce").dropna().to_numpy(dtype=float)
if unc.size == 0:
unc = np.full(pred.shape[0], np.nanstd(pred) if pred.size > 1 else 1.0)
if unc.size != pred.size:
unc = np.full(pred.shape[0], np.nanmean(unc) if unc.size else 1.0)
optimistic = pred - float(max(0.0, uncertainty_weight)) * np.abs(unc)
optimistic_best = float(np.nanmin(optimistic)) if np.isfinite(optimistic).any() else float(np.nanmin(pred))
if not np.isfinite(optimistic_best):
return 0.0
return float(max(0.0, float(incumbent_best_score) - optimistic_best))
def estimate_probability_target_percentile(
*,
best_rank_percentile: float,
target_percentile: float,
marginal_expected_gain: float,
mean_uncertainty: float,
improvement_slope: float,
params: StopModelParams,
) -> float:
p_rank = _sigmoid((float(target_percentile) - float(best_rank_percentile)) / max(0.25, float(target_percentile)))
p_gain = _sigmoid((float(params.gain_threshold) - float(marginal_expected_gain)) / max(1e-3, float(params.gain_threshold)))
p_unc = 0.5 if not np.isfinite(mean_uncertainty) else _sigmoid(
(float(params.uncertainty_threshold) - float(mean_uncertainty)) / max(1e-3, float(params.uncertainty_threshold))
)
p_slope = 0.5 if not np.isfinite(improvement_slope) else _sigmoid(
(float(params.min_improvement_delta) - abs(float(improvement_slope))) / max(1e-3, float(params.min_improvement_delta))
)
return float(np.clip(0.45 * p_rank + 0.25 * p_gain + 0.15 * p_unc + 0.15 * p_slope, 0.0, 1.0))
def _rank_slope(rank_history: Sequence[float], window: int) -> float:
w = max(2, int(window))
if len(rank_history) < w:
return float("nan")
a = float(rank_history[-w])
b = float(rank_history[-1])
return float((a - b) / max(1, w - 1))
def _stop_condition(
model_name: str,
*,
params: StopModelParams,
n_evaluated: int,
max_budget: int,
estimated_probability_target_percentile: float,
marginal_expected_gain: float,
expected_quality_loss: float,
utility_value: float,
mean_uncertainty: float,
improvement_slope: float,
) -> tuple[bool, str]:
if int(n_evaluated) >= int(max_budget):
return True, "max_budget_reached"
if int(n_evaluated) < int(params.min_budget):
return False, "below_min_budget"
if model_name == "percentile_target":
if (
float(estimated_probability_target_percentile) >= float(params.probability_threshold)
and float(marginal_expected_gain) <= float(params.gain_threshold)
):
return True, "percentile_target_stop"
return False, "continue_percentile_target"
if model_name == "regret_constrained":
if (
float(expected_quality_loss) <= float(params.epsilon_quality)
and float(marginal_expected_gain) <= float(params.gain_threshold)
):
return True, "regret_constrained_stop"
return False, "continue_regret_constrained"
if model_name == "utility_maximizing":
if float(utility_value) <= float(params.utility_threshold):
return True, "utility_maximizing_stop"
return False, "continue_utility_maximizing"
if model_name == "hybrid":
hybrid_ready = (
float(estimated_probability_target_percentile) >= float(params.probability_threshold)
and float(marginal_expected_gain) <= float(params.gain_threshold)
and (not np.isfinite(mean_uncertainty) or float(mean_uncertainty) <= float(params.uncertainty_threshold))
and (not np.isfinite(improvement_slope) or abs(float(improvement_slope)) <= float(params.min_improvement_delta))
)
if hybrid_ready or (
float(expected_quality_loss) <= float(params.epsilon_quality) and float(utility_value) <= float(params.utility_threshold)
):
return True, "hybrid_stop"
return False, "continue_hybrid"
raise ValueError(f"Unsupported stop model: {model_name}")
def simulate_stop_model(
order_df: pd.DataFrame,
*,
truth_map: Mapping[str, Mapping[str, float]],
model_name: str,
budget: int,
params: StopModelParams,
wall_time_per_dock: float,
uncertainty_weight: float = 0.5,
) -> tuple[pd.DataFrame, pd.DataFrame]:
if model_name not in STOP_MODELS:
raise ValueError(f"Unsupported stop model `{model_name}`")
if order_df.empty:
return order_df.copy(), pd.DataFrame()
cap = int(max(1, min(int(budget), int(params.max_budget), int(order_df.shape[0]))))
ordered = order_df.sort_values("step").head(cap).copy().reset_index(drop=True)
selected_rows: list[dict[str, Any]] = []
selected_ids: list[str] = []
rank_history: list[float] = []
score_history: list[float] = []
trace_rows: list[dict[str, Any]] = []
for i, row in ordered.iterrows():
row_d = row.to_dict()
selected_rows.append(row_d)
lid = str(row_d.get("ligand_id"))
selected_ids.append(lid)
dscore = _safe_float(row_d.get("docking_score"), np.nan)
if np.isfinite(dscore):
score_history.append(float(dscore))
incumbent_best = float(np.nanmin(np.asarray(score_history, dtype=float))) if score_history else float("inf")
best_pct = _best_rank_percentile(selected_ids, truth_map)
rank_history.append(best_pct)
slope = _rank_slope(rank_history, int(params.confirmation_window))
remaining = ordered.iloc[i + 1 :].copy()
marginal_gain = estimate_marginal_expected_gain(
remaining_df=remaining,
incumbent_best_score=incumbent_best,
uncertainty_weight=float(uncertainty_weight),
)
recent_unc = pd.to_numeric(remaining.head(32).get("predicted_uncertainty_prebatch", np.nan), errors="coerce").dropna()
mean_unc = float(recent_unc.mean()) if not recent_unc.empty else float("nan")
p_target = estimate_probability_target_percentile(
best_rank_percentile=best_pct,
target_percentile=float(params.target_percentile),
marginal_expected_gain=marginal_gain,
mean_uncertainty=mean_unc,
improvement_slope=slope,
params=params,
)
expected_quality_loss = float(marginal_gain / max(1.0, abs(incumbent_best))) if np.isfinite(incumbent_best) else float("inf")
utility_value = float(marginal_gain - float(params.utility_lambda) * max(1e-9, float(wall_time_per_dock)))
stop, reason = _stop_condition(
model_name=model_name,
params=params,
n_evaluated=int(i + 1),
max_budget=min(cap, int(params.max_budget)),
estimated_probability_target_percentile=p_target,
marginal_expected_gain=marginal_gain,
expected_quality_loss=expected_quality_loss,
utility_value=utility_value,
mean_uncertainty=mean_unc,
improvement_slope=slope,
)
trace_rows.append(
{
"step": int(i),
"ligand_id": lid,
"stop_model": model_name,
"best_rank_percentile": float(best_pct),
"improvement_slope": float(slope) if np.isfinite(slope) else np.nan,
"estimated_probability_target_percentile": float(p_target),
"marginal_expected_gain": float(marginal_gain),
"expected_quality_loss": float(expected_quality_loss),
"utility_value": float(utility_value),
"mean_uncertainty": float(mean_unc) if np.isfinite(mean_unc) else np.nan,
"stop": bool(stop),
"stop_reason": str(reason),
"estimated_wall_time_seconds": float((i + 1) * max(1e-9, float(wall_time_per_dock))),
}
)
if stop:
break
selected_df = pd.DataFrame(selected_rows)
if not selected_df.empty:
selected_df["step"] = np.arange(selected_df.shape[0], dtype=int)
return selected_df, pd.DataFrame(trace_rows)
def objective_value(row: Mapping[str, Any], objective: str, target_percentile: float = 1.0) -> float:
rank_pct = _safe_float(row.get("best_found_rank_percentile"), 100.0)
q_loss = _safe_float(row.get("quality_loss_vs_exhaustive_best"), 1.0)
red = _safe_float(row.get("docking_reduction_fraction"), 0.0)
qpt = _safe_float(row.get("quality_per_time"), 0.0)
qpd = _safe_float(row.get("quality_per_docking"), 0.0)
p_est = _safe_float(row.get("estimated_probability_target_percentile"), 0.0)
gain = _safe_float(row.get("marginal_expected_gain"), 0.0)
if objective == "quality_per_time":
return float(qpt)
if objective == "quality_per_docking":
return float(qpd)
if objective == "rank_percentile_minimization":
return float(-rank_pct)
if objective == "regret_constrained_utility":
return float((1.0 - q_loss) + 0.5 * red - 0.2 * gain)
if objective == "target_percentile_attainment":
hit = 1.0 if float(rank_pct) <= float(target_percentile) else 0.0
return float(2.0 * hit + 0.5 * red + p_est - 0.1 * gain)
if objective == "hybrid_objective":
return float(0.35 * qpt + 0.25 * qpd + 0.25 * (1.0 - q_loss) + 0.15 * p_est - 0.15 * (rank_pct / 100.0))
raise ValueError(f"Unsupported objective `{objective}`")
def is_trivial_objective_solution(best_budget: int, budget_grid: Sequence[int]) -> bool:
if not budget_grid:
return False
low = min(int(x) for x in budget_grid)
return int(best_budget) <= int(low)