from __future__ import annotations import argparse import json import math import random import shutil import sys import time import urllib.parse from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Iterable, List, Sequence 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 requests from rdkit import Chem, DataStructs from rdkit.Chem import AllChem from rdkit.Chem.Scaffolds import MurckoScaffold from sklearn import metrics as sk_metrics from environment.doctor import run_doctor from libs.adaptive.clustering import cluster_ligands_butina from libs.adaptive.features import ( FeatureBundle, FeatureValue, build_complex_feature_bundle, build_ligand_feature_bundle, build_protein_feature_bundle, build_rdock_feature_bundle, bundles_to_wide_frames, compute_feature_diagnostics, merge_bundles, ) from libs.adaptive.hyperclustering import hypercluster_representatives from libs.adaptive.metrics import enrichment_metrics from libs.adaptive.policies import PrioritizationPolicy from libs.adaptive.scheduler import AdaptiveScheduler, SchedulerConfig from libs.adaptive.surrogate_model import SurrogateConfig from libs.adaptive.weight_schedule import WeightScheduleConfig from libs.benchmark.runtime import enforce_thread_fairness from libs.docking.backend_rdock import RDockBackend, RDockConfig from libs.docking.base import DockingError from libs.encoders.ligand_encoder import LigandEncoder, LigandEncoderConfig from libs.encoders.protein_encoder import ProteinEncoder from libs.utils.config import load_config from libs.utils.logging_utils import get_logger @dataclass class StageTimer: name: str start: float end: float @property def seconds(self) -> float: return float(self.end - self.start) def _time_stage(name: str, fn): t0 = time.time() result = fn() t1 = time.time() return result, StageTimer(name=name, start=t0, end=t1) def _canonicalize_smiles(smiles: str) -> str | None: mol = Chem.MolFromSmiles(smiles) if mol is None: return None return Chem.MolToSmiles(mol, canonical=True) def _morgan_bv(smiles: str, nbits: int = 2048): mol = Chem.MolFromSmiles(smiles) if mol is None: return None return AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=nbits) def _tanimoto(smiles_a: str, smiles_b: str) -> float: fp_a = _morgan_bv(smiles_a) fp_b = _morgan_bv(smiles_b) if fp_a is None or fp_b is None: return 0.0 return float(DataStructs.TanimotoSimilarity(fp_a, fp_b)) def _scaffold_smiles(smiles: str) -> str | None: mol = Chem.MolFromSmiles(smiles) if mol is None: return None try: return MurckoScaffold.MurckoScaffoldSmiles(mol=mol) except Exception: return None def _chemcomp_info(comp_id: str) -> Dict[str, Any]: r = requests.get(f"https://data.rcsb.org/rest/v1/core/chemcomp/{comp_id}", timeout=30) r.raise_for_status() d = r.json() desc = d.get("rcsb_chem_comp_descriptor", {}) smiles = desc.get("SMILES_stereo") or desc.get("SMILES") return { "comp_id": comp_id, "name": d.get("chem_comp", {}).get("name"), "formula_weight": d.get("chem_comp", {}).get("formula_weight"), "smiles": smiles, "inchi_key": desc.get("InChIKey"), } def _entry_resolution_and_title(pdb_id: str) -> Dict[str, Any]: r = requests.get(f"https://data.rcsb.org/rest/v1/core/entry/{pdb_id}", timeout=30) r.raise_for_status() d = r.json() return { "resolution": (d.get("rcsb_entry_info", {}).get("resolution_combined") or [None])[0], "title": d.get("struct", {}).get("title", ""), } def _download_pdb(pdb_id: str, out_path: Path) -> Path: out_path.parent.mkdir(parents=True, exist_ok=True) url = f"https://files.rcsb.org/download/{pdb_id}.pdb" r = requests.get(url, timeout=60) r.raise_for_status() out_path.write_text(r.text, encoding="utf-8") return out_path def _pubchem_similarity_cids(smiles: str, threshold: int, max_records: int) -> list[int]: enc = urllib.parse.quote(smiles, safe="") url = ( "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/" f"{enc}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}" ) r = requests.get(url, timeout=120) if r.status_code != 200: return [] d = r.json() return [int(x) for x in d.get("IdentifierList", {}).get("CID", [])] def _pubchem_properties_for_cids(cids: Sequence[int]) -> pd.DataFrame: if not cids: return pd.DataFrame(columns=["cid", "smiles", "molecular_formula", "molecular_weight"]) rows: list[dict[str, Any]] = [] chunk_size = 100 for i in range(0, len(cids), chunk_size): chunk = cids[i : i + chunk_size] joined = ",".join(str(x) for x in chunk) url = ( "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" f"{joined}/property/SMILES,ConnectivitySMILES,MolecularFormula,MolecularWeight/JSON" ) r = requests.get(url, timeout=120) if r.status_code != 200: continue props = r.json().get("PropertyTable", {}).get("Properties", []) for p in props: rows.append( { "cid": int(p.get("CID")), "smiles": str(p.get("SMILES") or p.get("ConnectivitySMILES") or ""), "molecular_formula": p.get("MolecularFormula"), "molecular_weight": p.get("MolecularWeight"), } ) return pd.DataFrame(rows) def _fetch_chembl_target_activities(target_chembl_id: str = "CHEMBL5023", max_rows: int = 20000) -> pd.DataFrame: rows: list[dict[str, Any]] = [] limit = 1000 offset = 0 while len(rows) < max_rows: url = ( "https://www.ebi.ac.uk/chembl/api/data/activity.json" f"?target_chembl_id={target_chembl_id}&limit={limit}&offset={offset}" ) r = requests.get(url, timeout=120) if r.status_code != 200: break d = r.json() acts = d.get("activities", []) if not acts: break for a in acts: smi = a.get("canonical_smiles") if not smi: continue csm = _canonicalize_smiles(str(smi)) if csm is None: continue std_type = str(a.get("standard_type") or "") std_units = str(a.get("standard_units") or "") std_value = a.get("standard_value") try: std_value = float(std_value) except Exception: std_value = np.nan pchembl = a.get("pchembl_value") try: pchembl = float(pchembl) except Exception: pchembl = np.nan rows.append( { "canonical_smiles": csm, "molecule_chembl_id": a.get("molecule_chembl_id"), "assay_chembl_id": a.get("assay_chembl_id"), "standard_type": std_type, "standard_relation": a.get("standard_relation"), "standard_units": std_units, "standard_value": std_value, "pchembl_value": pchembl, } ) offset += limit if d.get("page_meta", {}).get("next") is None: break if not rows: return pd.DataFrame( columns=[ "canonical_smiles", "molecule_chembl_id", "assay_chembl_id", "standard_type", "standard_relation", "standard_units", "standard_value", "pchembl_value", ] ) out = pd.DataFrame(rows) out = out[out["standard_type"].isin(["IC50", "Ki", "Kd", "EC50"])] out = out[np.isfinite(pd.to_numeric(out["standard_value"], errors="coerce"))] return out.reset_index(drop=True) def _ranked_similarity_table(reference_smiles: str, props_df: pd.DataFrame, min_similarity: float) -> pd.DataFrame: ref_c = _canonicalize_smiles(reference_smiles) if ref_c is None or props_df.empty: return pd.DataFrame() ref_fp = _morgan_bv(ref_c) if ref_fp is None: return pd.DataFrame() records = [] for row in props_df.itertuples(index=False): smi = _canonicalize_smiles(str(row.smiles)) if smi is None: continue fp = _morgan_bv(smi) if fp is None: continue sim = float(DataStructs.TanimotoSimilarity(ref_fp, fp)) if sim < min_similarity: continue records.append( { "cid": int(row.cid), "smiles": smi, "similarity_to_reference": sim, "molecular_formula": row.molecular_formula, "molecular_weight": row.molecular_weight, "scaffold_smiles": _scaffold_smiles(smi), } ) if not records: return pd.DataFrame() return pd.DataFrame(records).sort_values("similarity_to_reference", ascending=False).reset_index(drop=True) def _build_dataset(config: Dict[str, Any], root: Path, logger) -> Dict[str, Any]: dataset_cfg = config["benchmark_dataset"] refs_cfg = config["references"]["complexes"] out_dir = root / dataset_cfg["output_dir"] out_dir.mkdir(parents=True, exist_ok=True) target_dir = root / "data" / "targets" / "experimental_benchmark" target_dir.mkdir(parents=True, exist_ok=True) reuse_existing = bool(dataset_cfg.get("reuse_existing", True)) reference_path = out_dir / "reference_ligands.csv" expanded_path = out_dir / "expanded_ligand_set.csv" dedup_path = out_dir / "expanded_ligand_set_dedup.csv" scaffold_path = out_dir / "scaffold_annotations.csv" provenance_path = out_dir / "ligand_provenance.csv" affinity_path = root / "data" / "benchmarks" / "experimental_affinity.csv" affinity_norm_path = root / "data" / "benchmarks" / "experimental_affinity_normalized.csv" metadata_path = root / "data" / "benchmarks" / "experimental_metadata.csv" docking_target_path = root / config["target"]["docking_target_path"] docking_ref = str(config["target"]["docking_reference_pdb"]) if reuse_existing: needed = [ reference_path, expanded_path, dedup_path, scaffold_path, provenance_path, affinity_path, affinity_norm_path, metadata_path, ] if all(p.exists() for p in needed): if not docking_target_path.exists(): _download_pdb(docking_ref, docking_target_path) logger.info("Reusing existing benchmark dataset from %s", out_dir) return { "reference_df": pd.read_csv(reference_path), "expanded_df": pd.read_csv(expanded_path), "dedup_df": pd.read_csv(dedup_path), "scaffold_df": pd.read_csv(scaffold_path), "provenance_df": pd.read_csv(provenance_path), "affinity_df": pd.read_csv(affinity_path), "affinity_norm_df": pd.read_csv(affinity_norm_path), "metadata_df": pd.read_csv(metadata_path), "out_dir": out_dir, "target_path": docking_target_path, } # 1) Reference selection metadata. reference_rows = [] for ref in refs_cfg: pdb_id = str(ref["pdb_id"]) comp_id = str(ref["ligand_comp_id"]) ref_id = str(ref["reference_id"]) entry = _entry_resolution_and_title(pdb_id) chem = _chemcomp_info(comp_id) csm = _canonicalize_smiles(str(chem["smiles"])) if csm is None: raise RuntimeError(f"Invalid reference SMILES from RCSB for {pdb_id}:{comp_id}") reference_rows.append( { "reference_id": ref_id, "pdb_id": pdb_id, "ligand_comp_id": comp_id, "ligand_name": chem["name"], "reference_smiles": csm, "reference_inchikey": chem["inchi_key"], "reference_mw": chem["formula_weight"], "resolution": entry["resolution"], "structure_title": entry["title"], } ) reference_df = pd.DataFrame(reference_rows) reference_df.to_csv(reference_path, index=False) # 2) Download docking target structure. _download_pdb(docking_ref, docking_target_path) # 3) Expand ligand set by reference similarity retrieval. per_ref_target = int(dataset_cfg["per_reference_target"]) max_records = int(dataset_cfg["pubchem_max_records"]) base_threshold = int(dataset_cfg["pubchem_similarity_threshold"]) min_similarity = float(dataset_cfg["min_similarity_keep"]) expanded_rows: list[dict[str, Any]] = [] provenance_rows: list[dict[str, Any]] = [] for ref in reference_df.itertuples(index=False): ref_id = str(ref.reference_id) ref_smiles = str(ref.reference_smiles) ref_scaffold = _scaffold_smiles(ref_smiles) threshold_ladder = [base_threshold, base_threshold - 5, base_threshold - 10, base_threshold - 15, base_threshold - 20] threshold_ladder = [max(50, int(x)) for x in threshold_ladder] collected: dict[str, dict[str, Any]] = {} for thr in threshold_ladder: if len(collected) >= per_ref_target: break cids = _pubchem_similarity_cids(ref_smiles, threshold=thr, max_records=max_records) if not cids: continue props_df = _pubchem_properties_for_cids(cids) sim_df = _ranked_similarity_table(ref_smiles, props_df, min_similarity=min_similarity) if sim_df.empty: continue for row in sim_df.itertuples(index=False): smi = str(row.smiles) if smi in collected: continue lig_id = f"{ref_id}_cid{int(row.cid)}" scaffold_match = 1 if _scaffold_smiles(smi) == ref_scaffold else 0 collected[smi] = { "ligand_id": lig_id, "source": "retrieved", "parent_reference_ligand": ref_id, "smiles": smi, "valid": True, "similarity_to_reference": float(row.similarity_to_reference), "scaffold_core": row.scaffold_smiles, "scaffold_match": int(scaffold_match), "pubchem_cid": int(row.cid), "retrieval_threshold": thr, "is_reference": False, } if len(collected) >= per_ref_target: break # Ensure original reference is included and traceable. if ref_smiles not in collected: collected[ref_smiles] = { "ligand_id": ref_id, "source": "reference", "parent_reference_ligand": ref_id, "smiles": ref_smiles, "valid": True, "similarity_to_reference": 1.0, "scaffold_core": ref_scaffold, "scaffold_match": 1, "pubchem_cid": np.nan, "retrieval_threshold": np.nan, "is_reference": True, } else: collected[ref_smiles]["is_reference"] = True collected[ref_smiles]["source"] = "reference" collected[ref_smiles]["ligand_id"] = ref_id collected[ref_smiles]["similarity_to_reference"] = 1.0 # If still short, keep what we got; documented later. rows = list(collected.values()) for idx, row in enumerate(rows): if row["source"] != "reference": row["ligand_id"] = f"{ref_id}_{idx:05d}" expanded_rows.append(row) provenance_rows.append( { "ligand_id": row["ligand_id"], "parent_reference_ligand": row["parent_reference_ligand"], "source": row["source"], "pubchem_cid": row["pubchem_cid"], "retrieval_threshold": row["retrieval_threshold"], "valid": row["valid"], } ) logger.info("Reference %s collected %s ligands", ref_id, len(rows)) expanded_df = pd.DataFrame(expanded_rows) expanded_df = expanded_df.sort_values(["parent_reference_ligand", "similarity_to_reference"], ascending=[True, False]).reset_index(drop=True) expanded_df.to_csv(expanded_path, index=False) # 4) Global deduplication by canonical SMILES. dedup_df = ( expanded_df.sort_values(["similarity_to_reference", "source"], ascending=[False, True]) .drop_duplicates(subset=["smiles"], keep="first") .reset_index(drop=True) ) # Ensure all 3 references are present in dedup set. for ref in reference_df.itertuples(index=False): ref_smiles = str(ref.reference_smiles) ref_id = str(ref.reference_id) if (dedup_df["smiles"] == ref_smiles).any(): mask = dedup_df["smiles"] == ref_smiles dedup_df.loc[mask, "ligand_id"] = ref_id dedup_df.loc[mask, "source"] = "reference" dedup_df.loc[mask, "is_reference"] = True dedup_df.to_csv(dedup_path, index=False) scaffold_annotations = dedup_df[ ["ligand_id", "parent_reference_ligand", "scaffold_core", "scaffold_match", "similarity_to_reference"] ].copy() scaffold_annotations.to_csv(scaffold_path, index=False) ligand_provenance_df = pd.DataFrame(provenance_rows) ligand_provenance_df.to_csv(provenance_path, index=False) # 5) Affinity retrieval from ChEMBL where available. chembl_df = _fetch_chembl_target_activities(target_chembl_id="CHEMBL5023", max_rows=25000) affinity_rows = [] if not chembl_df.empty: grouped = ( chembl_df.groupby(["canonical_smiles", "standard_type", "standard_units"], as_index=False) .agg( standard_value_median=("standard_value", "median"), pchembl_value_median=("pchembl_value", "median"), measurements=("standard_value", "count"), ) .reset_index(drop=True) ) lookup = grouped.sort_values("measurements", ascending=False).drop_duplicates(subset=["canonical_smiles"], keep="first") lookup = lookup.set_index("canonical_smiles") for row in dedup_df.itertuples(index=False): smi = str(row.smiles) if smi not in lookup.index: continue v = lookup.loc[smi] affinity_rows.append( { "ligand_id": row.ligand_id, "smiles": smi, "parent_reference_ligand": row.parent_reference_ligand, "standard_type": v["standard_type"], "standard_units": v["standard_units"], "standard_value_median": float(v["standard_value_median"]), "pchembl_value_median": float(v["pchembl_value_median"]) if np.isfinite(v["pchembl_value_median"]) else np.nan, "measurements": int(v["measurements"]), "source": "chembl", } ) affinity_df = pd.DataFrame(affinity_rows) affinity_path.parent.mkdir(parents=True, exist_ok=True) affinity_df.to_csv(affinity_path, index=False) if affinity_df.empty: affinity_norm_df = pd.DataFrame( columns=[ "ligand_id", "smiles", "parent_reference_ligand", "standard_type", "standard_value_median", "pchembl_value_median", "pchembl_zscore", "pchembl_minmax", ] ) else: vals = pd.to_numeric(affinity_df["pchembl_value_median"], errors="coerce") mean = float(vals.mean()) if np.isfinite(vals).any() else 0.0 std = float(vals.std()) if np.isfinite(vals).any() else 1.0 vmin = float(vals.min()) if np.isfinite(vals).any() else 0.0 vmax = float(vals.max()) if np.isfinite(vals).any() else 1.0 affinity_norm_df = affinity_df.copy() affinity_norm_df["pchembl_zscore"] = (vals - mean) / (std if std > 1e-9 else 1.0) affinity_norm_df["pchembl_minmax"] = (vals - vmin) / (max(1e-9, vmax - vmin)) affinity_norm_df.to_csv(affinity_norm_path, index=False) metadata_rows = [] for ref in reference_df.itertuples(index=False): count_ref = int((expanded_df["parent_reference_ligand"] == ref.reference_id).sum()) metadata_rows.append( { "target_name": config["target"]["protein_name"], "target_id": config["target"]["target_id"], "reference_id": ref.reference_id, "pdb_id": ref.pdb_id, "ligand_comp_id": ref.ligand_comp_id, "reference_smiles": ref.reference_smiles, "reference_resolution": ref.resolution, "reference_title": ref.structure_title, "ligand_count_before_dedup": count_ref, "dataset_build_date": pd.Timestamp.utcnow().isoformat(), } ) metadata_df = pd.DataFrame(metadata_rows) metadata_df.to_csv(metadata_path, index=False) return { "reference_df": reference_df, "expanded_df": expanded_df, "dedup_df": dedup_df, "scaffold_df": scaffold_annotations, "provenance_df": ligand_provenance_df, "affinity_df": affinity_df, "affinity_norm_df": affinity_norm_df, "metadata_df": metadata_df, "out_dir": out_dir, "target_path": docking_target_path, } def _write_target_selection_markdown(config: Dict[str, Any], dataset_info: Dict[str, Any], output_dir: Path) -> Path: refs = dataset_info["reference_df"] lines = [ "# Target Selection", "", f"Chosen target: `{config['target']['protein_name']}` (`{config['target']['target_id']}`)", "", "Selected experimental complexes:", ] for row in refs.itertuples(index=False): lines.extend( [ f"- `{row.pdb_id}` ligand `{row.ligand_comp_id}` ({row.reference_id})", f" - Resolution: `{row.resolution}`", f" - Ligand name: `{row.ligand_name}`", f" - SMILES: `{row.reference_smiles}`", ] ) lines.extend( [ "", "Why selected:", "- All three complexes correspond to the same target protein (MDM2).", "- High-resolution crystal structures with resolved bound small-molecule ligands.", "- The three ligands represent related but non-identical chemotypes suitable for analog recovery benchmarking.", "- MDM2 has substantial public medicinal chemistry data enabling large similarity-based expansion.", ] ) path = output_dir / "target_selection.md" path.write_text("\n".join(lines), encoding="utf-8") return path def _cluster_bundle(ligand_id: str, cluster_id: int, hypercluster_id: int) -> FeatureBundle: return FeatureBundle( object_id=ligand_id, features={ "cluster_id_feature": FeatureValue(float(cluster_id), True, "clustering", "exact"), "hypercluster_id_feature": FeatureValue(float(hypercluster_id), True, "clustering", "exact"), }, ) def _build_initial_feature_bundles( ligands_df: pd.DataFrame, ligand_encodings, protein_encoding, cluster_map: Dict[str, int], hyper_map: Dict[int, int], ) -> tuple[FeatureBundle, Dict[str, FeatureBundle], List[str]]: # Use first reference ligand as comparison anchor for similarity features. reference_smiles = str(ligands_df.loc[ligands_df["is_reference"].astype(bool), "smiles"].iloc[0]) reference_mol = Chem.MolFromSmiles(reference_smiles) protein_bundle = build_protein_feature_bundle( target_id=str(protein_encoding.target_id), sequence_features=protein_encoding.sequence_features, structure_features=protein_encoding.structure_features, ) bundles: Dict[str, FeatureBundle] = {} ligand_ids = [] for enc in ligand_encodings: ligand_ids.append(enc.ligand_id) intrinsic = build_ligand_feature_bundle( ligand_id=enc.ligand_id, smiles=enc.smiles, fingerprint=enc.fingerprint, reference_mol=reference_mol, ) cluster_bundle = _cluster_bundle(enc.ligand_id, int(cluster_map[enc.ligand_id]), int(hyper_map.get(cluster_map[enc.ligand_id], -1))) bundles[enc.ligand_id] = merge_bundles(enc.ligand_id, [intrinsic, protein_bundle, cluster_bundle]) _, _, feature_names = bundles_to_wide_frames([bundles[lid] for lid in ligand_ids]) return protein_bundle, bundles, feature_names def _strict_backend_check(parsed_rows: Sequence[Dict[str, Any]]) -> None: bad = [ r for r in parsed_rows if r.get("backend_mode") != "real-rdock" or bool(r.get("fallback_used")) or not str(r.get("score_source", "")).startswith("rdock_tag:") ] if bad: raise DockingError(f"Strict backend violation detected: {bad[:2]}") def _prepare_backend(config: Dict[str, Any], command_log_path: Path) -> RDockBackend: alloc = enforce_thread_fairness(config) logger = get_logger("backend_setup") logger.info( "Thread fairness enforced: policy=%s system_threads=%s reserve=%s threads_used=%s", alloc.policy, alloc.system_threads, alloc.reserve_threads, alloc.threads_used, ) return RDockBackend( RDockConfig( n_runs=int(config["backend"].get("n_runs", 1)), mapper_radius=float(config["backend"].get("mapper_radius", 6.0)), command_timeout_seconds=int(config["backend"].get("command_timeout_seconds", 180)), parallel_jobs=int(config["backend"].get("parallel_jobs", 1)), allow_partial_failures=bool(config["backend"].get("allow_skip_failed_ligands", False)), protocol_prm=config["backend"].get("protocol_prm"), rbt_root=config["backend"].get("rbt_root"), command_log_path=str(command_log_path), pocket_mode=str(config["backend"].get("pocket_mode", "reference_complex_pocket")), pocket_center=config["backend"].get("pocket_center"), pocket_box_size=config["backend"].get("pocket_box_size"), pocket_radius=config["backend"].get("pocket_radius"), pocket_reference_ligand_id=config["backend"].get("pocket_reference_ligand_id"), pocket_relaxation_margin=float(config["backend"].get("pocket_relaxation_margin", 0.0)), ) ) def _compute_final_score( docking_score: float, interface_contact_proxy: float, interaction_decomp: float | None, burial_ratio: float | None, rdock_row: Dict[str, Any], feature_mode: str, score_variant: str, ) -> tuple[float, float]: """ Return (feature_rescore, final_score). `docking_only`: - `top1`: final_score = docking_score - `multipose`: uses rDock-native multi-pose stats only `full_feature`: - keeps existing rich feature rescoring and interface term. """ mode = str(feature_mode).strip().lower() variant = str(score_variant).strip().lower() if mode == "docking_only": if variant == "top1": return 0.0, float(docking_score) mean_top3 = float(rdock_row.get("mean_top3_pose_score", docking_score) or docking_score) std_top5 = float(rdock_row.get("std_top5_pose_score", 0.0) or 0.0) gap12 = float(rdock_row.get("pose_score_gap_1_2", 0.0) or 0.0) native_term = 0.25 * (mean_top3 - docking_score) + 0.10 * std_top5 + 0.05 * max(0.0, gap12) return float(native_term), float(docking_score + native_term) interaction_term = float(interaction_decomp or 0.0) burial_term = float(burial_ratio or 0.0) feature_rescore = 0.15 * interaction_term - 0.1 * burial_term final_score = docking_score - interface_contact_proxy + feature_rescore return float(feature_rescore), float(final_score) def _filter_mode_feature_tables( values_df: pd.DataFrame, masks_df: pd.DataFrame, feature_mode: str, ) -> tuple[pd.DataFrame, pd.DataFrame]: mode = str(feature_mode).strip().lower() if mode != "docking_only": return values_df, masks_df keep_cols = ["ligand_id"] allowed_exact = { "cluster_id_feature", "hypercluster_id_feature", "rdock_total_score", "rdock_pose_rank", "n_generated_poses", "best_pose_score", "mean_top3_pose_score", "mean_top5_pose_score", "std_top5_pose_score", "pose_score_gap_1_2", "rdock_restraint_term", "rdock_internal_ligand_term", "rdock_polar_term", "rdock_vdw_term", } keep_cols.extend([c for c in values_df.columns if c in allowed_exact]) keep_cols = [c for c in keep_cols if c in values_df.columns] out_values = values_df[keep_cols].copy() mask_cols = ["ligand_id"] + [f"mask_{c}" for c in keep_cols if c != "ligand_id" and f"mask_{c}" in masks_df.columns] out_masks = masks_df[mask_cols].copy() return out_values, out_masks def _run_adaptive_strategy( config: Dict[str, Any], root: Path, output_dir: Path, ligands_df: pd.DataFrame, ligand_encodings, cluster_map: Dict[str, int], hyper_map: Dict[int, int], protein_encoding, target_path: Path, stage_timers: List[StageTimer], feature_mode: str = "full_feature", score_variant: str = "full_feature", strategy_name: str = "adaptive", strategy_subdir: str = "adaptive", ) -> Dict[str, Any]: logger = get_logger("benchmark_adaptive") run_cfg = config["run"] scheduler_cfg = config["scheduler"] budget = int(run_cfg["adaptive_budget"]) batch_size = int(run_cfg["batch_size"]) max_batches = int(run_cfg["max_batches"]) require_real_backend = bool(config["backend"].get("require_real_backend", True)) adaptive_root = output_dir / strategy_subdir work_dir = adaptive_root / "work" raw_root = adaptive_root / "raw_rdock_outputs" cmd_log = adaptive_root / "rdock_commands.log" work_dir.mkdir(parents=True, exist_ok=True) raw_root.mkdir(parents=True, exist_ok=True) weight_cfg = WeightScheduleConfig( sample_knots=tuple(scheduler_cfg["model_weight_schedule"].get("sample_knots", [20, 50, 100, 200])), weight_knots=tuple(scheduler_cfg["model_weight_schedule"].get("weight_knots", [0.1, 0.3, 0.5, 0.8])), max_weight=float(scheduler_cfg["model_weight_schedule"].get("max_weight", 0.9)), min_weight=float(scheduler_cfg["model_weight_schedule"].get("min_weight", 0.05)), instability_threshold=float(scheduler_cfg["model_weight_schedule"].get("instability_threshold", 2.0)), instability_decay=float(scheduler_cfg["model_weight_schedule"].get("instability_decay", 0.25)), ) surrogate_cfg = SurrogateConfig( prefer_xgboost=bool(scheduler_cfg["surrogate"].get("prefer_xgboost", True)), random_state=int(run_cfg["random_seed"]), n_estimators=int(scheduler_cfg["surrogate"].get("n_estimators", 200)), min_train_samples=int(scheduler_cfg["surrogate"].get("min_train_samples", 12)), max_depth_small=int(scheduler_cfg["surrogate"].get("max_depth_small", 3)), max_depth_large=int(scheduler_cfg["surrogate"].get("max_depth_large", 6)), ) scheduler = AdaptiveScheduler( config=SchedulerConfig( batch_size=batch_size, init_coverage_fraction=float(scheduler_cfg.get("init_coverage_fraction", 0.35)), conservative_deprioritize=bool(scheduler_cfg.get("conservative_deprioritize", True)), state_path=str(adaptive_root / "scheduler_state.json"), weight_schedule=weight_cfg, ), policy=PrioritizationPolicy(), surrogate_config=surrogate_cfg, ) backend = _prepare_backend(config, cmd_log) cap = backend.check_capability() if require_real_backend and not cap.available: raise DockingError(f"Strict benchmark requires real backend. Capability failure: {cap.details}") scheduler.initialize(ligands_df[["ligand_id"]], cluster_map, hyper_map) target_context = backend.prepare_target(target_path, work_dir / "target") protein_bundle, bundles, ordered_names = _build_initial_feature_bundles( ligands_df=ligands_df, ligand_encodings=ligand_encodings, protein_encoding=protein_encoding, cluster_map=cluster_map, hyper_map=hyper_map, ) ligand_ids = ligands_df["ligand_id"].astype(str).tolist() evaluated_records: list[dict[str, Any]] = [] selected_records: list[dict[str, Any]] = [] pose_feature_records: list[dict[str, Any]] = [] model_weight_records: list[dict[str, Any]] = [] total_evaluated = 0 step_counter = 0 loop_start = time.time() for round_idx in range(max_batches): if total_evaluated >= budget: break batch_ids = scheduler.select_batch() if not batch_ids: # If active queue is empty before budget is exhausted, reactivate deprioritized items. reactivated = 0 for item in scheduler.queue_manager.items.values(): if item.status in {"deprioritized", "frozen"}: item.status = "active" reactivated += 1 if reactivated > 0: logger.info( "Reactivated %s deprioritized/frozen ligands at round %s to continue budget consumption", reactivated, round_idx, ) batch_ids = scheduler.select_batch() if not batch_ids: logger.info("No selectable ligands left at round %s", round_idx) break remain = budget - total_evaluated batch_ids = batch_ids[:remain] full_values_df, full_masks_df, _ = bundles_to_wide_frames( [bundles[lid] for lid in ligand_ids], ordered_feature_names=ordered_names, ) model_values_df, model_masks_df = _filter_mode_feature_tables(full_values_df, full_masks_df, feature_mode=feature_mode) id_to_idx = {lid: i for i, lid in enumerate(model_values_df["ligand_id"].astype(str).tolist())} # pre-docking surrogate predictions for diagnostics pred_map: Dict[str, tuple[float, float]] = {} if scheduler.surrogate.model is not None: x = model_values_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) m = model_masks_df.drop(columns=["ligand_id"]).to_numpy(dtype=float) x_batch = np.vstack([x[id_to_idx[lid]] for lid in batch_ids]) m_batch = np.vstack([m[id_to_idx[lid]] for lid in batch_ids]) pred = scheduler.surrogate.predict_bundle(x_batch, m_batch) for i, lid in enumerate(batch_ids): pred_map[lid] = (float(pred["expected_score"][i]), float(pred["uncertainty"][i])) round_dir = work_dir / f"batch_{round_idx:03d}" round_dir.mkdir(parents=True, exist_ok=True) ligand_files = [] for lid in batch_ids: smi = str(ligands_df.loc[ligands_df["ligand_id"] == lid, "smiles"].iloc[0]) lig_file = backend.prepare_ligand(lid, smi, round_dir / "ligands") ligand_files.append(lig_file) selected_records.append({"strategy": strategy_name, "round": round_idx, "step": step_counter, "ligand_id": lid}) docked = backend.dock( target_context, ligand_files, round_dir / "docking", allow_mock=False, require_real_backend=True, ) parsed = backend.parse_results(docked) _strict_backend_check(parsed) raw_batch_dir = raw_root / f"batch_{round_idx:03d}" raw_batch_dir.mkdir(parents=True, exist_ok=True) for item in sorted((round_dir / "docking").glob("*")): if item.is_file(): shutil.copy2(item, raw_batch_dir / item.name) interface = backend.extract_interface_features(parsed) batch_rows = [] for row, ifeat in zip(parsed, interface): lid = str(row["ligand_id"]) docking_score = float(row["docking_score"]) rdock_bundle = build_rdock_feature_bundle(ligand_id=lid, parsed_row=row) complex_bundle = build_complex_feature_bundle( ligand_id=lid, docking_score=docking_score, interface_features=ifeat, ligand_bundle=bundles[lid], protein_bundle=protein_bundle, ) bundles[lid] = merge_bundles(lid, [bundles[lid], rdock_bundle, complex_bundle]) interaction_decomp = complex_bundle.features["energy_interaction_decomposition"].value burial_ratio = complex_bundle.features["complex_ligand_burial_ratio"].value feature_rescore, final_score = _compute_final_score( docking_score=docking_score, interface_contact_proxy=float(ifeat["interface_contact_proxy"]), interaction_decomp=interaction_decomp, burial_ratio=burial_ratio, rdock_row=row, feature_mode=feature_mode, score_variant=score_variant, ) pred_score, pred_unc = pred_map.get(lid, (np.nan, np.nan)) abs_err = abs(pred_score - docking_score) if np.isfinite(pred_score) else np.nan batch_rows.append( { "strategy": strategy_name, "round": round_idx, "step": step_counter, "ligand_id": lid, "smiles": str(ligands_df.loc[ligands_df["ligand_id"] == lid, "smiles"].iloc[0]), "parent_reference_ligand": str( ligands_df.loc[ligands_df["ligand_id"] == lid, "parent_reference_ligand"].iloc[0] ), "is_reference": bool(ligands_df.loc[ligands_df["ligand_id"] == lid, "is_reference"].iloc[0]), "similarity_to_parent_reference": float( ligands_df.loc[ligands_df["ligand_id"] == lid, "similarity_to_reference"].iloc[0] ), "backend_name": str(row["backend_name"]), "backend_mode": str(row["backend_mode"]), "score_source": str(row["score_source"]), "raw_output_file": str(row["raw_output_file"]), "parsed_from": str(row["parsed_from"]), "fallback_used": bool(row["fallback_used"]), "success": bool(row["success"]), "command": str(row.get("command", "")), "quantity_type": str(row.get("quantity_type", "docking_score")), "cluster_id": int(cluster_map[lid]), "hypercluster_id": int(hyper_map.get(cluster_map[lid], -1)), "docking_score": docking_score, "feature_rescore": float(feature_rescore), "final_score": float(final_score), "predicted_score_prebatch": pred_score, "predicted_uncertainty_prebatch": pred_unc, "prediction_abs_error": abs_err, "rdock_total_score": row.get("rdock_total_score", np.nan), "rdock_pose_rank": row.get("rdock_pose_rank", np.nan), "n_generated_poses": row.get("n_generated_poses", np.nan), "best_pose_score": row.get("best_pose_score", np.nan), "mean_top3_pose_score": row.get("mean_top3_pose_score", np.nan), "mean_top5_pose_score": row.get("mean_top5_pose_score", np.nan), "std_top5_pose_score": row.get("std_top5_pose_score", np.nan), "pose_score_gap_1_2": row.get("pose_score_gap_1_2", np.nan), "rdock_restraint_term": row.get("rdock_restraint_term", np.nan), "rdock_internal_ligand_term": row.get("rdock_internal_ligand_term", np.nan), "rdock_polar_term": row.get("rdock_polar_term", np.nan), "rdock_vdw_term": row.get("rdock_vdw_term", np.nan), "top_pose_rmsd_consistency": row.get("top_pose_rmsd_consistency", np.nan), "contact_overlap_consistency": row.get("contact_overlap_consistency", np.nan), "hotspot_contact_frequency": row.get("hotspot_contact_frequency", np.nan), "subpocket_match_score": row.get("subpocket_match_score", np.nan), "replicate_mean_score": row.get("replicate_mean_score", np.nan), "replicate_score_variance": row.get("replicate_score_variance", np.nan), "replicate_consensus_score": row.get("replicate_consensus_score", np.nan), "rdock_feature_provenance": row.get("rdock_feature_provenance", "[]"), **ifeat, } ) for rec in complex_bundle.to_records(channel="complex", round_idx=round_idx): rec["strategy"] = strategy_name rec["step"] = step_counter pose_feature_records.append(rec) for rec in rdock_bundle.to_records(channel="rdock", round_idx=round_idx): rec["strategy"] = strategy_name rec["step"] = step_counter pose_feature_records.append(rec) step_counter += 1 total_evaluated += len(batch_rows) evaluated_records.extend(batch_rows) batch_df = pd.DataFrame(batch_rows) values_df, masks_df, ordered_names = bundles_to_wide_frames( [bundles[lid] for lid in ligand_ids], ordered_feature_names=None, ) model_values_df, model_masks_df = _filter_mode_feature_tables(values_df, masks_df, feature_mode=feature_mode) fit_stats = scheduler.update_from_batch(batch_df[["ligand_id", "docking_score"]], model_values_df, model_masks_df) scheduler.save_state(adaptive_root / f"scheduler_state_batch_{round_idx:03d}.json") model_weight_records.append( { "strategy": strategy_name, "round": round_idx, "model_weight": float(scheduler.last_model_weight), "n_train": float(fit_stats.get("n_train", 0.0)), "train_mae": float(fit_stats.get("train_mae", np.nan)), "val_mae": float(fit_stats.get("val_mae", np.nan)), "instability_ratio": float(fit_stats.get("instability_ratio", np.nan)), "surrogate_backend": scheduler.surrogate.backend, } ) loop_end = time.time() stage_timers.append(StageTimer(name="adaptive_loop", start=loop_start, end=loop_end)) values_df, masks_df, ordered_names = bundles_to_wide_frames( [bundles[lid] for lid in ligand_ids], ordered_feature_names=ordered_names, ) return { "evaluated_df": pd.DataFrame(evaluated_records), "selected_df": pd.DataFrame(selected_records), "pose_features_df": pd.DataFrame(pose_feature_records), "feature_values_df": values_df, "feature_masks_df": masks_df, "ordered_feature_names": ordered_names, "model_weight_df": pd.DataFrame(model_weight_records), "scheduler": scheduler, "backend_capability": cap, "command_log": cmd_log, "raw_root": raw_root, "strategy_root": adaptive_root, } def _run_random_baseline( config: Dict[str, Any], output_dir: Path, ligands_df: pd.DataFrame, cluster_map: Dict[str, int], hyper_map: Dict[int, int], target_path: Path, seed: int, feature_mode: str = "full_feature", score_variant: str = "top1", strategy_name: str = "baseline_random", strategy_subdir: str = "baseline_random", static_order: Sequence[str] | None = None, ) -> Dict[str, Any]: logger = get_logger("benchmark_baseline") budget = int(config["run"]["baseline_budget"]) batch_size = int(config["run"]["batch_size"]) baseline_root = output_dir / strategy_subdir work_dir = baseline_root / "work" raw_root = baseline_root / "raw_rdock_outputs" cmd_log = baseline_root / "rdock_commands.log" work_dir.mkdir(parents=True, exist_ok=True) raw_root.mkdir(parents=True, exist_ok=True) backend = _prepare_backend(config, cmd_log) cap = backend.check_capability() if bool(config["backend"].get("require_real_backend", True)) and not cap.available: raise DockingError(f"Strict benchmark requires real backend. Capability failure: {cap.details}") target_context = backend.prepare_target(target_path, work_dir / "target") if static_order is None: ids = ligands_df["ligand_id"].astype(str).tolist() rng = random.Random(seed) rng.shuffle(ids) selected = ids[:budget] else: selected = [str(x) for x in static_order][:budget] evaluated_rows: list[dict[str, Any]] = [] selected_rows: list[dict[str, Any]] = [] step = 0 for round_idx, start in enumerate(range(0, len(selected), batch_size)): batch_ids = selected[start : start + batch_size] round_dir = work_dir / f"batch_{round_idx:03d}" round_dir.mkdir(parents=True, exist_ok=True) ligand_files = [] for lid in batch_ids: smi = str(ligands_df.loc[ligands_df["ligand_id"] == lid, "smiles"].iloc[0]) lig_file = backend.prepare_ligand(lid, smi, round_dir / "ligands") ligand_files.append(lig_file) selected_rows.append({"strategy": strategy_name, "round": round_idx, "step": step, "ligand_id": lid}) docked = backend.dock( target_context, ligand_files, round_dir / "docking", allow_mock=False, require_real_backend=True, ) parsed = backend.parse_results(docked) _strict_backend_check(parsed) interface = backend.extract_interface_features(parsed) raw_batch_dir = raw_root / f"batch_{round_idx:03d}" raw_batch_dir.mkdir(parents=True, exist_ok=True) for item in sorted((round_dir / "docking").glob("*")): if item.is_file(): shutil.copy2(item, raw_batch_dir / item.name) for row, ifeat in zip(parsed, interface): lid = str(row["ligand_id"]) docking_score = float(row["docking_score"]) feature_rescore, final_score = _compute_final_score( docking_score=docking_score, interface_contact_proxy=float(ifeat["interface_contact_proxy"]), interaction_decomp=None, burial_ratio=None, rdock_row=row, feature_mode=feature_mode, score_variant=score_variant, ) evaluated_rows.append( { "strategy": strategy_name, "round": round_idx, "step": step, "ligand_id": lid, "smiles": str(ligands_df.loc[ligands_df["ligand_id"] == lid, "smiles"].iloc[0]), "parent_reference_ligand": str( ligands_df.loc[ligands_df["ligand_id"] == lid, "parent_reference_ligand"].iloc[0] ), "is_reference": bool(ligands_df.loc[ligands_df["ligand_id"] == lid, "is_reference"].iloc[0]), "similarity_to_parent_reference": float( ligands_df.loc[ligands_df["ligand_id"] == lid, "similarity_to_reference"].iloc[0] ), "backend_name": str(row["backend_name"]), "backend_mode": str(row["backend_mode"]), "score_source": str(row["score_source"]), "raw_output_file": str(row["raw_output_file"]), "parsed_from": str(row["parsed_from"]), "fallback_used": bool(row["fallback_used"]), "success": bool(row["success"]), "command": str(row.get("command", "")), "quantity_type": str(row.get("quantity_type", "docking_score")), "cluster_id": int(cluster_map[lid]), "hypercluster_id": int(hyper_map.get(cluster_map[lid], -1)), "docking_score": docking_score, "feature_rescore": feature_rescore, "final_score": final_score, "predicted_score_prebatch": np.nan, "predicted_uncertainty_prebatch": np.nan, "prediction_abs_error": np.nan, "rdock_total_score": row.get("rdock_total_score", np.nan), "rdock_pose_rank": row.get("rdock_pose_rank", np.nan), "n_generated_poses": row.get("n_generated_poses", np.nan), "best_pose_score": row.get("best_pose_score", np.nan), "mean_top3_pose_score": row.get("mean_top3_pose_score", np.nan), "mean_top5_pose_score": row.get("mean_top5_pose_score", np.nan), "std_top5_pose_score": row.get("std_top5_pose_score", np.nan), "pose_score_gap_1_2": row.get("pose_score_gap_1_2", np.nan), "rdock_restraint_term": row.get("rdock_restraint_term", np.nan), "rdock_internal_ligand_term": row.get("rdock_internal_ligand_term", np.nan), "rdock_polar_term": row.get("rdock_polar_term", np.nan), "rdock_vdw_term": row.get("rdock_vdw_term", np.nan), "top_pose_rmsd_consistency": row.get("top_pose_rmsd_consistency", np.nan), "contact_overlap_consistency": row.get("contact_overlap_consistency", np.nan), "hotspot_contact_frequency": row.get("hotspot_contact_frequency", np.nan), "subpocket_match_score": row.get("subpocket_match_score", np.nan), "replicate_mean_score": row.get("replicate_mean_score", np.nan), "replicate_score_variance": row.get("replicate_score_variance", np.nan), "replicate_consensus_score": row.get("replicate_consensus_score", np.nan), "rdock_feature_provenance": row.get("rdock_feature_provenance", "[]"), **ifeat, } ) step += 1 logger.info("Baseline %s round %s evaluated %s ligands", strategy_name, round_idx, len(batch_ids)) return { "evaluated_df": pd.DataFrame(evaluated_rows), "selected_df": pd.DataFrame(selected_rows), "backend_capability": cap, "command_log": cmd_log, "raw_root": raw_root, "strategy_root": baseline_root, } def _recovery_tables( combined_df: pd.DataFrame, ligands_df: pd.DataFrame, references: Sequence[str], analog_similarity_threshold: float, topk_values: Sequence[int], ) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]: recovery_rows: list[dict[str, Any]] = [] comparison_rows: list[dict[str, Any]] = [] baseline_cmp_rows: list[dict[str, Any]] = [] for strategy in sorted(combined_df["strategy"].unique().tolist()): sdf = combined_df[combined_df["strategy"] == strategy].copy() if sdf.empty: continue rank_df = sdf.sort_values("final_score", ascending=True).reset_index(drop=True) rank_df["rank"] = np.arange(1, rank_df.shape[0] + 1) rank_map = dict(zip(rank_df["ligand_id"], rank_df["rank"])) first_step_map = ( sdf.sort_values("step", ascending=True) .groupby("ligand_id", as_index=False) .first() .set_index("ligand_id")["step"] .to_dict() ) budget = int(rank_df.shape[0]) early_cut = max(1, int(0.33 * budget)) late_cut = max(1, int(0.66 * budget)) for ref_id in references: ref_rank = rank_map.get(ref_id) ref_step = first_step_map.get(ref_id) if ref_step is None: stage = "never" elif ref_step <= early_cut: stage = "early" elif ref_step <= late_cut: stage = "mid" else: stage = "late" analog_pool = ligands_df[ (ligands_df["parent_reference_ligand"] == ref_id) & ( (pd.to_numeric(ligands_df["similarity_to_reference"], errors="coerce") >= analog_similarity_threshold) | (pd.to_numeric(ligands_df.get("scaffold_match", 0), errors="coerce") >= 1) ) ]["ligand_id"].astype(str) analog_pool_set = set(analog_pool.tolist()) eval_order = sdf.sort_values("step") analog_hits = eval_order[eval_order["ligand_id"].isin(analog_pool_set)] first_analog_step = int(analog_hits["step"].iloc[0]) if not analog_hits.empty else np.nan topk_stats = {} for k in topk_values: kk = min(int(k), rank_df.shape[0]) top_ids = set(rank_df.head(kk)["ligand_id"].astype(str).tolist()) recovered = len(top_ids.intersection(analog_pool_set)) topk_stats[f"analog_recovered_top{k}"] = int(recovered) recovery_rows.append( { "strategy": strategy, "reference_id": ref_id, "reference_rank": int(ref_rank) if ref_rank is not None else np.nan, "reference_step": int(ref_step) if ref_step is not None else np.nan, "reference_recovery_stage": stage, "first_analog_step": first_analog_step, "analog_pool_size": int(len(analog_pool_set)), **topk_stats, } ) top_n = min(30, rank_df.shape[0]) for row in rank_df.head(top_n).itertuples(index=False): sim_map = { ref_id: _tanimoto(str(row.smiles), str(ligands_df.loc[ligands_df["ligand_id"] == ref_id, "smiles"].iloc[0])) for ref_id in references } closest_ref = max(sim_map.items(), key=lambda kv: kv[1])[0] comparison_rows.append( { "strategy": strategy, "rank": int(row.rank), "ligand_id": str(row.ligand_id), "docking_score": float(row.docking_score), "final_score": float(row.final_score), "closest_reference": closest_ref, "closest_reference_similarity": float(sim_map[closest_ref]), "is_reference": bool(row.is_reference), "parent_reference_ligand": row.parent_reference_ligand, } ) analog_like = ( (pd.to_numeric(sdf["similarity_to_parent_reference"], errors="coerce") >= analog_similarity_threshold) | (sdf["is_reference"].astype(bool)) ) topk_hit = enrichment_metrics( scores=sdf["final_score"].astype(float).tolist(), labels=analog_like.astype(int).tolist(), topk=min(50, sdf.shape[0]), ) baseline_cmp_rows.append( { "strategy": strategy, "budget_used": int(sdf.shape[0]), "best_docking_score": float(sdf["docking_score"].min()), "best_final_score": float(sdf["final_score"].min()), "mean_final_score": float(sdf["final_score"].mean()), "selection_diversity_proxy": float(sdf["cluster_id"].nunique() / max(1, sdf.shape[0])), "topk_hit_rate": float(topk_hit["topk_hit_rate"]), "enrichment_like": float(topk_hit["enrichment_like"]), } ) return ( pd.DataFrame(recovery_rows), pd.DataFrame(comparison_rows), pd.DataFrame(baseline_cmp_rows), ) def _plot_outputs( output_dir: Path, combined_df: pd.DataFrame, recovery_df: pd.DataFrame, feature_importance: Dict[str, float], surrogate_diag: pd.DataFrame, ) -> list[Path]: plots_dir = output_dir / "plots" plots_dir.mkdir(parents=True, exist_ok=True) plot_paths: list[Path] = [] def savefig(name: str): path = plots_dir / name plt.tight_layout() plt.savefig(path, dpi=160) plt.close() plot_paths.append(path) # 1) docking_score_vs_step plt.figure(figsize=(8, 4)) for strategy, sdf in combined_df.groupby("strategy"): d = sdf.sort_values("step") plt.plot(d["step"], d["docking_score"], label=strategy, alpha=0.8) plt.xlabel("Step") plt.ylabel("Docking score") plt.title("Docking Score vs Step") plt.legend() savefig("docking_score_vs_step.png") # 2) final_score_vs_step plt.figure(figsize=(8, 4)) for strategy, sdf in combined_df.groupby("strategy"): d = sdf.sort_values("step") plt.plot(d["step"], d["final_score"], label=strategy, alpha=0.8) plt.xlabel("Step") plt.ylabel("Final score") plt.title("Final Score vs Step") plt.legend() savefig("final_score_vs_step.png") # 3) cumulative best plt.figure(figsize=(8, 4)) for strategy, sdf in combined_df.groupby("strategy"): d = sdf.sort_values("step") cum_best = np.minimum.accumulate(d["final_score"].to_numpy(dtype=float)) plt.plot(d["step"], cum_best, label=strategy) plt.xlabel("Step") plt.ylabel("Cumulative best final score") plt.title("Best Score Cumulative") plt.legend() savefig("best_score_cumulative.png") # 4) adaptive_vs_baseline bar plt.figure(figsize=(7, 4)) agg = combined_df.groupby("strategy", as_index=False).agg(best_final=("final_score", "min"), mean_final=("final_score", "mean")) x = np.arange(agg.shape[0]) plt.bar(x - 0.15, agg["best_final"], width=0.3, label="best_final") plt.bar(x + 0.15, agg["mean_final"], width=0.3, label="mean_final") plt.xticks(x, agg["strategy"], rotation=20) plt.ylabel("Score") plt.title("Adaptive vs Baseline") plt.legend() savefig("adaptive_vs_baseline.png") # 5) predicted_vs_realized plt.figure(figsize=(5, 5)) if not surrogate_diag.empty: plt.scatter(surrogate_diag["predicted"], surrogate_diag["realized"], s=18, alpha=0.6) plt.xlabel("Predicted score") plt.ylabel("Realized docking score") plt.title("Predicted vs Realized") savefig("predicted_vs_realized.png") # 6) residuals_over_time plt.figure(figsize=(8, 4)) if not surrogate_diag.empty: plt.plot(surrogate_diag["step"], surrogate_diag["residual"], marker="o", linewidth=1) plt.xlabel("Step") plt.ylabel("Residual (pred - real)") plt.title("Residuals Over Time") savefig("residuals_over_time.png") # 7) uncertainty_vs_error plt.figure(figsize=(6, 4)) if not surrogate_diag.empty: plt.scatter(surrogate_diag["uncertainty"], surrogate_diag["abs_error"], s=18, alpha=0.6) plt.xlabel("Predicted uncertainty") plt.ylabel("Absolute error") plt.title("Uncertainty vs Error") savefig("uncertainty_vs_error.png") # 8) cluster selection over time plt.figure(figsize=(8, 4)) adf = combined_df[combined_df["strategy"] == "adaptive"].sort_values("step") if not adf.empty: plt.plot(adf["step"], adf["cluster_id"], marker=".", linewidth=0.8) plt.xlabel("Step") plt.ylabel("Cluster ID") plt.title("Cluster Selection Over Time (Adaptive)") savefig("cluster_selection_over_time.png") # 9) topk recovery over time plt.figure(figsize=(8, 4)) for strategy, sdf in combined_df.groupby("strategy"): d = sdf.sort_values("step").copy() active_like = ( (pd.to_numeric(d["similarity_to_parent_reference"], errors="coerce") >= 0.65) | (d["is_reference"].astype(bool)) ) csum = np.cumsum(active_like.astype(int).to_numpy()) plt.plot(d["step"], csum, label=strategy) plt.xlabel("Step") plt.ylabel("Cumulative recovered active-like") plt.title("Top-k Recovery Over Time") plt.legend() savefig("topk_recovery_over_time.png") # 10) reference rank positions plt.figure(figsize=(8, 4)) rr = recovery_df[["strategy", "reference_id", "reference_rank"]].copy() rr["reference_rank"] = pd.to_numeric(rr["reference_rank"], errors="coerce") labels = [f"{r.reference_id}-{r.strategy}" for r in rr.itertuples(index=False)] plt.bar(np.arange(rr.shape[0]), rr["reference_rank"].fillna(rr["reference_rank"].max() + 10).to_numpy()) plt.xticks(np.arange(rr.shape[0]), labels, rotation=40, ha="right") plt.ylabel("Rank") plt.title("Reference Rank Positions") savefig("reference_rank_positions.png") # 11) reference similarity vs rank plt.figure(figsize=(6, 4)) ad = combined_df[combined_df["strategy"] == "adaptive"].copy() if not ad.empty: ad_rank = ad.sort_values("final_score").reset_index(drop=True) ad_rank["rank"] = np.arange(1, ad_rank.shape[0] + 1) plt.scatter(ad_rank["rank"], ad_rank["similarity_to_parent_reference"], s=18, alpha=0.6) plt.xlabel("Rank") plt.ylabel("Similarity to parent reference") plt.title("Reference Similarity vs Rank (Adaptive)") savefig("reference_similarity_vs_rank.png") # 12) feature importance barplot plt.figure(figsize=(9, 5)) ranked = sorted(feature_importance.items(), key=lambda kv: kv[1], reverse=True)[:20] if ranked: names = [k for k, _ in ranked] vals = [v for _, v in ranked] plt.barh(np.arange(len(vals)), vals) plt.yticks(np.arange(len(vals)), names) plt.gca().invert_yaxis() plt.title("Feature Importance (Top 20)") savefig("feature_importance_barplot.png") # 13) metric correlation heatmap plt.figure(figsize=(7, 6)) cols = [ "docking_score", "final_score", "interface_contact_proxy", "hbond_proxy", "shape_proxy", "similarity_to_parent_reference", ] corr_df = combined_df[cols].apply(pd.to_numeric, errors="coerce") corr = corr_df.corr().fillna(0.0) plt.imshow(corr.to_numpy(), cmap="coolwarm", vmin=-1.0, vmax=1.0) plt.xticks(np.arange(len(cols)), cols, rotation=40, ha="right") plt.yticks(np.arange(len(cols)), cols) plt.colorbar(label="Pearson r") plt.title("Metric Correlation Heatmap") savefig("metric_correlation_heatmap.png") # 14/15) AUC and PR (defensible analog-like label) # Label definition: reference ligands or similarity >= 0.65 to parent reference. adf = combined_df[combined_df["strategy"] == "adaptive"].copy() if not adf.empty: y_true = ( (adf["is_reference"].astype(bool)) | (pd.to_numeric(adf["similarity_to_parent_reference"], errors="coerce") >= 0.65) ).astype(int) y_score = -pd.to_numeric(adf["final_score"], errors="coerce").fillna(0.0) if y_true.nunique() > 1: fpr, tpr, _ = sk_metrics.roc_curve(y_true, y_score) prec, rec, _ = sk_metrics.precision_recall_curve(y_true, y_score) plt.figure(figsize=(5, 4)) plt.plot(fpr, tpr) plt.xlabel("FPR") plt.ylabel("TPR") plt.title("ROC Curve (analog-like label)") savefig("auc_curve.png") plt.figure(figsize=(5, 4)) plt.plot(rec, prec) plt.xlabel("Recall") plt.ylabel("Precision") plt.title("PR Curve (analog-like label)") savefig("pr_curve.png") else: plt.figure(figsize=(5, 4)) plt.text(0.5, 0.5, "ROC not defensible\\n(single class label)", ha="center", va="center") plt.axis("off") savefig("auc_curve.png") plt.figure(figsize=(5, 4)) plt.text(0.5, 0.5, "PR not defensible\\n(single class label)", ha="center", va="center") plt.axis("off") savefig("pr_curve.png") else: plt.figure(figsize=(5, 4)) plt.text(0.5, 0.5, "ROC not available", ha="center", va="center") plt.axis("off") savefig("auc_curve.png") plt.figure(figsize=(5, 4)) plt.text(0.5, 0.5, "PR not available", ha="center", va="center") plt.axis("off") savefig("pr_curve.png") return plot_paths def _self_audit( output_dir: Path, required_files: Sequence[str], required_plots: Sequence[str], reference_ids: Sequence[str], ) -> Path: issues: list[str] = [] checks: list[str] = [] for rel in required_files: p = output_dir / rel ok = p.exists() and p.stat().st_size > 0 checks.append(f"- file `{rel}` exists and non-empty: `{ok}`") if not ok: issues.append(f"Missing/empty required file: {rel}") for rel in required_plots: p = output_dir / "plots" / rel ok = p.exists() and p.stat().st_size > 0 checks.append(f"- plot `{rel}` exists and non-empty: `{ok}`") if not ok: issues.append(f"Missing/empty required plot: {rel}") parsed = pd.read_csv(output_dir / "parsed_scores.csv") if (output_dir / "parsed_scores.csv").exists() else pd.DataFrame() if parsed.empty: issues.append("parsed_scores.csv is empty") else: no_fallback = not parsed["fallback_used"].astype(bool).any() real_mode = bool((parsed["backend_mode"] == "real-rdock").all()) checks.append(f"- no fallback rows in parsed_scores: `{no_fallback}`") checks.append(f"- backend_mode is real-rdock for all rows: `{real_mode}`") if not no_fallback: issues.append("Fallback rows found in parsed_scores") if not real_mode: issues.append("Non real-rdock rows found in parsed_scores") ligands_df = pd.read_csv(output_dir / "dataset_snapshot.csv") if (output_dir / "dataset_snapshot.csv").exists() else pd.DataFrame() for ref in reference_ids: present = (not ligands_df.empty) and bool((ligands_df["ligand_id"].astype(str) == str(ref)).any()) checks.append(f"- reference ligand `{ref}` present in benchmark universe: `{present}`") if not present: issues.append(f"Reference ligand {ref} missing from benchmark universe") rec_df = pd.read_csv(output_dir / "reference_recovery.csv") if (output_dir / "reference_recovery.csv").exists() else pd.DataFrame() checks.append(f"- reference_recovery.csv populated: `{not rec_df.empty}`") if rec_df.empty: issues.append("reference_recovery.csv empty") feat_df = pd.read_csv(output_dir / "features_per_ligand.csv") if (output_dir / "features_per_ligand.csv").exists() else pd.DataFrame() checks.append(f"- features_per_ligand.csv populated: `{not feat_df.empty}`") if feat_df.empty: issues.append("features_per_ligand.csv empty") resc_df = pd.read_csv(output_dir / "rescoring_terms.csv") if (output_dir / "rescoring_terms.csv").exists() else pd.DataFrame() if resc_df.empty: issues.append("rescoring_terms.csv empty") else: same = np.isclose(resc_df["docking_score"].to_numpy(dtype=float), resc_df["final_score"].to_numpy(dtype=float), atol=1e-9) same_frac = float(np.mean(same)) checks.append(f"- fraction(final_score == docking_score): `{same_frac:.4f}`") if same_frac > 0.98: issues.append("Final score is almost identical to docking score across rows") report_lines = [ "# Self Audit Report", "", "## Checks", *checks, "", "## Issues", ] if not issues: report_lines.append("- None") else: report_lines.extend([f"- {x}" for x in issues]) report_path = output_dir / "self_audit_report.md" report_path.write_text("\n".join(report_lines), encoding="utf-8") if issues: raise RuntimeError("Self-audit failed:\n" + "\n".join(issues)) return report_path def run_benchmark(config_path: str | Path) -> Dict[str, Any]: logger = get_logger("experimental_benchmark") config = load_config(config_path) root = Path(__file__).resolve().parents[1] run_cfg = config["run"] output_dir = root / run_cfg["output_dir"] if output_dir.exists(): shutil.rmtree(output_dir) output_dir.mkdir(parents=True, exist_ok=True) np.random.seed(int(run_cfg["random_seed"])) random.seed(int(run_cfg["random_seed"])) stage_timers: list[StageTimer] = [] doctor, tm = _time_stage("environment_check", run_doctor) stage_timers.append(tm) dataset_info, tm = _time_stage("dataset_build", lambda: _build_dataset(config, root, logger)) stage_timers.append(tm) target_selection_path, tm = _time_stage( "target_selection_report", lambda: _write_target_selection_markdown(config, dataset_info, output_dir), ) stage_timers.append(tm) ligands_df = dataset_info["dedup_df"].copy() ligands_df = ligands_df.reset_index(drop=True) ligands_df["ligand_id"] = ligands_df["ligand_id"].astype(str) ligands_df["smiles"] = ligands_df["smiles"].astype(str) subset_size = run_cfg.get("dataset_subset_size") if subset_size is not None: subset_size = int(subset_size) if subset_size > 0 and subset_size < ligands_df.shape[0]: rng = np.random.default_rng(int(run_cfg["random_seed"])) refs = ligands_df[ligands_df["is_reference"].astype(bool)].copy() non_refs = ligands_df[~ligands_df["is_reference"].astype(bool)].copy() keep_non_ref = max(0, subset_size - refs.shape[0]) if keep_non_ref < non_refs.shape[0]: idx = rng.choice(non_refs.index.to_numpy(), size=keep_non_ref, replace=False) non_refs = non_refs.loc[idx].copy() ligands_df = pd.concat([refs, non_refs], axis=0).drop_duplicates(subset=["ligand_id"]).reset_index(drop=True) # Ensure unique ligand IDs post-dedup. if ligands_df["ligand_id"].duplicated().any(): new_ids = [] seen = {} for lid in ligands_df["ligand_id"].tolist(): c = seen.get(lid, 0) seen[lid] = c + 1 new_ids.append(lid if c == 0 else f"{lid}_dup{c}") ligands_df["ligand_id"] = new_ids (ligand_encodings, protein_encoding, cluster_map, hyper_map), tm = _time_stage( "encode_cluster", lambda: _encode_and_cluster(config, ligands_df, dataset_info["target_path"]), ) stage_timers.append(tm) adaptive_info = _run_adaptive_strategy( config=config, root=root, output_dir=output_dir, ligands_df=ligands_df, ligand_encodings=ligand_encodings, cluster_map=cluster_map, hyper_map=hyper_map, protein_encoding=protein_encoding, target_path=dataset_info["target_path"], stage_timers=stage_timers, ) baseline_start = time.time() baseline_info = _run_random_baseline( config=config, output_dir=output_dir, ligands_df=ligands_df, cluster_map=cluster_map, hyper_map=hyper_map, target_path=dataset_info["target_path"], seed=int(run_cfg["random_seed"]) + 101, ) baseline_end = time.time() stage_timers.append(StageTimer(name="baseline_random_loop", start=baseline_start, end=baseline_end)) # Combine outputs. adaptive_df = adaptive_info["evaluated_df"].copy() baseline_df = baseline_info["evaluated_df"].copy() combined_df = pd.concat([adaptive_df, baseline_df], axis=0, ignore_index=True) if combined_df.empty: raise RuntimeError("Benchmark produced no evaluated rows") _strict_backend_check(combined_df.to_dict(orient="records")) # Final ranking by strategy. ranking_rows = [] for strategy, sdf in combined_df.groupby("strategy"): r = sdf.sort_values("final_score").copy().reset_index(drop=True) r["rank"] = np.arange(1, r.shape[0] + 1) ranking_rows.append(r) ranking_df = pd.concat(ranking_rows, axis=0, ignore_index=True) reference_ids = dataset_info["reference_df"]["reference_id"].astype(str).tolist() recovery_df, ref_cmp_df, baseline_cmp_df = _recovery_tables( combined_df=combined_df, ligands_df=ligands_df, references=reference_ids, analog_similarity_threshold=float(config["analysis"].get("analog_similarity_threshold", 0.65)), topk_values=[int(x) for x in config["analysis"].get("topk_values", [10, 25, 50, 100])], ) # Feature outputs from adaptive path. feature_values_df = adaptive_info["feature_values_df"].copy() feature_masks_df = adaptive_info["feature_masks_df"].copy() pose_features_df = adaptive_info["pose_features_df"].copy() model_weight_df = adaptive_info["model_weight_df"].copy() feature_diag_df = compute_feature_diagnostics( feature_values_df, feature_masks_df, target=feature_values_df["ligand_id"].map( adaptive_df.groupby("ligand_id")["docking_score"].min().to_dict() ), ) # Surrogate diagnostics using final adaptive model over evaluated adaptive rows. scheduler = adaptive_info["scheduler"] ad_eval = adaptive_df.sort_values("step").copy() if not ad_eval.empty: merged = ad_eval[["ligand_id", "step", "docking_score"]].merge(feature_values_df, on="ligand_id", how="left") merged_mask = ad_eval[["ligand_id"]].merge(feature_masks_df, on="ligand_id", how="left") x = merged.drop(columns=["ligand_id", "step", "docking_score"]).to_numpy(dtype=float) m = merged_mask.drop(columns=["ligand_id"]).to_numpy(dtype=float) pred = scheduler.surrogate.predict_bundle(x, m) surrogate_diag = pd.DataFrame( { "step": merged["step"].to_numpy(dtype=int), "ligand_id": merged["ligand_id"].astype(str).to_numpy(), "predicted": pred["expected_score"], "realized": merged["docking_score"].to_numpy(dtype=float), "residual": pred["expected_score"] - merged["docking_score"].to_numpy(dtype=float), "uncertainty": pred["uncertainty"], } ) surrogate_diag["abs_error"] = surrogate_diag["residual"].abs() else: surrogate_diag = pd.DataFrame(columns=["step", "ligand_id", "predicted", "realized", "residual", "uncertainty", "abs_error"]) feature_importance = scheduler.surrogate.feature_importance() # Save outputs. paths = { "summary": output_dir / "summary.json", "final_ranking": output_dir / "final_ranking.csv", "batch_history": output_dir / "batch_history.csv", "timings": output_dir / "timings.csv", "clusters": output_dir / "clusters.csv", "hyperclusters": output_dir / "hyperclusters.csv", "selected_ligands": output_dir / "selected_ligands.csv", "reference_recovery": output_dir / "reference_recovery.csv", "reference_comparison": output_dir / "reference_comparison.csv", "surrogate_diagnostics": output_dir / "surrogate_diagnostics.csv", "baseline_comparison": output_dir / "baseline_comparison.csv", "parsed_scores": output_dir / "parsed_scores.csv", "features_per_ligand": output_dir / "features_per_ligand.csv", "features_per_pose": output_dir / "features_per_pose.csv", "feature_masks": output_dir / "feature_masks.csv", "feature_importance": output_dir / "feature_importance.json", "model_weight_over_time": output_dir / "model_weight_over_time.csv", "feature_diagnostics": output_dir / "feature_diagnostics.csv", "rescoring_terms": output_dir / "rescoring_terms.csv", "backend_validation_snapshot": output_dir / "backend_validation_snapshot.csv", "readme": output_dir / "README_results.md", "validation_report": output_dir / "validation_report.md", "dataset_snapshot": output_dir / "dataset_snapshot.csv", } ranking_df.to_csv(paths["final_ranking"], index=False) pd.DataFrame(scheduler.state.batch_history).to_csv(paths["batch_history"], index=False) pd.DataFrame([{"stage": t.name, "seconds": t.seconds} for t in stage_timers]).to_csv(paths["timings"], index=False) pd.DataFrame( [{"ligand_id": lid, "cluster_id": int(cluster_map[lid]), "hypercluster_id": int(hyper_map.get(cluster_map[lid], -1))} for lid in ligands_df["ligand_id"]] ).to_csv(paths["clusters"], index=False) pd.DataFrame([{"cluster_id": int(k), "hypercluster_id": int(v)} for k, v in sorted(hyper_map.items())]).to_csv( paths["hyperclusters"], index=False ) pd.concat([adaptive_info["selected_df"], baseline_info["selected_df"]], axis=0, ignore_index=True).to_csv(paths["selected_ligands"], index=False) recovery_df.to_csv(paths["reference_recovery"], index=False) ref_cmp_df.to_csv(paths["reference_comparison"], index=False) surrogate_diag.to_csv(paths["surrogate_diagnostics"], index=False) baseline_cmp_df.to_csv(paths["baseline_comparison"], index=False) combined_df.to_csv(paths["parsed_scores"], index=False) feature_values_df.to_csv(paths["features_per_ligand"], index=False) pose_features_df.to_csv(paths["features_per_pose"], index=False) feature_masks_df.to_csv(paths["feature_masks"], index=False) paths["feature_importance"].write_text(json.dumps(feature_importance, indent=2), encoding="utf-8") model_weight_df.to_csv(paths["model_weight_over_time"], index=False) feature_diag_df.to_csv(paths["feature_diagnostics"], index=False) combined_df[["strategy", "step", "ligand_id", "docking_score", "interface_contact_proxy", "feature_rescore", "final_score"]].to_csv( paths["rescoring_terms"], index=False ) pd.DataFrame( [ { "strategy": "adaptive", "backend_name": adaptive_info["backend_capability"].backend_name, "backend_available": adaptive_info["backend_capability"].available, "details": json.dumps(adaptive_info["backend_capability"].details), "command_log": str(adaptive_info["command_log"]), "raw_output_root": str(adaptive_info["raw_root"]), }, { "strategy": "baseline_random", "backend_name": baseline_info["backend_capability"].backend_name, "backend_available": baseline_info["backend_capability"].available, "details": json.dumps(baseline_info["backend_capability"].details), "command_log": str(baseline_info["command_log"]), "raw_output_root": str(baseline_info["raw_root"]), }, ] ).to_csv(paths["backend_validation_snapshot"], index=False) ligands_df.to_csv(paths["dataset_snapshot"], index=False) # Merge command logs for convenience. merged_log = output_dir / "rdock_commands.log" merged_log.write_text( "\n".join( [ "# Adaptive", adaptive_info["command_log"].read_text(encoding="utf-8") if adaptive_info["command_log"].exists() else "", "# Baseline Random", baseline_info["command_log"].read_text(encoding="utf-8") if baseline_info["command_log"].exists() else "", ] ), encoding="utf-8", ) # Copy raw outputs into common root. common_raw = output_dir / "raw_rdock_outputs" if common_raw.exists(): shutil.rmtree(common_raw) common_raw.mkdir(parents=True, exist_ok=True) shutil.copytree(adaptive_info["raw_root"], common_raw / "adaptive", dirs_exist_ok=True) shutil.copytree(baseline_info["raw_root"], common_raw / "baseline_random", dirs_exist_ok=True) # Plots. plot_paths = _plot_outputs( output_dir=output_dir, combined_df=combined_df, recovery_df=recovery_df, feature_importance=feature_importance, surrogate_diag=surrogate_diag, ) # Summary + reports. counts_by_ref = ligands_df.groupby("parent_reference_ligand").size().to_dict() reached_full_target = all(v >= int(config["benchmark_dataset"]["per_reference_target"]) for v in counts_by_ref.values()) summary = { "run_name": run_cfg["name"], "target": config["target"], "references": dataset_info["reference_df"].to_dict(orient="records"), "ligands_per_reference": {k: int(v) for k, v in counts_by_ref.items()}, "total_ligand_count": int(ligands_df.shape[0]), "per_reference_target": int(config["benchmark_dataset"]["per_reference_target"]), "full_4500_target_reached": bool(reached_full_target and ligands_df.shape[0] >= 4500), "cluster_count": int(len(set(cluster_map.values()))), "hypercluster_count": int(len(set(hyper_map.values()))), "adaptive_budget_used": int(adaptive_df.shape[0]), "baseline_budget_used": int(baseline_df.shape[0]), "real_rdock_only": bool((combined_df["backend_mode"] == "real-rdock").all() and (not combined_df["fallback_used"].astype(bool).any())), "runtime_seconds": float(sum(t.seconds for t in stage_timers)), "runtime_by_stage_seconds": {t.name: t.seconds for t in stage_timers}, } paths["summary"].write_text(json.dumps(summary, indent=2), encoding="utf-8") paths["readme"].write_text( "\n".join( [ "# Experimental Benchmark Results", "", f"- Target: `{config['target']['protein_name']}`", f"- References: `{', '.join(reference_ids)}`", f"- Total ligands: `{ligands_df.shape[0]}`", f"- Adaptive budget used: `{adaptive_df.shape[0]}`", f"- Baseline budget used: `{baseline_df.shape[0]}`", f"- Real rDock only: `{summary['real_rdock_only']}`", "", "Key outputs:", "- `summary.json`", "- `final_ranking.csv`", "- `reference_recovery.csv`", "- `reference_comparison.csv`", "- `baseline_comparison.csv`", "- `surrogate_diagnostics.csv`", "- `feature_importance.json`", "- `plots/`", ] ), encoding="utf-8", ) val_lines = [ "# Validation Report", "", "## Strict Backend", f"- real-rDock-only rows: `{summary['real_rdock_only']}`", f"- fallback rows: `{int(combined_df['fallback_used'].astype(bool).sum())}`", "", "## Adaptive vs Baseline", ] for row in baseline_cmp_df.itertuples(index=False): val_lines.append( f"- `{row.strategy}` best_final=`{row.best_final_score:.4f}` mean_final=`{row.mean_final_score:.4f}` topk_hit_rate=`{row.topk_hit_rate:.4f}`" ) val_lines.extend( [ "", "## Reference Recovery", ] ) for row in recovery_df.itertuples(index=False): val_lines.append( f"- `{row.strategy}` `{row.reference_id}` rank=`{row.reference_rank}` step=`{row.reference_step}` stage=`{row.reference_recovery_stage}`" ) val_lines.extend( [ "", "## Dataset Scale", f"- per_reference_target=`{config['benchmark_dataset']['per_reference_target']}`", f"- counts_by_reference=`{counts_by_ref}`", "- If any reference is below target count, retrieval constraints are documented in target_selection and summary.", "", "## Classification Metric Note", "- ROC/PR curves are computed using a defensible analog-like label (reference ligands or high-similarity analogs).", "- These curves evaluate enrichment behavior, not absolute biological activity prediction.", ] ) paths["validation_report"].write_text("\n".join(val_lines), encoding="utf-8") required_files = [ "summary.json", "final_ranking.csv", "batch_history.csv", "timings.csv", "clusters.csv", "hyperclusters.csv", "selected_ligands.csv", "reference_recovery.csv", "reference_comparison.csv", "surrogate_diagnostics.csv", "baseline_comparison.csv", "parsed_scores.csv", "features_per_ligand.csv", "features_per_pose.csv", "feature_masks.csv", "feature_importance.json", "model_weight_over_time.csv", "feature_diagnostics.csv", "rescoring_terms.csv", "backend_validation_snapshot.csv", "README_results.md", "validation_report.md", "target_selection.md", "dataset_snapshot.csv", ] required_plots = [ "docking_score_vs_step.png", "final_score_vs_step.png", "best_score_cumulative.png", "adaptive_vs_baseline.png", "predicted_vs_realized.png", "residuals_over_time.png", "uncertainty_vs_error.png", "cluster_selection_over_time.png", "topk_recovery_over_time.png", "reference_rank_positions.png", "reference_similarity_vs_rank.png", "feature_importance_barplot.png", "metric_correlation_heatmap.png", "auc_curve.png", "pr_curve.png", ] self_audit_path = _self_audit( output_dir=output_dir, required_files=required_files, required_plots=required_plots, reference_ids=reference_ids, ) return { "summary": summary, "output_dir": str(output_dir), "paths": {k: str(v) for k, v in paths.items()} | { "self_audit_report": str(self_audit_path), "target_selection": str(target_selection_path), "plots": str(output_dir / "plots"), "raw_rdock_outputs": str(common_raw), "rdock_commands": str(merged_log), }, "plot_paths": [str(p) for p in plot_paths], "doctor": { "python_ok": doctor.python_ok, "imports_ok": doctor.imports_ok, "rdock_execs": doctor.rdock_execs, "gcc_available": doctor.gcc_available, "popt_available": doctor.popt_available, }, } def _encode_and_cluster(config: Dict[str, Any], ligands_df: pd.DataFrame, target_path: Path): protein_encoder = ProteinEncoder() protein_encoding = protein_encoder.encode_structure(target_id=config["target"]["target_id"], structure_path=target_path) ligand_encoder = LigandEncoder( LigandEncoderConfig( radius=int(config["encoding"].get("fingerprint_radius", 2)), n_bits=int(config["encoding"].get("fingerprint_bits", 1024)), generate_3d=bool(config["encoding"].get("generate_3d", False)), ) ) ligand_encodings = ligand_encoder.encode_table(ligands_df[["ligand_id", "smiles"]]) ligand_ids = [e.ligand_id for e in ligand_encodings] fingerprints = [e.fingerprint for e in ligand_encodings] vectors = np.vstack([e.vector for e in ligand_encodings]) cluster_map = cluster_ligands_butina( ligand_ids=ligand_ids, fingerprints=fingerprints, cutoff=float(config["clustering"].get("butina_cutoff", 0.35)), ) reps: Dict[int, np.ndarray] = {} id_to_index = {lid: i for i, lid in enumerate(ligand_ids)} for cid in sorted(set(cluster_map.values())): members = [lid for lid in ligand_ids if cluster_map[lid] == cid] reps[cid] = np.mean(np.vstack([vectors[id_to_index[lid]] for lid in members]), axis=0) hyper_map = hypercluster_representatives(reps, n_hyperclusters=int(config["clustering"].get("n_hyperclusters", 20))) return ligand_encodings, protein_encoding, cluster_map, hyper_map def main() -> int: parser = argparse.ArgumentParser(description="Run strict experimental benchmark") parser.add_argument("--config", default="configs/experimental_benchmark.yaml", help="Benchmark config path") args = parser.parse_args() result = run_benchmark(args.config) print(json.dumps(result["summary"], indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())