| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import random |
| import shutil |
| import sys |
| import time |
| from pathlib import Path |
| from typing import Any, Dict, 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 |
| from rdkit import Chem, DataStructs |
| from rdkit.Chem import AllChem |
|
|
| from environment.doctor import run_doctor |
| from libs.adaptive.features import bundles_to_wide_frames, compute_feature_diagnostics |
| from libs.adaptive.metrics import enrichment_metrics |
| from libs.utils.config import load_config |
| from libs.utils.logging_utils import get_logger |
| from pipeline.run_experimental_benchmark import ( |
| StageTimer, |
| _build_dataset, |
| _encode_and_cluster, |
| _recovery_tables, |
| _run_adaptive_strategy, |
| _run_random_baseline, |
| _strict_backend_check, |
| ) |
|
|
|
|
| def _time_stage(name: str, fn): |
| t0 = time.time() |
| out = fn() |
| t1 = time.time() |
| return out, StageTimer(name=name, start=t0, end=t1) |
|
|
|
|
| def _canonical(s: str) -> str | None: |
| mol = Chem.MolFromSmiles(str(s)) |
| if mol is None: |
| return None |
| return Chem.MolToSmiles(mol, canonical=True) |
|
|
|
|
| def _sim(smiles_a: str, smiles_b: str) -> float: |
| ma = Chem.MolFromSmiles(smiles_a) |
| mb = Chem.MolFromSmiles(smiles_b) |
| if ma is None or mb is None: |
| return 0.0 |
| fa = AllChem.GetMorganFingerprintAsBitVect(ma, radius=2, nBits=2048) |
| fb = AllChem.GetMorganFingerprintAsBitVect(mb, radius=2, nBits=2048) |
| return float(DataStructs.TanimotoSimilarity(fa, fb)) |
|
|
|
|
| def _annotate_similarity_to_refs(library_df: pd.DataFrame, refs_df: pd.DataFrame, analog_thr: float) -> pd.DataFrame: |
| out = library_df.copy() |
| refs = refs_df[["reference_id", "reference_smiles"]].copy() |
|
|
| sim_cols = [] |
| for ref in refs.itertuples(index=False): |
| col = f"sim_{ref.reference_id}" |
| sim_cols.append(col) |
| out[col] = out["smiles"].astype(str).map(lambda s: _sim(str(s), str(ref.reference_smiles))) |
|
|
| out["max_similarity_to_any_reference"] = out[sim_cols].max(axis=1) |
| out["best_reference"] = out[sim_cols].idxmax(axis=1).str.replace("sim_", "", regex=False) |
|
|
| def parent_refs(row: pd.Series) -> str: |
| ids = [] |
| for ref in refs["reference_id"].tolist(): |
| if float(row[f"sim_{ref}"]) >= analog_thr: |
| ids.append(ref) |
| if not ids: |
| ids = [str(row["best_reference"])] |
| return ";".join(sorted(set(ids))) |
|
|
| out["parent_references"] = out.apply(parent_refs, axis=1) |
| return out |
|
|
|
|
| def _select_shared_library(annotated_df: pd.DataFrame, refs_df: pd.DataFrame, target_size: int) -> pd.DataFrame: |
| ref_ids = set(refs_df["reference_id"].astype(str).tolist()) |
| ref_rows = annotated_df[annotated_df["ligand_id"].astype(str).isin(ref_ids)].copy() |
|
|
| non_ref = annotated_df[~annotated_df["ligand_id"].astype(str).isin(ref_ids)].copy() |
| non_ref = non_ref.sort_values( |
| ["max_similarity_to_any_reference", "similarity_to_reference"], |
| ascending=[False, False], |
| ) |
|
|
| |
| ref_targets = max(1, (target_size - ref_rows.shape[0]) // 3) |
| picked = [] |
| taken = set(ref_rows["ligand_id"].astype(str).tolist()) |
|
|
| for ref_id in refs_df["reference_id"].astype(str).tolist(): |
| cand = non_ref[non_ref["best_reference"] == ref_id] |
| for row in cand.itertuples(index=False): |
| if row.ligand_id in taken: |
| continue |
| picked.append(row) |
| taken.add(row.ligand_id) |
| if sum(1 for r in picked if r.best_reference == ref_id) >= ref_targets: |
| break |
|
|
| if len(picked) < target_size - ref_rows.shape[0]: |
| for row in non_ref.itertuples(index=False): |
| if row.ligand_id in taken: |
| continue |
| picked.append(row) |
| taken.add(row.ligand_id) |
| if len(picked) >= target_size - ref_rows.shape[0]: |
| break |
|
|
| pick_df = pd.DataFrame([r._asdict() for r in picked]) if picked else pd.DataFrame(columns=annotated_df.columns) |
| shared = pd.concat([ref_rows, pick_df], axis=0, ignore_index=True) |
| shared = shared.drop_duplicates(subset=["smiles"], keep="first").reset_index(drop=True) |
|
|
| |
| if shared.shape[0] > target_size: |
| refs = shared[shared["ligand_id"].astype(str).isin(ref_ids)] |
| others = shared[~shared["ligand_id"].astype(str).isin(ref_ids)].sort_values( |
| ["max_similarity_to_any_reference"], ascending=False |
| ) |
| keep_others = max(0, target_size - refs.shape[0]) |
| shared = pd.concat([refs, others.head(keep_others)], axis=0, ignore_index=True) |
|
|
| shared["is_reference"] = shared["ligand_id"].astype(str).isin(ref_ids) |
| return shared.reset_index(drop=True) |
|
|
|
|
| def _build_single_library_dataset(config: Dict[str, Any], root: Path, logger) -> Dict[str, Any]: |
| data = _build_dataset(config, root, logger) |
|
|
| out_dir = root / config["benchmark_dataset"]["output_dir"] |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| refs = data["reference_df"].copy() |
| raw = data["dedup_df"].copy() |
|
|
| analog_thr = float(config["benchmark_dataset"].get("analog_similarity_threshold", 0.65)) |
| target_size = int(config["benchmark_dataset"].get("shared_library_target_size", 1500)) |
|
|
| annotated = _annotate_similarity_to_refs(raw, refs, analog_thr=analog_thr) |
| shared = _select_shared_library(annotated, refs, target_size=target_size) |
|
|
| |
| ref_smiles_map = dict(zip(refs["reference_id"], refs["reference_smiles"])) |
| for ref_id, ref_smiles in ref_smiles_map.items(): |
| c = _canonical(str(ref_smiles)) |
| if c is None: |
| continue |
| mask = shared["smiles"].astype(str).map(_canonical) == c |
| if mask.any(): |
| shared.loc[mask, "ligand_id"] = ref_id |
| shared.loc[mask, "is_reference"] = True |
| shared.loc[mask, "source"] = "reference" |
|
|
| |
| aff = data["affinity_norm_df"].copy() |
| ref_aff = [] |
| for ref in refs.itertuples(index=False): |
| ref_s = _canonical(str(ref.reference_smiles)) |
| rec = { |
| "reference_id": ref.reference_id, |
| "pdb_id": ref.pdb_id, |
| "ligand_comp_id": ref.ligand_comp_id, |
| "ligand_name": ref.ligand_name, |
| "source_structure": ref.pdb_id, |
| "reference_smiles": ref.reference_smiles, |
| "affinity_type": np.nan, |
| "affinity_value": np.nan, |
| "affinity_units": np.nan, |
| "pchembl_value": np.nan, |
| } |
| if not aff.empty: |
| sub = aff[aff["smiles"].astype(str).map(_canonical) == ref_s] |
| if not sub.empty: |
| best = sub.sort_values("measurements", ascending=False).iloc[0] |
| rec["affinity_type"] = best.get("standard_type") |
| rec["affinity_value"] = best.get("standard_value_median") |
| rec["affinity_units"] = best.get("standard_units") |
| rec["pchembl_value"] = best.get("pchembl_value_median") |
| ref_aff.append(rec) |
|
|
| refs_out = pd.DataFrame(ref_aff) |
|
|
| |
| sim_cols = [c for c in shared.columns if c.startswith("sim_ref_")] |
| scaffold_cols = [ |
| "ligand_id", |
| "smiles", |
| "scaffold_core", |
| "scaffold_match", |
| "best_reference", |
| "parent_references", |
| *sim_cols, |
| ] |
| scaffold_df = shared[[c for c in scaffold_cols if c in shared.columns]].copy() |
|
|
| prov_cols = [ |
| "ligand_id", |
| "smiles", |
| "source", |
| "is_reference", |
| "parent_references", |
| "best_reference", |
| "similarity_to_reference", |
| "max_similarity_to_any_reference", |
| "pubchem_cid", |
| "retrieval_threshold", |
| *sim_cols, |
| ] |
| provenance_df = shared[[c for c in prov_cols if c in shared.columns]].copy() |
|
|
| |
| refs_out.to_csv(out_dir / "reference_ligands.csv", index=False) |
| annotated.to_csv(out_dir / "shared_library_raw.csv", index=False) |
| shared.to_csv(out_dir / "shared_library_dedup.csv", index=False) |
| scaffold_df.to_csv(out_dir / "scaffold_annotations.csv", index=False) |
| provenance_df.to_csv(out_dir / "ligand_provenance.csv", index=False) |
|
|
| return { |
| **data, |
| "reference_df": refs_out, |
| "shared_raw_df": annotated, |
| "shared_library_df": shared, |
| "scaffold_df": scaffold_df, |
| "provenance_df": provenance_df, |
| "out_dir": out_dir, |
| } |
|
|
|
|
| def _build_reference_plots(output_dir: Path, combined: pd.DataFrame, recovery: pd.DataFrame, analog_thr: float) -> list[str]: |
| plots_dir = output_dir / "plots" |
| plots_dir.mkdir(parents=True, exist_ok=True) |
| paths: list[str] = [] |
|
|
| def save(name: str): |
| p = plots_dir / name |
| plt.tight_layout() |
| plt.savefig(p, dpi=160) |
| plt.close() |
| paths.append(str(p)) |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.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("Selected Score vs Step") |
| plt.legend() |
| save("selected_score_vs_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.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("Selected Final Score vs Step") |
| plt.legend() |
| save("selected_final_score_vs_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.groupby("strategy"): |
| d = sdf.sort_values("step") |
| y = np.minimum.accumulate(d["docking_score"].to_numpy(dtype=float)) |
| plt.plot(d["step"], y, label=strategy) |
| plt.xlabel("Step") |
| plt.ylabel("Best docking score so far") |
| plt.title("Best Score So Far vs Step") |
| plt.legend() |
| save("best_score_so_far_vs_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.groupby("strategy"): |
| d = sdf.sort_values("step") |
| y = np.minimum.accumulate(d["final_score"].to_numpy(dtype=float)) |
| plt.plot(d["step"], y, label=strategy) |
| plt.xlabel("Step") |
| plt.ylabel("Best final score so far") |
| plt.title("Best Final Score So Far vs Step") |
| plt.legend() |
| save("best_final_score_so_far_vs_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.groupby("strategy"): |
| d = sdf.sort_values("step") |
| roll = d["docking_score"].rolling(window=100, min_periods=10).mean() |
| plt.plot(d["step"], roll, label=strategy) |
| plt.xlabel("Step") |
| plt.ylabel("Rolling mean docking score") |
| plt.title("Rolling Mean Score vs Step") |
| plt.legend() |
| save("rolling_mean_score_vs_step.png") |
|
|
| |
| q = float(combined["docking_score"].quantile(0.1)) |
| plt.figure(figsize=(8, 4)) |
| for strategy, sdf in combined.groupby("strategy"): |
| d = sdf.sort_values("step").copy() |
| good = (d["docking_score"] <= q).astype(int) |
| frac = good.rolling(window=100, min_periods=10).mean() |
| plt.plot(d["step"], frac, label=strategy) |
| plt.xlabel("Step") |
| plt.ylabel("Rolling good-hit fraction") |
| plt.title("Rolling Good Hit Fraction vs Step") |
| plt.legend() |
| save("rolling_good_hit_fraction_vs_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| sub = recovery[["strategy", "reference_id", "reference_step"]].copy() |
| x = np.arange(sub.shape[0]) |
| labels = [f"{r.reference_id}-{r.strategy}" for r in sub.itertuples(index=False)] |
| y = pd.to_numeric(sub["reference_step"], errors="coerce") |
| y = y.fillna(combined["step"].max() + 5) |
| plt.bar(x, y) |
| plt.xticks(x, labels, rotation=40, ha="right") |
| plt.ylabel("Discovery step") |
| plt.title("Reference Discovery Step") |
| save("reference_discovery_step.png") |
|
|
| |
| plt.figure(figsize=(8, 4)) |
| sub = recovery[["strategy", "reference_id", "first_analog_step"]].copy() |
| x = np.arange(sub.shape[0]) |
| labels = [f"{r.reference_id}-{r.strategy}" for r in sub.itertuples(index=False)] |
| y = pd.to_numeric(sub["first_analog_step"], errors="coerce") |
| y = y.fillna(combined["step"].max() + 5) |
| plt.bar(x, y) |
| plt.xticks(x, labels, rotation=40, ha="right") |
| plt.ylabel("Discovery step") |
| plt.title("Reference Analog Discovery Step") |
| save("reference_analog_discovery_step.png") |
|
|
| |
| ad = combined[combined["strategy"] == "adaptive"].copy() |
| ad = ad[np.isfinite(pd.to_numeric(ad["predicted_score_prebatch"], errors="coerce"))] |
|
|
| plt.figure(figsize=(5, 5)) |
| if not ad.empty: |
| plt.scatter(ad["predicted_score_prebatch"], ad["docking_score"], s=16, alpha=0.6) |
| plt.xlabel("Predicted") |
| plt.ylabel("Realized") |
| plt.title("Predicted vs Realized") |
| save("predicted_vs_realized.png") |
|
|
| plt.figure(figsize=(8, 4)) |
| if not ad.empty: |
| res = pd.to_numeric(ad["predicted_score_prebatch"], errors="coerce") - pd.to_numeric(ad["docking_score"], errors="coerce") |
| plt.plot(ad["step"], res, marker=".", linewidth=0.8) |
| plt.xlabel("Step") |
| plt.ylabel("Residual") |
| plt.title("Residuals Over Time") |
| save("residuals_over_time.png") |
|
|
| plt.figure(figsize=(6, 4)) |
| if not ad.empty: |
| abs_err = ( |
| pd.to_numeric(ad["predicted_score_prebatch"], errors="coerce") - pd.to_numeric(ad["docking_score"], errors="coerce") |
| ).abs() |
| plt.scatter(pd.to_numeric(ad["predicted_uncertainty_prebatch"], errors="coerce"), abs_err, s=16, alpha=0.6) |
| plt.xlabel("Uncertainty") |
| plt.ylabel("Absolute error") |
| plt.title("Uncertainty vs Error") |
| save("uncertainty_vs_error.png") |
|
|
| |
| plt.figure(figsize=(9, 5)) |
| if "feature_contribution" in combined.columns: |
| pass |
| plt.title("Feature Importance") |
| |
| plt.text(0.5, 0.5, "See feature_importance.json", ha="center", va="center") |
| plt.axis("off") |
| save("feature_importance_barplot.png") |
|
|
| |
| cols = ["docking_score", "final_score", "interface_contact_proxy", "hbond_proxy", "shape_proxy", "similarity_to_parent_reference"] |
| cdf = combined[[c for c in cols if c in combined.columns]].apply(pd.to_numeric, errors="coerce") |
| corr = cdf.corr().fillna(0) |
| plt.figure(figsize=(7, 6)) |
| plt.imshow(corr.to_numpy(), cmap="coolwarm", vmin=-1, vmax=1) |
| plt.xticks(np.arange(corr.shape[1]), corr.columns, rotation=35, ha="right") |
| plt.yticks(np.arange(corr.shape[0]), corr.index) |
| plt.colorbar(label="Pearson r") |
| plt.title("Metric Correlation Heatmap") |
| save("metric_correlation_heatmap.png") |
|
|
| return paths |
|
|
|
|
| def _replace_feature_importance_plot(output_dir: Path, feature_importance: Dict[str, float]) -> None: |
| p = output_dir / "plots" / "feature_importance_barplot.png" |
| plt.figure(figsize=(9, 5)) |
| items = sorted(feature_importance.items(), key=lambda kv: kv[1], reverse=True)[:20] |
| if items: |
| names = [k for k, _ in items] |
| vals = [v for _, v in items] |
| plt.barh(np.arange(len(vals)), vals) |
| plt.yticks(np.arange(len(vals)), names) |
| plt.gca().invert_yaxis() |
| plt.title("Feature Importance (Top 20)") |
| else: |
| plt.text(0.5, 0.5, "No feature importance available", ha="center", va="center") |
| plt.axis("off") |
| plt.tight_layout() |
| plt.savefig(p, dpi=160) |
| plt.close() |
|
|
|
|
| def _ordering_metrics(df: pd.DataFrame) -> Dict[str, float]: |
| d = df.sort_values("step").copy() |
| n = d.shape[0] |
| if n == 0: |
| return {} |
|
|
| e = max(1, int(0.2 * n)) |
| l = max(1, int(0.2 * n)) |
|
|
| early_mean = float(d.head(e)["docking_score"].mean()) |
| late_mean = float(d.tail(l)["docking_score"].mean()) |
|
|
| q10 = float(d["docking_score"].quantile(0.1)) |
|
|
| def frac_found(pct: float) -> float: |
| k = max(1, int(pct * n)) |
| top = d.sort_values("docking_score").head(max(1, int(0.1 * n))) |
| top_ids = set(top["ligand_id"].astype(str).tolist()) |
| first_ids = set(d.head(k)["ligand_id"].astype(str).tolist()) |
| return float(len(top_ids & first_ids) / max(1, len(top_ids))) |
|
|
| best_so_far = np.minimum.accumulate(d["docking_score"].to_numpy(dtype=float)) |
| auc_best = float(np.trapz(best_so_far, dx=1.0)) |
|
|
| concentration = ( |
| d.assign(good=(d["docking_score"] <= q10).astype(int)) |
| .assign(cum_good=lambda x: x["good"].cumsum()) |
| .assign(step1=lambda x: x["step"] + 1) |
| ) |
| concentration_idx = float((concentration["cum_good"] / concentration["step1"]).mean()) |
|
|
| return { |
| "early_window_mean_score": early_mean, |
| "late_window_mean_score": late_mean, |
| "top10pct_found_in_first10pct": frac_found(0.10), |
| "top10pct_found_in_first20pct": frac_found(0.20), |
| "top10pct_found_in_first30pct": frac_found(0.30), |
| "area_under_best_score_so_far_curve": auc_best, |
| "score_concentration_index": concentration_idx, |
| } |
|
|
|
|
| def _self_audit(output_dir: Path, refs: Sequence[str], target_size: int) -> Path: |
| issues = [] |
| checks = [] |
|
|
| required_files = [ |
| "summary.json", |
| "final_ranking_adaptive.csv", |
| "final_ranking_naive.csv", |
| "batch_history_adaptive.csv", |
| "batch_history_naive.csv", |
| "timings.csv", |
| "clusters.csv", |
| "hyperclusters.csv", |
| "selected_ligands_adaptive.csv", |
| "selected_ligands_naive.csv", |
| "reference_recovery.csv", |
| "reference_comparison.csv", |
| "surrogate_diagnostics.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", |
| "README_results.md", |
| "validation_report.md", |
| "self_audit_report.md", |
| ] |
| required_plots = [ |
| "selected_score_vs_step.png", |
| "selected_final_score_vs_step.png", |
| "best_score_so_far_vs_step.png", |
| "best_final_score_so_far_vs_step.png", |
| "rolling_mean_score_vs_step.png", |
| "rolling_good_hit_fraction_vs_step.png", |
| "reference_discovery_step.png", |
| "reference_analog_discovery_step.png", |
| "predicted_vs_realized.png", |
| "residuals_over_time.png", |
| "uncertainty_vs_error.png", |
| "feature_importance_barplot.png", |
| "metric_correlation_heatmap.png", |
| ] |
|
|
| for f in required_files: |
| p = output_dir / f |
| ok = p.exists() and p.stat().st_size > 0 |
| checks.append(f"- file `{f}` ok: `{ok}`") |
| if not ok: |
| issues.append(f"Missing file: {f}") |
|
|
| for f in required_plots: |
| p = output_dir / "plots" / f |
| ok = p.exists() and p.stat().st_size > 0 |
| checks.append(f"- plot `{f}` ok: `{ok}`") |
| if not ok: |
| issues.append(f"Missing plot: {f}") |
|
|
| data = pd.read_csv(output_dir / "data_snapshot.csv") if (output_dir / "data_snapshot.csv").exists() else pd.DataFrame() |
| for r in refs: |
| present = (not data.empty) and bool((data["ligand_id"].astype(str) == str(r)).any()) |
| checks.append(f"- reference `{r}` in library: `{present}`") |
| if not present: |
| issues.append(f"Reference missing in library: {r}") |
|
|
| if not data.empty: |
| n = int(data.shape[0]) |
| around = abs(n - target_size) <= 200 |
| checks.append(f"- library size around {target_size}: `{around}` (n={n})") |
| if not around: |
| issues.append(f"Library size not around {target_size}: {n}") |
|
|
| parsed = pd.read_csv(output_dir / "parsed_scores.csv") if (output_dir / "parsed_scores.csv").exists() else pd.DataFrame() |
| if not parsed.empty: |
| no_fallback = not parsed["fallback_used"].astype(bool).any() |
| real = bool((parsed["backend_mode"] == "real-rdock").all()) |
| checks.append(f"- no fallback rows: `{no_fallback}`") |
| checks.append(f"- backend_mode real-rdock only: `{real}`") |
| if not no_fallback: |
| issues.append("Fallback rows detected") |
| if not real: |
| issues.append("Non-real backend rows detected") |
|
|
| by_strategy = parsed.groupby("strategy", as_index=False).size() |
| if by_strategy.shape[0] >= 2: |
| vals = by_strategy["size"].astype(int).tolist() |
| comparable = len(set(vals)) == 1 |
| checks.append(f"- adaptive/naive comparable evaluated counts: `{comparable}` ({vals})") |
| if not comparable: |
| issues.append(f"Adaptive/naive evaluated counts differ: {vals}") |
|
|
| report_lines = ["# Self Audit Report", "", "## Checks", *checks, "", "## Issues"] |
| if issues: |
| report_lines.extend([f"- {i}" for i in issues]) |
| else: |
| report_lines.append("- None") |
|
|
| 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_single_library_benchmark(config_path: str | Path) -> Dict[str, Any]: |
| logger = get_logger("benchmark_single_library") |
| 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"])) |
|
|
| timers: list[StageTimer] = [] |
|
|
| doctor, tm = _time_stage("environment_check", run_doctor) |
| timers.append(tm) |
|
|
| dataset_info, tm = _time_stage("build_shared_library", lambda: _build_single_library_dataset(config, root, logger)) |
| timers.append(tm) |
|
|
| shared_df = dataset_info["shared_library_df"].copy() |
| shared_df = shared_df.reset_index(drop=True) |
| shared_df["ligand_id"] = shared_df["ligand_id"].astype(str) |
| shared_df["smiles"] = shared_df["smiles"].astype(str) |
|
|
| refs = dataset_info["reference_df"]["reference_id"].astype(str).tolist() |
| for r in refs: |
| if not (shared_df["ligand_id"].astype(str) == r).any(): |
| raise RuntimeError(f"Reference ligand missing from shared library: {r}") |
|
|
| (encodings, protein_encoding, cluster_map, hyper_map), tm = _time_stage( |
| "encode_cluster", |
| lambda: _encode_and_cluster(config, shared_df, dataset_info["target_path"]), |
| ) |
| timers.append(tm) |
|
|
| adaptive_info = _run_adaptive_strategy( |
| config=config, |
| root=root, |
| output_dir=output_dir, |
| ligands_df=shared_df, |
| ligand_encodings=encodings, |
| cluster_map=cluster_map, |
| hyper_map=hyper_map, |
| protein_encoding=protein_encoding, |
| target_path=dataset_info["target_path"], |
| stage_timers=timers, |
| ) |
|
|
| t0 = time.time() |
| naive_info = _run_random_baseline( |
| config=config, |
| output_dir=output_dir, |
| ligands_df=shared_df, |
| cluster_map=cluster_map, |
| hyper_map=hyper_map, |
| target_path=dataset_info["target_path"], |
| seed=int(run_cfg["random_seed"]) + 101, |
| ) |
| timers.append(StageTimer(name="naive_loop", start=t0, end=time.time())) |
|
|
| adf = adaptive_info["evaluated_df"].copy() |
| ndf = naive_info["evaluated_df"].copy() |
| ndf["strategy"] = "naive" |
| adf["strategy"] = "adaptive" |
|
|
| combined = pd.concat([adf, ndf], axis=0, ignore_index=True) |
| _strict_backend_check(combined.to_dict(orient="records")) |
|
|
| |
| rank_ad = adf.sort_values("final_score").reset_index(drop=True) |
| rank_ad["rank"] = np.arange(1, rank_ad.shape[0] + 1) |
| rank_nv = ndf.sort_values("final_score").reset_index(drop=True) |
| rank_nv["rank"] = np.arange(1, rank_nv.shape[0] + 1) |
|
|
| recovery_df, ref_cmp_df, baseline_cmp_df = _recovery_tables( |
| combined_df=combined, |
| ligands_df=shared_df, |
| references=refs, |
| analog_similarity_threshold=float(config["analysis"].get("analog_similarity_threshold", 0.65)), |
| topk_values=[10, 25, 50, 100], |
| ) |
|
|
| |
| bh_naive = ( |
| ndf.groupby("round", as_index=False) |
| .agg(batch_size=("ligand_id", "count"), mean_score=("docking_score", "mean"), best_score=("docking_score", "min")) |
| .rename(columns={"round": "round_idx"}) |
| ) |
|
|
| |
| ad_pred = adf[np.isfinite(pd.to_numeric(adf["predicted_score_prebatch"], errors="coerce"))].copy() |
| if ad_pred.empty: |
| surrogate_diag = pd.DataFrame(columns=["step", "ligand_id", "predicted", "realized", "residual", "uncertainty", "abs_error"]) |
| else: |
| surrogate_diag = pd.DataFrame( |
| { |
| "step": ad_pred["step"], |
| "ligand_id": ad_pred["ligand_id"], |
| "predicted": pd.to_numeric(ad_pred["predicted_score_prebatch"], errors="coerce"), |
| "realized": pd.to_numeric(ad_pred["docking_score"], errors="coerce"), |
| "uncertainty": pd.to_numeric(ad_pred["predicted_uncertainty_prebatch"], errors="coerce"), |
| } |
| ) |
| surrogate_diag["residual"] = surrogate_diag["predicted"] - surrogate_diag["realized"] |
| surrogate_diag["abs_error"] = surrogate_diag["residual"].abs() |
|
|
| |
| paths = { |
| "summary": output_dir / "summary.json", |
| "final_ranking_adaptive": output_dir / "final_ranking_adaptive.csv", |
| "final_ranking_naive": output_dir / "final_ranking_naive.csv", |
| "batch_history_adaptive": output_dir / "batch_history_adaptive.csv", |
| "batch_history_naive": output_dir / "batch_history_naive.csv", |
| "timings": output_dir / "timings.csv", |
| "clusters": output_dir / "clusters.csv", |
| "hyperclusters": output_dir / "hyperclusters.csv", |
| "selected_ligands_adaptive": output_dir / "selected_ligands_adaptive.csv", |
| "selected_ligands_naive": output_dir / "selected_ligands_naive.csv", |
| "reference_recovery": output_dir / "reference_recovery.csv", |
| "reference_comparison": output_dir / "reference_comparison.csv", |
| "surrogate_diagnostics": output_dir / "surrogate_diagnostics.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", |
| "readme": output_dir / "README_results.md", |
| "validation_report": output_dir / "validation_report.md", |
| "data_snapshot": output_dir / "data_snapshot.csv", |
| "target_selection": output_dir / "target_selection.md", |
| "provenance_table": output_dir / "ligand_provenance.csv", |
| "scaffold_table": output_dir / "scaffold_annotations.csv", |
| "reference_table": output_dir / "reference_ligands.csv", |
| "shared_library_raw": output_dir / "shared_library_raw.csv", |
| "shared_library_dedup": output_dir / "shared_library_dedup.csv", |
| } |
|
|
| rank_ad.to_csv(paths["final_ranking_adaptive"], index=False) |
| rank_nv.to_csv(paths["final_ranking_naive"], index=False) |
| pd.DataFrame(adaptive_info["scheduler"].state.batch_history).to_csv(paths["batch_history_adaptive"], index=False) |
| bh_naive.to_csv(paths["batch_history_naive"], index=False) |
| pd.DataFrame([{"stage": t.name, "seconds": t.seconds} for t in 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 shared_df["ligand_id"]] |
| ).to_csv(paths["clusters"], index=False) |
| pd.DataFrame([{"cluster_id": int(c), "hypercluster_id": int(h)} for c, h in sorted(hyper_map.items())]).to_csv( |
| paths["hyperclusters"], index=False |
| ) |
| adaptive_info["selected_df"].to_csv(paths["selected_ligands_adaptive"], index=False) |
| naive_info["selected_df"].to_csv(paths["selected_ligands_naive"], 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) |
| combined.to_csv(paths["parsed_scores"], index=False) |
|
|
| 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() |
| 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) |
|
|
| feature_importance = adaptive_info["scheduler"].surrogate.feature_importance() |
| paths["feature_importance"].write_text(json.dumps(feature_importance, indent=2), encoding="utf-8") |
| adaptive_info["model_weight_df"].to_csv(paths["model_weight_over_time"], index=False) |
|
|
| feat_diag = compute_feature_diagnostics( |
| feature_values_df, |
| feature_masks_df, |
| target=feature_values_df["ligand_id"].map(adf.groupby("ligand_id")["docking_score"].min().to_dict()), |
| ) |
| feat_diag.to_csv(paths["feature_diagnostics"], index=False) |
|
|
| combined[["strategy", "step", "ligand_id", "docking_score", "interface_contact_proxy", "feature_rescore", "final_score"]].to_csv( |
| paths["rescoring_terms"], index=False |
| ) |
|
|
| shared_df.to_csv(paths["data_snapshot"], index=False) |
| dataset_info["provenance_df"].to_csv(paths["provenance_table"], index=False) |
| dataset_info["scaffold_df"].to_csv(paths["scaffold_table"], index=False) |
| dataset_info["reference_df"].to_csv(paths["reference_table"], index=False) |
| dataset_info["shared_raw_df"].to_csv(paths["shared_library_raw"], index=False) |
| dataset_info["shared_library_df"].to_csv(paths["shared_library_dedup"], index=False) |
|
|
| |
| refs_info = dataset_info["reference_df"].copy() |
| lines = ["# Target Selection", "", "Chosen target: `MDM2`", "", "Reference complexes:"] |
| for row in refs_info.itertuples(index=False): |
| lines.append( |
| f"- `{row.reference_id}` | pdb `{row.pdb_id}` | ligand `{row.ligand_comp_id}` | name `{row.ligand_name}` | affinity `{row.affinity_value}` `{row.affinity_units}`" |
| ) |
| lines.append(f" - reference_smiles: `{row.reference_smiles}`") |
| paths["target_selection"].write_text("\n".join(lines), encoding="utf-8") |
|
|
| |
| raw_root = output_dir / "raw_rdock_outputs" |
| raw_root.mkdir(parents=True, exist_ok=True) |
| shutil.copytree(adaptive_info["raw_root"], raw_root / "adaptive", dirs_exist_ok=True) |
| shutil.copytree(naive_info["raw_root"], raw_root / "naive", dirs_exist_ok=True) |
|
|
| log_path = output_dir / "rdock_commands.log" |
| log_path.write_text( |
| "\n".join( |
| [ |
| "# adaptive", |
| adaptive_info["command_log"].read_text(encoding="utf-8") if adaptive_info["command_log"].exists() else "", |
| "# naive", |
| naive_info["command_log"].read_text(encoding="utf-8") if naive_info["command_log"].exists() else "", |
| ] |
| ), |
| encoding="utf-8", |
| ) |
|
|
| |
| metrics_ad = _ordering_metrics(adf) |
| metrics_nv = _ordering_metrics(ndf) |
|
|
| topk_hit_ad = enrichment_metrics( |
| scores=adf["docking_score"].astype(float).tolist(), |
| labels=(adf["docking_score"] <= float(combined["docking_score"].quantile(0.1))).astype(int).tolist(), |
| topk=min(150, adf.shape[0]), |
| ) |
| topk_hit_nv = enrichment_metrics( |
| scores=ndf["docking_score"].astype(float).tolist(), |
| labels=(ndf["docking_score"] <= float(combined["docking_score"].quantile(0.1))).astype(int).tolist(), |
| topk=min(150, ndf.shape[0]), |
| ) |
|
|
| plot_paths = _build_reference_plots( |
| output_dir=output_dir, |
| combined=combined, |
| recovery=recovery_df, |
| analog_thr=float(config["analysis"].get("analog_similarity_threshold", 0.65)), |
| ) |
| _replace_feature_importance_plot(output_dir=output_dir, feature_importance=feature_importance) |
|
|
| summary = { |
| "target": "MDM2", |
| "reference_ids": refs, |
| "shared_library_size": int(shared_df.shape[0]), |
| "reference_ligands_present": all((shared_df["ligand_id"].astype(str) == r).any() for r in refs), |
| "cluster_count": int(len(set(cluster_map.values()))), |
| "hypercluster_count": int(len(set(hyper_map.values()))), |
| "adaptive_evaluated_count": int(adf.shape[0]), |
| "naive_evaluated_count": int(ndf.shape[0]), |
| "target_full_budget_per_strategy": int(shared_df.shape[0]), |
| "budget_reduction_applied": bool( |
| int(run_cfg["adaptive_budget"]) < int(shared_df.shape[0]) or int(run_cfg["baseline_budget"]) < int(shared_df.shape[0]) |
| ), |
| "real_rdock_only": bool((combined["backend_mode"] == "real-rdock").all() and (not combined["fallback_used"].astype(bool).any())), |
| "discovery_step_adaptive": { |
| r: ( |
| None |
| if adf[adf["ligand_id"] == r].empty |
| else int(adf[adf["ligand_id"] == r].sort_values("step").iloc[0]["step"]) |
| ) |
| for r in refs |
| }, |
| "discovery_step_naive": { |
| r: ( |
| None |
| if ndf[ndf["ligand_id"] == r].empty |
| else int(ndf[ndf["ligand_id"] == r].sort_values("step").iloc[0]["step"]) |
| ) |
| for r in refs |
| }, |
| "ordering_metrics": { |
| "adaptive": metrics_ad, |
| "naive": metrics_nv, |
| }, |
| "topk_hit_rate": { |
| "adaptive": float(topk_hit_ad["topk_hit_rate"]), |
| "naive": float(topk_hit_nv["topk_hit_rate"]), |
| }, |
| "runtime_by_stage_seconds": {t.name: t.seconds for t in timers}, |
| "total_runtime_seconds": float(sum(t.seconds for t in timers)), |
| } |
| paths["summary"].write_text(json.dumps(summary, indent=2), encoding="utf-8") |
|
|
| |
| report_lines = [ |
| "# Validation Report", |
| "", |
| "## 1. Target and Complexes", |
| "- Target: MDM2", |
| "- Complexes: 4HG7/NUT, 4J7D/I31, 4LWU/20U", |
| "", |
| "## 2. Shared Library Construction", |
| f"- Built from public similarity retrieval and global deduplication to shared universe of `{shared_df.shape[0]}` ligands.", |
| "- Includes reference ligands and close analogs/scaffold-related compounds.", |
| "", |
| "## 3. Reference Inclusion", |
| f"- All references present: `{summary['reference_ligands_present']}`", |
| f"- Reference IDs: `{', '.join(refs)}`", |
| "", |
| "## 4. Adaptive vs Naive Ordering", |
| f"- Adaptive early mean score: `{metrics_ad.get('early_window_mean_score', np.nan):.4f}`", |
| f"- Adaptive late mean score: `{metrics_ad.get('late_window_mean_score', np.nan):.4f}`", |
| f"- Naive early mean score: `{metrics_nv.get('early_window_mean_score', np.nan):.4f}`", |
| f"- Naive late mean score: `{metrics_nv.get('late_window_mean_score', np.nan):.4f}`", |
| f"- Adaptive top10%-in-first20%: `{metrics_ad.get('top10pct_found_in_first20pct', np.nan):.4f}`", |
| f"- Naive top10%-in-first20%: `{metrics_nv.get('top10pct_found_in_first20pct', np.nan):.4f}`", |
| f"- Full-library target budget per strategy: `{shared_df.shape[0]}`", |
| f"- Actual adaptive budget: `{adf.shape[0]}`", |
| f"- Actual naive budget: `{ndf.shape[0]}`", |
| f"- Budget reduction applied: `{summary['budget_reduction_applied']}`", |
| "", |
| "## 5. Reference and Analog Discovery", |
| ] |
| for r in refs: |
| report_lines.append( |
| f"- {r}: adaptive_step={summary['discovery_step_adaptive'][r]}, naive_step={summary['discovery_step_naive'][r]}" |
| ) |
| report_lines.extend( |
| [ |
| "", |
| "## 6. Surrogate Impact", |
| "- Model warm-up and weight progression are logged in model_weight_over_time.csv.", |
| "- Adaptive ordering metrics are compared against naive baseline in summary and plots.", |
| "", |
| "## 7. Overfitting Signals", |
| "- Train-vs-future error gap tracked via scheduler instability ratio.", |
| "- Residual and uncertainty diagnostics saved for inspection.", |
| "", |
| "## 8. Limitations", |
| "- Docking scores are not direct affinity estimates.", |
| "- Analog labeling uses similarity/scaffold heuristics.", |
| "", |
| "## 9. Next Steps", |
| "- Add static cluster-first baseline.", |
| "- Run replicate random baselines for confidence intervals.", |
| ] |
| ) |
| paths["validation_report"].write_text("\n".join(report_lines), encoding="utf-8") |
|
|
| paths["readme"].write_text( |
| "\n".join( |
| [ |
| "# Experimental Benchmark (Single Shared Library)", |
| "", |
| f"- Shared library size: `{shared_df.shape[0]}`", |
| f"- Adaptive evaluated: `{adf.shape[0]}`", |
| f"- Naive evaluated: `{ndf.shape[0]}`", |
| f"- Real rDock only: `{summary['real_rdock_only']}`", |
| "", |
| "Key files:", |
| "- summary.json", |
| "- final_ranking_adaptive.csv", |
| "- final_ranking_naive.csv", |
| "- reference_recovery.csv", |
| "- reference_comparison.csv", |
| "- parsed_scores.csv", |
| "- plots/", |
| ] |
| ), |
| encoding="utf-8", |
| ) |
|
|
| |
| (output_dir / "self_audit_report.md").write_text("placeholder", encoding="utf-8") |
| self_audit_path = _self_audit(output_dir, refs=refs, target_size=int(config["benchmark_dataset"].get("shared_library_target_size", 1500))) |
|
|
| 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), |
| "plots": str(output_dir / "plots"), |
| "rdock_commands": str(log_path), |
| "raw_rdock_outputs": str(raw_root), |
| }, |
| "plot_paths": 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 main() -> int: |
| parser = argparse.ArgumentParser(description="Corrected single-library experimental benchmark") |
| parser.add_argument("--config", default="configs/experimental_benchmark_single_library.yaml") |
| args = parser.parse_args() |
|
|
| result = run_single_library_benchmark(args.config) |
| print(json.dumps(result["summary"], indent=2)) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|