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

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

from .config_io import dump_json_like, load_structured_file
from .dataset import repair_dataset_dir
from .provenance import RDockPipelineError, require_file
from .rdock import TargetConfig, load_target_config
from .sdf import write_rows_csv


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 _load_json_if_exists(path: str | Path) -> dict[str, Any]:
    candidate = Path(path)
    if not candidate.exists():
        return {}
    try:
        payload = json.loads(candidate.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return payload if isinstance(payload, dict) else {}


def _load_struct_if_exists(path: str | Path) -> dict[str, Any]:
    candidate = Path(path)
    if not candidate.exists():
        return {}
    try:
        return load_structured_file(candidate)
    except Exception:
        return {}


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 _finite(value: object) -> float | None:
    out = _float(value, None)
    if out is None or not math.isfinite(out):
        return None
    return out


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


def _boolish(value: object) -> bool:
    return str(value).strip().lower() in {"1", "true", "yes", "y"}


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


def _stdev(values: list[float], center: float) -> float:
    if not values:
        return 1.0
    variance = sum((value - center) ** 2 for value in values) / max(1, len(values))
    return math.sqrt(variance) or 1.0


def _sort_by_score(rows: list[dict[str, Any]], *keys: str) -> list[dict[str, Any]]:
    return sorted(
        rows,
        key=lambda row: (
            _score_from_row(row, *keys) if _score_from_row(row, *keys) is not None else float("inf"),
            str(row.get("ligand_id", "")),
        ),
    )


def _augment_full_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    success_rows = [row for row in rows if str(row.get("rdock_success", "true")).lower() in {"true", "1", ""} and _score_from_row(row, "best_score", "SCORE", "final_score") is not None]
    ordered = _sort_by_score(success_rows, "best_score", "SCORE", "final_score")
    total = max(1, len(ordered))
    enriched: list[dict[str, Any]] = []
    for idx, row in enumerate(ordered, start=1):
        item = dict(row)
        percentile = 100.0 if total == 1 else 100.0 * (1.0 - ((idx - 1) / (total - 1)))
        item["full_rank"] = idx
        item["rank_vs_full"] = idx
        item["full_percentile"] = percentile
        item["percentile_vs_full"] = percentile
        enriched.append(item)
    return enriched


def _normalize_target_config(cfg: TargetConfig) -> dict[str, Any]:
    return {
        "receptor_name": Path(cfg.receptor).name,
        "reference_ligand_name": Path(cfg.reference_ligand).name,
        "receptor_mol2_name": Path(cfg.receptor_mol2).name,
        "receptor_prm_name": Path(cfg.receptor_prm).name,
        "cavity_as_name": Path(cfg.cavity_as).name,
        "pocket_center": [round(float(value), 4) for value in cfg.pocket_center],
        "pocket_radius": round(float(cfg.pocket_radius), 4),
    }


def _same_target_config(run_dir: Path, dataset_dir: Path | None) -> tuple[bool, list[str]]:
    reasons: list[str] = []
    root_cfg_path = run_dir / "target" / "rdock_prm" / "target_config.yaml"
    if not root_cfg_path.exists():
        reasons.append("missing run target_config.yaml")
        return False, reasons
    root_cfg = _normalize_target_config(load_target_config(root_cfg_path))
    if dataset_dir is None:
        reasons.append("dataset_dir unavailable")
        return False, reasons
    dataset_cfg_path = dataset_dir / "target" / "rdock_prm" / "target_config.yaml"
    if not dataset_cfg_path.exists():
        reasons.append("missing dataset target_config.yaml")
        return False, reasons
    dataset_cfg = _normalize_target_config(load_target_config(dataset_cfg_path))
    if root_cfg != dataset_cfg:
        reasons.append("run target_config differs from dataset target_config")
        return False, reasons
    return True, reasons


def _apply_component_flags(
    rows: list[dict[str, Any]],
    score_z_threshold: float = 5.0,
    intra_z_threshold: float = 4.0,
    max_intra_fraction_soft: float = 0.75,
    max_intra_fraction_hard: float = 0.9,
) -> list[dict[str, Any]]:
    score_values = [_score_from_row(row, "final_score", "SCORE") for row in rows]
    score_values = [value for value in score_values if value is not None]
    intra_values = [_score_from_row(row, "SCORE.INTRA") for row in rows]
    intra_values = [value for value in intra_values if value is not None]
    score_mean = _mean(score_values)
    score_sd = _stdev(score_values, score_mean)
    intra_mean = _mean(intra_values)
    intra_sd = _stdev(intra_values, intra_mean)
    enriched: list[dict[str, Any]] = []
    for row in rows:
        item = dict(row)
        score = _score_from_row(item, "final_score", "SCORE")
        intra = _score_from_row(item, "SCORE.INTRA")
        inter = _score_from_row(item, "SCORE.INTER")
        restr = _score_from_row(item, "SCORE.RESTR")
        intra_fraction = None
        if score is not None and abs(score) > 1e-9 and intra is not None:
            intra_fraction = abs(intra) / abs(score)
        elif intra is not None and abs(intra) > 0.0:
            intra_fraction = math.inf
        intra_z = ((intra - intra_mean) / intra_sd) if intra is not None and intra_sd else 0.0
        score_z = ((score - score_mean) / score_sd) if score is not None and score_sd else 0.0
        dominant_intra_soft = bool(intra_fraction is not None and math.isfinite(intra_fraction) and intra_fraction >= max_intra_fraction_soft)
        dominant_intra_hard = bool(intra_fraction is not None and math.isfinite(intra_fraction) and intra_fraction >= max_intra_fraction_hard)
        intra_outlier = _boolish(item.get("intra_outlier")) or bool(intra is not None and intra_z <= -abs(intra_z_threshold)) or dominant_intra_soft
        score_outlier = _boolish(item.get("score_outlier")) or bool(score is not None and score_z <= -abs(score_z_threshold))
        warnings = [token for token in str(item.get("component_warning", "")).split(",") if token.strip()]
        if intra_outlier and "intra_outlier" not in warnings:
            warnings.append("intra_outlier")
        if score_outlier and "score_outlier" not in warnings:
            warnings.append("score_outlier")
        if dominant_intra_soft and "intra_dominance" not in warnings:
            warnings.append("intra_dominance")
        severe_combined = (score_outlier and intra_outlier) or dominant_intra_hard
        item["SCORE"] = score if score is not None else item.get("SCORE", "")
        item["SCORE.INTER"] = inter if inter is not None else item.get("SCORE.INTER", "")
        item["SCORE.INTRA"] = intra if intra is not None else item.get("SCORE.INTRA", "")
        item["SCORE.RESTR"] = restr if restr is not None else item.get("SCORE.RESTR", "")
        item["intra_fraction"] = intra_fraction if intra_fraction is not None and math.isfinite(intra_fraction) else ("" if intra_fraction is None else "inf")
        item["intra_dominance"] = dominant_intra_soft
        item["intra_outlier"] = intra_outlier
        item["score_outlier"] = score_outlier
        item["component_warning"] = ",".join(warnings)
        penalty = 0.0
        if intra_outlier:
            penalty += 2.0
        if score_outlier:
            penalty += 2.0
        if dominant_intra_soft:
            penalty += 3.0
        if severe_combined:
            penalty += 8.0
        item["adjusted_score"] = (score + penalty) if score is not None else ""
        filtered_reasons: list[str] = []
        if severe_combined and intra_outlier:
            filtered_reasons.append("intra_outlier")
        if severe_combined and score_outlier:
            filtered_reasons.append("score_outlier")
        if dominant_intra_hard:
            filtered_reasons.append("intra_dominance")
        item["filtered_out"] = bool(filtered_reasons)
        item["filtered_reason"] = ",".join(filtered_reasons)
        item["downranked"] = bool(warnings) and not item["filtered_out"]
        item["potential_strain_artifact"] = intra_outlier or dominant_intra_soft
        enriched.append(item)
    return enriched


def _attach_vs_full(
    rows: list[dict[str, Any]],
    full_rows: list[dict[str, Any]],
    universe_complete: bool,
) -> list[dict[str, Any]]:
    full_map = {
        str(row["ligand_id"]): {
            "rank_vs_full": int(row["rank_vs_full"]),
            "percentile_vs_full": float(row["percentile_vs_full"]),
            "full_score": _score_from_row(row, "SCORE"),
        }
        for row in full_rows
    }
    enriched: list[dict[str, Any]] = []
    for row in rows:
        item = dict(row)
        ligand_id = str(item.get("ligand_id", ""))
        entry = full_map.get(ligand_id)
        if entry and universe_complete:
            item["rank_vs_full"] = entry["rank_vs_full"]
            item["percentile_vs_full"] = entry["percentile_vs_full"]
            item["not_comparable"] = False
            item["not_comparable_reason"] = ""
        else:
            item["rank_vs_full"] = ""
            item["percentile_vs_full"] = ""
            item["not_comparable"] = True
            item["not_comparable_reason"] = "ligand_missing_in_full" if entry is None else "full_universe_incomplete"
        enriched.append(item)
    return enriched


def _best_row(rows: list[dict[str, Any]], *score_keys: str) -> dict[str, Any] | None:
    ranked = [row for row in rows if _score_from_row(row, *score_keys) is not None]
    if not ranked:
        return None
    return _sort_by_score(ranked, *score_keys)[0]


def _overlap_count(full_rows: list[dict[str, Any]], sample_rows: list[dict[str, Any]], n: int, *score_keys: str) -> int:
    full_top = {str(row["ligand_id"]) for row in _sort_by_score(full_rows, "SCORE")[:n]}
    sample_top = {str(row["ligand_id"]) for row in _sort_by_score(sample_rows, *score_keys)[:n]}
    return len(full_top & sample_top)


def _trace_lookup(trace_rows: list[dict[str, Any]], final_level: int) -> dict[str, dict[str, Any]]:
    by_id: dict[str, dict[str, Any]] = {}
    for row in trace_rows:
        ligand_id = str(row.get("ligand_id", ""))
        prev = by_id.get(ligand_id)
        level = int(_float(row.get("selected_fidelity_runs"), 0.0) or 0)
        prev_level = int(_float(prev.get("selected_fidelity_runs"), 0.0) or 0) if prev else -1
        if prev is None or level > prev_level or (level == final_level and prev_level != final_level):
            by_id[ligand_id] = dict(row)
    return by_id


def _estimate_total_runs(rows: list[dict[str, Any]], fallback_runs: int) -> int:
    values = []
    for row in rows:
        value = _float(row.get("n_rdock_runs_total_spent"))
        if value is not None:
            values.append(int(value))
    if values:
        return sum(values)
    return len(rows) * max(0, int(fallback_runs))


def _load_reference_ids(run_dir: Path, reference_mode: str) -> list[str]:
    if reference_mode != "sampled":
        return []
    sample_path = run_dir / "tables" / "reference_sample_ligand_ids.txt"
    if not sample_path.exists():
        return []
    return [line.strip() for line in sample_path.read_text(encoding="utf-8").splitlines() if line.strip()]


def _time_breakdown(run_dir: Path, existing_metrics: dict[str, Any], final_level: int) -> dict[str, Any]:
    checkpoints = run_dir / "checkpoints"
    full_ckpt = _load_json_if_exists(checkpoints / "full_docking.json")
    single_ckpt = _load_json_if_exists(checkpoints / "single_fidelity.json")
    random_ckpt = _load_json_if_exists(checkpoints / "random_baseline.json")
    walltime = _float(existing_metrics.get("walltime_total_seconds"), 0.0) or 0.0
    docking_total = _float(existing_metrics.get("docking_time_seconds"), 0.0) or 0.0
    full_docking = _float(full_ckpt.get("full_docking_seconds"), 0.0) or 0.0
    single_docking = _float(single_ckpt.get("seconds"), 0.0) or 0.0
    random_docking = _float(random_ckpt.get("seconds"), 0.0) or 0.0
    training = _float(existing_metrics.get("training_time_seconds"), 0.0) or 0.0
    parsing = _float(existing_metrics.get("parsing_time_seconds"), 0.0) or 0.0
    split_merge = _float(existing_metrics.get("sdf_split_merge_time_seconds"), 0.0) or 0.0
    scheduler = _float(existing_metrics.get("scheduler_time_seconds"), 0.0) or 0.0
    io_time = _float(existing_metrics.get("io_time_seconds"), 0.0) or 0.0
    known = docking_total + training + parsing + split_merge + scheduler + io_time
    overhead = max(0.0, walltime - known)
    overhead_fraction = (overhead / walltime) if walltime > 0 else 0.0
    warnings: list[str] = []
    if overhead_fraction > 0.30:
        warnings.append("overhead_fraction_gt_30pct")
    return {
        "walltime_total_seconds": walltime,
        "docking_time_seconds": docking_total,
        "training_time_seconds": training,
        "parsing_time_seconds": parsing,
        "sdf_split_merge_time_seconds": split_merge,
        "scheduler_time_seconds": scheduler,
        "io_time_seconds": io_time,
        "overhead_unclassified_seconds": overhead,
        "overhead_fraction": overhead_fraction,
        "time_warnings": warnings,
        "final_fidelity_runs": final_level,
        "full_docking_time_seconds": full_docking,
        "single_fidelity_time_seconds": single_docking,
        "random_baseline_time_seconds": random_docking,
        "multifidelity_docking_time_seconds": max(0.0, docking_total - full_docking - single_docking - random_docking),
    }


def _render_report(
    run_dir: Path,
    metrics: dict[str, Any],
    comparability: dict[str, Any],
    final_raw_rows: list[dict[str, Any]],
    final_downranked_rows: list[dict[str, Any]],
    final_filtered_rows: list[dict[str, Any]],
) -> str:
    lines = [
        f"# benchmark-adaptive audit: {metrics.get('target_id') or run_dir.name}",
        "",
        f"## {metrics.get('benchmark_status', 'BENCHMARK PARTIAL / NOT COMPARABLE')}",
        "",
        "## Comparability",
        f"- comparable: `{comparability.get('comparable')}`",
        f"- same_target_config: `{comparability.get('same_target_config')}`",
        f"- same_dataset_manifest: `{comparability.get('same_dataset_manifest')}`",
        f"- same_final_fidelity_runs: `{comparability.get('same_final_fidelity_runs')}`",
        f"- stale_checkpoint_detected: `{comparability.get('stale_checkpoint_detected')}`",
    ]
    for reason in comparability.get("reasons", []):
        lines.append(f"- reason: `{reason}`")
    if not comparability.get("comparable"):
        lines.extend(["", "> WARNING: this benchmark is not fully comparable; rank/percentile claims should be treated as non-authoritative."])
    lines.extend(
        [
            "",
            "## Corrected Metrics",
        ]
    )
    ordered_keys = [
        "best_raw_hit_ligand_id",
        "best_raw_hit_score",
        "best_filtered_hit_ligand_id",
        "best_filtered_hit_score",
        "best_random_hit_ligand_id",
        "best_random_hit_score",
        "best_random_filtered_hit_ligand_id",
        "best_random_filtered_hit_score",
        "best_single_fidelity_ligand_id",
        "best_single_fidelity_score",
        "best_full_docking_ligand_id",
        "best_full_docking_score",
        "multifidelity_rank_vs_full",
        "multifidelity_percentile_vs_full",
        "random_rank_vs_full",
        "random_percentile_vs_full",
        "single_fidelity_rank_vs_full",
        "single_fidelity_percentile_vs_full",
        "adaptive_gain_score",
        "adaptive_gain_score_filtered",
        "multifidelity_total_runs_spent",
        "random_total_runs_spent",
        "single_fidelity_total_runs_spent",
        "cost_ratio",
        "walltime_total_seconds",
        "docking_time_seconds",
        "training_time_seconds",
        "parsing_time_seconds",
        "sdf_split_merge_time_seconds",
        "scheduler_time_seconds",
        "io_time_seconds",
        "overhead_unclassified_seconds",
        "overhead_fraction",
        "filtered_outlier_count",
    ]
    for key in ordered_keys:
        if key in metrics:
            lines.append(f"- {key}: `{metrics.get(key)}`")
    for warning in metrics.get("warnings", []):
        lines.append(f"- warning: `{warning}`")
    lines.extend(["", "## Top Raw Final Hits"])
    for row in final_raw_rows[:20]:
        lines.append(
            f"- `{row.get('ligand_id')}` SCORE `{row.get('final_score', row.get('SCORE', ''))}` "
            f"SCORE.INTER `{row.get('SCORE.INTER', '')}` SCORE.INTRA `{row.get('SCORE.INTRA', '')}` "
            f"SCORE.RESTR `{row.get('SCORE.RESTR', '')}` intra_fraction `{row.get('intra_fraction', '')}` "
            f"raw_rank `{row.get('raw_rank', '')}` downranked_rank `{row.get('downranked_rank', '')}` filtered_rank `{row.get('filtered_rank', '')}` "
            f"rank_vs_full `{row.get('rank_vs_full', '')}` percentile_vs_full `{row.get('percentile_vs_full', '')}` "
            f"warnings `{row.get('component_warning', '')}`"
        )
    lines.extend(["", "## Top Downranked Final Hits"])
    for row in final_downranked_rows[:20]:
        lines.append(
            f"- `{row.get('ligand_id')}` SCORE `{row.get('final_score', row.get('SCORE', ''))}` "
            f"adjusted `{row.get('adjusted_score', '')}` SCORE.INTER `{row.get('SCORE.INTER', '')}` SCORE.INTRA `{row.get('SCORE.INTRA', '')}` "
            f"intra_fraction `{row.get('intra_fraction', '')}` raw_rank `{row.get('raw_rank', '')}` downranked_rank `{row.get('downranked_rank', '')}` "
            f"warnings `{row.get('component_warning', '')}`"
        )
    lines.extend(["", "## Top Filtered Final Hits"])
    for row in final_filtered_rows[:20]:
        lines.append(
            f"- `{row.get('ligand_id')}` SCORE `{row.get('final_score', row.get('SCORE', ''))}` "
            f"SCORE.INTER `{row.get('SCORE.INTER', '')}` SCORE.INTRA `{row.get('SCORE.INTRA', '')}` "
            f"SCORE.RESTR `{row.get('SCORE.RESTR', '')}` intra_fraction `{row.get('intra_fraction', '')}` "
            f"raw_rank `{row.get('raw_rank', '')}` downranked_rank `{row.get('downranked_rank', '')}` filtered_rank `{row.get('filtered_rank', '')}` "
            f"rank_vs_full `{row.get('rank_vs_full', '')}` percentile_vs_full `{row.get('percentile_vs_full', '')}` "
            f"warnings `{row.get('component_warning', '')}`"
        )
    return "\n".join(lines) + "\n"


def audit_benchmark_run(run_dir: str | Path) -> dict[str, Any]:
    root = Path(run_dir)
    tables = root / "tables"
    metrics_dir = root / "metrics"
    raw_metrics = _load_json_if_exists(metrics_dir / "adaptive_benchmark_metrics_raw.json")
    existing_metrics = raw_metrics or _load_json_if_exists(metrics_dir / "adaptive_benchmark_metrics.json")
    validation_metrics = _load_json_if_exists(metrics_dir / "validation_metrics.json")
    signature = _load_json_if_exists(root / "checkpoints" / "run_signature.json")
    config = _load_struct_if_exists(root / "config.yaml")
    manifest = _load_json_if_exists(root / "manifest.json")
    dataset_dir_value = config.get("dataset_dir") or existing_metrics.get("dataset_dir") or manifest.get("dataset_dir")
    dataset_dir = Path(dataset_dir_value) if dataset_dir_value else None
    dataset_repair: dict[str, Any] = {}
    dataset_manifest: dict[str, Any] = {}
    if dataset_dir and dataset_dir.exists():
        dataset_repair = repair_dataset_dir(dataset_dir)
        dataset_manifest = _load_json_if_exists(dataset_dir / "dataset_manifest.json")
    reference_mode = str(
        config.get("reference_mode")
        or signature.get("reference_mode")
        or raw_metrics.get("reference_mode")
        or validation_metrics.get("reference_mode")
        or existing_metrics.get("reference_mode")
        or "full"
    ).lower()
    evaluation_pool_mode = str(
        config.get("evaluation_pool_mode")
        or signature.get("evaluation_pool_mode")
        or raw_metrics.get("evaluation_pool_mode")
        or validation_metrics.get("evaluation_pool_mode")
        or existing_metrics.get("evaluation_pool_mode")
        or "same_pool"
    ).lower()
    final_level = 0
    levels = config.get("fidelity_levels") or signature.get("fidelity_levels") or raw_metrics.get("fidelity_levels") or validation_metrics.get("fidelity_levels") or existing_metrics.get("fidelity_levels") or []
    if isinstance(levels, list) and levels:
        final_level = int(levels[-1])
    elif isinstance(levels, str) and levels.strip():
        final_level = int(str(levels).split(",")[-1].strip())

    full_table_rows = _read_rows(tables / "full_docking_scores.csv") if (tables / "full_docking_scores.csv").exists() else []
    full_rows = _augment_full_rows(full_table_rows) if full_table_rows else []
    full_rank_map = {str(row["ligand_id"]): row for row in full_rows}
    normalized_full_rows: list[dict[str, Any]] = []
    for row in full_table_rows:
        item = dict(row)
        item.update({k: v for k, v in full_rank_map.get(str(row.get("ligand_id", "")), {}).items() if k not in item or item[k] in {"", None}})
        normalized_full_rows.append(item)
    if normalized_full_rows:
        write_rows_csv(normalized_full_rows, tables / "full_docking_scores.csv")
    full_ligand_ids = {str(row["ligand_id"]) for row in normalized_full_rows}
    expected_universe = int(_float(dataset_manifest.get("ligands_prepared"), len(full_rows)) or len(full_rows))
    reference_ids = _load_reference_ids(root, reference_mode)
    reference_sample_size = int(
        _float(
            config.get("reference_sample_size")
            or signature.get("reference_sample_size")
            or raw_metrics.get("reference_sample_size")
            or validation_metrics.get("reference_sample_size"),
            len(normalized_full_rows) if reference_mode == "sampled" else expected_universe,
        )
        or (len(normalized_full_rows) if reference_mode == "sampled" else expected_universe)
    )
    n_reference_ligands = expected_universe if reference_mode == "full" else (len(reference_ids) if reference_ids else reference_sample_size if reference_mode == "sampled" else 0)
    reference_completion_fraction = len(normalized_full_rows) / max(1, n_reference_ligands) if n_reference_ligands else 0.0
    full_universe_complete = reference_mode == "full" and reference_completion_fraction >= 0.99

    audit_settings = {
        "score_z_threshold": float(config.get("score_z_threshold") or signature.get("command_args", {}).get("score_z_threshold") or validation_metrics.get("score_z_threshold") or 5.0),
        "intra_z_threshold": float(config.get("intra_z_threshold") or signature.get("command_args", {}).get("intra_z_threshold") or validation_metrics.get("intra_z_threshold") or 4.0),
        "max_intra_fraction_soft": float(config.get("max_intra_fraction_soft") or signature.get("command_args", {}).get("max_intra_fraction_soft") or validation_metrics.get("max_intra_fraction_soft") or config.get("max_intra_fraction") or 0.75),
        "max_intra_fraction_hard": float(config.get("max_intra_fraction_hard") or signature.get("command_args", {}).get("max_intra_fraction_hard") or validation_metrics.get("max_intra_fraction_hard") or 0.9),
    }

    random_rows = _apply_component_flags(
        _attach_vs_full(_read_rows(tables / "random_baseline_scores.csv"), full_rows, full_universe_complete),
        **audit_settings,
    )
    single_path = tables / "single_fidelity_adaptive_scores.csv"
    if not single_path.exists():
        single_path = tables / "single_fidelity_scores.csv"
    single_rows = _apply_component_flags(_attach_vs_full(_read_rows(single_path), full_rows, full_universe_complete), **audit_settings)
    trace_rows = _read_rows(tables / "multifidelity_trace.csv") if (tables / "multifidelity_trace.csv").exists() else []
    final_seed_rows = _read_rows(tables / "final_hits.csv")
    trace_map = _trace_lookup(trace_rows, final_level)
    final_raw_rows: list[dict[str, Any]] = []
    for row in final_seed_rows:
        ligand_id = str(row.get("ligand_id", ""))
        merged = dict(row)
        merged.update({key: value for key, value in trace_map.get(ligand_id, {}).items() if key not in {"ligand_id"}})
        if "final_score" not in merged or str(merged.get("final_score", "")).strip() == "":
            if str(merged.get("is_final_fidelity", "")).lower() in {"true", "1"}:
                merged["final_score"] = merged.get("SCORE", merged.get("current_best_score", ""))
        final_raw_rows.append(merged)
    final_raw_rows = _apply_component_flags(_attach_vs_full(final_raw_rows, full_rows, full_universe_complete), **audit_settings)
    final_raw_rows = _sort_by_score(final_raw_rows, "final_score", "SCORE")
    for idx, row in enumerate(final_raw_rows, start=1):
        row["raw_rank"] = idx
    write_rows_csv(final_raw_rows, tables / "final_hits_raw.csv")
    final_downranked_rows = _sort_by_score([dict(row) for row in final_raw_rows], "adjusted_score", "final_score", "SCORE")
    for idx, row in enumerate(final_downranked_rows, start=1):
        row["downranked_rank"] = idx
    downrank_map = {str(row["ligand_id"]): row["downranked_rank"] for row in final_downranked_rows}
    write_rows_csv(final_downranked_rows, tables / "final_hits_downranked.csv")
    final_filtered_rows = [dict(row) for row in final_downranked_rows if not _boolish(row.get("filtered_out"))]
    final_filtered_rows = _sort_by_score(final_filtered_rows, "final_score", "SCORE")
    for idx, row in enumerate(final_filtered_rows, start=1):
        row["filtered_rank"] = idx
    filtered_map = {str(row["ligand_id"]): row["filtered_rank"] for row in final_filtered_rows}
    for row in final_raw_rows:
        row["downranked_rank"] = downrank_map.get(str(row.get("ligand_id", "")), "")
        row["filtered_rank"] = filtered_map.get(str(row.get("ligand_id", "")), "")
    for row in final_downranked_rows:
        row["raw_rank"] = next((raw["raw_rank"] for raw in final_raw_rows if str(raw.get("ligand_id")) == str(row.get("ligand_id"))), "")
        row["filtered_rank"] = filtered_map.get(str(row.get("ligand_id", "")), "")
    write_rows_csv(final_filtered_rows, tables / "final_hits_filtered.csv")

    random_filtered_rows = [dict(row) for row in random_rows if not _boolish(row.get("filtered_out"))]
    single_filtered_rows = [dict(row) for row in single_rows if not _boolish(row.get("filtered_out"))]

    best_full = _best_row(full_rows, "SCORE")
    best_raw = _best_row(final_raw_rows, "final_score", "SCORE")
    best_filtered = _best_row(final_filtered_rows, "final_score", "SCORE")
    best_random = _best_row(random_rows, "final_score", "SCORE")
    best_random_filtered = _best_row(random_filtered_rows, "final_score", "SCORE")
    best_single = _best_row(single_rows, "final_score", "SCORE")

    reference_id_set = set(reference_ids) if reference_ids else full_ligand_ids
    overlap_multifidelity_full = len({str(row["ligand_id"]) for row in final_raw_rows} & reference_id_set)
    overlap_random_full = len({str(row["ligand_id"]) for row in random_rows} & reference_id_set)
    overlap_single_full = len({str(row["ligand_id"]) for row in single_rows} & reference_id_set)
    same_target_config, target_reasons = _same_target_config(root, dataset_dir)
    same_dataset_manifest = bool(dataset_dir and dataset_dir.exists() and dataset_manifest)
    same_final_fidelity_runs = True
    final_reasons: list[str] = []
    full_run_metrics = _load_json_if_exists(root / "full_docking" / "metrics" / "rdock_metrics.json")
    random_run_metrics = _load_json_if_exists(root / "random_baseline" / "metrics" / "rdock_metrics.json")
    single_run_metrics = _load_json_if_exists(root / "single_fidelity_adaptive" / "metrics" / "rdock_metrics.json")
    for label, payload in (("full_docking", full_run_metrics), ("random_baseline", random_run_metrics), ("single_fidelity", single_run_metrics)):
        if payload:
            n_runs = int(_float(payload.get("n_runs"), final_level) or final_level)
            if final_level and n_runs != final_level:
                same_final_fidelity_runs = False
                final_reasons.append(f"{label}_n_runs={n_runs} differs from final_fidelity={final_level}")
    stale_checkpoint_detected = (root / "checkpoints" / "failure.json").exists()
    reasons: list[str] = []
    reasons.extend(target_reasons)
    reasons.extend(final_reasons)
    if reference_mode == "full" and not full_universe_complete:
        reasons.append(f"incomplete_full_reference coverage={reference_completion_fraction:.4f}")
    expected_overlap_size = len(reference_id_set) if reference_mode == "sampled" and evaluation_pool_mode == "same_pool" else None
    for label, rows, overlap in (
        ("multifidelity", final_raw_rows, overlap_multifidelity_full),
        ("random", random_rows, overlap_random_full),
        ("single_fidelity", single_rows, overlap_single_full),
    ):
        if overlap != len(rows):
            reasons.append(f"{label}_contains_ligands_missing_from_full")
        if expected_overlap_size is not None and any(str(row.get("ligand_id", "")) not in reference_id_set for row in rows):
            reasons.append(f"{label}_contains_ligands_missing_from_reference_sample")
    if best_raw and str(best_raw.get("ligand_id")) not in full_ligand_ids:
        reasons.append("best_multifidelity_ligand_missing_from_full")
    if best_random and str(best_random.get("ligand_id")) not in full_ligand_ids:
        reasons.append("best_random_ligand_missing_from_full")
    if best_single and str(best_single.get("ligand_id")) not in full_ligand_ids:
        reasons.append("best_single_fidelity_ligand_missing_from_full")
    if best_single and best_full and same_target_config and same_dataset_manifest and same_final_fidelity_runs and overlap_single_full == len(single_rows):
        if _score_from_row(best_single, "final_score", "SCORE") is not None and _score_from_row(best_full, "SCORE") is not None:
            epsilon = float(config.get("single_full_score_epsilon") or signature.get("command_args", {}).get("single_full_score_epsilon") or 1.0)
            if _score_from_row(best_single, "final_score", "SCORE") < (_score_from_row(best_full, "SCORE") - epsilon):
                reasons.append("hard_warning_single_fidelity_better_than_full_docking_in_same_universe")
    if stale_checkpoint_detected:
        reasons.append("stale_checkpoint_detected")
    time_metrics = _time_breakdown(root, existing_metrics, final_level)
    multifidelity_total_runs = int(
        _float(validation_metrics.get("multifidelity_total_runs_spent"), None)
        or _float(validation_metrics.get("total_rdock_runs_spent"), None)
        or _float(raw_metrics.get("multifidelity_total_runs_spent"), None)
        or _float(raw_metrics.get("total_rdock_runs_spent"), None)
        or _float(existing_metrics.get("multifidelity_total_runs_spent"), None)
        or _float(existing_metrics.get("total_rdock_runs_spent"), None)
        or _estimate_total_runs(trace_rows, 0)
        or _estimate_total_runs(final_raw_rows, final_level)
    )
    random_total_runs = _estimate_total_runs(random_rows, final_level)
    single_total_runs = _estimate_total_runs(single_rows, final_level)
    cost_ratio = (random_total_runs / multifidelity_total_runs) if multifidelity_total_runs else None
    cost_ratio_single = (single_total_runs / multifidelity_total_runs) if multifidelity_total_runs else None
    warnings = list(time_metrics.get("time_warnings", []))
    if cost_ratio is not None and abs(cost_ratio - 1.0) > 0.05:
        warnings.append("cost_ratio_differs_by_more_than_5pct")
        reasons.append("not_cost_comparable_random")
    if cost_ratio_single is not None and abs(cost_ratio_single - 1.0) > 0.05:
        warnings.append("single_cost_ratio_differs_by_more_than_5pct")
        reasons.append("not_cost_comparable_single")
    if reference_mode == "none":
        reasons.append("reference_mode_none")
    comparable = False if reference_mode == "none" else not reasons

    best_raw_score = _score_from_row(best_raw or {}, "final_score", "SCORE")
    best_filtered_score = _score_from_row(best_filtered or {}, "final_score", "SCORE")
    best_random_score = _score_from_row(best_random or {}, "final_score", "SCORE")
    best_random_filtered_score = _score_from_row(best_random_filtered or {}, "final_score", "SCORE")
    best_single_score = _score_from_row(best_single or {}, "final_score", "SCORE")
    best_full_score = _score_from_row(best_full or {}, "SCORE")

    corrected_metrics: dict[str, Any] = {
        "strategy": config.get("strategy") or existing_metrics.get("strategy"),
        "dataset_dir": str(dataset_dir) if dataset_dir else "",
        "target_id": (dataset_manifest.get("pdb_id") or existing_metrics.get("target_id") or root.name),
        "reference_mode": reference_mode,
        "evaluation_pool_mode": evaluation_pool_mode,
        "benchmark_status": (
            "BENCHMARK COMPLETE"
            if reference_mode == "full" and comparable
            else "BENCHMARK SAMPLED REFERENCE"
            if reference_mode == "sampled" and not reasons
            else "BENCHMARK PARTIAL / NOT COMPARABLE"
        ),
        "best_final_SCORE_found_by_multifidelity": best_raw_score,
        "best_filtered_SCORE_found_by_multifidelity": best_filtered_score,
        "best_final_SCORE_found_by_random_at_same_cost": best_random_score,
        "best_filtered_SCORE_found_by_random_at_same_cost": best_random_filtered_score,
        "best_final_SCORE_found_by_single_fidelity": best_single_score,
        "best_SCORE_in_full_docking": best_full_score,
        "best_raw_hit_ligand_id": best_raw.get("ligand_id") if best_raw else None,
        "best_raw_hit_score": best_raw_score,
        "best_filtered_hit_ligand_id": best_filtered.get("ligand_id") if best_filtered else None,
        "best_filtered_hit_score": best_filtered_score,
        "best_random_hit_ligand_id": best_random.get("ligand_id") if best_random else None,
        "best_random_hit_score": best_random_score,
        "best_random_filtered_hit_ligand_id": best_random_filtered.get("ligand_id") if best_random_filtered else None,
        "best_random_filtered_hit_score": best_random_filtered_score,
        "best_single_fidelity_ligand_id": best_single.get("ligand_id") if best_single else None,
        "best_single_fidelity_score": best_single_score,
        "best_full_docking_ligand_id": best_full.get("ligand_id") if best_full else None,
        "best_full_docking_score": best_full_score,
        "multifidelity_rank_vs_full": best_raw.get("rank_vs_full") if best_raw and not _boolish(best_raw.get("not_comparable")) else None,
        "multifidelity_percentile_vs_full": best_raw.get("percentile_vs_full") if best_raw and not _boolish(best_raw.get("not_comparable")) else None,
        "random_rank_vs_full": best_random.get("rank_vs_full") if best_random and not _boolish(best_random.get("not_comparable")) else None,
        "random_percentile_vs_full": best_random.get("percentile_vs_full") if best_random and not _boolish(best_random.get("not_comparable")) else None,
        "single_fidelity_rank_vs_full": best_single.get("rank_vs_full") if best_single and not _boolish(best_single.get("not_comparable")) else None,
        "single_fidelity_percentile_vs_full": best_single.get("percentile_vs_full") if best_single and not _boolish(best_single.get("not_comparable")) else None,
        "adaptive_gain_score": (best_random_score - best_raw_score) if best_random_score is not None and best_raw_score is not None else None,
        "adaptive_gain_score_filtered": (best_random_filtered_score - best_filtered_score) if best_random_filtered_score is not None and best_filtered_score is not None else None,
        "adaptive_gain_over_random": (best_random_score - best_raw_score) if best_random_score is not None and best_raw_score is not None else None,
        "multifidelity_total_runs_spent": multifidelity_total_runs,
        "random_total_runs_spent": random_total_runs,
        "single_fidelity_total_runs_spent": single_total_runs,
        "cost_ratio": cost_ratio,
        "cost_ratio_single": cost_ratio_single,
        "reference_completion_fraction": reference_completion_fraction,
        "filtered_outlier_count": sum(1 for row in final_raw_rows if _boolish(row.get("filtered_out"))),
        "raw_final_hits_count": len(final_raw_rows),
        "downranked_final_hits_count": len(final_downranked_rows),
        "filtered_final_hits_count": len(final_filtered_rows),
        "outlier_policy": config.get("outlier_policy") or signature.get("command_args", {}).get("outlier_policy") or "downrank",
        "warnings": warnings,
        "dataset_repair_warnings": dataset_repair.get("warnings", []),
    }
    corrected_metrics.update(time_metrics)

    comparability = {
        "dataset_ligands_prepared": expected_universe,
        "n_reference_ligands": n_reference_ligands,
        "n_full_ligands": len(normalized_full_rows),
        "n_multifidelity_ligands": len(final_raw_rows),
        "n_random_ligands": len(random_rows),
        "n_single_fidelity_ligands": len(single_rows),
        "overlap_multifidelity_reference": overlap_multifidelity_full,
        "overlap_random_reference": overlap_random_full,
        "overlap_single_reference": overlap_single_full,
        "cost_ratio_random_vs_multifidelity": cost_ratio,
        "cost_ratio_single_vs_multifidelity": cost_ratio_single,
        "same_target_config": same_target_config,
        "same_dataset_manifest": same_dataset_manifest,
        "same_final_fidelity_runs": same_final_fidelity_runs,
        "stale_checkpoint_detected": stale_checkpoint_detected,
        "comparable": comparable,
        "reasons": reasons,
    }

    if existing_metrics:
        dump_json_like(metrics_dir / "adaptive_benchmark_metrics_raw.json", existing_metrics)
    dump_json_like(metrics_dir / "adaptive_benchmark_metrics.json", corrected_metrics)
    dump_json_like(metrics_dir / "adaptive_benchmark_metrics_corrected.json", corrected_metrics)
    dump_json_like(metrics_dir / "comparability_audit.json", comparability)
    (root / "report.md").write_text(_render_report(root, corrected_metrics, comparability, final_raw_rows, final_downranked_rows, final_filtered_rows), encoding="utf-8")
    return {
        "run_dir": str(root),
        "metrics": corrected_metrics,
        "comparability_audit": comparability,
        "final_hits_raw": str(tables / "final_hits_raw.csv"),
        "final_hits_downranked": str(tables / "final_hits_downranked.csv"),
        "final_hits_filtered": str(tables / "final_hits_filtered.csv"),
        "report": str(root / "report.md"),
    }


def build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Re-audit an existing adaptive benchmark run without re-running docking.")
    parser.add_argument("--run-dir", required=True)
    return parser


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


def main() -> int:
    parser = build_arg_parser()
    args = parser.parse_args()
    try:
        print(json.dumps(run_from_args(args), indent=2))
    except Exception as exc:
        failure = {
            "error": str(exc),
            "traceback": traceback.format_exc(),
            "run_dir": str(args.run_dir),
        }
        target = Path(args.run_dir) / "checkpoints" / "audit_failure.json"
        dump_json_like(target, failure)
        raise
    return 0