File size: 12,192 Bytes
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
from __future__ import annotations

import argparse
import csv
import json
import math
from pathlib import Path
from typing import Any

from .audit_benchmark import audit_benchmark_run
from .provenance import require_file
from .validate_fidelity import validate_fidelity


def _read_rows(path: str | Path) -> list[dict[str, str]]:
    with require_file(path, "benchmark table").open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle))


def _float(value: object, default: float | None = None) -> float | None:
    try:
        text = str(value).strip()
        if not text:
            return default
        return float(text)
    except Exception:
        return default


def _score(row: dict[str, Any], *keys: str) -> float | None:
    for key in keys:
        value = _float(row.get(key), None)
        if value is not None and math.isfinite(value):
            return value
    return None


def _mean(values: list[float]) -> float:
    return sum(values) / len(values) if values else 0.0


def _spearman(xs: list[float], ys: list[float]) -> float | None:
    if len(xs) < 2 or len(xs) != len(ys):
        return None

    def _ranks(values: list[float]) -> list[float]:
        order = sorted(range(len(values)), key=lambda i: values[i])
        ranks = [0.0] * len(values)
        for rank, idx in enumerate(order, start=1):
            ranks[idx] = float(rank)
        return ranks

    rx = _ranks(xs)
    ry = _ranks(ys)
    mx = _mean(rx)
    my = _mean(ry)
    num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
    denx = math.sqrt(sum((a - mx) ** 2 for a in rx))
    deny = math.sqrt(sum((b - my) ** 2 for b in ry))
    if denx == 0.0 or deny == 0.0:
        return None
    return num / (denx * deny)


def _ensure_matplotlib():
    try:
        import matplotlib

        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
    except Exception:
        return None
    return plt


def _write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2), encoding="utf-8")


def _validation_plots(run_dir: Path, metrics: dict[str, Any]) -> list[str]:
    plt = _ensure_matplotlib()
    plot_dir = run_dir / "plots"
    plot_dir.mkdir(parents=True, exist_ok=True)
    out: list[str] = []
    if plt is None:
        return out

    trace_rows = _read_rows(run_dir / "tables" / "multifidelity_trace.csv") if (run_dir / "tables" / "multifidelity_trace.csv").exists() else []
    final_filtered = _read_rows(run_dir / "tables" / "final_hits_filtered.csv") if (run_dir / "tables" / "final_hits_filtered.csv").exists() else []
    random_rows = _read_rows(run_dir / "tables" / "random_baseline_scores.csv") if (run_dir / "tables" / "random_baseline_scores.csv").exists() else []
    single_rows = _read_rows(run_dir / "tables" / "single_fidelity_adaptive_scores.csv") if (run_dir / "tables" / "single_fidelity_adaptive_scores.csv").exists() else []

    def save(fig, name: str) -> None:
        path = plot_dir / name
        fig.tight_layout()
        fig.savefig(path, dpi=160)
        plt.close(fig)
        out.append(str(path))

    # cost balance comparison
    fig, ax = plt.subplots(figsize=(7, 4))
    labels = ["adaptive", "random", "single"]
    vals = [
        float(metrics.get("multifidelity_total_runs_spent") or 0.0),
        float(metrics.get("random_total_runs_spent") or 0.0),
        float(metrics.get("single_fidelity_total_runs_spent") or 0.0),
    ]
    ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a4f9d"])
    ax.set_title("Cost balance comparison across benchmark strategies")
    ax.set_xlabel("Strategy")
    ax.set_ylabel("Total rDock runs spent")
    save(fig, "cost_balance_comparison.png")

    # top-k filtered score comparison
    fig, ax = plt.subplots(figsize=(8, 4))
    ks = [1, 5, 10, 20]
    series = {}
    for name, rows in {
        "adaptive": final_filtered,
        "random": random_rows,
        "single": single_rows,
    }.items():
        ranked = sorted(
            [row for row in rows if _score(row, "final_score", "SCORE") is not None],
            key=lambda row: _score(row, "final_score", "SCORE") or float("inf"),
        )
        series[name] = [_mean([_score(row, "final_score", "SCORE") or 0.0 for row in ranked[:k]]) if ranked[:k] else math.nan for k in ks]
    for idx, (name, vals_) in enumerate(series.items()):
        ax.plot(ks, vals_, marker="o", linewidth=2, label=name)
    ax.set_title("Top-k filtered score comparison by strategy")
    ax.set_xlabel("k")
    ax.set_ylabel("Mean filtered docking SCORE")
    ax.legend()
    save(fig, "topk_filtered_score_comparison.png")

    # surrogate calibration and uncertainty
    pred_obs = []
    unc_err = []
    for row in trace_rows:
        pred = _score(row, "pre_docking_predicted_score", "predicted_filtered_score")
        obs = _score(row, "ranking_score", "SCORE")
        unc = _score(row, "pre_docking_predicted_uncertainty", "predicted_uncertainty")
        if pred is not None and obs is not None:
            if _score(row, "pre_docking_predicted_score") is None and _score(row, "predicted_uncertainty") == 0.0:
                continue
            pred_obs.append((pred, obs))
            if unc is not None:
                unc_err.append((unc, abs(pred - obs)))
    if pred_obs:
        fig, ax = plt.subplots(figsize=(5, 5))
        xs = [item[0] for item in pred_obs]
        ys = [item[1] for item in pred_obs]
        ax.scatter(xs, ys, alpha=0.7, color="#3b6ea8")
        lo = min(xs + ys)
        hi = max(xs + ys)
        ax.plot([lo, hi], [lo, hi], linestyle="--", color="gray")
        ax.set_title("Surrogate calibration: predicted vs observed score")
        ax.set_xlabel("Predicted filtered score")
        ax.set_ylabel("Observed docking score")
        save(fig, "surrogate_calibration.png")
    if unc_err:
        fig, ax = plt.subplots(figsize=(5, 4))
        xs = [item[0] for item in unc_err]
        ys = [item[1] for item in unc_err]
        ax.scatter(xs, ys, alpha=0.7, color="#7a4f9d")
        ax.set_title("Surrogate uncertainty versus absolute error")
        ax.set_xlabel("Predicted uncertainty")
        ax.set_ylabel("Absolute prediction error")
        save(fig, "surrogate_uncertainty_vs_error.png")

    # cluster diversity over time
    if trace_rows:
        fig, ax = plt.subplots(figsize=(7, 4))
        seen = set()
        xs: list[int] = []
        ys: list[int] = []
        for idx, row in enumerate(sorted(trace_rows, key=lambda r: (int(float(r.get("batch_id") or 0.0)), int(float(r.get("selected_fidelity_runs") or 0.0)))), start=1):
            seen.add(str(row.get("cluster_id", "")))
            xs.append(idx)
            ys.append(len(seen))
        ax.plot(xs, ys, color="#3b6ea8")
        ax.set_title("Cluster diversity over adaptive screening time")
        ax.set_xlabel("Processed multifidelity records")
        ax.set_ylabel("Unique clusters seen")
        save(fig, "cluster_diversity_over_time.png")

    return out


def validate_benchmark_model(run_dir: str | Path) -> dict[str, Any]:
    root = Path(run_dir)
    audit = audit_benchmark_run(root)
    fidelity = validate_fidelity(root)
    metrics = dict(audit["metrics"])
    comparability = dict(audit["comparability_audit"])
    trace_rows = _read_rows(root / "tables" / "multifidelity_trace.csv") if (root / "tables" / "multifidelity_trace.csv").exists() else []
    raw_rows = _read_rows(root / "tables" / "final_hits_raw.csv") if (root / "tables" / "final_hits_raw.csv").exists() else []
    filtered_rows = _read_rows(root / "tables" / "final_hits_filtered.csv") if (root / "tables" / "final_hits_filtered.csv").exists() else []

    pred = []
    obs = []
    unc = []
    abs_err = []
    for row in trace_rows:
        predicted = _score(row, "pre_docking_predicted_score", "predicted_filtered_score")
        observed = _score(row, "ranking_score", "SCORE")
        uncertainty = _score(row, "pre_docking_predicted_uncertainty", "predicted_uncertainty")
        if predicted is not None and observed is not None:
            if _score(row, "pre_docking_predicted_score") is None and _score(row, "predicted_uncertainty") == 0.0:
                continue
            pred.append(predicted)
            obs.append(observed)
            abs_err.append(abs(predicted - observed))
            if uncertainty is not None:
                unc.append((uncertainty, abs(predicted - observed)))

    mae = _mean(abs_err) if abs_err else None
    spearman = _spearman(pred, obs)
    uncertainty_spearman = _spearman([x for x, _ in unc], [y for _, y in unc]) if unc else None
    raw_ids = {str(row.get("ligand_id", "")) for row in raw_rows}
    filtered_ids = {str(row.get("ligand_id", "")) for row in filtered_rows}
    dropped_raw = len(raw_ids - filtered_ids)

    validation_metrics = {
        "run_dir": str(root),
        "benchmark_status": metrics.get("benchmark_status"),
        "comparable": comparability.get("comparable"),
        "cost_ratio_random_vs_multifidelity": comparability.get("cost_ratio_random_vs_multifidelity"),
        "cost_ratio_single_vs_multifidelity": comparability.get("cost_ratio_single_vs_multifidelity"),
        "filter_retention_fraction": (len(filtered_rows) / len(raw_rows)) if raw_rows else 0.0,
        "raw_hits_dropped_after_filtering": dropped_raw,
        "surrogate_mae": mae,
        "surrogate_spearman": spearman,
        "uncertainty_vs_error_spearman": uncertainty_spearman,
        "n_surrogate_points": len(pred),
        "fidelity_reliability": fidelity,
        "reasons": comparability.get("reasons", []),
    }
    if spearman is None or spearman <= 0.0:
        validation_metrics.setdefault("warnings", []).append("MODEL DOES NOT PROVIDE USEFUL RANKING SIGNAL YET")
    if not fidelity.get("low_fidelity_reliable", True):
        validation_metrics.setdefault("warnings", []).append("LOW FIDELITY IS NOT RELIABLE ENOUGH FOR AGGRESSIVE PRUNING")
    plots = _validation_plots(root, metrics)
    _write_json(root / "metrics" / "validation_metrics.json", validation_metrics)
    report_lines = [
        f"# validation_report: {root.name}",
        "",
        f"- comparable: `{validation_metrics['comparable']}`",
        f"- benchmark_status: `{validation_metrics['benchmark_status']}`",
        f"- cost_ratio_random_vs_multifidelity: `{validation_metrics['cost_ratio_random_vs_multifidelity']}`",
        f"- cost_ratio_single_vs_multifidelity: `{validation_metrics['cost_ratio_single_vs_multifidelity']}`",
        f"- filter_retention_fraction: `{validation_metrics['filter_retention_fraction']}`",
        f"- raw_hits_dropped_after_filtering: `{validation_metrics['raw_hits_dropped_after_filtering']}`",
        f"- surrogate_mae: `{validation_metrics['surrogate_mae']}`",
        f"- surrogate_spearman: `{validation_metrics['surrogate_spearman']}`",
        f"- uncertainty_vs_error_spearman: `{validation_metrics['uncertainty_vs_error_spearman']}`",
        f"- low_fidelity_reliable: `{fidelity.get('low_fidelity_reliable')}`",
    ]
    for warning in validation_metrics.get("warnings", []):
        report_lines.append(f"- warning: `{warning}`")
    for reason in validation_metrics["reasons"]:
        report_lines.append(f"- reason: `{reason}`")
    report_lines.extend(["", "## Diagnostic Plots"])
    for path in plots:
        report_lines.append(f"- `{path}`")
    (root / "validation_report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8")
    return {"validation_metrics": validation_metrics, "validation_report": str(root / "validation_report.md"), "plots": plots}


def build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Validate an existing adaptive benchmark run and generate diagnostic plots.")
    parser.add_argument("--run-dir", required=True)
    return parser


def run_from_args(args: argparse.Namespace) -> dict[str, Any]:
    return validate_benchmark_model(args.run_dir)


def main() -> int:
    parser = build_arg_parser()
    args = parser.parse_args()
    print(json.dumps(run_from_args(args), indent=2))
    return 0