File size: 44,293 Bytes
c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 24f6204 c289d87 | 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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 | 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])) # type: ignore[index]
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: # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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"): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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): # type: ignore[no-untyped-def]
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
|