| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| import math |
| import random |
| import shutil |
| from argparse import Namespace |
| from pathlib import Path |
| from typing import Any |
|
|
| from .benchmark_adaptive import ( |
| MultiFidelityAdaptiveRunner, |
| MultiFidelityConfig, |
| _bool_arg, |
| _evaluate_selection_against_reference, |
| _float, |
| _requested_survivor_count, |
| _select_diverse, |
| _write_json, |
| ) |
| from .dataset import validate_dataset_dir |
| from .provenance import RDockPipelineError, require_file |
| from .rdock import RDockEngine, RDockRunConfig, _sanitize_chunk_output_scores |
| from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, write_rows_csv |
|
|
|
|
| def _read_rows(path: str | Path) -> list[dict[str, str]]: |
| with Path(path).open("r", encoding="utf-8", newline="") as handle: |
| return list(csv.DictReader(handle)) |
|
|
|
|
| def _mean(values: list[float]) -> float: |
| return sum(values) / len(values) if values else 0.0 |
|
|
|
|
| def _median(values: list[float]) -> float | None: |
| if not values: |
| return None |
| ordered = sorted(values) |
| mid = len(ordered) // 2 |
| if len(ordered) % 2: |
| return ordered[mid] |
| return 0.5 * (ordered[mid - 1] + ordered[mid]) |
|
|
|
|
| def _ensure_matplotlib(): |
| try: |
| import matplotlib |
|
|
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| except Exception: |
| return None |
| return plt |
|
|
|
|
| def _save_plot(plot_dir: Path, name: str, fn) -> str | None: |
| plt = _ensure_matplotlib() |
| if plt is None: |
| return None |
| fig = fn(plt) |
| fig.tight_layout() |
| path = plot_dir / name |
| fig.savefig(path, dpi=160) |
| plt.close(fig) |
| return str(path) |
|
|
|
|
| def _build_config(args: argparse.Namespace, strategy: str, seed: int) -> MultiFidelityConfig: |
| return MultiFidelityConfig( |
| strategy=strategy, |
| fidelity_levels=[5, 10, 15, 30, 50], |
| cost_budget_runs=int(getattr(args, "cost_budget_runs", max(1000, args.calibration_size * 5 + args.fidelity_validation_size * 50))), |
| adaptive_budget_ligands=None, |
| promotion_fraction=0.5, |
| min_per_cluster=1, |
| max_per_cluster=50, |
| outlier_intra_z_threshold=3.0, |
| score_component_filter="warn", |
| final_fidelity_only_hits=True, |
| checkpoint_every=1, |
| jobs=args.jobs, |
| cpu_fraction=float(args.cpu_fraction), |
| resume=bool(getattr(args, "resume", False)), |
| reference_mode=args.reference_mode, |
| evaluation_pool_mode="same_pool", |
| balanced_baselines=True, |
| reference_sample_size=int(args.reference_sample_size), |
| reference_sample_seed=int(args.reference_sample_seed), |
| posthoc_score_selected_hits=False, |
| posthoc_final_runs=50, |
| force_resume_stale=False, |
| outlier_policy="downrank", |
| intra_z_threshold=4.0, |
| score_z_threshold=5.0, |
| max_intra_fraction=0.75, |
| max_intra_fraction_soft=0.75, |
| max_intra_fraction_hard=0.9, |
| exploration_fraction=0.35, |
| diversity_weight=0.75, |
| uncertainty_weight=0.35, |
| outlier_risk_weight=2.0, |
| cluster_min_coverage=1, |
| use_reference_features=False, |
| production_reference_free_mode=True, |
| calibration_size=int(args.calibration_size), |
| calibration_fraction=0.2, |
| min_clusters_covered=8, |
| calibration_random_fraction=0.15, |
| calibration_diversity_weight=1.0, |
| fidelity_validation_size=int(args.fidelity_validation_size), |
| fidelity_validation_policy="cluster_stratified", |
| promotion_policy=str(getattr(args, "promotion_policy", "conservative")), |
| min_final_ligands=int(getattr(args, "min_final_ligands", 20)), |
| min_promotion_per_level=int(getattr(args, "min_promotion_per_level", 8)), |
| promotion_fraction_by_level=str(getattr(args, "promotion_fraction_by_level", "")), |
| triage_retain_fraction=float(args.triage_retain_fraction), |
| triage_target_recall=float(args.triage_target_recall), |
| triage_min_survivors=50, |
| triage_max_survivors=0, |
| cluster_min_survivors=1, |
| cluster_max_survivors=0, |
| rescue_fraction=0.05, |
| rare_cluster_rescue=20, |
| uncertainty_rescue=20, |
| allow_low_confidence_triage=False, |
| top_good_fraction=0.1, |
| minimum_training_ligands=50, |
| triage_controller="auto_recall", |
| max_retain_fraction_before_not_useful=0.5, |
| classifier_top_percentile=float(getattr(args, "classifier_top_percentile", 0.1)), |
| triage_model=str(getattr(args, "triage_model", "classifier")), |
| classifier_threshold_mode=str(getattr(args, "classifier_threshold_mode", "recall_target")), |
| classifier_min_positives=int(getattr(args, "classifier_min_positives", 10)), |
| classifier_holdout_fraction=float(getattr(args, "classifier_holdout_fraction", 0.25)), |
| classifier_fallback=str(getattr(args, "classifier_fallback", "cluster_only")), |
| model_fallback_if_worse=str(getattr(args, "model_fallback_if_worse", "none")), |
| survivor_combination_policy=str(getattr(args, "survivor_combination_policy", "model_only")), |
| adaptive_policy=str(getattr(args, "adaptive_policy", "hybrid_rank")), |
| regressor_contribution_mode=str(getattr(args, "regressor_contribution_mode", "linear")), |
| classifier_weight=float(getattr(args, "classifier_weight", 1.0)), |
| regressor_weight=float(getattr(args, "regressor_weight", 0.35)), |
| cluster_quality_weight=float(getattr(args, "cluster_quality_weight", 0.5)), |
| 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")), |
| model_validation_split=str(getattr(args, "model_validation_split", "cluster")), |
| cluster_quota=int(getattr(args, "cluster_quota", 0)), |
| promotion_temperature=float(getattr(args, "promotion_temperature", 1.0)), |
| diagnostics_level=str(getattr(args, "diagnostics_level", "standard")), |
| classifier_gate_fraction=float(getattr(args, "classifier_gate_fraction", 0.15)), |
| classifier_max_gate_fraction=float(getattr(args, "classifier_max_gate_fraction", 0.2)), |
| final_survivor_enumerate_variants=False, |
| variant_stage="none", |
| enumerate_stereoisomers="none", |
| max_stereoisomers_per_parent=2, |
| enumerate_tautomers="none", |
| max_tautomers_per_parent=1, |
| enumerate_protonation="none", |
| ph=7.4, |
| max_protomer_states_per_parent=1, |
| max_conformers_per_variant=1, |
| max_total_variants_per_parent=1, |
| posthoc_top_parents=100, |
| posthoc_max_total_variants_per_parent=20, |
| variant_fairness_policy="cap", |
| ) |
|
|
|
|
| def _ensure_reference_full( |
| dataset_dir: Path, |
| out_dir: Path, |
| jobs: str, |
| cpu_fraction: float, |
| force: bool, |
| *, |
| reference_mode: str, |
| reference_sample_size: int, |
| resume: bool = False, |
| rdock_timeout_seconds: int = 3600, |
| ) -> Path: |
| ref_dir = out_dir / "reference_full" |
| table = ref_dir / "tables" / "full_docking_scores.csv" |
| if force and ref_dir.exists(): |
| shutil.rmtree(ref_dir) |
| if table.exists(): |
| return table |
| manifest = json.loads(require_file(dataset_dir / "dataset_manifest.json", "dataset manifest").read_text(encoding="utf-8")) |
| expected_count = int(manifest.get("ligands_prepared", 0)) |
| if str(reference_mode).lower() == "sampled" and reference_sample_size > 0: |
| expected_count = reference_sample_size |
| candidates = [ |
| Path("/tmp/ref_free_triage_benchmark_v2/tables/full_docking_scores.csv"), |
| Path("/tmp/ref_free_triage_benchmark/tables/full_docking_scores.csv"), |
| Path("results/rdock_4wkq_pubchem_1500_medium_comparable_v5/tables/full_docking_scores.csv"), |
| Path("results/rdock_4wkq_pubchem_1500_medium_comparable_v4/tables/full_docking_scores.csv"), |
| Path("results/rdock_4wkq_pubchem_1500_medium_comparable_v3/tables/full_docking_scores.csv"), |
| ] |
| for candidate in candidates: |
| if candidate.exists(): |
| try: |
| row_count = len(_read_rows(candidate)) |
| except Exception: |
| row_count = 0 |
| if expected_count > 0 and row_count != expected_count: |
| continue |
| table.parent.mkdir(parents=True, exist_ok=True) |
| shutil.copy2(candidate, table) |
| return table |
| ref_dir.mkdir(parents=True, exist_ok=True) |
| partial_chunks = sorted((ref_dir / "full_docking" / "rdock").glob("chunk_*_out.sd")) |
| if partial_chunks: |
| rows = [] |
| for chunk in partial_chunks: |
| valid_records, _ = _sanitize_chunk_output_scores(chunk) |
| if not valid_records: |
| continue |
| rows.extend(records_to_rows(best_per_ligand(valid_records))) |
| unique_ids = {str(row.get("ligand_id", "")) for row in rows if str(row.get("ligand_id", ""))} |
| if rows and (expected_count <= 0 or len(unique_ids) >= expected_count): |
| table.parent.mkdir(parents=True, exist_ok=True) |
| write_rows_csv(rows, table) |
| return table |
| engine = RDockEngine(RDockRunConfig(n_runs=50, jobs=jobs, cpu_fraction=cpu_fraction, timeout_seconds=int(rdock_timeout_seconds))) |
| config = _build_config( |
| Namespace( |
| reference_mode="full", |
| reference_sample_size=0, |
| reference_sample_seed=42, |
| calibration_size=50, |
| fidelity_validation_size=20, |
| triage_retain_fraction=0.2, |
| triage_target_recall=0.95, |
| jobs=jobs, |
| cpu_fraction=cpu_fraction, |
| resume=resume, |
| ), |
| strategy="reference_free_triage_bandit_v1", |
| seed=0, |
| ) |
| runner = MultiFidelityAdaptiveRunner(dataset_dir, ref_dir, engine, config) |
| runner._prepare_output_layout() |
| runner._run_full_docking() |
| if not table.exists(): |
| raise RDockPipelineError(f"Failed to produce full reference table at {table}") |
| return table |
|
|
|
|
| def _reference_lookup(full_rows: list[dict[str, str]]) -> dict[str, dict[str, str]]: |
| return {str(row["ligand_id"]): row for row in full_rows} |
|
|
|
|
| def _cluster_random_selection(rows: list[dict[str, Any]], requested: int, seed: int, min_per_cluster: int, max_per_cluster: int) -> list[dict[str, Any]]: |
| shuffled = list(rows) |
| rng = random.Random(seed) |
| rng.shuffle(shuffled) |
| return _select_diverse(shuffled, requested, min_per_cluster, max_per_cluster) |
|
|
|
|
| def _evaluate_strategy_offline( |
| runner: MultiFidelityAdaptiveRunner, |
| strategy: str, |
| seed: int, |
| reference_rows: list[dict[str, str]], |
| seed_dir: Path, |
| ) -> dict[str, Any]: |
| full_lookup = _reference_lookup(reference_rows) |
| screenable_rows = runner._prefilter_candidate_rows() |
| requested = _requested_survivor_count( |
| len(screenable_rows), |
| runner.config.triage_retain_fraction, |
| runner.config.triage_min_survivors, |
| runner.config.triage_max_survivors, |
| ) |
| selected_rows: list[dict[str, Any]] |
| selection_metrics: dict[str, Any] |
| if strategy == "cluster_only_triage": |
| selected_rows, selection_metrics = runner._cluster_only_selection(screenable_rows) |
| elif strategy == "cheap_descriptor_filter_only": |
| selected_rows, selection_metrics = runner._descriptor_filter_selection(screenable_rows) |
| elif strategy == "diverse_random_cost_balanced": |
| selected_rows = _cluster_random_selection(screenable_rows, requested, seed, runner.config.cluster_min_survivors, runner.config.cluster_max_survivors or runner.config.max_per_cluster) |
| selection_metrics = {"requested_survivor_count": requested, "final_survivor_count": len(selected_rows)} |
| elif strategy == "single_fidelity_cost_balanced": |
| ordered = sorted(screenable_rows, key=lambda row: (-float(row.get("model_score", 0.0)), str(row.get("cluster_id", "")), str(row.get("ligand_id", "")))) |
| selected_rows = _select_diverse(ordered, requested, runner.config.cluster_min_survivors, runner.config.cluster_max_survivors or runner.config.max_per_cluster) |
| selection_metrics = {"requested_survivor_count": requested, "final_survivor_count": len(selected_rows)} |
| else: |
| calibration_rows = runner._select_calibration_rows(screenable_rows) |
| rng = random.Random(seed) |
| rng.shuffle(calibration_rows) |
| calibration_rows = calibration_rows[: runner.config.calibration_size] |
| labeled_rows: list[dict[str, Any]] = [] |
| for row in calibration_rows: |
| ligand_id = str(row["ligand_id"]) |
| ref = full_lookup.get(ligand_id) |
| if ref is None: |
| continue |
| merged = dict(row) |
| merged["final_score"] = ref.get("SCORE", ref.get("best_score", "")) |
| merged["ranking_score"] = merged["final_score"] |
| merged["SCORE"] = merged["final_score"] |
| merged["rdock_success"] = str(ref.get("rdock_success", "true")).lower() in {"true", "1"} |
| merged["component_warning"] = "" |
| labeled_rows.append(merged) |
| selected_rows, selection_metrics = runner._triage_survivors(screenable_rows, labeled_rows) |
| selected_ids = {str(row["ligand_id"]) for row in selected_rows} |
| selection_metrics.update(_evaluate_selection_against_reference(reference_rows, selected_ids, top_fraction=runner.config.classifier_top_percentile)) |
| survivor_scores = [ |
| _float(full_lookup[ligand_id].get("SCORE", full_lookup[ligand_id].get("best_score")), None) |
| for ligand_id in selected_ids |
| if ligand_id in full_lookup |
| ] |
| survivor_scores = [score for score in survivor_scores if score is not None] |
| selected_ranked = [ |
| full_lookup[ligand_id] |
| for ligand_id in sorted(selected_ids, key=lambda ligand_id: _float(full_lookup.get(ligand_id, {}).get("SCORE", full_lookup.get(ligand_id, {}).get("best_score")), float("inf"))) |
| if ligand_id in full_lookup |
| ] |
| topk_means = {} |
| for k in (1, 5, 10): |
| scores = [ |
| _float(row.get("SCORE", row.get("best_score")), None) |
| for row in selected_ranked[: min(k, len(selected_ranked))] |
| ] |
| scores = [score for score in scores if score is not None] |
| topk_means[f"top{k}_mean_score"] = _mean(scores) if scores else None |
| estimated_full_runs = len(reference_rows) * 50 |
| if strategy in {"reference_free_triage_bandit_v1", "reference_free_active_learning_v2"}: |
| estimated_runs = len(selected_rows) * 50 + min(len(screenable_rows), runner.config.calibration_size) * 5 + min(len(screenable_rows), runner.config.fidelity_validation_size) * (10 + 15 + 30 + 50) |
| else: |
| estimated_runs = len(selected_rows) * 50 |
| output = { |
| "strategy": strategy, |
| "seed": seed, |
| "initial_ligands": len(screenable_rows), |
| "survivor_count": len(selected_rows), |
| "survivor_fraction": len(selected_rows) / max(1, len(screenable_rows)), |
| "reduction_fraction": 1.0 - (len(selected_rows) / max(1, len(screenable_rows))), |
| "estimated_total_runs_spent": estimated_runs, |
| "estimated_runs_saved_vs_full": max(0, estimated_full_runs - estimated_runs), |
| "best_survivor_score": _float(selected_ranked[0].get("SCORE", selected_ranked[0].get("best_score")), None) if selected_ranked else None, |
| "best_survivor_ligand_id": selected_ranked[0].get("ligand_id") if selected_ranked else None, |
| } |
| output.update(topk_means) |
| output.update(selection_metrics) |
| seed_dir.mkdir(parents=True, exist_ok=True) |
| write_rows_csv(selected_rows, seed_dir / f"{strategy}_survivors.csv") |
| rejected_rows = [row for row in screenable_rows if str(row["ligand_id"]) not in selected_ids] |
| write_rows_csv(rejected_rows, seed_dir / f"{strategy}_rejected.csv") |
| _write_json(seed_dir / f"{strategy}_metrics.json", output) |
| return output |
|
|
|
|
| def _write_summary_plots(out_dir: Path, rows: list[dict[str, Any]]) -> list[str]: |
| plot_dir = out_dir / "plots" |
| plot_dir.mkdir(parents=True, exist_ok=True) |
| paths: list[str] = [] |
| if not rows: |
| return paths |
| by_strategy: dict[str, list[dict[str, Any]]] = {} |
| for row in rows: |
| by_strategy.setdefault(str(row["strategy"]), []).append(row) |
|
|
| def _save_csv(name: str, payload: list[dict[str, Any]]) -> str: |
| path = plot_dir / name |
| write_rows_csv(payload, path) |
| return str(path) |
|
|
| summary_csv_rows = [] |
| for strategy, items in by_strategy.items(): |
| summary_csv_rows.append( |
| { |
| "strategy": strategy, |
| "median_top5pct_recall": _median([float(item.get("top5pct_recall") or 0.0) for item in items]), |
| "median_reduction_fraction": _median([float(item.get("reduction_fraction") or 0.0) for item in items]), |
| "median_best_survivor_score": _median([float(item.get("best_survivor_score") or 0.0) for item in items if item.get("best_survivor_score") is not None]), |
| } |
| ) |
| _save_csv("strategy_comparison_recall_cost.csv", summary_csv_rows) |
|
|
| def bar_plot(plt): |
| labels = [row["strategy"] for row in summary_csv_rows] |
| recalls = [float(row["median_top5pct_recall"] or 0.0) for row in summary_csv_rows] |
| reductions = [float(row["median_reduction_fraction"] or 0.0) for row in summary_csv_rows] |
| fig, ax1 = plt.subplots(figsize=(9, 4)) |
| ax1.bar(labels, recalls, color="#3b6ea8", alpha=0.8, label="top5% recall") |
| ax1.set_ylabel("Median top-5% recall") |
| ax1.set_xlabel("Strategy") |
| ax1.set_title("Strategy comparison: recall versus reduction") |
| ax1.tick_params(axis="x", rotation=25) |
| ax2 = ax1.twinx() |
| ax2.plot(labels, reductions, color="#bf7f2f", marker="o", linewidth=2, label="reduction") |
| ax2.set_ylabel("Median reduction fraction") |
| return fig |
|
|
| def scatter_plot(plt): |
| fig, ax = plt.subplots(figsize=(7, 5)) |
| colors = { |
| "reference_free_triage_bandit_v1": "#3b6ea8", |
| "cluster_only_triage": "#7a9d54", |
| "cheap_descriptor_filter_only": "#bf7f2f", |
| "diverse_random_cost_balanced": "#7a4f9d", |
| } |
| for strategy, items in by_strategy.items(): |
| xs = [float(item.get("reduction_fraction") or 0.0) for item in items] |
| ys = [float(item.get("top5pct_recall") or 0.0) for item in items] |
| ax.scatter(xs, ys, alpha=0.8, s=60, label=strategy, color=colors.get(strategy, "#444444")) |
| ax.set_xlabel("Reduction fraction") |
| ax.set_ylabel("Top-5% recall") |
| ax.set_title("Triage safety tradeoff: reduction versus recall") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles and labels: |
| ax.legend() |
| return fig |
|
|
| def false_negative_plot(plt): |
| strategies = list(by_strategy.keys()) |
| medians = [_median([float(item.get("false_negative_rate") or 0.0) for item in by_strategy[strategy]]) or 0.0 for strategy in strategies] |
| fig, ax = plt.subplots(figsize=(8, 4)) |
| ax.bar(strategies, medians, color="#a83b3b") |
| ax.set_xlabel("Strategy") |
| ax.set_ylabel("Median false negative rate") |
| ax.set_title("False negative rate by triage strategy") |
| ax.tick_params(axis="x", rotation=25) |
| return fig |
|
|
| for name, fn in ( |
| ("strategy_comparison_recall_cost.png", bar_plot), |
| ("triage_safety_tradeoff.png", scatter_plot), |
| ("false_negative_rate_by_strategy.png", false_negative_plot), |
| ): |
| path = _save_plot(plot_dir, name, fn) |
| if path: |
| paths.append(path) |
| return paths |
|
|
|
|
| def benchmark_triage_repeated(args: argparse.Namespace) -> dict[str, Any]: |
| dataset_dir = Path(args.dataset_dir) |
| validate_dataset_dir(dataset_dir, check_rdock_tools=False) |
| out_dir = Path(args.out) |
| preserved_reference_chunks: Path | None = None |
| if args.force and out_dir.exists(): |
| partial_chunk_dir = out_dir / "reference_full" / "full_docking" / "rdock" |
| if partial_chunk_dir.exists() and any(partial_chunk_dir.glob("chunk_*_out.sd")): |
| preserved_reference_chunks = out_dir.parent / f"{out_dir.name}_preserved_reference_full" |
| if preserved_reference_chunks.exists(): |
| shutil.rmtree(preserved_reference_chunks) |
| shutil.copytree(out_dir / "reference_full", preserved_reference_chunks) |
| shutil.rmtree(out_dir) |
| out_dir.mkdir(parents=True, exist_ok=True) |
| if preserved_reference_chunks is not None: |
| shutil.copytree(preserved_reference_chunks, out_dir / "reference_full") |
| shutil.rmtree(preserved_reference_chunks) |
| seeds = [int(part.strip()) for part in str(args.seeds).split(",") if part.strip()] |
| strategies = [str(args.strategy)] + [part.strip() for part in str(args.baselines).split(",") if part.strip()] |
| reference_table = _ensure_reference_full( |
| dataset_dir, |
| out_dir, |
| args.jobs, |
| float(args.cpu_fraction), |
| bool(args.force), |
| reference_mode=str(args.reference_mode), |
| reference_sample_size=int(args.reference_sample_size), |
| ) |
| reference_rows = [row for row in _read_rows(reference_table) if str(row.get("rdock_success", "")).lower() in {"true", "1"} and _float(row.get("SCORE", row.get("best_score")), None) is not None] |
| reference_rows.sort(key=lambda row: (_float(row.get("SCORE", row.get("best_score")), float("inf")), str(row.get("ligand_id", "")))) |
| all_results: list[dict[str, Any]] = [] |
| for seed in seeds: |
| for strategy in strategies: |
| seed_dir = out_dir / f"seed_{seed:02d}" |
| strategy_out = seed_dir / strategy |
| strategy_out.mkdir(parents=True, exist_ok=True) |
| config = _build_config(args, strategy, seed) |
| config.reference_sample_seed = seed |
| runner = MultiFidelityAdaptiveRunner( |
| dataset_dir, |
| strategy_out, |
| RDockEngine(RDockRunConfig(n_runs=50, jobs=args.jobs, cpu_fraction=float(args.cpu_fraction), timeout_seconds=3600)), |
| config, |
| ) |
| result = _evaluate_strategy_offline(runner, strategy, seed, reference_rows, strategy_out / "tables") |
| all_results.append(result) |
| write_rows_csv(all_results, out_dir / "tables" / "triage_repeated_results.csv") |
| summary: dict[str, Any] = { |
| "dataset_dir": str(dataset_dir), |
| "reference_mode": args.reference_mode, |
| "reference_count": len(reference_rows), |
| "seeds": seeds, |
| "strategies": strategies, |
| "by_strategy": {}, |
| } |
| for strategy in strategies: |
| items = [row for row in all_results if str(row["strategy"]) == strategy] |
| recalls = [float(row.get("top5pct_recall") or 0.0) for row in items] |
| reductions = [float(row.get("reduction_fraction") or 0.0) for row in items] |
| best_scores = [float(row.get("best_survivor_score")) for row in items if row.get("best_survivor_score") is not None] |
| summary["by_strategy"][strategy] = { |
| "median_top5pct_recall": _median(recalls), |
| "median_reduction_fraction": _median(reductions), |
| "median_best_survivor_score": _median(best_scores), |
| "median_false_negative_rate": _median([float(row.get("false_negative_rate") or 0.0) for row in items]), |
| "median_estimated_runs_saved_vs_full": _median([float(row.get("estimated_runs_saved_vs_full") or 0.0) for row in items]), |
| } |
| model_summary = summary["by_strategy"].get(args.strategy, {}) |
| cluster_summary = summary["by_strategy"].get("cluster_only_triage", {}) |
| model_beats_cluster = False |
| if model_summary and cluster_summary: |
| model_score = model_summary.get("median_best_survivor_score") |
| cluster_score = cluster_summary.get("median_best_survivor_score") |
| if model_score is not None and cluster_score is not None: |
| model_beats_cluster = float(model_score) < float(cluster_score) |
| summary["model_beats_cluster_only"] = model_beats_cluster |
| plots = _write_summary_plots(out_dir, all_results) |
| _write_json(out_dir / "metrics" / "triage_repeated_summary.json", summary) |
| lines = [ |
| f"# benchmark-triage-repeated: {dataset_dir.name}", |
| "", |
| "## Triage Safety", |
| f"- target_recall: `{args.triage_target_recall}`", |
| f"- requested_retain_fraction: `{args.triage_retain_fraction}`", |
| f"- model_beats_cluster_only: `{model_beats_cluster}`", |
| "", |
| "## Computational Value", |
| ] |
| for strategy in strategies: |
| item = summary["by_strategy"][strategy] |
| lines.extend( |
| [ |
| f"- {strategy} median_reduction_fraction: `{item.get('median_reduction_fraction')}`", |
| f"- {strategy} median_estimated_runs_saved_vs_full: `{item.get('median_estimated_runs_saved_vs_full')}`", |
| ] |
| ) |
| lines.extend(["", "## Final Hit Quality"]) |
| for strategy in strategies: |
| item = summary["by_strategy"][strategy] |
| lines.append(f"- {strategy} median_best_survivor_score: `{item.get('median_best_survivor_score')}`") |
| lines.extend(["", "## Baseline Comparison"]) |
| if not model_beats_cluster: |
| lines.append("- warning: `MODEL TRIAGE DOES NOT OUTPERFORM SIMPLE CLUSTERING.`") |
| for strategy in strategies: |
| item = summary["by_strategy"][strategy] |
| lines.append( |
| f"- {strategy}: median_top5pct_recall `{item.get('median_top5pct_recall')}`, " |
| f"median_false_negative_rate `{item.get('median_false_negative_rate')}`" |
| ) |
| lines.extend(["", "## Plots"]) |
| lines.extend([f"- `{path}`" for path in plots] or ["- no_plots"]) |
| (out_dir / "report.md").write_text("\n".join(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="Repeated offline triage benchmark against a real full-reference docking table.") |
| parser.add_argument("--dataset-dir", required=True) |
| parser.add_argument("--reference-mode", default="full", choices=["full", "sampled"]) |
| parser.add_argument("--reference-sample-size", type=int, default=500) |
| parser.add_argument("--reference-sample-seed", type=int, default=42) |
| parser.add_argument("--strategy", default="reference_free_triage_bandit_v1") |
| parser.add_argument("--baselines", default="cluster_only_triage,cheap_descriptor_filter_only,diverse_random_cost_balanced") |
| 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("--calibration-size", type=int, default=300) |
| parser.add_argument("--fidelity-validation-size", type=int, default=100) |
| 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("--model-fallback-if-worse", default="none") |
| parser.add_argument("--survivor-combination-policy", default="model_only") |
| parser.add_argument("--seeds", default="1,2,3") |
| parser.add_argument("--jobs", default="auto") |
| 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("--force", action="store_true") |
| return parser |
|
|
|
|
| def run_from_args(args: argparse.Namespace) -> dict[str, Any]: |
| return benchmark_triage_repeated(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()) |
|
|