File size: 8,376 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
from __future__ import annotations

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


def _read_rows(path: Path) -> list[dict[str, str]]:
    with path.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
        value_f = float(text)
        return value_f if math.isfinite(value_f) else default
    except Exception:
        return default


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 idx: values[idx])
        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 _plot(run_dir: Path, name: str, fn) -> str | None:  # type: ignore[no-untyped-def]
    plt = _ensure_matplotlib()
    if plt is None:
        return None
    plot_dir = run_dir / "plots"
    plot_dir.mkdir(parents=True, exist_ok=True)
    fig = fn(plt)
    fig.tight_layout()
    path = plot_dir / name
    fig.savefig(path, dpi=160)
    plt.close(fig)
    return str(path)


def validate_fidelity(run_dir: str | Path) -> dict[str, Any]:
    root = Path(run_dir)
    trace_path = root / "tables" / "multifidelity_trace.csv"
    rows = _read_rows(trace_path) if trace_path.exists() else []
    per_ligand: dict[str, dict[int, dict[str, Any]]] = {}
    for row in rows:
        ligand_id = str(row.get("ligand_id", ""))
        level = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
        score = _float(row.get("SCORE"), None)
        if not ligand_id or level <= 0 or score is None:
            continue
        per_ligand.setdefault(ligand_id, {})[level] = dict(row)
    levels = sorted({level for values in per_ligand.values() for level in values})
    final_level = levels[-1] if levels else 0
    final_rows = {ligand_id: values for ligand_id, values in per_ligand.items() if final_level in values}
    correlations: dict[str, float | None] = {}
    recovery: dict[str, float] = {}
    false_negative: dict[str, float] = {}
    final_scores = {ligand_id: _float(values[final_level].get("SCORE"), 0.0) or 0.0 for ligand_id, values in final_rows.items()}
    ranked_final = sorted(final_scores.items(), key=lambda item: item[1])
    top_5_final = {ligand_id for ligand_id, _ in ranked_final[: max(1, int(math.ceil(len(ranked_final) * 0.05)))]}
    top_10_final = {ligand_id for ligand_id, _ in ranked_final[: max(1, int(math.ceil(len(ranked_final) * 0.10)))]}
    for level in levels:
        if level == final_level:
            continue
        xs: list[float] = []
        ys: list[float] = []
        low_scores: dict[str, float] = {}
        for ligand_id, values in final_rows.items():
            if level not in values:
                continue
            low = _float(values[level].get("SCORE"), None)
            final = _float(values[final_level].get("SCORE"), None)
            if low is None or final is None:
                continue
            xs.append(low)
            ys.append(final)
            low_scores[ligand_id] = low
        correlations[f"spearman_{level}_vs_{final_level}"] = _spearman(xs, ys)
        ranked_low = sorted(low_scores.items(), key=lambda item: item[1])
        top_5_low = {ligand_id for ligand_id, _ in ranked_low[: max(1, int(math.ceil(len(ranked_low) * 0.05)))]}
        top_10_low = {ligand_id for ligand_id, _ in ranked_low[: max(1, int(math.ceil(len(ranked_low) * 0.10)))]}
        recovery[f"top5pct_recovery_{level}_vs_{final_level}"] = len(top_5_low & top_5_final) / max(1, len(top_5_final))
        recovery[f"top10pct_recovery_{level}_vs_{final_level}"] = len(top_10_low & top_10_final) / max(1, len(top_10_final))
        false_negative[f"false_negative_rate_{level}_vs_{final_level}"] = 1.0 - recovery[f"top10pct_recovery_{level}_vs_{final_level}"]

    payload = {
        "run_dir": str(root),
        "levels": levels,
        "final_level": final_level,
        "n_multilevel_ligands": len(final_rows),
        "correlations": correlations,
        "rank_recovery": recovery,
        "promotion_false_negative_rate": false_negative,
        "low_fidelity_reliable": all((value or -1.0) >= 0.35 for key, value in correlations.items() if key.startswith("spearman_5") or key.startswith("spearman_10")),
    }
    metrics_path = root / "metrics" / "fidelity_reliability.json"
    metrics_path.parent.mkdir(parents=True, exist_ok=True)
    metrics_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")

    plots: list[str] = []
    if final_level:
        for level in levels:
            if level == final_level:
                continue
            points = []
            for ligand_id, values in final_rows.items():
                if level not in values:
                    continue
                low = _float(values[level].get("SCORE"), None)
                final = _float(values[final_level].get("SCORE"), None)
                if low is not None and final is not None:
                    points.append((low, final))
            if points:
                plot_name = f"fidelity_score_correlation_{level}_vs_{final_level}.png"
                result = _plot(
                    root,
                    plot_name,
                    lambda plt, pts=points, lvl=level: _scatter_plot(plt, pts, lvl, final_level),
                )
                if result:
                    plots.append(result)
        if correlations:
            result = _plot(root, "fidelity_rank_recovery.png", lambda plt: _recovery_plot(plt, recovery))
            if result:
                plots.append(result)
            result = _plot(root, "promotion_false_negative_rate.png", lambda plt: _recovery_plot(plt, false_negative, ylabel="False negative rate"))
            if result:
                plots.append(result)
    payload["plots"] = plots
    metrics_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    return payload


def _scatter_plot(plt, points: list[tuple[float, float]], level: int, final_level: int):  # type: ignore[no-untyped-def]
    fig, ax = plt.subplots(figsize=(5, 5))
    xs = [item[0] for item in points]
    ys = [item[1] for item in points]
    ax.scatter(xs, ys, alpha=0.7, color="#3b6ea8")
    ax.set_title(f"Fidelity score correlation: {level} vs {final_level} runs")
    ax.set_xlabel(f"SCORE at {level} runs")
    ax.set_ylabel(f"SCORE at {final_level} runs")
    return fig


def _recovery_plot(plt, values: dict[str, float], ylabel: str = "Recovery fraction"):  # type: ignore[no-untyped-def]
    fig, ax = plt.subplots(figsize=(8, 4))
    labels = list(values.keys())
    scores = [float(values[key]) for key in labels]
    ax.bar(range(len(labels)), scores, color="#7a9d54")
    ax.set_xticks(range(len(labels)))
    ax.set_xticklabels(labels, rotation=35, ha="right")
    ax.set_ylabel(ylabel)
    ax.set_title(f"{ylabel} across fidelity comparisons")
    return fig


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


def build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Validate how reliable low-fidelity rDock scores are relative to final fidelity.")
    parser.add_argument("--run-dir", required=True)
    return parser


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


if __name__ == "__main__":
    raise SystemExit(main())