from __future__ import annotations import argparse import json import math import os import shutil import sys import threading import time from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Iterable, List, Tuple ROOT_DIR = Path(__file__).resolve().parents[1] if str(ROOT_DIR) not in sys.path: sys.path.insert(0, str(ROOT_DIR)) import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd import psutil from rdkit import Chem from rdkit.Chem import Descriptors, rdMolDescriptors from sklearn.metrics import average_precision_score, precision_recall_curve, roc_auc_score, roc_curve from libs.analysis.ranking import resolve_reference_rank_percentile from libs.adaptive.scheduler import AdaptiveScheduler, SchedulerConfig from libs.adaptive.surrogate_model import SurrogateConfig from libs.adaptive.weight_schedule import WeightScheduleConfig from libs.benchmark.disk_guard import append_disk_snapshot, snapshot_disk_state from libs.docking.backend_rdock import RDockBackend, RDockConfig from libs.docking.backend_smina import SminaBackend, SminaConfig from libs.docking.base import DockingError from libs.docking.pocket import PocketSpec, extract_reference_ligand_coords from libs.utils.logging_utils import get_logger @dataclass class StrictDataset: name: str target_name: str target_path: Path shared_path: Path reference_csv: Path oracle_master_path: Path class CPUMonitor: def __init__(self, interval_s: float = 1.0) -> None: self.interval_s = float(interval_s) self.samples: list[float] = [] self._stop = threading.Event() self._thread: threading.Thread | None = None def _run(self) -> None: # warm-up read psutil.cpu_percent(interval=None) while not self._stop.is_set(): self.samples.append(float(psutil.cpu_percent(interval=self.interval_s))) def start(self) -> None: self._thread = threading.Thread(target=self._run, daemon=True) self._thread.start() def stop(self) -> None: self._stop.set() if self._thread is not None: self._thread.join(timeout=5) def summary(self) -> dict[str, float]: if not self.samples: return {"cpu_mean_pct": float("nan"), "cpu_p10_pct": float("nan"), "cpu_min_pct": float("nan")} arr = np.asarray(self.samples, dtype=float) return { "cpu_mean_pct": float(np.nanmean(arr)), "cpu_p10_pct": float(np.nanpercentile(arr, 10)), "cpu_min_pct": float(np.nanmin(arr)), } def _strict_dataset_catalog() -> list[StrictDataset]: return [ StrictDataset( name="strict_dataset_1", target_name="EGFR", target_path=ROOT_DIR / "data/targets/prelim_set_egfr_4wkq/egfr_4wkq.pdb", shared_path=ROOT_DIR / "data/ligands/prelim_set_egfr_4wkq/shared_library_shuffled.csv", reference_csv=ROOT_DIR / "data/ligands/prelim_set_egfr_4wkq/reference_ligands.csv", oracle_master_path=ROOT_DIR / "data/benchmarks/prelim_oracles/oracle_egfr.csv", ), StrictDataset( name="strict_dataset_2", target_name="ABL1", target_path=ROOT_DIR / "data/targets/prelim_set_abl1_1iep/abl1_1iep.pdb", shared_path=ROOT_DIR / "data/ligands/prelim_set_abl1_1iep/shared_library_shuffled.csv", reference_csv=ROOT_DIR / "data/ligands/prelim_set_abl1_1iep/reference_ligands.csv", oracle_master_path=ROOT_DIR / "data/benchmarks/prelim_oracles/oracle_abl1.csv", ), StrictDataset( name="strict_dataset_3", target_name="MDM2", target_path=ROOT_DIR / "data/targets/prelim_set_mdm2_4hg7/mdm2_4hg7.pdb", shared_path=ROOT_DIR / "data/ligands/prelim_set_mdm2_4hg7/shared_library_shuffled.csv", reference_csv=ROOT_DIR / "data/ligands/prelim_set_mdm2_4hg7/reference_ligands.csv", oracle_master_path=ROOT_DIR / "data/benchmarks/prelim_oracles/oracle_mdm2.csv", ), ] def _assert_redocking_gate(strict_datasets: Iterable[StrictDataset]) -> None: gate_path = ROOT_DIR / "results/redocking_validation/summary.json" if not gate_path.exists(): raise DockingError( "Redocking validation gate failed: missing results/redocking_validation/summary.json. " "Run pipeline/run_redocking_validation.py first." ) payload = json.loads(gate_path.read_text(encoding="utf-8")) if not bool(payload.get("all_targets_go", False)): raise DockingError( "Redocking validation gate failed: one or more targets are NO-GO. " "Fix pocket/preparation/backend issues before screening." ) expected = {str(d.name) for d in strict_datasets} observed = {str(x) for x in payload.get("datasets", [])} if expected and not expected.issubset(observed): raise DockingError( f"Redocking validation gate failed: missing validated datasets. expected={sorted(expected)} observed={sorted(observed)}" ) def _read_reference(ref_csv: Path) -> dict[str, str]: df = pd.read_csv(ref_csv) row = df.iloc[0] return { "reference_id": str(row.get("reference_id", "")), "ligand_comp_id": str(row.get("ligand_comp_id", "")), "reference_smiles": str(row.get("reference_smiles", "")), "pdb_id": str(row.get("pdb_id", "")), } def _prepare_new_dataset_views( out_data_root: Path, datasets: Iterable[StrictDataset], *, subset_size: int, logger, ) -> list[StrictDataset]: out_data_root.mkdir(parents=True, exist_ok=True) prepared: list[StrictDataset] = [] for ds in datasets: lig = pd.read_csv(ds.shared_path).drop_duplicates(subset=["ligand_id"]).reset_index(drop=True) lig = lig.head(int(subset_size)).copy() ref = _read_reference(ds.reference_csv) rid = str(ref["reference_id"]) if rid not in set(lig["ligand_id"].astype(str)): src = pd.read_csv(ds.shared_path) rr = src[src["ligand_id"].astype(str) == rid] if rr.empty: raise DockingError(f"Reference ligand `{rid}` missing in {ds.shared_path}") lig = pd.concat([lig, rr], ignore_index=True).drop_duplicates(subset=["ligand_id"]).head(int(subset_size)).copy() target_dir = out_data_root / ds.name target_dir.mkdir(parents=True, exist_ok=True) new_shared = target_dir / "shared_library_shuffled.csv" new_ref = target_dir / "reference_ligands.csv" lig.to_csv(new_shared, index=False) pd.read_csv(ds.reference_csv).to_csv(new_ref, index=False) logger.info("Prepared dataset view %s size=%s", ds.name, lig.shape[0]) prepared.append( StrictDataset( name=ds.name, target_name=ds.target_name, target_path=ds.target_path, shared_path=new_shared, reference_csv=new_ref, oracle_master_path=ds.oracle_master_path, ) ) return prepared def _make_features(lig_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, int], dict[int, int]]: rows_v: list[dict[str, float]] = [] rows_m: list[dict[str, float]] = [] cluster_map: dict[str, int] = {} for row in lig_df.itertuples(index=False): lid = str(row.ligand_id) smi = str(row.smiles) mol = Chem.MolFromSmiles(smi) vals: dict[str, float] = {"ligand_id": lid} masks: dict[str, float] = {"ligand_id": lid} if mol is None: for c in ["mw", "logp", "tpsa", "hbd", "hba", "rotb", "arom", "charge"]: vals[c] = np.nan masks[c] = 0.0 fp = np.zeros(64, dtype=float) else: vals.update( { "mw": float(Descriptors.MolWt(mol)), "logp": float(Descriptors.MolLogP(mol)), "tpsa": float(rdMolDescriptors.CalcTPSA(mol)), "hbd": float(rdMolDescriptors.CalcNumHBD(mol)), "hba": float(rdMolDescriptors.CalcNumHBA(mol)), "rotb": float(rdMolDescriptors.CalcNumRotatableBonds(mol)), "arom": float(rdMolDescriptors.CalcNumAromaticRings(mol)), "charge": float(sum(a.GetFormalCharge() for a in mol.GetAtoms())), } ) for c in ["mw", "logp", "tpsa", "hbd", "hba", "rotb", "arom", "charge"]: masks[c] = 1.0 fp = np.asarray(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=64), dtype=float) for i, bit in enumerate(fp.tolist()): vals[f"mfp_{i:03d}"] = float(bit) masks[f"mfp_{i:03d}"] = 1.0 rows_v.append(vals) rows_m.append(masks) key = int(sum((i + 1) * int(x) for i, x in enumerate(fp[:16].tolist()))) cluster_map[lid] = key % 256 hyper_map = {cid: int(cid // 8) for cid in set(cluster_map.values())} return pd.DataFrame(rows_v), pd.DataFrame(rows_m), cluster_map, hyper_map def _build_backend( backend_name: str, *, threads_used: int, work_dir: Path, pocket_reference_ligand_id: str, ): if backend_name == "rdock": return RDockBackend( RDockConfig( n_runs=4, command_timeout_seconds=240, parallel_jobs=int(threads_used), command_log_path=str(work_dir / "rdock_commands.log"), pocket_mode="reference_complex_pocket", pocket_reference_ligand_id=pocket_reference_ligand_id, pocket_relaxation_margin=0.0, ) ) if backend_name == "smina": return SminaBackend( SminaConfig( command_timeout_seconds=30, exhaustiveness=6, num_modes=5, cpu=1, parallel_jobs=int(threads_used), seed=20260422, pocket_mode="reference_complex_pocket", pocket_reference_ligand_id=pocket_reference_ligand_id, pocket_relaxation_margin=0.0, ) ) raise ValueError(f"Unsupported backend: {backend_name}") def _validate_fixed_pocket(target_context: Dict[str, Any], target_path: Path, ligand_comp_id: str) -> dict[str, Any]: pocket_json = target_context.get("pocket_spec_json") or target_context.get("pocket_json") if pocket_json is None or not Path(pocket_json).exists(): raise DockingError("Missing pocket specification file in target context") spec = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8"))) if spec.source != "reference_complex_ligand": raise DockingError(f"Invalid strict pocket source: {spec.source}") coords, _meta = extract_reference_ligand_coords(target_path=target_path, pocket_reference_ligand_id=ligand_comp_id) if coords.size == 0: raise DockingError(f"Cannot locate crystal ligand `{ligand_comp_id}` in target for strict pocket validation") ref_center = coords.mean(axis=0) pocket_center = np.asarray(spec.center, dtype=float) dist = float(np.linalg.norm(ref_center - pocket_center)) if dist > 4.0: raise DockingError(f"Pocket validation failed: reference center distance {dist:.3f} A > 4.0 A") return { "pocket_mode": spec.mode, "pocket_source": spec.source, "pocket_center_x": float(spec.center[0]), "pocket_center_y": float(spec.center[1]), "pocket_center_z": float(spec.center[2]), "pocket_radius": float(spec.radius), "reference_center_distance_A": float(dist), } def _dock_multistage_batch( backend_name: str, backend: Any, target_context: Dict[str, Any], batch_df: pd.DataFrame, round_dir: Path, reference_id: str, cpu_samples: list[float] | None = None, cpu_highload_samples: list[float] | None = None, ) -> pd.DataFrame: round_dir.mkdir(parents=True, exist_ok=True) lig_dir = round_dir / "ligands" lig_dir.mkdir(parents=True, exist_ok=True) total_ligands = int(batch_df.shape[0]) lig_files: dict[str, Path] = {} failed_counts: dict[str, int] = {} prep_errors: dict[str, str] = {} for r in batch_df.itertuples(index=False): lid = str(r.ligand_id) failed_counts[lid] = 0 try: lig_files[lid] = backend.prepare_ligand(lid, str(r.smiles), lig_dir) except Exception as exc: failed_counts[lid] = failed_counts.get(lid, 0) + 1 prep_errors[lid] = str(exc) by_lig: dict[str, list[dict[str, Any]]] = {lid: [] for lid in lig_files} if not by_lig: raise DockingError(f"{backend_name}: all ligands failed preparation in batch") def run_attempts(stage: str, ligand_ids: List[str], n_attempts: int, effort_idx: int) -> None: if not ligand_ids or n_attempts <= 0: return for attempt in range(n_attempts): if backend_name == "rdock": backend.config.n_runs = [32, 48, 64][effort_idx] else: backend.config.exhaustiveness = [6, 8, 10][effort_idx] backend.config.num_modes = [4, 5, 6][effort_idx] backend.config.seed = 20260422 + effort_idx * 100 + attempt files = [lig_files[lid] for lid in ligand_ids] dock_cpu = CPUMonitor(interval_s=0.5) dock_cpu.start() try: docked = backend.dock( target_context=target_context, ligand_files=files, work_dir=round_dir / f"{stage}_attempt_{attempt:02d}", allow_mock=False, require_real_backend=True, ) finally: dock_cpu.stop() if dock_cpu.samples and cpu_samples is not None: cpu_samples.extend(dock_cpu.samples) if dock_cpu.samples and cpu_highload_samples is not None: highload_cutoff = max(4, int(math.ceil(0.8 * max(1, int(getattr(backend.config, "parallel_jobs", 1)))))) if len(files) >= highload_cutoff: cpu_highload_samples.extend(dock_cpu.samples) parsed = backend.parse_results(docked) for row in parsed: lid = str(row["ligand_id"]) if lid not in by_lig: continue score = float(row.get("docking_score", np.nan)) if (not bool(row.get("success", False))) or (not np.isfinite(score)): failed_counts[lid] = failed_counts.get(lid, 0) + 1 continue row["stage"] = stage row["attempt"] = int(attempt) by_lig[lid].append(row) all_ids = list(lig_files.keys()) run_attempts("screening", all_ids, n_attempts=2, effort_idx=0) screen_best = sorted( [(lid, min(float(r["docking_score"]) for r in rows)) for lid, rows in by_lig.items() if rows], key=lambda x: x[1], ) if not screen_best: raise DockingError(f"{backend_name}: no successful docking rows after screening attempts") promoted_n = max(1, int(math.ceil(0.30 * len(screen_best)))) promoted = [x[0] for x in screen_best[:promoted_n]] run_attempts("promoted", promoted, n_attempts=1, effort_idx=1) merged_best = sorted( [(lid, min(float(r["docking_score"]) for r in rows)) for lid, rows in by_lig.items() if rows], key=lambda x: x[1], ) final_n = max(1, int(math.ceil(0.10 * len(merged_best)))) final_ids = [x[0] for x in merged_best[:final_n]] if reference_id in all_ids and reference_id not in final_ids: final_ids.append(reference_id) run_attempts("final", final_ids, n_attempts=1, effort_idx=2) out_rows: list[dict[str, Any]] = [] for lid, rows in by_lig.items(): if not rows: continue vals = np.asarray([float(r["docking_score"]) for r in rows], dtype=float) best_idx = int(np.argmin(vals)) best_row = rows[best_idx] topk = np.sort(vals)[: min(3, len(vals))] out_rows.append( { "ligand_id": lid, "docking_score": float(np.min(vals)), "best_score": float(np.min(vals)), "topk_mean_score": float(np.mean(topk)), "score_spread": float(np.std(vals)) if vals.size > 1 else 0.0, "attempt_count": int(vals.size), "backend_name": str(best_row.get("backend_name", backend_name)), "backend_mode": str(best_row.get("backend_mode", f"real-{backend_name}")), "score_source": str(best_row.get("score_source", "")), "raw_output_file": str(best_row.get("raw_output_file", "")), "parsed_from": str(best_row.get("parsed_from", "")), "fallback_used": bool(best_row.get("fallback_used", False)), "success": True, "pose_in_fixed_pocket": bool(best_row.get("pose_in_fixed_pocket", False)), "pose_distance_to_pocket_center": float(best_row.get("pose_distance_to_pocket_center", np.nan)), "failed_attempts": int(failed_counts.get(lid, 0)), "prep_error": prep_errors.get(lid, ""), } ) out_df = pd.DataFrame(out_rows) if out_df.empty: raise DockingError(f"{backend_name}: batch produced zero successful docking rows") failed_ratio = 1.0 - (out_df.shape[0] / max(1, total_ligands)) if failed_ratio > 0.9: raise DockingError( f"{backend_name}: batch failure ratio too high ({failed_ratio:.2%}); aborting strict run" ) return out_df def _oracle_table(master_path: Path) -> pd.DataFrame: m = pd.read_csv(master_path)[["ligand_id", "docking_score"]].copy() m["ligand_id"] = m["ligand_id"].astype(str) m["docking_score"] = pd.to_numeric(m["docking_score"], errors="coerce") m = m.dropna(subset=["docking_score"]).sort_values("docking_score", ascending=True).reset_index(drop=True) m["rank"] = np.arange(1, m.shape[0] + 1) m["rank_percentile"] = 100.0 * m["rank"] / max(1, m.shape[0]) return m def _run_backend_adaptive( ds: StrictDataset, backend_name: str, output_root: Path, *, threads_used: int, system_threads: int, max_budget: int, min_budget: int, patience_rounds: int, min_improvement_abs: float, logger, ) -> tuple[pd.DataFrame, dict[str, Any], pd.DataFrame]: run_dir = output_root / ds.name / backend_name run_dir.mkdir(parents=True, exist_ok=True) lig_df = pd.read_csv(ds.shared_path).drop_duplicates(subset=["ligand_id"]).head(10000).copy() lig_df["ligand_id"] = lig_df["ligand_id"].astype(str) lig_df["smiles"] = lig_df["smiles"].astype(str) ref = _read_reference(ds.reference_csv) reference_id = str(ref["reference_id"]) ligand_comp_id = str(ref["ligand_comp_id"]) if reference_id not in set(lig_df["ligand_id"]): raise DockingError(f"{ds.name}: reference ligand `{reference_id}` not present in shared library") values_df, masks_df, cluster_map, hyper_map = _make_features(lig_df) scheduler = AdaptiveScheduler( config=SchedulerConfig( batch_size=max(36, int(5 * threads_used)), init_coverage_fraction=0.4, conservative_deprioritize=True, state_path=str(run_dir / "scheduler_state.json"), weight_schedule=WeightScheduleConfig(), ), surrogate_config=SurrogateConfig( prefer_xgboost=False, n_estimators=120, random_state=20260422, min_train_samples=12, max_depth_small=4, max_depth_large=6, ), ) scheduler.initialize(lig_df[["ligand_id"]], cluster_map, hyper_map) backend = _build_backend( backend_name=backend_name, threads_used=threads_used, work_dir=run_dir, pocket_reference_ligand_id=ligand_comp_id, ) cap = backend.check_capability() if not cap.available: raise DockingError(f"{backend_name} unavailable: {cap.details}") target_ctx = backend.prepare_target(ds.target_path, run_dir / "target") pocket_meta = _validate_fixed_pocket(target_ctx, ds.target_path, ligand_comp_id) eval_rows: list[dict[str, Any]] = [] batch_rows: list[dict[str, Any]] = [] best_so_far = float("inf") last_improve_round = 0 stop_reason = "max_budget" cpu_samples: list[float] = [] cpu_highload_samples: list[float] = [] t0 = time.time() try: round_idx = 0 evaluated_ids: set[str] = set() attempted_ids: set[str] = set() while len(attempted_ids) < int(max_budget): batch_ids = scheduler.select_batch() if not batch_ids: stop_reason = "queue_exhausted" break remain = int(max_budget) - len(attempted_ids) batch_ids = [bid for bid in batch_ids if bid not in attempted_ids][:remain] if not batch_ids: break if reference_id not in evaluated_ids and reference_id not in batch_ids: if len(batch_ids) < remain: batch_ids.append(reference_id) elif batch_ids: batch_ids[-1] = reference_id batch_ids = list(dict.fromkeys(batch_ids)) attempted_ids.update(batch_ids) batch_df = lig_df[lig_df["ligand_id"].isin(batch_ids)].copy().reset_index(drop=True) batch_eval = _dock_multistage_batch( backend_name=backend_name, backend=backend, target_context=target_ctx, batch_df=batch_df, round_dir=run_dir / f"round_{round_idx:04d}", reference_id=reference_id, cpu_samples=cpu_samples, cpu_highload_samples=cpu_highload_samples, ) batch_eval["round_idx"] = int(round_idx) eval_rows.extend(batch_eval.to_dict(orient="records")) evaluated_ids.update(batch_eval["ligand_id"].astype(str).tolist()) scheduler.update_from_batch(batch_eval[["ligand_id", "docking_score"]], values_df, masks_df) scheduler.save_state() round_best = float(pd.to_numeric(batch_eval["docking_score"], errors="coerce").min()) improved = (best_so_far - round_best) > float(min_improvement_abs) if improved: best_so_far = round_best last_improve_round = round_idx batch_rows.append( { "dataset": ds.name, "backend": backend_name, "round_idx": int(round_idx), "evaluated_total": int(len(attempted_ids)), "round_best_score": float(round_best), "best_score_so_far": float(best_so_far), "improved": bool(improved), } ) if len(attempted_ids) >= int(min_budget) and (round_idx - last_improve_round) >= int(patience_rounds): stop_reason = "epsilon_regret_plateau" break round_idx += 1 finally: pass wall_s = float(time.time() - t0) eval_df = pd.DataFrame(eval_rows) if eval_df.empty: raise DockingError(f"{ds.name}/{backend_name}: no docking rows generated") if reference_id not in set(eval_df["ligand_id"].astype(str)): ref_rows = lig_df[lig_df["ligand_id"].astype(str) == reference_id] if ref_rows.empty: raise DockingError(f"{ds.name}/{backend_name}: missing reference ligand row `{reference_id}` for rescue docking") ref_smiles = str(ref_rows.iloc[0]["smiles"]) rescue_dir = run_dir / "reference_rescue" rescue_lig_dir = rescue_dir / "ligands" rescue_lig_dir.mkdir(parents=True, exist_ok=True) rescue_file = backend.prepare_ligand(reference_id, ref_smiles, rescue_lig_dir) rescue_parsed_rows: list[dict[str, Any]] = [] rescue_attempts = 2 for ridx in range(rescue_attempts): if backend_name == "rdock": backend.config.n_runs = max(10, int(getattr(backend.config, "n_runs", 10))) else: backend.config.exhaustiveness = 4 backend.config.num_modes = 4 backend.config.seed = 303030 + ridx backend.config.command_timeout_seconds = max(60, int(getattr(backend.config, "command_timeout_seconds", 60))) rescue_cpu = CPUMonitor(interval_s=0.5) rescue_cpu.start() try: rescue_docked = backend.dock( target_context=target_ctx, ligand_files=[rescue_file], work_dir=rescue_dir / f"attempt_{ridx:02d}", allow_mock=False, require_real_backend=True, ) finally: rescue_cpu.stop() if rescue_cpu.samples: cpu_samples.extend(rescue_cpu.samples) cpu_highload_samples.extend(rescue_cpu.samples) rescue_parsed_rows.extend(backend.parse_results(rescue_docked)) good_rescue = [ row for row in rescue_parsed_rows if bool(row.get("success", False)) and np.isfinite(float(row.get("docking_score", np.nan))) ] if not good_rescue: raise DockingError(f"{ds.name}/{backend_name}: reference ligand `{reference_id}` rescue docking failed") rescue_scores = np.asarray([float(r["docking_score"]) for r in good_rescue], dtype=float) rescue_best = good_rescue[int(np.argmin(rescue_scores))] rescue_topk = np.sort(rescue_scores)[: min(3, len(rescue_scores))] eval_rows.append( { "ligand_id": reference_id, "docking_score": float(np.min(rescue_scores)), "best_score": float(np.min(rescue_scores)), "topk_mean_score": float(np.mean(rescue_topk)), "score_spread": float(np.std(rescue_scores)) if rescue_scores.size > 1 else 0.0, "attempt_count": int(len(rescue_scores)), "backend_name": str(rescue_best.get("backend_name", backend_name)), "backend_mode": str(rescue_best.get("backend_mode", f"real-{backend_name}")), "score_source": str(rescue_best.get("score_source", "")), "raw_output_file": str(rescue_best.get("raw_output_file", "")), "parsed_from": str(rescue_best.get("parsed_from", "")), "fallback_used": bool(rescue_best.get("fallback_used", False)), "success": True, "pose_in_fixed_pocket": bool(rescue_best.get("pose_in_fixed_pocket", False)), "pose_distance_to_pocket_center": float(rescue_best.get("pose_distance_to_pocket_center", np.nan)), "failed_attempts": 0, "prep_error": "", "round_idx": -1, } ) eval_df = pd.DataFrame(eval_rows) if (eval_df["attempt_count"].astype(int) <= 1).any(): raise DockingError(f"{ds.name}/{backend_name}: single-attempt ligands detected") if (eval_df["fallback_used"].astype(bool)).any(): raise DockingError(f"{ds.name}/{backend_name}: fallback rows detected") util_samples = cpu_highload_samples if cpu_highload_samples else cpu_samples if util_samples: cpu_arr = np.asarray(util_samples, dtype=float) cpu_stats = { "cpu_mean_pct": float(np.nanmean(cpu_arr)), "cpu_p10_pct": float(np.nanpercentile(cpu_arr, 10)), "cpu_min_pct": float(np.nanmin(cpu_arr)), } else: cpu_stats = {"cpu_mean_pct": float("nan"), "cpu_p10_pct": float("nan"), "cpu_min_pct": float("nan")} alloc_target_pct = 100.0 * (float(threads_used) / max(1.0, float(system_threads))) cpu_of_alloc = float("nan") if np.isfinite(cpu_stats["cpu_mean_pct"]) and alloc_target_pct > 0: cpu_of_alloc = float((cpu_stats["cpu_mean_pct"] / alloc_target_pct) * 100.0) if np.isfinite(cpu_of_alloc) and cpu_of_alloc < 60.0: raise DockingError( f"{ds.name}/{backend_name}: sustained CPU below threshold: mean={cpu_of_alloc:.2f}% of allocated thread capacity" ) oracle = _oracle_table(ds.oracle_master_path) merged = eval_df.merge(oracle[["ligand_id", "rank_percentile"]], on="ligand_id", how="left") merged["rank_percentile"] = pd.to_numeric(merged["rank_percentile"], errors="coerce") merged = merged.sort_values("docking_score", ascending=True).reset_index(drop=True) merged["step"] = np.arange(1, merged.shape[0] + 1) merged["run_rank_percentile"] = 100.0 * merged["step"] / max(1, merged.shape[0]) merged["best_score_so_far"] = merged["docking_score"].cummin() merged["top1pct_hit"] = (merged["rank_percentile"] <= 1.0).astype(float) merged["top01pct_hit"] = (merged["rank_percentile"] <= 0.1).astype(float) merged["top1pct_recovery"] = merged["top1pct_hit"].cumsum() / max(1.0, float((oracle["rank_percentile"] <= 1.0).sum())) merged["top01pct_recovery"] = merged["top01pct_hit"].cumsum() / max(1.0, float((oracle["rank_percentile"] <= 0.1).sum())) ref_sub = merged[merged["ligand_id"] == reference_id] if ref_sub.empty: raise DockingError(f"{ds.name}/{backend_name}: reference ligand `{reference_id}` was not successfully docked") ref_rank_pct, ref_rank_source = resolve_reference_rank_percentile( merged_df=merged, reference_ligand_id=reference_id, oracle_rank_col="rank_percentile", run_rank_col="run_rank_percentile", ) ref_score = float(ref_sub["docking_score"].iloc[0]) if not ref_sub.empty else float("nan") best_score = float(pd.to_numeric(merged["docking_score"], errors="coerce").min()) # Surrogate ROC/PR using oracle top10% as positive class. roc_auc = float("nan") pr_auc = float("nan") try: id_to_idx = {str(v): i for i, v in enumerate(values_df["ligand_id"].astype(str).tolist())} eval_ids = merged["ligand_id"].astype(str).tolist() idx = [id_to_idx[i] for i in eval_ids if i in id_to_idx] if idx and scheduler.surrogate.model is not None: x = values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)[idx] m = masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float)[idx] bundle = scheduler.surrogate.predict_bundle(x, m) pred = -np.asarray(bundle["expected_score"], dtype=float) y = (pd.to_numeric(merged["rank_percentile"], errors="coerce").to_numpy(dtype=float) <= 10.0).astype(int) if len(np.unique(y)) > 1: roc_auc = float(roc_auc_score(y, pred)) pr_auc = float(average_precision_score(y, pred)) fpr, tpr, _ = roc_curve(y, pred) prec, rec, _ = precision_recall_curve(y, pred) pd.DataFrame({"fpr": fpr, "tpr": tpr}).to_csv(run_dir / "roc_curve.csv", index=False) pd.DataFrame({"recall": rec, "precision": prec}).to_csv(run_dir / "pr_curve.csv", index=False) except Exception: pass metrics = { "dataset": ds.name, "target_name": ds.target_name, "backend": backend_name, "n_library": int(lig_df.shape[0]), "attempted_count": int(len(attempted_ids)), "evaluated_count": int(merged.shape[0]), "stop_reason": stop_reason, "reference_ligand_id": reference_id, "reference_ligand_rank_percentile": ref_rank_pct, "reference_ligand_rank_source": ref_rank_source, "reference_ligand_score": ref_score, "best_ligand_score": best_score, "top_1pct_recovery_final": float(merged["top1pct_recovery"].iloc[-1]), "top_0_1pct_recovery_final": float(merged["top01pct_recovery"].iloc[-1]), "roc_auc_surrogate": roc_auc, "pr_auc_surrogate": pr_auc, "docking_reduction_fraction": float(1.0 - (len(attempted_ids) / max(1, lig_df.shape[0]))), "runtime_seconds": wall_s, "runtime_per_ligand_seconds": float(wall_s / max(1, merged.shape[0])), "cpu_mean_pct": cpu_stats["cpu_mean_pct"], "cpu_p10_pct": cpu_stats["cpu_p10_pct"], "cpu_min_pct": cpu_stats["cpu_min_pct"], "cpu_sample_count": int(len(cpu_samples)), "cpu_highload_sample_count": int(len(cpu_highload_samples)), "cpu_alloc_target_pct": alloc_target_pct, "cpu_mean_pct_of_alloc": cpu_of_alloc, **pocket_meta, } pd.DataFrame(batch_rows).to_csv(run_dir / "batch_history.csv", index=False) merged.to_csv(run_dir / "evaluated_ligands.csv", index=False) return merged, metrics, pd.DataFrame(batch_rows) def _plot_all(out_dir: Path, combined: pd.DataFrame, metrics_df: pd.DataFrame) -> list[str]: pdir = out_dir / "plots" pdir.mkdir(parents=True, exist_ok=True) out: list[str] = [] if not combined.empty: plt.figure(figsize=(10, 5)) for (ds, bk), sub in combined.groupby(["dataset", "backend"]): sub = sub.sort_values("step") plt.plot(sub["step"], sub["docking_score"], alpha=0.6, label=f"{ds}:{bk}") plt.xlabel("step") plt.ylabel("score") plt.title("score vs step") plt.legend(fontsize=7, ncol=2) plt.tight_layout() p = pdir / "score_vs_step.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) plt.figure(figsize=(10, 5)) for (ds, bk), sub in combined.groupby(["dataset", "backend"]): sub = sub.sort_values("step") plt.plot(sub["step"], sub["best_score_so_far"], alpha=0.7, label=f"{ds}:{bk}") plt.xlabel("step") plt.ylabel("best score so far") plt.title("best score progression") plt.legend(fontsize=7, ncol=2) plt.tight_layout() p = pdir / "best_score_progression.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) plt.figure(figsize=(10, 5)) for (ds, bk), sub in combined.groupby(["dataset", "backend"]): sub = sub.sort_values("step") plt.plot(sub["step"], sub["top1pct_recovery"], alpha=0.7, label=f"{ds}:{bk}:top1%") plt.plot(sub["step"], sub["top01pct_recovery"], alpha=0.5, linestyle="--", label=f"{ds}:{bk}:top0.1%") plt.xlabel("step") plt.ylabel("recovery") plt.title("top-k recovery") plt.legend(fontsize=6, ncol=2) plt.tight_layout() p = pdir / "topk_recovery.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) if not metrics_df.empty: plt.figure(figsize=(8, 4)) x = np.arange(metrics_df.shape[0]) plt.bar(x, pd.to_numeric(metrics_df["runtime_per_ligand_seconds"], errors="coerce")) plt.xticks(x, metrics_df["dataset"].astype(str) + ":" + metrics_df["backend"].astype(str), rotation=25, ha="right") plt.ylabel("runtime per ligand (s)") plt.title("backend comparison") plt.tight_layout() p = pdir / "backend_comparison.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) plt.figure(figsize=(8, 4)) x = np.arange(metrics_df.shape[0]) plt.bar(x - 0.2, pd.to_numeric(metrics_df["reference_ligand_score"], errors="coerce"), width=0.4, label="reference") plt.bar(x + 0.2, pd.to_numeric(metrics_df["best_ligand_score"], errors="coerce"), width=0.4, label="best") plt.xticks(x, metrics_df["dataset"].astype(str) + ":" + metrics_df["backend"].astype(str), rotation=25, ha="right") plt.ylabel("score") plt.title("reference vs best") plt.legend(fontsize=8) plt.tight_layout() p = pdir / "reference_vs_best.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) roc = metrics_df.dropna(subset=["roc_auc_surrogate"]) if not roc.empty: plt.figure(figsize=(8, 4)) x = np.arange(roc.shape[0]) plt.bar(x - 0.2, roc["roc_auc_surrogate"], width=0.4, label="ROC AUC") plt.bar(x + 0.2, roc["pr_auc_surrogate"], width=0.4, label="PR AUC") plt.xticks(x, roc["dataset"].astype(str) + ":" + roc["backend"].astype(str), rotation=25, ha="right") plt.ylim(0, 1) plt.title("surrogate ROC/PR") plt.legend(fontsize=8) plt.tight_layout() p = pdir / "roc_curve.png" plt.savefig(p, dpi=150) plt.close() out.append(str(p)) return out def run_final_strict_run( output_dir: str | Path = ROOT_DIR / "results/final_strict_run", *, subset_size: int = 1000, max_budget: int = 10000, min_budget: int = 60, patience_rounds: int = 3, min_improvement_abs: float = 0.25, backends: list[str] | None = None, enforce_redocking_gate: bool = True, ) -> dict[str, Any]: logger = get_logger("final_strict_run") out_dir = Path(output_dir) out_dir.mkdir(parents=True, exist_ok=True) snap0 = snapshot_disk_state(ROOT_DIR, "final_strict_run_start", "before strict full run", projected_output_gb=6.0) append_disk_snapshot(ROOT_DIR / "results/disk_usage_before_after.csv", snap0) agents = ROOT_DIR / "AGENTS.md" if not agents.exists(): raise RuntimeError("AGENTS.md not found") # Hard backend cleanup checks. forbidden_bins = {k: shutil.which(k) for k in ["vina", "gnina", "haddock3-score"]} if (ROOT_DIR / "libs/docking/backend_haddock.py").exists(): raise RuntimeError("Forbidden backend wrapper still present: libs/docking/backend_haddock.py") system_threads = max(1, int(os.cpu_count() or 1)) threads_used = max(1, int(math.floor(0.85 * system_threads))) strict_catalog = _strict_dataset_catalog() if enforce_redocking_gate: _assert_redocking_gate(strict_catalog) datasets = _prepare_new_dataset_views( ROOT_DIR / "data/ligands/final_strict_run", strict_catalog, subset_size=int(subset_size), logger=logger, ) dataset_manifest_rows = [] for ds in datasets: lig = pd.read_csv(ds.shared_path) ref = _read_reference(ds.reference_csv) dataset_manifest_rows.append( { "dataset": ds.name, "target_name": ds.target_name, "target_path": str(ds.target_path), "library_size": int(lig.shape[0]), "reference_ligand_id": ref["reference_id"], "reference_present": bool(ref["reference_id"] in set(lig["ligand_id"].astype(str))), "source_shared": str(ds.shared_path), } ) pd.DataFrame(dataset_manifest_rows).to_csv(out_dir / "datasets_manifest.csv", index=False) requested_backends: list[str] = [] for b in (backends or ["rdock", "smina"]): bb = str(b).strip().lower() if bb and bb not in requested_backends: requested_backends.append(bb) allowed_backends = {"rdock", "smina"} if not requested_backends: raise RuntimeError("No backends selected") invalid = [b for b in requested_backends if b not in allowed_backends] if invalid: raise RuntimeError(f"Unsupported backends requested: {invalid}. Allowed: {sorted(allowed_backends)}") all_eval: list[pd.DataFrame] = [] all_metrics: list[dict[str, Any]] = [] all_batches: list[pd.DataFrame] = [] for ds in datasets: for backend in requested_backends: logger.info("Running strict adaptive benchmark dataset=%s backend=%s", ds.name, backend) eval_df, metrics, batch_df = _run_backend_adaptive( ds=ds, backend_name=backend, output_root=out_dir, threads_used=threads_used, system_threads=system_threads, max_budget=max_budget, min_budget=min_budget, patience_rounds=patience_rounds, min_improvement_abs=min_improvement_abs, logger=logger, ) all_eval.append(eval_df.assign(dataset=ds.name, backend=backend)) all_metrics.append(metrics) all_batches.append(batch_df) combined = pd.concat(all_eval, ignore_index=True) if all_eval else pd.DataFrame() metrics_df = pd.DataFrame(all_metrics) batch_df = pd.concat(all_batches, ignore_index=True) if all_batches else pd.DataFrame() combined.to_csv(out_dir / "all_evaluated_ligands.csv", index=False) metrics_df.to_csv(out_dir / "per_dataset_metrics.csv", index=False) batch_df.to_csv(out_dir / "batch_history.csv", index=False) metrics_df.to_csv(out_dir / "backend_comparison.csv", index=False) metrics_df[ [ "dataset", "target_name", "backend", "reference_ligand_id", "reference_ligand_rank_percentile", "reference_ligand_score", "best_ligand_score", "pocket_mode", "pocket_source", "reference_center_distance_A", ] ].to_csv(out_dir / "reference_ligand_diagnostics.csv", index=False) plots = _plot_all(out_dir, combined, metrics_df) summary = { "run_name": "final_strict_run", "datasets": [d.name for d in datasets], "backends_active": requested_backends, "system_threads": system_threads, "threads_used": threads_used, "thread_formula": "threads_used = floor(0.85 * system_threads)", "forbidden_binaries": forbidden_bins, "max_budget": int(max_budget), "subset_size": int(subset_size), "min_budget": int(min_budget), "num_rows_metrics": int(metrics_df.shape[0]), "plots": plots, } (out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") issues: list[str] = [] active_backends = set(summary["backends_active"]) if not active_backends or not active_backends.issubset(allowed_backends): issues.append("active backends must be a non-empty subset of {'rdock','smina'}") if any((ROOT_DIR / p).exists() for p in ["libs/docking/backend_haddock.py"]): issues.append("forbidden backend wrapper still exists") if not metrics_df.empty: if (metrics_df["reference_center_distance_A"] > 4.0).any(): issues.append("fixed pocket validation failed on one or more runs") if (metrics_df["cpu_mean_pct_of_alloc"] < 70.0).any(): issues.append("CPU utilization below 70% of allocated thread capacity for one or more runs") if (metrics_df["evaluated_count"] <= 0).any(): issues.append("empty evaluated run detected") if combined.empty: issues.append("no evaluated ligands produced") for req in [ out_dir / "summary.json", out_dir / "per_dataset_metrics.csv", out_dir / "backend_comparison.csv", out_dir / "reference_ligand_diagnostics.csv", ]: if not req.exists(): issues.append(f"missing output: {req}") audit = [ "# Self Audit Report", "", f"- only allowed backends active: `{bool(set(summary['backends_active'])) and set(summary['backends_active']).issubset({'rdock', 'smina'})}`", f"- forbidden backend wrappers removed: `{not (ROOT_DIR / 'libs/docking/backend_haddock.py').exists()}`", f"- fixed pocket source strict reference: `{False if metrics_df.empty else bool((metrics_df['pocket_source'] == 'reference_complex_ligand').all())}`", f"- reference center distance <= 4A: `{False if metrics_df.empty else bool((metrics_df['reference_center_distance_A'] <= 4.0).all())}`", f"- multi-docking active: `{False if combined.empty else bool((combined['attempt_count'] > 1).all())}`", f"- cpu utilization >= 60% of allocated capacity: `{False if metrics_df.empty else bool((metrics_df['cpu_mean_pct_of_alloc'] >= 60.0).all())}`", f"- adaptive stop reasons present: `{False if metrics_df.empty else bool(metrics_df['stop_reason'].notna().all())}`", "", "## Issues", ] if issues: audit.extend([f"- {x}" for x in issues]) else: audit.append("- none") (out_dir / "self_audit_report.md").write_text("\n".join(audit) + "\n", encoding="utf-8") snap1 = snapshot_disk_state(ROOT_DIR, "final_strict_run_end", "after strict full run", projected_output_gb=0.0) append_disk_snapshot(ROOT_DIR / "results/disk_usage_before_after.csv", snap1) return summary def main() -> int: parser = argparse.ArgumentParser(description="Strict final run: rDock + smina only") parser.add_argument("--output-dir", default=str(ROOT_DIR / "results/final_strict_run")) parser.add_argument("--subset-size", type=int, default=1000) parser.add_argument("--max-budget", type=int, default=10000) parser.add_argument("--min-budget", type=int, default=60) parser.add_argument("--patience-rounds", type=int, default=3) parser.add_argument("--min-improvement-abs", type=float, default=0.25) parser.add_argument("--backends", nargs="+", choices=["rdock", "smina"], default=["rdock", "smina"]) parser.add_argument("--skip-redocking-gate", action="store_true") args = parser.parse_args() summary = run_final_strict_run( output_dir=args.output_dir, subset_size=args.subset_size, max_budget=args.max_budget, min_budget=args.min_budget, patience_rounds=args.patience_rounds, min_improvement_abs=args.min_improvement_abs, backends=args.backends, enforce_redocking_gate=not bool(args.skip_redocking_gate), ) print(json.dumps(summary, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())