from __future__ import annotations import argparse import json import shutil import time from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List import sys ROOT_DIR = Path(__file__).resolve().parents[1] if str(ROOT_DIR) not in sys.path: sys.path.insert(0, str(ROOT_DIR)) import numpy as np import pandas as pd from rdkit import Chem from environment.doctor import run_doctor from libs.adaptive.clustering import cluster_ligands_butina from libs.adaptive.diversity import selection_diversity from libs.adaptive.features import ( FeatureBundle, FeatureValue, build_complex_feature_bundle, build_ligand_feature_bundle, build_protein_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 resolve_threads_used 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.io_smiles import read_smiles_table from libs.utils.logging_utils import get_logger from libs.utils.paths import ProjectPaths @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 _save_json(payload: Dict[str, Any], path: Path) -> Path: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, indent=2) return path def _cluster_feature_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 _select_reference_mol(ligands_df: pd.DataFrame) -> Chem.Mol | None: if ligands_df.empty or "smiles" not in ligands_df.columns: return None reference_smiles: str | None = None if "label" in ligands_df.columns: positives = ligands_df.loc[pd.to_numeric(ligands_df["label"], errors="coerce") > 0.5] if not positives.empty: reference_smiles = str(positives.iloc[0]["smiles"]) if reference_smiles is None: reference_smiles = str(ligands_df.iloc[0]["smiles"]) return Chem.MolFromSmiles(reference_smiles) def _top_feature_importance(importance: Dict[str, float], topn: int = 20) -> List[tuple[str, float]]: ranked = sorted(importance.items(), key=lambda kv: kv[1], reverse=True) return [(name, float(value)) for name, value in ranked[:topn]] def _compute_correlation_pairs(values_df: pd.DataFrame, max_pairs: int = 200) -> pd.DataFrame: feature_cols = [c for c in values_df.columns if c != "ligand_id"] compact_cols = [c for c in feature_cols if not c.startswith("morgan_fp_")] # Keep a manageable subset of fingerprints for diagnostics-only correlation pairs. fp_cols = sorted([c for c in feature_cols if c.startswith("morgan_fp_")])[:64] corr_cols = compact_cols + fp_cols if len(corr_cols) < 2: return pd.DataFrame(columns=["row_type", "feature", "feature_b", "corr"]) corr_input = values_df[corr_cols].apply(pd.to_numeric, errors="coerce") # Drop constant channels to avoid undefined correlation noise. nunique = corr_input.nunique(dropna=True) corr_input = corr_input.loc[:, nunique > 1] if corr_input.shape[1] < 2: return pd.DataFrame(columns=["row_type", "feature", "feature_b", "corr"]) corr = corr_input.corr() rows = [] cols = corr.columns.tolist() for i in range(len(cols)): for j in range(i + 1, len(cols)): val = corr.iloc[i, j] if pd.notna(val): rows.append({"row_type": "corr_pair", "feature": cols[i], "feature_b": cols[j], "corr": float(val)}) if not rows: return pd.DataFrame(columns=["row_type", "feature", "feature_b", "corr"]) out = pd.DataFrame(rows) out["abs_corr"] = out["corr"].abs() out = out.sort_values("abs_corr", ascending=False).head(max_pairs).drop(columns=["abs_corr"]) return out.reset_index(drop=True) def _baseline_vs_model_metrics(best_df: pd.DataFrame, ligands_df: pd.DataFrame, topk: int = 10) -> Dict[str, float]: if best_df.empty or "label" not in ligands_df.columns: return { "baseline_topk_hit_rate": 0.0, "baseline_enrichment_like": 0.0, "model_topk_hit_rate": 0.0, "model_enrichment_like": 0.0, "hit_rate_delta_model_minus_baseline": 0.0, } merged = best_df.merge(ligands_df[["ligand_id", "label"]], on="ligand_id", how="left") labels = merged["label"].fillna(0).astype(int).tolist() baseline = enrichment_metrics( scores=merged["docking_score"].astype(float).tolist(), labels=labels, topk=min(topk, merged.shape[0]), ) model = enrichment_metrics( scores=merged["final_score"].astype(float).tolist(), labels=labels, topk=min(topk, merged.shape[0]), ) return { "baseline_topk_hit_rate": float(baseline["topk_hit_rate"]), "baseline_enrichment_like": float(baseline["enrichment_like"]), "model_topk_hit_rate": float(model["topk_hit_rate"]), "model_enrichment_like": float(model["enrichment_like"]), "hit_rate_delta_model_minus_baseline": float(model["topk_hit_rate"] - baseline["topk_hit_rate"]), } def _write_backend_proof( output_dir: Path, cap: Dict[str, Any], command_log_path: Path, raw_output_root: Path, parsed_df: pd.DataFrame, require_real_backend: bool, ) -> Path: proof_path = output_dir / "backend_proof.md" raw_files = sorted([str(p) for p in raw_output_root.rglob("*") if p.is_file()]) sample_rows = parsed_df[["ligand_id", "docking_score", "score_source", "parsed_from", "backend_mode"]].head(5) lines = [ "# Backend Proof", "", "## Binaries Called", f"- rbdock: `{cap.get('details', {}).get('rbdock')}`", f"- rbcavity: `{cap.get('details', {}).get('rbcavity')}`", f"- sdtether: `{cap.get('details', {}).get('sdtether')}`", "", "## Commands Executed", f"- Command log: `{command_log_path}`", f"- Strict real backend required: `{require_real_backend}`", "", "## Output Files Created", f"- Raw output root: `{raw_output_root}`", f"- Raw output files count: `{len(raw_files)}`", ] for item in raw_files[:30]: lines.append(f"- `{item}`") lines.extend( [ "", "## Score Parsing Source", "Scores are parsed from real rDock SDF output tag `` in files referenced by `parsed_from`.", "", "## Parsed Score Examples", "```text", sample_rows.to_string(index=False) if not sample_rows.empty else "No parsed records", "```", "", "## Why These Are Real rDock Scores", "- Commands in `rdock_commands.log` include direct `rbcavity` and `rbdock` invocations.", "- Raw SDF outputs are stored under `raw_rdock_outputs/`.", "- Each result row stores provenance: `backend_mode`, `score_source`, `raw_output_file`, `parsed_from`.", "- In strict mode, any fallback or missing real output aborts the run.", ] ) proof_path.write_text("\n".join(lines), encoding="utf-8") return proof_path def _write_validation_report( output_dir: Path, summary: Dict[str, Any], feature_catalog_df: pd.DataFrame, feature_diag_df: pd.DataFrame, model_weight_df: pd.DataFrame, feature_importance: Dict[str, float], baseline_comparison: Dict[str, float], ) -> Path: report_path = output_dir / "validation_report.md" feature_rows = feature_diag_df[feature_diag_df.get("row_type", pd.Series(dtype=str)) == "feature"] top_missing = feature_rows.sort_values("missing_frac", ascending=False).head(15) importance_ranked = _top_feature_importance(feature_importance, topn=20) exact_count = int((feature_catalog_df["feature_type"] == "exact").sum()) if not feature_catalog_df.empty else 0 approx_count = int((feature_catalog_df["feature_type"] == "approximate").sum()) if not feature_catalog_df.empty else 0 proxy_count = int((feature_catalog_df["feature_type"] == "proxy").sum()) if not feature_catalog_df.empty else 0 model_weights = model_weight_df["model_weight"].tolist() if "model_weight" in model_weight_df.columns else [] early_weight = float(model_weights[0]) if model_weights else 0.0 late_weight = float(model_weights[-1]) if model_weights else 0.0 lines = [ "# Validation Report", "", "## Feature Set", f"- Total features: `{summary.get('feature_count', 0)}`", f"- Exact features: `{exact_count}`", f"- Approximate features: `{approx_count}`", f"- Proxy features: `{proxy_count}`", f"- Global missing fraction: `{summary.get('feature_missing_fraction', 0.0):.4f}`", "", "## Missingness and Availability", "Top missing features:", ] if top_missing.empty: lines.append("- No feature diagnostics available") else: for row in top_missing.itertuples(index=False): lines.append(f"- `{row.feature}` missing=`{row.missing_frac:.3f}`") lines.extend( [ "", "## Feature Importance", "Top surrogate channels:", ] ) if not importance_ranked: lines.append("- No feature importance available (surrogate in warm-up or unsupported backend)") else: for name, value in importance_ranked: lines.append(f"- `{name}`: `{value:.6f}`") lines.extend( [ "", "## Early vs Late Stage Behavior", f"- Early model weight: `{early_weight:.3f}`", f"- Late model weight: `{late_weight:.3f}`", "- Model weight increases with sample count and is reduced when instability rises.", "", "## Docking-Only Baseline Comparison", f"- Baseline top-k hit rate: `{baseline_comparison['baseline_topk_hit_rate']:.4f}`", f"- Model-assisted top-k hit rate: `{baseline_comparison['model_topk_hit_rate']:.4f}`", f"- Hit-rate delta (model - baseline): `{baseline_comparison['hit_rate_delta_model_minus_baseline']:.4f}`", "", "## Notes", "- Missing features are represented via explicit mask channels, never silently replaced with zeros.", "- Surrogate input contains ligand/protein/complex channels plus missingness masks.", "- Strict backend mode still enforces real-rDock-only score provenance when enabled.", ] ) report_path.write_text("\n".join(lines), encoding="utf-8") return report_path def run_pipeline(config_path: str | Path) -> Dict[str, Any]: config = load_config(config_path) logger = get_logger("pipeline") seed = int(config.get("run", {}).get("random_seed", 42)) np.random.seed(seed) root = Path(__file__).resolve().parents[1] paths = ProjectPaths(root=root) paths.ensure() output_dir = root / str(config["run"]["output_dir"]) work_dir = output_dir / "work" raw_output_root = output_dir / "raw_rdock_outputs" command_log_path = output_dir / "rdock_commands.log" if output_dir.exists(): shutil.rmtree(output_dir) output_dir.mkdir(parents=True, exist_ok=True) work_dir.mkdir(parents=True, exist_ok=True) raw_output_root.mkdir(parents=True, exist_ok=True) stage_timers: List[StageTimer] = [] # Stage 1: environment capability. doctor_report, tm = _time_stage("environment_check", run_doctor) stage_timers.append(tm) # Stage 2: load inputs. def _load_inputs(): ligands = read_smiles_table(root / config["data"]["ligand_table"]) target_path = root / config["data"]["target_path"] return ligands, target_path (ligands_df, target_path), tm = _time_stage("load_inputs", _load_inputs) stage_timers.append(tm) # Stage 3: encode target and ligands. def _encode_all(): protein_encoder = ProteinEncoder() protein_enc = protein_encoder.encode_structure( target_id=str(config["data"]["target_id"]), structure_path=target_path, ) ligand_encoder = LigandEncoder( LigandEncoderConfig( radius=int(config["encoding"]["fingerprint_radius"]), n_bits=int(config["encoding"]["fingerprint_bits"]), generate_3d=bool(config["encoding"].get("generate_3d", False)), ) ) ligand_encodings = ligand_encoder.encode_table(ligands_df) return protein_enc, ligand_encodings (protein_encoding, ligand_encodings), tm = _time_stage("encoding", _encode_all) stage_timers.append(tm) 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]) id_to_index = {lid: idx for idx, lid in enumerate(ligand_ids)} # Stage 4: clustering + hyperclustering. def _cluster(): cluster_map = cluster_ligands_butina( ligand_ids=ligand_ids, fingerprints=fingerprints, cutoff=float(config["clustering"]["butina_cutoff"]), ) reps: Dict[int, np.ndarray] = {} 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"]["n_hyperclusters"]), ) return cluster_map, hyper_map (cluster_map, hyper_map), tm = _time_stage("clustering", _cluster) stage_timers.append(tm) # Stage 5: build feature bundles for all ligands. def _build_feature_bundles(): reference_mol = _select_reference_mol(ligands_df) protein_bundle = build_protein_feature_bundle( target_id=str(config["data"]["target_id"]), sequence_features=protein_encoding.sequence_features, structure_features=protein_encoding.structure_features, ) bundles: Dict[str, FeatureBundle] = {} for enc in ligand_encodings: cluster_id = int(cluster_map[enc.ligand_id]) hyper_id = int(hyper_map.get(cluster_id, -1)) intrinsic = build_ligand_feature_bundle( ligand_id=enc.ligand_id, smiles=enc.smiles, fingerprint=enc.fingerprint, reference_mol=reference_mol, ) cluster_bundle = _cluster_feature_bundle(enc.ligand_id, cluster_id, hyper_id) bundles[enc.ligand_id] = merge_bundles( enc.ligand_id, [intrinsic, protein_bundle, cluster_bundle], ) values_df, masks_df, ordered_names = bundles_to_wide_frames([bundles[lid] for lid in ligand_ids]) return protein_bundle, bundles, values_df, masks_df, ordered_names (protein_bundle, ligand_feature_bundles, feature_values_df, feature_masks_df, ordered_feature_names), tm = _time_stage( "feature_setup", _build_feature_bundles ) stage_timers.append(tm) max_batches = int(config["run"]["max_batches"]) allow_mock = bool(config.get("backend", {}).get("allow_mock_if_missing", False)) require_real_backend = bool(config.get("backend", {}).get("require_real_backend", False)) if require_real_backend: allow_mock = False interface_weight = float(config["scoring"].get("interface_weight", 1.0)) scheduler_cfg = config.get("scheduler", {}) weight_cfg_data = scheduler_cfg.get("model_weight_schedule", {}) surrogate_cfg_data = scheduler_cfg.get("surrogate", {}) weight_cfg = WeightScheduleConfig( sample_knots=tuple(weight_cfg_data.get("sample_knots", [20, 50, 100, 200])), weight_knots=tuple(weight_cfg_data.get("weight_knots", [0.1, 0.3, 0.5, 0.8])), max_weight=float(weight_cfg_data.get("max_weight", 0.9)), min_weight=float(weight_cfg_data.get("min_weight", 0.05)), instability_threshold=float(weight_cfg_data.get("instability_threshold", 2.0)), instability_decay=float(weight_cfg_data.get("instability_decay", 0.25)), ) surrogate_config = SurrogateConfig( prefer_xgboost=bool(surrogate_cfg_data.get("prefer_xgboost", True)), random_state=seed, n_estimators=int(surrogate_cfg_data.get("n_estimators", 200)), min_train_samples=int(surrogate_cfg_data.get("min_train_samples", 8)), max_depth_small=int(surrogate_cfg_data.get("max_depth_small", 3)), max_depth_large=int(surrogate_cfg_data.get("max_depth_large", 6)), ) # Stage 6: scheduler and docking backend setup. def _setup_runtime(): thread_alloc = resolve_threads_used(config["backend"].get("parallel_jobs", "auto-minus-4"), reserve_threads=4) backend = RDockBackend( RDockConfig( n_runs=int(config["backend"].get("n_runs", 5)), protocol_prm=config["backend"].get("protocol_prm"), rbt_root=config["backend"].get("rbt_root"), command_log_path=str(command_log_path), mapper_radius=float(config["backend"].get("mapper_radius", 6.0)), command_timeout_seconds=int(config["backend"].get("command_timeout_seconds", 180)), parallel_jobs=int(thread_alloc.threads_used), auto_batch_memory=bool(config["backend"].get("auto_batch_memory", True)), memory_safety_fraction=float(config["backend"].get("memory_safety_fraction", 0.85)), min_memory_per_job_mb=int(config["backend"].get("min_memory_per_job_mb", 256)), memory_probe_ligands=int(config["backend"].get("memory_probe_ligands", 2)), enable_plip_interactions=bool(config["backend"].get("enable_plip_interactions", True)), plip_timeout_seconds=int(config["backend"].get("plip_timeout_seconds", 120)), 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)), ) ) cap = backend.check_capability() if require_real_backend and not cap.available: raise DockingError(f"Strict mode requires real rDock backend, capability check failed: {cap.details}") scheduler = AdaptiveScheduler( config=SchedulerConfig( batch_size=int(scheduler_cfg["batch_size"]), init_coverage_fraction=float(scheduler_cfg["init_coverage_fraction"]), conservative_deprioritize=bool(scheduler_cfg.get("conservative_deprioritize", True)), state_path=str(output_dir / "scheduler_state.json"), weight_schedule=weight_cfg, ), policy=PrioritizationPolicy(), surrogate_config=surrogate_config, ) scheduler.initialize(ligands_df[["ligand_id"]], cluster_map, hyper_map) target_context = backend.prepare_target(target_path, work_dir / "target") return backend, cap, scheduler, target_context (backend, capability, scheduler, target_context), tm = _time_stage("setup_runtime", _setup_runtime) stage_timers.append(tm) evaluated_records: List[Dict[str, Any]] = [] selected_records: List[Dict[str, Any]] = [] pose_feature_records: List[Dict[str, Any]] = [] seen_scores: Dict[str, float] = {} model_weight_records: List[Dict[str, Any]] = [] # Stage 7: adaptive loop. loop_start = time.time() for round_idx in range(max_batches): batch_ids = scheduler.select_batch() if not batch_ids: logger.info("No active ligands left to evaluate; stopping at round %s", round_idx) break round_dir = work_dir / f"batch_{round_idx:03d}" round_dir.mkdir(parents=True, exist_ok=True) ligand_files = [] for ligand_id in batch_ids: smiles = str(ligands_df.loc[ligands_df["ligand_id"] == ligand_id, "smiles"].iloc[0]) ligand_file = backend.prepare_ligand(ligand_id, smiles, round_dir / "ligands") ligand_files.append(ligand_file) selected_records.append({"round": round_idx, "ligand_id": ligand_id}) docked = backend.dock( target_context, ligand_files, round_dir / "docking", allow_mock=allow_mock, require_real_backend=require_real_backend, ) parsed = backend.parse_results(docked) if require_real_backend: violations = [ row for row in parsed if row.get("backend_mode") != "real-rdock" or bool(row.get("fallback_used")) or not str(row.get("score_source", "")).startswith("rdock_tag:") ] if violations: raise DockingError(f"Strict mode violation: non-real backend result detected: {violations[:2]}") # Persist raw backend outputs for proof. raw_batch_dir = raw_output_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): docking_score = float(row["docking_score"]) ligand_id = str(row["ligand_id"]) complex_bundle = build_complex_feature_bundle( ligand_id=ligand_id, docking_score=docking_score, interface_features=ifeat, ligand_bundle=ligand_feature_bundles[ligand_id], protein_bundle=protein_bundle, ) ligand_feature_bundles[ligand_id] = merge_bundles( ligand_id, [ligand_feature_bundles[ligand_id], complex_bundle], ) for rec in complex_bundle.to_records(channel="complex", round_idx=round_idx): rec.update( { "ligand_id": ligand_id, "docking_score": docking_score, } ) pose_feature_records.append(rec) interaction_decomp = complex_bundle.features["energy_interaction_decomposition"].value burial_ratio = complex_bundle.features["complex_ligand_burial_ratio"].value interaction_term = float(interaction_decomp) if interaction_decomp is not None else 0.0 burial_term = float(burial_ratio) if burial_ratio is not None else 0.0 try: biological_interaction_proxy = float(row.get("biological_interaction_proxy_score", 0.0) or 0.0) except Exception: biological_interaction_proxy = 0.0 try: post_docking_confidence = float(row.get("post_docking_confidence_score", 0.0) or 0.0) except Exception: post_docking_confidence = 0.0 feature_rescore = 0.15 * interaction_term - 0.1 * burial_term interaction_rescore = -0.5 * biological_interaction_proxy final_score = docking_score - interface_weight * float(ifeat["interface_contact_proxy"]) + feature_rescore + interaction_rescore batch_rows.append( { "round": round_idx, "ligand_id": ligand_id, "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", "")), "docking_score": docking_score, "top_pose_rmsd_consistency": row.get("top_pose_rmsd_consistency", ""), "pose_distance_to_pocket_center": row.get("pose_distance_to_pocket_center", ""), "pose_in_fixed_pocket": bool(row.get("pose_in_fixed_pocket", False)), "feature_rescore": float(feature_rescore), "interaction_rescore": float(interaction_rescore), "final_score": float(final_score), "post_docking_confidence_score": post_docking_confidence, "biological_interaction_proxy_score": biological_interaction_proxy, "interaction_weighted_docking_score": row.get("interaction_weighted_docking_score", ""), "interaction_filter_pass": bool(row.get("interaction_filter_pass", False)), "interaction_feature_source": str(row.get("interaction_feature_source", "")), "plip_available": bool(row.get("plip_available", False)), "plip_success": bool(row.get("plip_success", False)), "plip_interaction_count": int(row.get("plip_interaction_count", 0) or 0), "plip_hydrophobic_count": int(row.get("plip_hydrophobic_count", 0) or 0), "plip_hbond_count": int(row.get("plip_hbond_count", 0) or 0), "plip_saltbridge_count": int(row.get("plip_saltbridge_count", 0) or 0), "plip_pistacking_count": int(row.get("plip_pistacking_count", 0) or 0), "plip_pication_count": int(row.get("plip_pication_count", 0) or 0), "plip_halogen_count": int(row.get("plip_halogen_count", 0) or 0), "plip_waterbridge_count": int(row.get("plip_waterbridge_count", 0) or 0), "plip_metal_count": int(row.get("plip_metal_count", 0) or 0), "plip_message": str(row.get("plip_message", "")), **ifeat, } ) prev = seen_scores.get(ligand_id) seen_scores[ligand_id] = min(prev, docking_score) if prev is not None else docking_score evaluated_records.extend(batch_rows) batch_df = pd.DataFrame(batch_rows) feature_values_df, feature_masks_df, ordered_feature_names = bundles_to_wide_frames( [ligand_feature_bundles[lid] for lid in ligand_ids], ordered_feature_names=None, ) fit_stats = scheduler.update_from_batch( batch_df[["ligand_id", "docking_score"]], feature_values_df, feature_masks_df, ) model_weight_records.append( { "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, } ) scheduler.save_state(output_dir / f"scheduler_state_batch_{round_idx:03d}.json") loop_end = time.time() stage_timers.append(StageTimer(name="adaptive_loop", start=loop_start, end=loop_end)) # Stage 8: exports. def _export_results() -> Dict[str, Any]: if evaluated_records: eval_df = pd.DataFrame(evaluated_records) best_df = ( eval_df.sort_values("final_score") .groupby("ligand_id", as_index=False) .first() .sort_values("final_score") .reset_index(drop=True) ) else: eval_df = pd.DataFrame( columns=[ "round", "ligand_id", "docking_score", "top_pose_rmsd_consistency", "pose_distance_to_pocket_center", "pose_in_fixed_pocket", "feature_rescore", "interaction_rescore", "final_score", "post_docking_confidence_score", "biological_interaction_proxy_score", "interaction_weighted_docking_score", "interaction_filter_pass", "interaction_feature_source", "plip_available", "plip_success", "plip_interaction_count", "plip_hydrophobic_count", "plip_hbond_count", "plip_saltbridge_count", "plip_pistacking_count", "plip_pication_count", "plip_halogen_count", "plip_waterbridge_count", "plip_metal_count", "plip_message", "backend_name", "backend_mode", "fallback_used", "score_source", "parsed_from", "raw_output_file", "success", ] ) best_df = eval_df.copy() if require_real_backend and not eval_df.empty: if eval_df["fallback_used"].astype(bool).any(): raise DockingError("Strict mode violation: fallback_used=true detected in final evaluation table") if (eval_df["backend_mode"] != "real-rdock").any(): raise DockingError("Strict mode violation: backend_mode!=real-rdock detected") final_values_df, final_masks_df, _ = bundles_to_wide_frames( [ligand_feature_bundles[lid] for lid in ligand_ids], ordered_feature_names=ordered_feature_names, ) model_weight_df = pd.DataFrame(model_weight_records) pose_features_df = pd.DataFrame(pose_feature_records) catalog_map: Dict[str, Dict[str, str]] = {} for bundle in ligand_feature_bundles.values(): for fname, fval in bundle.features.items(): if fname not in catalog_map: catalog_map[fname] = { "feature_name": fname, "source": fval.source, "feature_type": fval.feature_type, } feature_catalog_df = pd.DataFrame(list(catalog_map.values())).sort_values("feature_name") if feature_catalog_df.empty: feature_catalog_df = pd.DataFrame(columns=["feature_name", "source", "feature_type"]) # Feature diagnostics and self-checks. target_series = final_values_df["ligand_id"].map(seen_scores) if not final_values_df.empty else None feature_diag_df = compute_feature_diagnostics(final_values_df, final_masks_df, target=target_series) feature_diag_df.insert(0, "row_type", "feature") if not final_masks_df.empty: mask_only = final_masks_df.drop(columns=["ligand_id"]).apply(pd.to_numeric, errors="coerce") missing_per_ligand = 1.0 - mask_only.mean(axis=1) ligand_missing_df = pd.DataFrame( { "row_type": "ligand_missing", "ligand_id": final_masks_df["ligand_id"], "missing_frac": missing_per_ligand, } ) global_missing = float(missing_per_ligand.mean()) else: ligand_missing_df = pd.DataFrame(columns=["row_type", "ligand_id", "missing_frac"]) global_missing = 0.0 corr_pairs_df = _compute_correlation_pairs(final_values_df) global_diag_df = pd.DataFrame( [ { "row_type": "global", "feature": "all_features", "missing_frac": global_missing, "feature_count": int(len(ordered_feature_names)), "sample_count": int(final_values_df.shape[0]), } ] ) diagnostics_df = pd.concat( [feature_diag_df, ligand_missing_df, corr_pairs_df, global_diag_df], axis=0, ignore_index=True, sort=False, ) feature_importance = scheduler.surrogate.feature_importance() baseline_comparison = _baseline_vs_model_metrics(best_df, ligands_df, topk=min(10, max(1, best_df.shape[0]))) clusters_df = pd.DataFrame( [ { "ligand_id": lid, "cluster_id": int(cluster_map[lid]), "hypercluster_id": int(hyper_map.get(cluster_map[lid], -1)), } for lid in ligand_ids ] ) hyper_df = pd.DataFrame( [{"cluster_id": int(cid), "hypercluster_id": int(hid)} for cid, hid in sorted(hyper_map.items())] ) selected_df = pd.DataFrame(selected_records) batch_history_df = pd.DataFrame(scheduler.state.batch_history) timings_df = pd.DataFrame([{"stage": t.name, "seconds": t.seconds} for t in stage_timers]) final_ranking_path = output_dir / "final_ranking.csv" parsed_scores_path = output_dir / "parsed_scores.csv" batch_history_path = output_dir / "batch_history.csv" clusters_path = output_dir / "clusters.csv" hyperclusters_path = output_dir / "hyperclusters.csv" timings_path = output_dir / "timings.csv" selected_path = output_dir / "selected_ligands.csv" features_per_ligand_path = output_dir / "features_per_ligand.csv" features_per_pose_path = output_dir / "features_per_pose.csv" feature_masks_path = output_dir / "feature_masks.csv" feature_importance_path = output_dir / "feature_importance.json" model_weight_path = output_dir / "model_weight_over_time.csv" feature_diag_path = output_dir / "feature_diagnostics.csv" best_df.to_csv(final_ranking_path, index=False) eval_df.to_csv(parsed_scores_path, index=False) batch_history_df.to_csv(batch_history_path, index=False) clusters_df.to_csv(clusters_path, index=False) hyper_df.to_csv(hyperclusters_path, index=False) timings_df.to_csv(timings_path, index=False) selected_df.to_csv(selected_path, index=False) final_values_df.to_csv(features_per_ligand_path, index=False) pose_features_df.to_csv(features_per_pose_path, index=False) final_masks_df.to_csv(feature_masks_path, index=False) model_weight_df.to_csv(model_weight_path, index=False) diagnostics_df.to_csv(feature_diag_path, index=False) _save_json(feature_importance, feature_importance_path) docking_scores = eval_df["docking_score"].tolist() if "docking_score" in eval_df.columns else [] final_scores = eval_df["final_score"].tolist() if "final_score" in eval_df.columns else [] label_metrics = {"topk_hit_rate": 0.0, "enrichment_like": 0.0} if not best_df.empty and "label" in ligands_df.columns: merged = best_df.merge(ligands_df[["ligand_id", "label"]], on="ligand_id", how="left") label_metrics = enrichment_metrics( scores=merged["final_score"].astype(float).tolist(), labels=merged["label"].fillna(0).astype(int).tolist(), topk=min(10, merged.shape[0]), ) selected_unique = [rid for rid in selected_df["ligand_id"].unique().tolist()] if not selected_df.empty else [] diversity = selection_diversity([fingerprints[id_to_index[lid]] for lid in selected_unique]) if selected_unique else 0.0 # Correlation summary with docking target. corr_series = feature_diag_df["corr_to_target"] if "corr_to_target" in feature_diag_df.columns else pd.Series(dtype=float) finite_corr = pd.to_numeric(corr_series, errors="coerce").dropna() mean_abs_corr = float(finite_corr.abs().mean()) if not finite_corr.empty else 0.0 summary = { "run_name": config["run"]["name"], "target_id": config["data"]["target_id"], "ligand_count": int(ligands_df.shape[0]), "cluster_count": int(clusters_df["cluster_id"].nunique()) if not clusters_df.empty else 0, "hypercluster_count": int(clusters_df["hypercluster_id"].nunique()) if not clusters_df.empty else 0, "evaluated_ligand_count": int(len(set(eval_df["ligand_id"].tolist()))) if not eval_df.empty else 0, "budget_used": int(selected_df.shape[0]), "runtime_by_stage_seconds": {t.name: t.seconds for t in stage_timers}, "total_runtime_seconds": float(sum(t.seconds for t in stage_timers)), "mean_docking_score": float(np.mean(docking_scores)) if docking_scores else 0.0, "best_docking_score": float(np.min(docking_scores)) if docking_scores else 0.0, "mean_final_score": float(np.mean(final_scores)) if final_scores else 0.0, "best_final_score": float(np.min(final_scores)) if final_scores else 0.0, "selection_diversity": float(diversity), "feature_count": int(len(ordered_feature_names)), "feature_missing_fraction": float(global_missing), "sample_count": int(final_values_df.shape[0]), "model_weight_progression": model_weight_df["model_weight"].astype(float).tolist() if "model_weight" in model_weight_df.columns else [], "feature_importance_top": [ {"feature": name, "importance": value} for name, value in _top_feature_importance(feature_importance, topn=10) ], "mean_abs_feature_target_correlation": mean_abs_corr, "baseline_vs_model": baseline_comparison, "backend": { "name": capability.backend_name, "available": capability.available, "details": capability.details, "allow_mock_if_missing": allow_mock, "require_real_backend": require_real_backend, "mode_used": "real-rdock-only" if not eval_df.empty and (eval_df["backend_mode"] == "real-rdock").all() else "mixed-or-empty", "fallback_records": int(eval_df["fallback_used"].sum()) if "fallback_used" in eval_df.columns else 0, }, **label_metrics, } _save_json(summary, output_dir / "summary.json") proof_path = _write_backend_proof( output_dir=output_dir, cap=summary["backend"], command_log_path=command_log_path, raw_output_root=raw_output_root, parsed_df=eval_df, require_real_backend=require_real_backend, ) validation_report_path = _write_validation_report( output_dir=output_dir, summary=summary, feature_catalog_df=feature_catalog_df, feature_diag_df=diagnostics_df, model_weight_df=model_weight_df, feature_importance=feature_importance, baseline_comparison=baseline_comparison, ) readme_results = output_dir / "README_results.md" readme_results.write_text( "\n".join( [ f"# Results: {config['run']['name']}", "", f"- Target: `{config['data']['target_id']}`", f"- Ligands input: `{config['data']['ligand_table']}`", f"- Backend available: `{capability.available}`", f"- Require real backend: `{require_real_backend}`", f"- Backend mode used: `{summary['backend']['mode_used']}`", f"- Evaluated ligands: `{summary['evaluated_ligand_count']}`", f"- Budget used: `{summary['budget_used']}`", f"- Best final score: `{summary['best_final_score']:.4f}`", f"- Feature count: `{summary['feature_count']}`", f"- Feature missing fraction: `{summary['feature_missing_fraction']:.4f}`", "", "Generated artifacts:", "- `summary.json`", "- `final_ranking.csv`", "- `parsed_scores.csv`", "- `batch_history.csv`", "- `clusters.csv`", "- `hyperclusters.csv`", "- `timings.csv`", "- `selected_ligands.csv`", "- `features_per_ligand.csv`", "- `features_per_pose.csv`", "- `feature_masks.csv`", "- `feature_importance.json`", "- `model_weight_over_time.csv`", "- `feature_diagnostics.csv`", "- `validation_report.md`", "- `rdock_commands.log`", "- `raw_rdock_outputs/`", "- `backend_proof.md`", ] ), encoding="utf-8", ) return { "output_dir": str(output_dir), "summary": summary, "paths": { "summary": str(output_dir / "summary.json"), "final_ranking": str(final_ranking_path), "parsed_scores": str(parsed_scores_path), "batch_history": str(batch_history_path), "clusters": str(clusters_path), "hyperclusters": str(hyperclusters_path), "timings": str(timings_path), "selected_ligands": str(selected_path), "features_per_ligand": str(features_per_ligand_path), "features_per_pose": str(features_per_pose_path), "feature_masks": str(feature_masks_path), "feature_importance": str(feature_importance_path), "model_weight_over_time": str(model_weight_path), "feature_diagnostics": str(feature_diag_path), "validation_report": str(validation_report_path), "readme_results": str(readme_results), "backend_proof": str(proof_path), "rdock_commands": str(command_log_path), "raw_rdock_outputs": str(raw_output_root), }, "doctor": { "python_ok": doctor_report.python_ok, "imports_ok": doctor_report.imports_ok, "rdock_execs": doctor_report.rdock_execs, "gcc_available": doctor_report.gcc_available, "popt_available": doctor_report.popt_available, }, } export_info, tm = _time_stage("export", _export_results) stage_timers.append(tm) logger.info("Pipeline completed. Outputs: %s", export_info["output_dir"]) return export_info def main() -> int: parser = argparse.ArgumentParser(description="Adaptive protein-ligand docking pipeline") parser.add_argument("--config", type=str, default="configs/default.yaml", help="Path to YAML config") args = parser.parse_args() result = run_pipeline(args.config) print(json.dumps(result["summary"], indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())