from __future__ import annotations import argparse import json import math import shutil from argparse import Namespace from pathlib import Path from typing import Any try: # pragma: no cover from tqdm import tqdm except Exception: # pragma: no cover tqdm = None # type: ignore[assignment] from .benchmark_triage_repeated import _build_config, _ensure_matplotlib, _median, _read_rows from .benchmark_triage_strategies import ( DIRECT_BASELINES, _collect_runner_result, _dock_reference_ligand_baseline, _ensure_reference_sample, _executive_decision, _json_or_empty, _numeric_median, _run_direct_baseline, _run_runner_strategy, _score_or_inf, _strategy_base_name, ) from .dataset import validate_dataset_dir from .provenance import RDockPipelineError from .sdf import write_rows_csv ABALATION_VARIANTS = ( "classifier_only_no_fallback", "classifier_only_union_fallback", "classifier_regressor_no_fallback", "classifier_regressor_union_fallback", "cluster_only_triage", "diverse_random_cost_balanced", "single_fidelity_cost_balanced", ) def _mean(values: list[float]) -> float | None: if not values: return None return sum(values) / len(values) def _float(value: Any, default: float | None = None) -> float | None: try: text = str(value).strip() if not text: return default return float(text) except Exception: return default def _variant_config(args: argparse.Namespace, variant: str) -> tuple[str, Namespace]: payload = Namespace(**vars(args)) payload.strategy = "reference_free_active_learning_v2" payload.adaptive_policy = "classifier_only" payload.regressor_contribution_mode = "none" payload.model_fallback_if_worse = "none" payload.survivor_combination_policy = "model_only" payload.classifier_weight = float(getattr(args, "classifier_weight", 1.0)) payload.regressor_weight = float(getattr(args, "regressor_weight", 0.35)) payload.cluster_quality_weight = float(getattr(args, "cluster_quality_weight", 0.5)) if variant == "classifier_only_union_fallback": payload.model_fallback_if_worse = "union_with_cluster_only" payload.survivor_combination_policy = "union" elif variant == "classifier_regressor_no_fallback": payload.regressor_contribution_mode = str(getattr(args, "regressor_contribution_mode", "gate")) elif variant == "classifier_regressor_union_fallback": payload.regressor_contribution_mode = str(getattr(args, "regressor_contribution_mode", "gate")) payload.model_fallback_if_worse = "union_with_cluster_only" payload.survivor_combination_policy = "union" return payload.strategy, payload def _variant_label(variant: str, policy: str = "classifier_only") -> str: if variant.startswith("classifier_"): return f"reference_free_active_learning_v2::{policy}::{variant}" return variant def _summary_rows(results: list[dict[str, Any]], estimated_full_runs: int, has_reference: bool) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for strategy in sorted({str(item["strategy"]) for item in results}): items = [row for row in results if str(row["strategy"]) == strategy] rows.append( { "strategy": strategy, "median_best_filtered_score": _numeric_median([row.get("best_filtered_hit_score") for row in items]), "median_top5_mean_filtered_score": _numeric_median([row.get("top5_mean_filtered_score") for row in items]), "median_top10_mean_filtered_score": _numeric_median([row.get("top10_mean_filtered_score") for row in items]), "median_reduction_fraction": _numeric_median([row.get("reduction_fraction") for row in items]), "median_total_runs_spent": _numeric_median([row.get("total_runs_spent") for row in items]), "median_walltime_total_seconds": _numeric_median([row.get("walltime_total_seconds") for row in items]), "median_top5pct_recall": _numeric_median([row.get("top5pct_recall") for row in items]) if has_reference else None, "median_false_negative_rate": _numeric_median([row.get("false_negative_rate") for row in items]) if has_reference else None, "median_survivors": _numeric_median([row.get("triage_survivor_count") for row in items]), "median_initial_ligands": _numeric_median([row.get("initial_ligands") for row in items]), "median_cost_saved_vs_full": _numeric_median([max(0.0, float(estimated_full_runs) - float(row.get("total_runs_spent") or 0.0)) for row in items]), "classifier_precision": _numeric_median([row.get("classifier_precision") for row in items]), "classifier_recall": _numeric_median([row.get("classifier_recall") for row in items]), "classifier_auc_pr": _numeric_median([row.get("classifier_auc_pr") for row in items]), } ) return rows def _regressor_value_added(summary_map: dict[str, dict[str, Any]]) -> tuple[bool, str]: cls = summary_map.get("classifier_only_no_fallback", {}) reg = summary_map.get("classifier_regressor_no_fallback", {}) if not cls or not reg: return False, "Missing ablation variants." cls_top5 = _float(cls.get("median_top5_mean_filtered_score"), None) reg_top5 = _float(reg.get("median_top5_mean_filtered_score"), None) cls_top10 = _float(cls.get("median_top10_mean_filtered_score"), None) reg_top10 = _float(reg.get("median_top10_mean_filtered_score"), None) cls_red = _float(cls.get("median_reduction_fraction"), None) reg_red = _float(reg.get("median_reduction_fraction"), None) if cls_top5 is None or reg_top5 is None or cls_top10 is None or reg_top10 is None: return False, "REGRESSOR_NOT_PROVEN_USEFUL" topk_better = reg_top5 < cls_top5 and reg_top10 < cls_top10 reduction_ok = cls_red is None or reg_red is None or reg_red >= cls_red * 0.9 if topk_better and reduction_ok: return True, "REGRESSOR_ADDS_VALUE" return False, "REGRESSOR_NOT_PROVEN_USEFUL" def _write_ablation_plots(out_dir: Path, summary_rows: list[dict[str, Any]], results: list[dict[str, Any]]) -> list[str]: plot_dir = out_dir / "plots" plot_dir.mkdir(parents=True, exist_ok=True) paths: list[str] = [] plt = _ensure_matplotlib() if plt is None: return paths def _save(name: str, fn) -> None: # type: ignore[no-untyped-def] fig = fn(plt) fig.tight_layout() path = plot_dir / name fig.savefig(path, dpi=160) plt.close(fig) paths.append(str(path)) def _bar(key: str, title: str, ylabel: str, name: str): # type: ignore[no-untyped-def] def _fn(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(10, 4)) labels = [row["strategy"] for row in summary_rows] vals = [float(row.get(key) or 0.0) for row in summary_rows] ax.bar(labels, vals, color="#4f7d3a") ax.set_title(title) ax.set_xlabel("Wariant / strategia") ax.set_ylabel(ylabel) ax.tick_params(axis="x", rotation=25) return fig _save(name, _fn) def _scatter(x_key: str, y_key: str, title: str, name: str): # type: ignore[no-untyped-def] def _fn(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(8, 5)) for row in summary_rows: x_val = _float(row.get(x_key), None) y_val = _float(row.get(y_key), None) if x_val is None or y_val is None: continue ax.scatter(x_val, y_val, alpha=0.7) ax.text(x_val, y_val, str(row["strategy"]), fontsize=7) ax.set_title(title) ax.set_xlabel(x_key.replace("_", " ")) ax.set_ylabel(y_key.replace("_", " ")) ax.grid(True, alpha=0.25) return fig _save(name, _fn) _bar("median_best_filtered_score", "Ablation: best filtered score", "Median best filtered SCORE", "ablation_best_score_by_strategy.png") _bar("median_top5_mean_filtered_score", "Ablation: top-5 mean filtered score", "Median top-5 mean filtered SCORE", "ablation_top5_mean_by_strategy.png") _bar("median_top10_mean_filtered_score", "Ablation: top-10 mean filtered score", "Median top-10 mean filtered SCORE", "ablation_top10_mean_by_strategy.png") _scatter("median_reduction_fraction", "median_top10_mean_filtered_score", "Ablation: reduction versus top-10 mean score", "ablation_reduction_vs_top10.png") _scatter("median_cost_saved_vs_full", "median_top10_mean_filtered_score", "Ablation: cost saved versus top-10 mean score", "ablation_cost_vs_top10.png") pred_rows = [row for row in _concat_csv_tables(results, "tables/regressor_validation_predictions.csv") if _float(row.get("predicted_score"), None) is not None and _float(row.get("observed_component_sane_score"), None) is not None] if pred_rows: def _pred_obs(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(5, 5)) xs = [float(row["predicted_score"]) for row in pred_rows] ys = [float(row["observed_component_sane_score"]) for row in pred_rows] ax.scatter(xs, ys, alpha=0.5) lo = min(xs + ys) hi = max(xs + ys) ax.plot([lo, hi], [lo, hi], linestyle="--", color="gray") ax.set_title("Regressor: predicted vs observed") ax.set_xlabel("Predicted component-sane score") ax.set_ylabel("Observed component-sane score") return fig _save("regressor_predicted_vs_observed.png", _pred_obs) def _pred_rank(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(5, 5)) ordered_pred = sorted(enumerate(pred_rows, start=1), key=lambda item: float(item[1]["predicted_score"])) ordered_obs = sorted(enumerate(pred_rows, start=1), key=lambda item: float(item[1]["observed_component_sane_score"])) pred_rank = {str(item[1]["ligand_id"]): idx for idx, item in enumerate(ordered_pred, start=1)} obs_rank = {str(item[1]["ligand_id"]): idx for idx, item in enumerate(ordered_obs, start=1)} xs = [] ys = [] for ligand_id in pred_rank: if ligand_id not in obs_rank: continue xs.append(pred_rank[ligand_id]) ys.append(obs_rank[ligand_id]) ax.scatter(xs, ys, alpha=0.5) ax.set_title("Regressor rank: predicted vs observed") ax.set_xlabel("Predicted rank") ax.set_ylabel("Observed rank") return fig _save("regressor_rank_predicted_vs_observed.png", _pred_rank) def _pred_dist(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(6, 4)) xs = [float(row["predicted_score"]) for row in pred_rows] ax.hist(xs, bins=30, color="#3b6ea8", alpha=0.8) ax.set_title("Regressor prediction distribution") ax.set_xlabel("Predicted component-sane score") ax.set_ylabel("Count") return fig _save("regressor_prediction_distribution.png", _pred_dist) sign_rows = _concat_csv_tables(results, "tables/regressor_sign_check.csv") if sign_rows: def _target_compare(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(8, 4)) labels = [str(row.get("comparison", "")) for row in sign_rows] vals = [float(_float(row.get("value"), 0.0) or 0.0) for row in sign_rows] ax.bar(labels, vals, color="#7a4f9d") ax.set_title("Regressor sign comparison") ax.set_ylabel("Spearman") ax.tick_params(axis="x", rotation=35) return fig _save("regressor_target_comparison_spearman.png", _target_compare) def _value_seed(plt): # type: ignore[no-untyped-def] fig, ax = plt.subplots(figsize=(9, 4)) groups: dict[str, list[dict[str, Any]]] = {} for row in results: groups.setdefault(str(row["strategy"]), []).append(row) for label, items in groups.items(): xs = [int(_float(item.get("seed"), 0.0) or 0) for item in items] ys = [float(_float(item.get("top10_mean_filtered_score"), 0.0) or 0.0) for item in items] if xs and ys: ax.plot(xs, ys, marker="o", label=label) ax.set_title("Regressor value added by seed") ax.set_xlabel("Seed") ax.set_ylabel("Top-10 mean filtered SCORE") handles, labels = ax.get_legend_handles_labels() if handles and labels: ax.legend(fontsize=8) return fig _save("regressor_value_added_by_seed.png", _value_seed) return paths def _concat_csv_tables(results: list[dict[str, Any]], relative_path: str) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] rel = Path(relative_path) for result in results: run_dir = Path(str(result.get("run_dir", ""))) path = run_dir / rel if not path.exists(): continue for row in _read_rows(path): item = dict(row) item.setdefault("strategy", str(result.get("strategy", ""))) item.setdefault("seed", str(result.get("seed", ""))) rows.append(item) return rows def benchmark_regressor_ablation(args: argparse.Namespace) -> dict[str, Any]: dataset_dir = Path(args.dataset_dir) dataset_validation = validate_dataset_dir(dataset_dir, check_rdock_tools=False) out_dir = Path(args.out) if args.force and args.resume: raise RDockPipelineError("benchmark-regressor-ablation does not allow using --force and --resume together") if args.force and out_dir.exists(): shutil.rmtree(out_dir) out_dir.mkdir(parents=True, exist_ok=True) seeds = [int(part.strip()) for part in str(args.seeds).split(",") if part.strip()] variants = [part.strip() for part in str(args.variants).split(",") if part.strip()] if getattr(args, "variants", "") else list(ABALATION_VARIANTS) invalid = [variant for variant in variants if variant not in ABALATION_VARIANTS] if invalid: raise RDockPipelineError(f"Unsupported regressor ablation variants: {invalid}") reference_rows = _ensure_reference_sample( dataset_dir, out_dir, args.jobs, float(args.cpu_fraction), int(args.reference_sample_size), int(args.reference_sample_seed), int(args.rdock_timeout_seconds), bool(args.resume), False, ) if str(args.reference_mode).lower() == "sampled" and int(args.reference_sample_size) > 0 else [] reference_ligand_baseline = _dock_reference_ligand_baseline( dataset_dir, out_dir, args.jobs, float(args.cpu_fraction), int(args.rdock_timeout_seconds), bool(args.resume), ) all_results: list[dict[str, Any]] = [] progress = tqdm(total=len(seeds) * len(variants), desc="Regressor ablation", unit="run") if tqdm is not None else None for seed in seeds: for variant in variants: run_dir = out_dir / f"seed_{seed:02d}" / variant run_dir.mkdir(parents=True, exist_ok=True) if variant in DIRECT_BASELINES: baseline_payload = _run_direct_baseline(dataset_dir, run_dir, args, variant, seed) result = _collect_runner_result(variant, seed, run_dir, reference_rows, set(baseline_payload.get("selected_ids", []))) elif variant == "cluster_only_triage": variant_args = Namespace(**vars(args)) variant_args.adaptive_policy = "classifier_only" variant_args.regressor_contribution_mode = "none" _run_runner_strategy(dataset_dir, run_dir, variant_args, "cluster_only_triage", seed) result = _collect_runner_result(variant, seed, run_dir, reference_rows) else: strategy_name, variant_args = _variant_config(args, variant) _run_runner_strategy(dataset_dir, run_dir, variant_args, strategy_name, seed) result = _collect_runner_result(_variant_label(variant), seed, run_dir, reference_rows) result["variant_name"] = variant result["strategy"] = variant all_results.append(result) if progress is not None: progress.update(1) progress.set_postfix(seed=seed, variant=variant) if progress is not None: progress.close() estimated_full_runs = len(_read_rows(dataset_dir / "ligands" / "ligand_metadata.csv")) * max(int(part) for part in str(args.fidelity_levels).split(",") if part.strip()) summary_rows = _summary_rows(all_results, estimated_full_runs, bool(reference_rows)) summary_map = {str(row["strategy"]): row for row in summary_rows} regressor_useful, regressor_reason = _regressor_value_added(summary_map) strategy_csv_rows = [] for row in summary_rows: item = dict(row) item["regressor_value_added"] = regressor_useful if str(row["strategy"]).startswith("classifier_regressor_") else "" strategy_csv_rows.append(item) write_rows_csv(all_results, out_dir / "tables" / "regressor_ablation_results.csv") write_rows_csv(strategy_csv_rows, out_dir / "tables" / "strategy_comparison_ablation.csv") write_rows_csv(_concat_csv_tables(all_results, "tables/regressor_validation_predictions.csv"), out_dir / "tables" / "regressor_validation_predictions.csv") write_rows_csv(_concat_csv_tables(all_results, "tables/regressor_sign_check.csv"), out_dir / "tables" / "regressor_sign_check.csv") write_rows_csv(_concat_csv_tables(all_results, "tables/regressor_target_comparison.csv"), out_dir / "tables" / "regressor_target_comparison.csv") write_rows_csv( [ { "strategy": row["strategy"], "best_filtered_hit_ligand_id": row.get("best_filtered_hit_ligand_id"), "best_filtered_hit_score": row.get("best_filtered_hit_score"), "top5_mean_filtered_score": row.get("top5_mean_filtered_score"), "top10_mean_filtered_score": row.get("top10_mean_filtered_score"), } for row in all_results ], out_dir / "tables" / "top_hits_by_ablation_strategy.csv", ) write_rows_csv( _concat_csv_tables(all_results, "tables/final_hits_raw.csv"), out_dir / "tables" / "top_hits_component_sanity_by_ablation_strategy.csv", ) cluster = summary_map.get("cluster_only_triage", {}) diverse = summary_map.get("diverse_random_cost_balanced", {}) single = summary_map.get("single_fidelity_cost_balanced", {}) for key in ("classifier_only_no_fallback", "classifier_only_union_fallback", "classifier_regressor_no_fallback", "classifier_regressor_union_fallback"): item = summary_map.get(key, {}) if not item: continue item["model_beats_cluster_only"] = _score_or_inf(item.get("median_best_filtered_score")) < _score_or_inf(cluster.get("median_best_filtered_score")) item["model_beats_diverse_random"] = _score_or_inf(item.get("median_best_filtered_score")) < _score_or_inf(diverse.get("median_best_filtered_score")) item["model_beats_single_fidelity"] = _score_or_inf(item.get("median_best_filtered_score")) < _score_or_inf(single.get("median_best_filtered_score")) if regressor_useful and summary_map.get("classifier_regressor_no_fallback"): recommended_final = "classifier_regressor_no_fallback" recommended_reason = "REGRESSOR_ADDS_VALUE" elif summary_map.get("classifier_only_no_fallback"): recommended_final = "classifier_only_no_fallback" recommended_reason = regressor_reason else: recommended_final = "cluster_only_triage" recommended_reason = regressor_reason regressor_audit_payload = { "fixed_score_regressor_name": str(getattr(args, "fixed_score_regressor_name", "fixed_score_regressor_v1")), "fixed_score_regressor_target": str(getattr(args, "fixed_score_regressor_target", "component_sane_affinity_like")), "regressor_model_type": str(getattr(args, "regressor_model_type", "extra_trees")), "regressor_useful": regressor_useful, "regressor_reason": regressor_reason, "per_variant": { variant: _json_or_empty(out_dir / f"seed_{seed:02d}" / variant / "metrics" / "regressor_audit_metrics.json") for variant in variants for seed in seeds[:1] if (out_dir / f"seed_{seed:02d}" / variant / "metrics" / "regressor_audit_metrics.json").exists() }, } summary = { "dataset_dir": str(dataset_dir), "reference_mode": str(args.reference_mode), "reference_sample_size": int(args.reference_sample_size), "reference_sample_docked_once_for_evaluation": bool(reference_rows), "scientifically_valid_model_benchmark": not bool(dataset_validation["manifest"].get("synthetic_expansion") or dataset_validation["manifest"].get("synthetic_stress_test_only")), "variants": variants, "seeds": seeds, "reference_ligand_baseline": reference_ligand_baseline, "by_strategy": summary_map, "recommended_strategy_final": recommended_final, "recommended_reason": recommended_reason, "regressor_adds_value": regressor_useful, } comparability = { "dataset_dir": str(dataset_dir), "reference_mode": str(args.reference_mode), "reference_sample_size": int(args.reference_sample_size), "reference_sample_seed": int(args.reference_sample_seed), "fidelity_levels": str(args.fidelity_levels), "cost_budget_runs": int(args.cost_budget_runs), "seeds": seeds, "variants": variants, } plots = _write_ablation_plots(out_dir, summary_rows, all_results) (out_dir / "metrics").mkdir(parents=True, exist_ok=True) _write_json(out_dir / "metrics" / "regressor_ablation_summary.json", summary) _write_json(out_dir / "metrics" / "regressor_audit_metrics.json", regressor_audit_payload) _write_json(out_dir / "metrics" / "ablation_comparability_manifest.json", comparability) report_lines = [ "# benchmark-regressor-ablation", "", "## Executive", f"- recommended_strategy_final: `{recommended_final}`", f"- recommended_reason: `{recommended_reason}`", f"- regressor_adds_value: `{regressor_useful}`", "", "## Variants", ] for row in summary_rows: report_lines.append( f"- {row['strategy']}: best `{row.get('median_best_filtered_score')}`, top5 `{row.get('median_top5_mean_filtered_score')}`, " f"top10 `{row.get('median_top10_mean_filtered_score')}`, reduction `{row.get('median_reduction_fraction')}`, " f"runs `{row.get('median_total_runs_spent')}`" ) report_lines.extend(["", "## Plots"]) report_lines.extend([f"- `{path}`" for path in plots] or ["- no_plots"]) (out_dir / "report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8") return {"run_dir": str(out_dir), "summary": summary, "plots": plots} def build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Run real rDock regressor ablation benchmark on independent adaptive variants.") parser.add_argument("--dataset-dir", required=True) parser.add_argument("--reference-mode", default="sampled", choices=["sampled", "none"]) parser.add_argument("--reference-sample-size", type=int, default=1000) parser.add_argument("--reference-sample-seed", type=int, default=42) parser.add_argument("--fidelity-levels", default="5,10,15,30,50") parser.add_argument("--cost-budget-runs", type=int, default=3000) parser.add_argument("--calibration-size", type=int, default=500) parser.add_argument("--fidelity-validation-size", type=int, default=150) parser.add_argument("--seeds", default="1,2,3") parser.add_argument("--jobs", default="10") parser.add_argument("--chunk-size", type=int, default=20) parser.add_argument("--cpu-fraction", type=float, default=0.85) parser.add_argument("--out", required=True) parser.add_argument("--resume", action="store_true") parser.add_argument("--force", action="store_true") parser.add_argument("--rdock-timeout-seconds", type=int, default=14400) parser.add_argument( "--rdock-safe-jobs", action="store_true", default=True, help="Clamp rDock jobs to ligand/stage size for tiny stages to avoid hangs on final batches.", ) parser.add_argument("--triage-target-recall", type=float, default=0.98) parser.add_argument("--triage-retain-fraction", type=float, default=0.02) parser.add_argument("--triage-model", default="classifier") parser.add_argument("--classifier-top-percentile", type=float, default=0.05) parser.add_argument("--classifier-threshold-mode", default="recall_target") parser.add_argument("--classifier-min-positives", type=int, default=10) parser.add_argument("--classifier-holdout-fraction", type=float, default=0.25) parser.add_argument("--classifier-fallback", default="cluster_only") parser.add_argument("--promotion-policy", default="balanced") parser.add_argument("--adaptive-policy", default="classifier_only") parser.add_argument("--regressor-contribution-mode", default="gate", choices=["none", "linear", "gate", "rescue"]) parser.add_argument("--classifier-weight", type=float, default=1.0) parser.add_argument("--regressor-weight", type=float, default=0.35) parser.add_argument("--cluster-quality-weight", type=float, default=0.5) parser.add_argument("--uncertainty-weight", type=float, default=0.35) parser.add_argument("--diversity-weight", type=float, default=0.75) parser.add_argument("--outlier-risk-weight", type=float, default=2.0) parser.add_argument("--fixed-score-regressor-name", default="fixed_score_regressor_v1") parser.add_argument("--fixed-score-regressor-target", default="component_sane_affinity_like") parser.add_argument("--regressor-model-type", default="extra_trees", choices=["extra_trees", "random_forest", "hist_gradient_boosting", "ridge"]) parser.add_argument("--model-validation-split", default="cluster", choices=["random", "cluster"]) parser.add_argument("--variants", default=",".join(ABALATION_VARIANTS)) return parser def run_from_args(args: argparse.Namespace) -> dict[str, Any]: return benchmark_regressor_ablation(args) def main() -> int: print(json.dumps(run_from_args(build_arg_parser().parse_args()), indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())