| from __future__ import annotations |
|
|
| import csv |
| import json |
| import math |
| import struct |
| import zlib |
| from pathlib import Path |
| from typing import Iterable |
|
|
|
|
| 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 _floats(rows: Iterable[dict[str, object]], key: str) -> list[float]: |
| out: list[float] = [] |
| for row in rows: |
| try: |
| out.append(float(row[key])) |
| except Exception: |
| continue |
| return out |
|
|
|
|
| def _boolish(value: object) -> bool: |
| return str(value).strip().lower() in {"1", "true", "yes", "y"} |
|
|
|
|
| def _float_or_zero(value: object) -> float: |
| try: |
| return float(value) |
| except Exception: |
| return 0.0 |
|
|
|
|
| def _first_float(row: dict[str, object], keys: list[str]) -> float | None: |
| for key in keys: |
| value = row.get(key) |
| try: |
| if value in ("", None): |
| continue |
| return float(value) |
| except Exception: |
| continue |
| return None |
|
|
|
|
| def _plot_or_skip(plot_dir: Path, name: str, fn) -> str | None: |
| try: |
| import matplotlib |
|
|
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| except Exception as exc: |
| (plot_dir / "skipped_plots.json").write_text( |
| json.dumps({"reason": f"matplotlib unavailable: {exc}"}, indent=2), |
| encoding="utf-8", |
| ) |
| return None |
| path = plot_dir / name |
| fig = fn(plt) |
| fig.tight_layout() |
| fig.savefig(path, dpi=160) |
| plt.close(fig) |
| return str(path) |
|
|
|
|
| def _write_png(path: Path, width: int, height: int, pixels: bytearray) -> str: |
| def chunk(tag: bytes, data: bytes) -> bytes: |
| return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) |
|
|
| raw = b"".join(b"\x00" + pixels[y * width * 3 : (y + 1) * width * 3] for y in range(height)) |
| png = ( |
| b"\x89PNG\r\n\x1a\n" |
| + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) |
| + chunk(b"IDAT", zlib.compress(raw, 9)) |
| + chunk(b"IEND", b"") |
| ) |
| path.write_bytes(png) |
| return str(path) |
|
|
|
|
| def _simple_plot(path: Path, values: list[float], kind: str = "hist") -> str: |
| width, height = 800, 480 |
| pix = bytearray([255] * width * height * 3) |
|
|
| def setpx(x: int, y: int, color: tuple[int, int, int]) -> None: |
| if 0 <= x < width and 0 <= y < height: |
| i = (y * width + x) * 3 |
| pix[i : i + 3] = bytes(color) |
|
|
| def line(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None: |
| dx, dy = abs(x1 - x0), -abs(y1 - y0) |
| sx = 1 if x0 < x1 else -1 |
| sy = 1 if y0 < y1 else -1 |
| err = dx + dy |
| while True: |
| setpx(x0, y0, color) |
| if x0 == x1 and y0 == y1: |
| break |
| e2 = 2 * err |
| if e2 >= dy: |
| err += dy |
| x0 += sx |
| if e2 <= dx: |
| err += dx |
| y0 += sy |
|
|
| def rect(x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int]) -> None: |
| for y in range(max(0, y0), min(height, y1)): |
| for x in range(max(0, x0), min(width, x1)): |
| setpx(x, y, color) |
|
|
| left, top, right, bottom = 70, 40, 760, 420 |
| line(left, bottom, right, bottom, (20, 20, 20)) |
| line(left, top, left, bottom, (20, 20, 20)) |
| vals = [v for v in values if math.isfinite(v)] |
| if not vals: |
| return _write_png(path, width, height, pix) |
| if kind == "bar": |
| ordered = vals[:20] |
| mn = min(0.0, min(ordered)) |
| mx = max(0.0, max(ordered)) |
| span = mx - mn or 1.0 |
| bw = max(2, int((right - left) / max(1, len(ordered)))) |
| for i, v in enumerate(ordered): |
| x0 = left + i * bw + 2 |
| x1 = left + (i + 1) * bw - 2 |
| y = int(bottom - ((v - mn) / span) * (bottom - top)) |
| y0, y1 = sorted([bottom, y]) |
| rect(x0, y0, x1, y1, (75, 125, 170)) |
| else: |
| bins = min(30, max(5, len(vals) // 3)) |
| mn, mx = min(vals), max(vals) |
| span = mx - mn or 1.0 |
| counts = [0] * bins |
| for v in vals: |
| idx = min(bins - 1, int(((v - mn) / span) * bins)) |
| counts[idx] += 1 |
| maxc = max(counts) or 1 |
| bw = int((right - left) / bins) |
| for i, c in enumerate(counts): |
| x0 = left + i * bw + 1 |
| x1 = left + (i + 1) * bw - 1 |
| y0 = int(bottom - (c / maxc) * (bottom - top)) |
| rect(x0, y0, x1, bottom, (75, 125, 170)) |
| return _write_png(path, width, height, pix) |
|
|
|
|
| def plot_score_outputs(best_csv: str | Path, plot_dir: str | Path, title_prefix: str = "rDock") -> list[str]: |
| pdir = Path(plot_dir) |
| pdir.mkdir(parents=True, exist_ok=True) |
| rows = _read_rows(best_csv) |
| scores = _floats(rows, "SCORE") |
| paths: list[str] = [] |
| if not scores: |
| return paths |
|
|
| def hist(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ax.hist(scores, bins=min(30, max(5, len(scores) // 5)), color="#3b6ea8", edgecolor="white") |
| ax.set_title(f"{title_prefix} SCORE distribution") |
| ax.set_xlabel("SCORE") |
| ax.set_ylabel("Count") |
| return fig |
|
|
| def topbar(plt): |
| ranked_rows = [row for row in rows if _first_float(row, ["SCORE", "best_score", "final_score"]) is not None] |
| ordered = sorted(ranked_rows, key=lambda r: _first_float(r, ["SCORE", "best_score", "final_score"]) or float("inf"))[:20] |
| labels = [str(r.get("ligand_id", "")) for r in ordered] |
| vals = [float(_first_float(r, ["SCORE", "best_score", "final_score"]) or float("nan")) for r in ordered] |
| fig, ax = plt.subplots(figsize=(9, 4)) |
| ax.bar(range(len(vals)), vals, color="#7a9d54") |
| ax.set_title(f"{title_prefix} top SCOREs") |
| ax.set_xlabel("Ligand rank") |
| ax.set_ylabel("SCORE") |
| ax.set_xticks(range(len(vals))) |
| ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8) |
| return fig |
|
|
| for name, fn in (("score_distribution.png", hist), ("top_scores.png", topbar)): |
| if path := _plot_or_skip(pdir, name, fn): |
| paths.append(path) |
| else: |
| paths.append(_simple_plot(pdir / name, scores if "distribution" in name else sorted(scores)[:20], "hist" if "distribution" in name else "bar")) |
| return paths |
|
|
|
|
| def plot_astex_outputs(summary_csv: str | Path, plot_dir: str | Path) -> list[str]: |
| pdir = Path(plot_dir) |
| pdir.mkdir(parents=True, exist_ok=True) |
| rows = _read_rows(summary_csv) |
| top1 = _floats(rows, "top1_rmsd") |
| best = _floats(rows, "best_of_n_rmsd") |
| scores = _floats(rows, "top1_SCORE") |
| paths: list[str] = [] |
| if not top1 and not best: |
| return paths |
|
|
| def hist(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| if top1: |
| ax.hist(top1, alpha=0.65, label="top1", bins=20) |
| if best: |
| ax.hist(best, alpha=0.65, label="best-of-n", bins=20) |
| ax.axvline(2.0, color="black", linestyle="--", linewidth=1) |
| ax.set_xlabel("RMSD (A)") |
| ax.set_ylabel("Systems") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def scatter(plt): |
| fig, ax = plt.subplots(figsize=(5, 5)) |
| ax.scatter(top1[: len(best)], best[: len(top1)], color="#3b6ea8") |
| ax.axhline(2.0, color="black", linestyle="--", linewidth=1) |
| ax.axvline(2.0, color="black", linestyle="--", linewidth=1) |
| ax.set_xlabel("Top1 RMSD (A)") |
| ax.set_ylabel("Best-of-n RMSD (A)") |
| return fig |
|
|
| def success_bar(plt): |
| top1_success = sum(1 for row in rows if _boolish(row.get("success_top1_rmsd_le_2A"))) |
| best_success = sum(1 for row in rows if _boolish(row.get("success_best_rmsd_le_2A"))) |
| total = max(1, len([r for r in rows if r.get("status") == "success"])) |
| fig, ax = plt.subplots(figsize=(5, 4)) |
| ax.bar(["top1 <= 2A", "best <= 2A"], [top1_success / total, best_success / total], color=["#3b6ea8", "#7a9d54"]) |
| ax.set_ylim(0, 1) |
| ax.set_ylabel("Successful fraction") |
| return fig |
|
|
| def score_vs_rmsd(plt): |
| n = min(len(scores), len(top1)) |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| ax.scatter(scores[:n], top1[:n], color="#7a4f9d") |
| ax.axhline(2.0, color="black", linestyle="--", linewidth=1) |
| ax.set_xlabel("Top pose SCORE") |
| ax.set_ylabel("Top1 RMSD (A)") |
| return fig |
|
|
| plot_specs = [("rmsd_distribution.png", hist), ("top1_vs_best_rmsd.png", scatter), ("success_rmsd_le_2A.png", success_bar)] |
| if scores and top1: |
| plot_specs.append(("score_vs_rmsd.png", score_vs_rmsd)) |
| for name, fn in plot_specs: |
| if path := _plot_or_skip(pdir, name, fn): |
| paths.append(path) |
| else: |
| values = scores if name == "score_vs_rmsd.png" else (top1 or []) + (best or []) |
| paths.append(_simple_plot(pdir / name, values, "hist")) |
| return paths |
|
|
|
|
| def plot_dud_outputs(best_csv: str | Path, enrichment_csv: str | Path, plot_dir: str | Path) -> list[str]: |
| pdir = Path(plot_dir) |
| pdir.mkdir(parents=True, exist_ok=True) |
| rows = _read_rows(best_csv) |
| scores = _floats(rows, "SCORE") |
| labels = [] |
| for row in rows: |
| try: |
| labels.append(int(float(row.get("label", 0)))) |
| except Exception: |
| labels.append(0) |
| paths: list[str] = [] |
| if not scores: |
| return paths |
|
|
| ordered = sorted(zip(scores, labels), key=lambda x: x[0]) |
| total_actives = max(1, sum(labels)) |
| x = [(i + 1) / len(ordered) for i in range(len(ordered))] |
| y = [] |
| seen = 0 |
| for _, label in ordered: |
| seen += int(label) |
| y.append(seen / total_actives) |
| total_decoys = max(1, len(labels) - sum(labels)) |
| roc_x: list[float] = [] |
| roc_y: list[float] = [] |
| tp = 0 |
| fp = 0 |
| for _, label in ordered: |
| if int(label) == 1: |
| tp += 1 |
| else: |
| fp += 1 |
| roc_x.append(fp / total_decoys) |
| roc_y.append(tp / total_actives) |
| ef_rows = _read_rows(enrichment_csv) if Path(enrichment_csv).exists() else [] |
|
|
| def cumulative(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ax.plot(x, y, color="#3b6ea8") |
| ax.set_xlabel("Ranked fraction") |
| ax.set_ylabel("Cumulative active recovery") |
| return fig |
|
|
| def score_by_label(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| active = [s for s, l in zip(scores, labels) if l == 1] |
| decoy = [s for s, l in zip(scores, labels) if l == 0] |
| if active: |
| ax.hist(active, alpha=0.6, label="actives", bins=20) |
| if decoy: |
| ax.hist(decoy, alpha=0.6, label="decoys", bins=20) |
| ax.set_xlabel("SCORE") |
| ax.set_ylabel("Ligands") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def roc_curve(plt): |
| fig, ax = plt.subplots(figsize=(5, 5)) |
| ax.plot([0, *roc_x], [0, *roc_y], color="#3b6ea8") |
| ax.plot([0, 1], [0, 1], color="gray", linestyle="--", linewidth=1) |
| ax.set_xlabel("False positive rate") |
| ax.set_ylabel("True positive rate") |
| return fig |
|
|
| def semilog_roc(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| xs = [max(0.0005, v) for v in roc_x] |
| ax.plot(xs, roc_y, color="#3b6ea8") |
| ax.set_xscale("log") |
| ax.set_xlabel("False positive rate") |
| ax.set_ylabel("True positive rate") |
| return fig |
|
|
| def ef_bar(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| labels_ef = [str(row.get("fraction", "")) for row in ef_rows] |
| vals = _floats(ef_rows, "enrichment_factor") |
| ax.bar(labels_ef, vals, color="#7a9d54") |
| ax.set_xlabel("Ranked fraction") |
| ax.set_ylabel("Enrichment factor") |
| return fig |
|
|
| plot_specs = [ |
| ("roc_curve.png", roc_curve), |
| ("semilog_roc.png", semilog_roc), |
| ("enrichment_factors.png", ef_bar), |
| ("cumulative_actives.png", cumulative), |
| ("score_distribution_by_label.png", score_by_label), |
| ] |
| for name, fn in plot_specs: |
| if path := _plot_or_skip(pdir, name, fn): |
| paths.append(path) |
| else: |
| paths.append(_simple_plot(pdir / name, y if "cumulative" in name else scores, "bar" if "cumulative" in name else "hist")) |
| return paths |
|
|
|
|
| def plot_adaptive_benchmark_outputs( |
| full_csv: str | Path, |
| adaptive_csv: str | Path, |
| random_csv: str | Path, |
| metrics_json: str | Path, |
| plot_dir: str | Path, |
| ) -> list[str]: |
| pdir = Path(plot_dir) |
| pdir.mkdir(parents=True, exist_ok=True) |
| full_rows = _read_rows(full_csv) |
| adaptive_rows = _read_rows(adaptive_csv) |
| random_rows = _read_rows(random_csv) |
| metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {} |
| full_scores = _floats(full_rows, "SCORE") |
| adaptive_scores = _floats(adaptive_rows, "SCORE") |
| random_scores = _floats(random_rows, "SCORE") |
| paths: list[str] = [] |
| if not full_scores: |
| return paths |
|
|
| def cumulative_best(rows: list[dict[str, str]]) -> list[float]: |
| vals = _floats(rows, "SCORE") |
| best: list[float] = [] |
| current = float("inf") |
| for value in vals: |
| current = min(current, value) |
| best.append(current) |
| return best |
|
|
| def cumulative_plot(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| full_curve = cumulative_best(full_rows) |
| adaptive_curve = cumulative_best(adaptive_rows) |
| random_curve = cumulative_best(random_rows) |
| if full_curve: |
| ax.plot(range(1, len(full_curve) + 1), full_curve, label="full") |
| if adaptive_curve: |
| ax.plot(range(1, len(adaptive_curve) + 1), adaptive_curve, label="adaptive") |
| if random_curve: |
| ax.plot(range(1, len(random_curve) + 1), random_curve, label="random") |
| ax.set_xlabel("Docked ligand count") |
| ax.set_ylabel("Best SCORE so far") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def percentile_bar(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| labels = ["adaptive", "random", "full"] |
| vals = [ |
| float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0), |
| float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0), |
| float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0), |
| ] |
| ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a9d54"]) |
| ax.set_ylim(0, 100) |
| ax.set_ylabel("Percentile in full ranking") |
| return fig |
|
|
| def runtime_bar(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| labels = ["full docking", "adaptive docking", "random docking", "adaptive model"] |
| vals = [ |
| float(metrics.get("full_docking_seconds", 0.0) or 0.0), |
| float(metrics.get("adaptive_docking_seconds", 0.0) or 0.0), |
| float(metrics.get("random_docking_seconds", 0.0) or 0.0), |
| float(metrics.get("adaptive_model_seconds", 0.0) or 0.0), |
| ] |
| ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#7a4f9d"]) |
| ax.set_ylabel("Seconds") |
| ax.tick_params(axis="x", rotation=20) |
| return fig |
|
|
| def success_bar(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| labels = ["full ok", "adaptive ok", "random ok", "failed"] |
| vals = [ |
| float(metrics.get("full_success_count", 0.0) or 0.0), |
| float(metrics.get("adaptive_success_count", 0.0) or 0.0), |
| float(metrics.get("random_success_count", 0.0) or 0.0), |
| float(metrics.get("failed_docking_count", 0.0) or 0.0), |
| ] |
| ax.bar(labels, vals, color=["#7a9d54", "#3b6ea8", "#bf7f2f", "#b14d4d"]) |
| ax.set_ylabel("Ligands") |
| ax.tick_params(axis="x", rotation=15) |
| return fig |
|
|
| def model_scatter(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| xs = _floats(adaptive_rows, "model_score") |
| ys = _floats(adaptive_rows, "SCORE") |
| n = min(len(xs), len(ys)) |
| ax.scatter(xs[:n], ys[:n], color="#3b6ea8") |
| ax.set_xlabel("Model score") |
| ax.set_ylabel("rDock SCORE") |
| return fig |
|
|
| plot_specs = [ |
| ("cumulative_best_score.png", cumulative_plot), |
| ("adaptive_random_full_percentile.png", percentile_bar), |
| ("runtime_summary.png", runtime_bar), |
| ("success_failure_summary.png", success_bar), |
| ] |
| if _floats(adaptive_rows, "model_score"): |
| plot_specs.append(("model_vs_rdock_score.png", model_scatter)) |
| for name, fn in plot_specs: |
| if path := _plot_or_skip(pdir, name, fn): |
| paths.append(path) |
| else: |
| fallback = full_scores |
| if name == "adaptive_random_full_percentile.png": |
| fallback = [ |
| float(metrics.get("adaptive_best_percentile_of_full", 0.0) or 0.0), |
| float(metrics.get("random_best_percentile_of_full", 0.0) or 0.0), |
| float(metrics.get("full_best_percentile_of_full", 100.0) or 100.0), |
| ] |
| paths.append(_simple_plot(pdir / name, fallback, "bar" if "summary" in name or "percentile" in name else "hist")) |
| return paths |
|
|
|
|
| def plot_multifidelity_outputs( |
| trace_csv: str | Path, |
| final_hits_csv: str | Path, |
| random_csv: str | Path, |
| single_csv: str | Path, |
| full_csv: str | Path, |
| metrics_json: str | Path, |
| plot_dir: str | Path, |
| ) -> list[str]: |
| pdir = Path(plot_dir) |
| pdir.mkdir(parents=True, exist_ok=True) |
| trace_rows = _read_rows(trace_csv) if Path(trace_csv).exists() else [] |
| final_rows = _read_rows(final_hits_csv) if Path(final_hits_csv).exists() else [] |
| random_rows = _read_rows(random_csv) if Path(random_csv).exists() else [] |
| single_rows = _read_rows(single_csv) if Path(single_csv).exists() else [] |
| full_rows = _read_rows(full_csv) if Path(full_csv).exists() else [] |
| metrics = json.loads(Path(metrics_json).read_text(encoding="utf-8")) if Path(metrics_json).exists() else {} |
| run_dir = pdir.parent |
| raw_rows = _read_rows(run_dir / "tables" / "final_hits_raw.csv") if (run_dir / "tables" / "final_hits_raw.csv").exists() else [] |
| downranked_rows = _read_rows(run_dir / "tables" / "final_hits_downranked.csv") if (run_dir / "tables" / "final_hits_downranked.csv").exists() else [] |
| filtered_rows = _read_rows(run_dir / "tables" / "final_hits_filtered.csv") if (run_dir / "tables" / "final_hits_filtered.csv").exists() else [] |
| validation_metrics = json.loads((run_dir / "metrics" / "validation_metrics.json").read_text(encoding="utf-8")) if (run_dir / "metrics" / "validation_metrics.json").exists() else {} |
| comparability = json.loads((run_dir / "metrics" / "comparability_audit.json").read_text(encoding="utf-8")) if (run_dir / "metrics" / "comparability_audit.json").exists() else {} |
| paths: list[str] = [] |
| if not trace_rows: |
| return paths |
|
|
| def cumulative_best_vs_cost(rows: list[dict[str, str]], score_key: str = "current_best_score"): |
| ordered = sorted(rows, key=lambda row: (_float_or_zero(row.get("n_rdock_runs_total_spent", 0.0)), _float_or_zero(row.get("selected_fidelity_runs", 0.0)))) |
| xs: list[float] = [] |
| ys: list[float] = [] |
| current = float("inf") |
| for row in ordered: |
| score = _float_or_zero(row.get(score_key, row.get("SCORE", 0.0))) |
| if score == 0.0 and row.get(score_key, row.get("SCORE", "")) in ("", None): |
| continue |
| current = min(current, score) |
| xs.append(_float_or_zero(row.get("n_rdock_runs_total_spent", 0.0))) |
| ys.append(current) |
| return xs, ys |
|
|
| def best_vs_cost(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| xs, ys = cumulative_best_vs_cost(trace_rows) |
| if xs and ys: |
| ax.plot(xs, ys, label="multifidelity") |
| random_vals = sorted(_floats(random_rows, "final_score") or _floats(random_rows, "SCORE")) |
| if random_vals: |
| ax.axhline(random_vals[0], color="#bf7f2f", linestyle="--", label="random best") |
| full_vals = sorted(_floats(full_rows, "SCORE")) |
| if full_vals: |
| ax.axhline(full_vals[0], color="#7a9d54", linestyle=":", label="full best") |
| ax.set_title("Best score vs cumulative rDock cost") |
| ax.set_xlabel("Total rDock runs spent") |
| ax.set_ylabel("Best SCORE so far") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def best_filtered_vs_cost(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
|
|
| def _curve(rows: list[dict[str, str]], score_keys: list[str], x_keys: list[str]) -> tuple[list[float], list[float]]: |
| ordered = sorted(rows, key=lambda row: (_first_float(row, x_keys) or float("inf"), str(row.get("ligand_id", "")))) |
| xs: list[float] = [] |
| ys: list[float] = [] |
| current = float("inf") |
| for row in ordered: |
| x = _first_float(row, x_keys) |
| y = _first_float(row, score_keys) |
| if x is None or y is None: |
| continue |
| current = min(current, y) |
| xs.append(x) |
| ys.append(current) |
| return xs, ys |
|
|
| mf_xs, mf_ys = _curve(filtered_rows, ["filtered_score", "adjusted_score", "ranking_score", "final_score", "SCORE"], ["n_rdock_runs_total_spent", "runs_spent"]) |
| rnd_xs, rnd_ys = _curve(random_rows, ["filtered_score", "final_score", "best_score", "SCORE"], ["n_rdock_runs_total_spent", "runs_spent"]) |
| sgl_xs, sgl_ys = _curve(single_rows, ["filtered_score", "final_score", "best_score", "SCORE"], ["n_rdock_runs_total_spent", "runs_spent"]) |
| if mf_xs: |
| ax.plot(mf_xs, mf_ys, label="adaptive filtered", color="#3b6ea8") |
| if rnd_xs: |
| ax.plot(rnd_xs, rnd_ys, label="random filtered", color="#bf7f2f") |
| if sgl_xs: |
| ax.plot(sgl_xs, sgl_ys, label="single filtered", color="#7a4f9d") |
| ax.set_title("Cumulative best filtered score versus total rDock runs") |
| ax.set_xlabel("Total rDock runs spent") |
| ax.set_ylabel("Best filtered SCORE so far") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| ax.grid(True, alpha=0.25) |
| return fig |
|
|
| def best_downranked_vs_cost(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ordered = sorted(downranked_rows, key=lambda row: (_first_float(row, ["n_rdock_runs_total_spent", "runs_spent"]) or float("inf"), str(row.get("ligand_id", "")))) |
| xs: list[float] = [] |
| ys: list[float] = [] |
| current = float("inf") |
| for row in ordered: |
| x = _first_float(row, ["n_rdock_runs_total_spent", "runs_spent"]) |
| y = _first_float(row, ["adjusted_score", "ranking_score", "final_score", "SCORE"]) |
| if x is None or y is None: |
| continue |
| current = min(current, y) |
| xs.append(x) |
| ys.append(current) |
| if xs: |
| ax.plot(xs, ys, color="#3b6ea8", label="adaptive downranked") |
| ax.set_title("Cumulative best downranked score versus total rDock runs") |
| ax.set_xlabel("Total rDock runs spent") |
| ax.set_ylabel("Best downranked SCORE so far") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| ax.grid(True, alpha=0.25) |
| return fig |
|
|
| def best_vs_walltime(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ordered = sorted(trace_rows, key=lambda row: _float_or_zero(row.get("timing_docking_seconds", 0.0)) + _float_or_zero(row.get("timing_training_seconds", 0.0))) |
| xs: list[float] = [] |
| ys: list[float] = [] |
| elapsed = 0.0 |
| current = float("inf") |
| for row in ordered: |
| score = _float_or_zero(row.get("current_best_score", row.get("SCORE", 0.0))) |
| elapsed += _float_or_zero(row.get("timing_docking_seconds", 0.0)) + _float_or_zero(row.get("timing_training_seconds", 0.0)) |
| current = min(current, score) |
| xs.append(elapsed) |
| ys.append(current) |
| if xs and ys: |
| ax.plot(xs, ys, color="#3b6ea8") |
| ax.set_title("Best score vs elapsed benchmark time") |
| ax.set_xlabel("Walltime (s)") |
| ax.set_ylabel("Best SCORE so far") |
| return fig |
|
|
| def cost_balance_bar(plt): |
| fig, axes = plt.subplots(1, 3, figsize=(12, 4)) |
| strategies = ["adaptive", "random", "single"] |
| runs = [ |
| float(metrics.get("multifidelity_total_runs_spent", 0.0) or 0.0), |
| float(metrics.get("random_total_runs_spent", 0.0) or 0.0), |
| float(metrics.get("single_fidelity_total_runs_spent", 0.0) or 0.0), |
| ] |
| wall = [ |
| float(metrics.get("walltime_total_seconds", 0.0) or 0.0), |
| float(metrics.get("random_walltime_seconds", 0.0) or 0.0), |
| float(metrics.get("single_fidelity_walltime_seconds", 0.0) or 0.0), |
| ] |
| ligs = [ |
| len({str(row.get("ligand_id", "")) for row in final_rows if str(row.get("ligand_id", ""))}), |
| len({str(row.get("ligand_id", "")) for row in random_rows if str(row.get("ligand_id", ""))}), |
| len({str(row.get("ligand_id", "")) for row in single_rows if str(row.get("ligand_id", ""))}), |
| ] |
| for ax, values, title, ylabel in zip( |
| axes, |
| [runs, wall, ligs], |
| ["Total rDock runs spent", "Walltime by strategy", "Ligands evaluated by strategy"], |
| ["Runs", "Seconds", "Ligands"], |
| ): |
| ax.bar(strategies, values, color=["#3b6ea8", "#bf7f2f", "#7a4f9d"]) |
| ax.set_title(title) |
| ax.set_ylabel(ylabel) |
| ax.tick_params(axis="x", rotation=15) |
| return fig |
|
|
| def fidelity_counts(plt): |
| counts: dict[str, int] = {} |
| for row in trace_rows: |
| level = str(row.get("selected_fidelity_runs", "")) |
| counts[level] = counts.get(level, 0) + 1 |
| labels = sorted(counts, key=lambda x: int(x or 0)) |
| vals = [counts[label] for label in labels] |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| ax.bar(labels, vals, color="#3b6ea8") |
| ax.set_title("Ligands screened at each fidelity level") |
| ax.set_xlabel("Fidelity runs") |
| ax.set_ylabel("Ligands screened") |
| return fig |
|
|
| def promotion_funnel(plt): |
| counts: dict[str, int] = {} |
| for row in trace_rows: |
| level = str(row.get("selected_fidelity_runs", "")) |
| counts[level] = counts.get(level, 0) + 1 |
| labels = sorted(counts, key=lambda x: int(x or 0)) |
| vals = [counts[label] for label in labels] |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| ax.plot(range(len(vals)), vals, marker="o", color="#7a4f9d") |
| ax.set_xticks(range(len(vals))) |
| ax.set_xticklabels(labels) |
| ax.set_title("Promotion funnel across fidelity levels") |
| ax.set_xlabel("Fidelity runs") |
| ax.set_ylabel("Ligands") |
| return fig |
|
|
| def percentile_bar(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| percentile_keys = [ |
| metrics.get("multifidelity_percentile_vs_full"), |
| metrics.get("random_percentile_vs_full"), |
| metrics.get("single_fidelity_percentile_vs_full"), |
| ] |
| if all(value in (None, "", "NA") for value in percentile_keys): |
| ax.axis("off") |
| message = ( |
| "Percentile versus full reference is not available.\n" |
| "This run used sampled reference or otherwise lacks\n" |
| "a complete comparable full-reference ranking." |
| ) |
| ax.text(0.5, 0.55, message, ha="center", va="center", fontsize=11) |
| ax.set_title("Percentile against full reference: not available") |
| return fig |
| labels = ["multifidelity", "random", "single", "full"] |
| vals = [ |
| float(metrics.get("multifidelity_percentile_vs_full", 0.0) or 0.0), |
| float(metrics.get("random_percentile_vs_full", 0.0) or 0.0), |
| float(metrics.get("single_fidelity_percentile_vs_full", 0.0) or 0.0), |
| 100.0, |
| ] |
| ax.bar(labels, vals, color=["#3b6ea8", "#bf7f2f", "#7a4f9d", "#7a9d54"]) |
| ax.set_ylim(0, 100) |
| ax.set_title("Percentile against full reference") |
| ax.set_ylabel("Percentile in full ranking") |
| return fig |
|
|
| def score_by_level(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| levels = sorted({str(row.get("selected_fidelity_runs", "")) for row in trace_rows}, key=lambda x: int(x or 0)) |
| for level in levels: |
| vals = [_float_or_zero(row.get("SCORE", 0.0)) for row in trace_rows if str(row.get("selected_fidelity_runs", "")) == level and row.get("SCORE", "") not in ("", None)] |
| if vals: |
| ax.hist(vals, bins=min(25, max(5, len(vals) // 3)), alpha=0.45, label=level) |
| ax.set_title("Score distribution at each fidelity level") |
| ax.set_xlabel("SCORE") |
| ax.set_ylabel("Records") |
| ax.legend(title="runs") |
| return fig |
|
|
| def intra_hist(plt): |
| vals = [_float_or_zero(row.get("SCORE.INTRA", 0.0)) for row in trace_rows if row.get("SCORE.INTRA", "") not in ("", None)] |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ax.hist(vals, bins=min(30, max(5, len(vals) // 3)), color="#bf7f2f") |
| ax.set_title("Distribution of SCORE.INTRA values") |
| ax.set_xlabel("SCORE.INTRA") |
| ax.set_ylabel("Records") |
| return fig |
|
|
| def score_vs_intra(plt): |
| xs = [_float_or_zero(row.get("SCORE.INTRA", 0.0)) for row in trace_rows if row.get("SCORE", "") not in ("", None) and row.get("SCORE.INTRA", "") not in ("", None)] |
| ys = [_float_or_zero(row.get("SCORE", 0.0)) for row in trace_rows if row.get("SCORE", "") not in ("", None) and row.get("SCORE.INTRA", "") not in ("", None)] |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| if xs and ys: |
| ax.scatter(xs, ys, c=["#b14d4d" if _boolish(row.get("intra_outlier", "")) else "#3b6ea8" for row in trace_rows[: min(len(xs), len(trace_rows))]], alpha=0.7) |
| ax.set_title("Score vs intra-molecular strain component") |
| ax.set_xlabel("SCORE.INTRA") |
| ax.set_ylabel("SCORE") |
| return fig |
|
|
| def score_vs_inter(plt): |
| candidates = [] |
| for source_name, rows in [("adaptive", raw_rows), ("random", random_rows), ("single", single_rows)]: |
| for row in rows: |
| inter = _first_float(row, ["SCORE.INTER"]) |
| score = _first_float(row, ["final_score", "best_score", "SCORE"]) |
| if inter is None or score is None: |
| continue |
| warnings = str(row.get("warnings", row.get("component_warning", ""))) |
| candidates.append((inter, score, source_name, warnings)) |
| fig, ax = plt.subplots(figsize=(7, 5)) |
| colors = {"adaptive": "#3b6ea8", "random": "#bf7f2f", "single": "#7a4f9d"} |
| for source_name in ["adaptive", "random", "single"]: |
| xs = [item[0] for item in candidates if item[2] == source_name] |
| ys = [item[1] for item in candidates if item[2] == source_name] |
| if xs: |
| ax.scatter(xs, ys, alpha=0.65, label=source_name, color=colors[source_name]) |
| ax.set_title("Docking score versus SCORE.INTER by strategy") |
| ax.set_xlabel("SCORE.INTER") |
| ax.set_ylabel("SCORE") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def intra_fraction_distribution(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| strategy_rows = [("adaptive", raw_rows, "#3b6ea8"), ("random", random_rows, "#bf7f2f"), ("single", single_rows, "#7a4f9d")] |
| for label, rows, color in strategy_rows: |
| vals = [_first_float(row, ["intra_fraction"]) for row in rows] |
| vals = [float(v) for v in vals if v is not None] |
| if vals: |
| ax.hist(vals, bins=20, alpha=0.45, label=label, color=color) |
| ax.set_title("Distribution of intra-fraction by strategy") |
| ax.set_xlabel("intra_fraction = abs(SCORE.INTRA) / abs(SCORE)") |
| ax.set_ylabel("Ligand count") |
| handles, labels = ax.get_legend_handles_labels() |
| if handles: |
| ax.legend() |
| return fig |
|
|
| def topk_comparison(plt): |
| fig, ax = plt.subplots(figsize=(7, 4)) |
| ks = [1, 5, 10, 20] |
| strategy_sets = [ |
| ("adaptive", filtered_rows, ["filtered_score", "adjusted_score", "final_score", "SCORE"], "#3b6ea8"), |
| ("random", random_rows, ["filtered_score", "final_score", "best_score", "SCORE"], "#bf7f2f"), |
| ("single", single_rows, ["filtered_score", "final_score", "best_score", "SCORE"], "#7a4f9d"), |
| ] |
| for label, rows, keys, color in strategy_sets: |
| ranked = sorted(((_first_float(row, keys), row) for row in rows), key=lambda item: item[0] if item[0] is not None else float("inf")) |
| vals = [] |
| for k in ks: |
| chunk = [item[0] for item in ranked[:k] if item[0] is not None] |
| vals.append(sum(chunk) / len(chunk) if chunk else math.nan) |
| ax.plot(ks, vals, marker="o", linewidth=2, label=label, color=color) |
| ax.set_title("Top-k filtered score comparison") |
| ax.set_xlabel("Top-k hits included") |
| ax.set_ylabel("Mean filtered SCORE") |
| ax.legend() |
| ax.grid(True, alpha=0.25) |
| return fig |
|
|
| def promotion_funnel_quality(plt): |
| fig, axes = plt.subplots(1, 3, figsize=(13, 4)) |
| levels = sorted({str(row.get("selected_fidelity_runs", "")) for row in trace_rows}, key=lambda x: int(x or 0)) |
| counts = [] |
| median_scores = [] |
| median_intra = [] |
| flagged_frac = [] |
| for level in levels: |
| items = [row for row in trace_rows if str(row.get("selected_fidelity_runs", "")) == level] |
| counts.append(len(items)) |
| scores = sorted([_first_float(row, ["ranking_score", "SCORE"]) for row in items if _first_float(row, ["ranking_score", "SCORE"]) is not None]) |
| med_score = scores[len(scores) // 2] if scores else math.nan |
| median_scores.append(med_score) |
| intra_vals = sorted([_first_float(row, ["intra_fraction"]) for row in items if _first_float(row, ["intra_fraction"]) is not None]) |
| median_intra.append(intra_vals[len(intra_vals) // 2] if intra_vals else math.nan) |
| flagged = sum(1 for row in items if str(row.get("component_warning", row.get("warnings", ""))).strip()) |
| flagged_frac.append((flagged / len(items)) if items else math.nan) |
| axes[0].bar(levels, counts, color="#3b6ea8") |
| axes[0].set_title("Promotion funnel counts") |
| axes[0].set_xlabel("Fidelity runs") |
| axes[0].set_ylabel("Ligands") |
| axes[1].plot(levels, median_scores, marker="o", color="#7a4f9d") |
| axes[1].set_title("Median score by fidelity") |
| axes[1].set_xlabel("Fidelity runs") |
| axes[1].set_ylabel("Median SCORE") |
| axes[2].plot(levels, flagged_frac, marker="o", color="#bf7f2f") |
| axes[2].set_title("Flagged fraction by fidelity") |
| axes[2].set_xlabel("Fidelity runs") |
| axes[2].set_ylabel("Fraction flagged") |
| return fig |
|
|
| def score_component_breakdown(plt): |
| ordered = sorted(raw_rows, key=lambda row: _first_float(row, ["final_score", "best_score", "SCORE"]) or float("inf"))[:10] |
| labels = [str(row.get("ligand_id", ""))[-12:] for row in ordered] |
| inter = [_first_float(row, ["SCORE.INTER"]) or 0.0 for row in ordered] |
| intra = [_first_float(row, ["SCORE.INTRA"]) or 0.0 for row in ordered] |
| restr = [_first_float(row, ["SCORE.RESTR"]) or 0.0 for row in ordered] |
| fig, ax = plt.subplots(figsize=(10, 5)) |
| ax.bar(range(len(labels)), inter, label="SCORE.INTER", color="#3b6ea8") |
| ax.bar(range(len(labels)), intra, bottom=inter, label="SCORE.INTRA", color="#bf7f2f") |
| bottoms = [a + b for a, b in zip(inter, intra)] |
| ax.bar(range(len(labels)), restr, bottom=bottoms, label="SCORE.RESTR", color="#7a4f9d") |
| ax.set_xticks(range(len(labels))) |
| ax.set_xticklabels(labels, rotation=45, ha="right") |
| ax.set_title("Score component breakdown for top raw hits") |
| ax.set_xlabel("Ligand") |
| ax.set_ylabel("Score component value") |
| ax.legend() |
| return fig |
|
|
| def benchmark_status_panel(plt): |
| fig, ax = plt.subplots(figsize=(9, 3)) |
| ax.axis("off") |
| lines = [ |
| f"Benchmark status: {metrics.get('benchmark_status', 'unknown')}", |
| f"Comparable: {comparability.get('comparable', 'unknown')}", |
| f"Reference mode: {comparability.get('reference_mode', metrics.get('reference_mode', 'unknown'))}", |
| f"Cost ratio random/adaptive: {comparability.get('cost_ratio_random_vs_multifidelity', 'NA')}", |
| f"Cost ratio single/adaptive: {comparability.get('cost_ratio_single_vs_multifidelity', 'NA')}", |
| f"Filtered outliers: {metrics.get('filtered_outlier_count', 0)}", |
| ] |
| reasons = comparability.get("reasons", []) |
| if reasons: |
| lines.append("Reasons:") |
| lines.extend(f"- {reason}" for reason in reasons[:5]) |
| ax.text(0.01, 0.98, "\n".join(lines), va="top", ha="left", fontsize=10, family="monospace") |
| return fig |
|
|
| def top_hits_bar(plt): |
| ordered = sorted( |
| [row for row in final_rows if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}], |
| key=lambda row: _float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))), |
| )[:20] |
| labels = [str(row.get("ligand_id", "")) for row in ordered] |
| vals = [_float_or_zero(row.get("final_score", row.get("current_best_score", 0.0))) for row in ordered] |
| fig, ax = plt.subplots(figsize=(9, 4)) |
| ax.bar(range(len(vals)), vals, color="#7a9d54") |
| ax.set_xticks(range(len(vals))) |
| ax.set_xticklabels(labels, rotation=60, ha="right", fontsize=8) |
| ax.set_title("Top final-fidelity hits") |
| ax.set_ylabel("Final SCORE") |
| return fig |
|
|
| def training_vs_docking(plt): |
| fig, ax = plt.subplots(figsize=(6, 4)) |
| ax.bar( |
| ["training", "docking", "overhead"], |
| [ |
| float(metrics.get("training_time_seconds", 0.0) or 0.0), |
| float(metrics.get("docking_time_seconds", 0.0) or 0.0), |
| float(metrics.get("overhead_unclassified_seconds", 0.0) or 0.0), |
| ], |
| color=["#7a4f9d", "#3b6ea8", "#bf7f2f"], |
| ) |
| ax.set_title("Runtime split") |
| ax.set_ylabel("Seconds") |
| return fig |
|
|
| def score_timeline_by_mode(plt): |
| fig, ax = plt.subplots(figsize=(9, 5)) |
|
|
| def timeline_series(rows: list[dict[str, str]], keys: list[str], final_only: bool = False) -> tuple[list[int], list[float]]: |
| series: list[float] = [] |
| ordered_rows = rows |
| if final_only: |
| ordered_rows = [row for row in rows if str(row.get("is_final_fidelity", "")).lower() in {"true", "1"}] |
| ordered_rows = sorted( |
| ordered_rows, |
| key=lambda row: ( |
| _float_or_zero(row.get("batch_id", 0.0)), |
| _float_or_zero(row.get("n_rdock_runs_total_spent", 0.0)), |
| str(row.get("ligand_id", "")), |
| ), |
| ) |
| for row in ordered_rows: |
| value = _first_float(row, keys) |
| if value is None: |
| continue |
| series.append(value) |
| return list(range(1, len(series) + 1)), series |
|
|
| mode_specs = [ |
| ("reference", full_rows, ["best_score", "SCORE"], False, "#7a9d54"), |
| ("adaptive final", final_rows, ["final_score", "current_best_score", "SCORE"], True, "#3b6ea8"), |
| ("random", random_rows, ["final_score", "best_score", "SCORE"], False, "#bf7f2f"), |
| ("single fidelity", single_rows, ["final_score", "best_score", "SCORE"], False, "#7a4f9d"), |
| ] |
| for label, rows, keys, final_only, color in mode_specs: |
| xs, ys = timeline_series(rows, keys, final_only=final_only) |
| if not xs: |
| continue |
| ax.plot(xs, ys, marker="o", markersize=3, linewidth=1.5, alpha=0.85, label=label, color=color) |
| ax.set_title("Timeline of processed ligand energies by benchmark mode") |
| ax.set_xlabel("Processed ligand index within mode") |
| ax.set_ylabel("Docking SCORE") |
| ax.legend() |
| ax.grid(True, alpha=0.25) |
| return fig |
|
|
| plot_specs = [ |
| ("cumulative_best_filtered_score_vs_runs.png", best_filtered_vs_cost), |
| ("cumulative_best_downranked_score_vs_runs.png", best_downranked_vs_cost), |
| ("cumulative_best_final_score_vs_runs.png", best_vs_cost), |
| ("cumulative_best_score_vs_walltime.png", best_vs_walltime), |
| ("cost_balance_comparison.png", cost_balance_bar), |
| ("ligands_per_fidelity_level.png", fidelity_counts), |
| ("promotion_funnel.png", promotion_funnel), |
| ("promotion_funnel_with_quality.png", promotion_funnel_quality), |
| ("adaptive_vs_random_vs_full_percentile.png", percentile_bar), |
| ("score_distribution_by_fidelity.png", score_by_level), |
| ("score_intra_distribution.png", intra_hist), |
| ("score_vs_score_intra_scatter.png", score_vs_intra), |
| ("score_vs_score_inter_scatter.png", score_vs_inter), |
| ("intra_fraction_distribution_by_strategy.png", intra_fraction_distribution), |
| ("topk_filtered_score_comparison.png", topk_comparison), |
| ("score_component_breakdown_top_hits.png", score_component_breakdown), |
| ("benchmark_status_panel.png", benchmark_status_panel), |
| ("top_final_hits.png", top_hits_bar), |
| ("training_vs_docking_time.png", training_vs_docking), |
| ("ligand_energy_timeline_by_mode.png", score_timeline_by_mode), |
| ] |
| for name, fn in plot_specs: |
| if path := _plot_or_skip(pdir, name, fn): |
| paths.append(path) |
| else: |
| vals = _floats(trace_rows, "SCORE") |
| paths.append(_simple_plot(pdir / name, vals, "bar" if "percentile" in name or "fidelity" in name or "top_" in name or "training" in name else "hist")) |
| return paths |
|
|