File size: 37,162 Bytes
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import csv
import json
import random
import shutil
import sys
import time
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from docking_pipeline.provenance import CommandRunner, RDockPipelineError, fail_if_bad_command, probe_version, require_executable, require_file
from docking_pipeline.rdock import RDockEngine, RDockRunConfig, TargetConfig
from docking_pipeline.reports.plots import plot_adaptive_benchmark_outputs, plot_score_outputs
from docking_pipeline.sdf import ligand_id_from_block, parse_tags, split_sdf_file, write_rows_csv, write_sdf_blocks


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 _float(value: object, default: float = 0.0) -> float:
    try:
        text = str(value).strip()
        if not text:
            return default
        return float(text)
    except Exception:
        return default


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


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


def _load_targets(path: Path) -> list[dict[str, str]]:
    text = require_file(path, "benchmark targets config").read_text(encoding="utf-8")
    payload = json.loads(text)
    targets = payload.get("targets", [])
    if not isinstance(targets, list) or not targets:
        raise RDockPipelineError(f"No targets defined in {path}")
    return [dict(item) for item in targets]


def _extract_receptor_and_ligand(
    pdb: Path,
    receptor_chain: str,
    ligand_resname: str,
    ligand_chain: str,
    out_dir: Path,
) -> tuple[Path, Path]:
    out_dir.mkdir(parents=True, exist_ok=True)
    receptor = out_dir / "receptor.pdb"
    ligand_pdb = out_dir / "reference_ligand.pdb"
    receptor_lines: list[str] = []
    ligand_lines: list[str] = []
    chains = {c.strip() for c in receptor_chain.split(",") if c.strip()}
    wanted_resname = ligand_resname.upper().strip()
    wanted_chain = ligand_chain.strip()
    for line in pdb.read_text(encoding="utf-8", errors="ignore").splitlines():
        record = line[:6].strip()
        chain = line[21:22].strip()
        resname = line[17:20].strip().upper()
        if record == "ATOM" and (not chains or chain in chains):
            receptor_lines.append(line)
        if record == "HETATM" and resname == wanted_resname and (not wanted_chain or chain == wanted_chain):
            ligand_lines.append(line)
    if not receptor_lines:
        raise RDockPipelineError(f"No receptor atoms found in {pdb} for chain(s) {receptor_chain}")
    if not ligand_lines:
        raise RDockPipelineError(f"No reference ligand {wanted_resname} chain {wanted_chain or '*'} found in {pdb}")
    receptor.write_text("\n".join(receptor_lines + ["END", ""]), encoding="utf-8")
    ligand_pdb.write_text("\n".join(ligand_lines + ["END", ""]), encoding="utf-8")
    return receptor, ligand_pdb


def _obabel_convert(runner: CommandRunner, stage: str, input_path: Path, output_path: Path, extra_args: list[str], cwd: Path) -> Path:
    obabel = require_executable("obabel")
    rec = runner.run(
        stage,
        [obabel, str(input_path.resolve()), *extra_args, "-O", str(output_path.resolve())],
        cwd,
        cwd / f"{stage}.stdout.log",
        cwd / f"{stage}.stderr.log",
    )
    fail_if_bad_command(rec, f"OpenBabel {stage}")
    return require_file(output_path, f"OpenBabel output {stage}")


def _count_sdf(path: Path) -> int:
    return len(split_sdf_file(path))


def _write_ligand_smi(rows: list[dict[str, str]], out_path: Path, count: int) -> Path:
    selected = rows[:count]
    if len(selected) != count:
        raise RDockPipelineError(f"Requested {count} ligands but only found {len(selected)} rows in {out_path.parent}")
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text("".join(f"{row['smiles']} {row['ligand_id']}\n" for row in selected), encoding="utf-8")
    return out_path


def _load_input_block_map(sdf_path: Path) -> dict[str, str]:
    block_map: dict[str, str] = {}
    for idx, block in enumerate(split_sdf_file(sdf_path)):
        tags = parse_tags(block)
        ligand_id = ligand_id_from_block(block, tags, idx)
        block_map[ligand_id] = block
    return block_map


def _write_selected_sdf(block_map: dict[str, str], ligand_ids: list[str], out_path: Path) -> Path:
    missing = [ligand_id for ligand_id in ligand_ids if ligand_id not in block_map]
    if missing:
        raise RDockPipelineError(f"Missing {len(missing)} ligand IDs in prepared SDF: {missing[:10]}")
    write_sdf_blocks([block_map[ligand_id] for ligand_id in ligand_ids], out_path)
    return out_path


def _prepare_library(
    runner: CommandRunner,
    ligands_csv: Path,
    ligand_count: int,
    out_dir: Path,
    resume: bool,
) -> tuple[list[dict[str, str]], Path]:
    rows = _read_rows(ligands_csv)
    if len(rows) < ligand_count:
        raise RDockPipelineError(f"{ligands_csv} contains {len(rows)} ligands, expected at least {ligand_count}")
    selected = rows[:ligand_count]
    smi = out_dir / "ligands" / "all_ligands.smi"
    sdf = out_dir / "ligands" / "all_ligands.sdf"
    if not (resume and sdf.exists() and _count_sdf(sdf) == ligand_count):
        _write_ligand_smi(selected, smi, ligand_count)
        _obabel_convert(runner, "smiles_to_all_ligands_sdf", smi, sdf, ["--gen3d", "-h"], out_dir)
    if _count_sdf(sdf) != ligand_count:
        raise RDockPipelineError(f"{sdf} does not contain exactly {ligand_count} ligands")
    return selected, sdf


def _build_model_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
    numeric_keys = [
        "reference_similarity",
        "molecular_weight",
        "xlogp",
        "tpsa",
        "hbd",
        "hba",
        "rotatable_bonds",
        "heavy_atom_count",
    ]
    features: dict[str, list[float]] = {key: [] for key in numeric_keys}
    parsed: list[dict[str, Any]] = []
    for row in rows:
        item: dict[str, Any] = dict(row)
        item["scaffold_match_num"] = 1.0 if _boolish(row.get("scaffold_match", "")) else 0.0
        item["is_reference_num"] = 1.0 if _boolish(row.get("is_reference", "")) else 0.0
        sim = _float(row.get("reference_similarity"), 0.0)
        item["model_score"] = sim + 0.1 * item["scaffold_match_num"] + 0.05 * item["is_reference_num"]
        for key in numeric_keys:
            value = _float(row.get(key), 0.0)
            item[key] = value
            features[key].append(value)
        parsed.append(item)
    means = {key: (sum(vals) / len(vals) if vals else 0.0) for key, vals in features.items()}
    stdevs = {}
    for key, vals in features.items():
        if not vals:
            stdevs[key] = 1.0
            continue
        mean = means[key]
        var = sum((value - mean) ** 2 for value in vals) / max(1, len(vals))
        stdevs[key] = var**0.5 or 1.0
    for item in parsed:
        item["feature_vector"] = [
            (float(item[key]) - means[key]) / stdevs[key]
            for key in numeric_keys
        ] + [float(item["scaffold_match_num"]), float(item["is_reference_num"])]
        item["adaptive_priority"] = float(item["model_score"])
        item["actually_docked"] = False
    return parsed


def _distance(a: list[float], b: list[float]) -> float:
    return sum((x - y) ** 2 for x, y in zip(a, b)) ** 0.5


class AdaptiveSurrogateScheduler:
    def __init__(self, rows: list[dict[str, Any]], budget: int, batch_size: int) -> None:
        self.rows = [dict(row) for row in rows]
        self.by_id = {str(row["ligand_id"]): row for row in self.rows}
        self.budget = int(budget)
        self.batch_size = int(batch_size)
        self.completed: list[str] = []
        self.observed_scores: dict[str, float] = {}
        self.attempted: set[str] = set()

    def next_batch(self) -> list[str]:
        remaining = [row for row in self.rows if str(row["ligand_id"]) not in self.attempted]
        remaining_budget = self.budget - len(self.attempted)
        if remaining_budget <= 0 or not remaining:
            return []
        ordered = sorted(
            remaining,
            key=lambda row: (-float(row["adaptive_priority"]), -float(row["model_score"]), str(row["ligand_id"])),
        )
        batch = [str(row["ligand_id"]) for row in ordered[: min(self.batch_size, remaining_budget)]]
        return batch

    def update(self, selected_ids: list[str], best_rows: list[dict[str, str]]) -> float:
        start = time.time()
        for ligand_id in selected_ids:
            self.attempted.add(str(ligand_id))
        for row in best_rows:
            ligand_id = str(row["ligand_id"])
            score = _float(row.get("SCORE"), 0.0)
            self.observed_scores[ligand_id] = score
            self.by_id[ligand_id]["actually_docked"] = True
            self.completed.append(ligand_id)
        docked_ids = list(self.observed_scores)
        if not docked_ids:
            return 0.0
        for row in self.rows:
            ligand_id = str(row["ligand_id"])
            if ligand_id in self.observed_scores:
                row["adaptive_priority"] = 1e9 - self.observed_scores[ligand_id]
                continue
            neighbors: list[tuple[float, float]] = []
            for docked_id in docked_ids:
                docked_row = self.by_id[docked_id]
                dist = _distance(row["feature_vector"], docked_row["feature_vector"])
                neighbors.append((dist, self.observed_scores[docked_id]))
            neighbors.sort(key=lambda item: item[0])
            top = neighbors[: min(12, len(neighbors))]
            weights = [1.0 / (1.0 + dist) for dist, _ in top]
            total_weight = sum(weights) or 1.0
            predicted = sum(weight * score for weight, (_, score) in zip(weights, top)) / total_weight
            prior = -10.0 * float(row["model_score"])
            uncertainty = sum(dist for dist, _ in top) / max(1, len(top))
            blended = (0.7 * predicted) + (0.3 * prior)
            row["adaptive_priority"] = -blended + (0.05 * uncertainty)
        return time.time() - start


def _read_result_rows(path: Path) -> list[dict[str, str]]:
    return _read_rows(path) if path.exists() else []


def _augment_full_rows(rows: list[dict[str, str]]) -> list[dict[str, Any]]:
    ordered = sorted(rows, key=lambda row: (_float(row.get("SCORE"), float("inf")), str(row.get("ligand_id", ""))))
    total = max(1, len(ordered))
    enriched: list[dict[str, Any]] = []
    for idx, row in enumerate(ordered, start=1):
        item: dict[str, Any] = dict(row)
        item["full_rank"] = idx
        item["full_percentile"] = 100.0 if total == 1 else 100.0 * (1.0 - ((idx - 1) / (total - 1)))
        enriched.append(item)
    return enriched


def _percentile_from_rank(rank: int, total: int) -> float:
    if total <= 1:
        return 100.0
    return 100.0 * (1.0 - ((rank - 1) / (total - 1)))


def _append_rank_metrics(rows: list[dict[str, Any]], full_rank_map: dict[str, int], total: int) -> list[dict[str, Any]]:
    enriched: list[dict[str, Any]] = []
    for row in rows:
        item = dict(row)
        ligand_id = str(item["ligand_id"])
        rank = full_rank_map.get(ligand_id)
        item["full_rank"] = rank if rank is not None else ""
        item["full_percentile"] = _percentile_from_rank(rank, total) if rank is not None else ""
        enriched.append(item)
    return enriched


def _top_overlap(full_rows: list[dict[str, Any]], sample_rows: list[dict[str, Any]], n: int) -> int:
    full_top = {str(row["ligand_id"]) for row in full_rows[:n]}
    sample_top = {str(row["ligand_id"]) for row in sorted(sample_rows, key=lambda row: _float(row.get("SCORE"), float("inf")))[:n]}
    return len(full_top & sample_top)


def _copy_full_aliases(root: Path, target_config: TargetConfig, full_rows: list[dict[str, Any]], n_runs: int) -> None:
    target_dir = root / "target"
    target_dir.mkdir(parents=True, exist_ok=True)
    shutil.copy2(require_file(target_config.receptor_mol2, "target mol2"), target_dir / "target.mol2")
    shutil.copy2(require_file(target_config.reference_ligand, "reference ligand"), target_dir / "reference_ligand.sdf")
    shutil.copy2(require_file(target_config.receptor_prm, "target prm"), target_dir / "target.prm")
    shutil.copy2(require_file(target_config.cavity_as, "cavity"), target_dir / Path(target_config.cavity_as).name)
    best_path = root / "poses" / f"best_ligand_{n_runs}.sdf"
    require_file(best_path, f"best_ligand_{n_runs}.sdf")
    if not full_rows:
        raise RDockPipelineError(f"No full docking rows found in {root}")


def _target_complete(root: Path, ligand_count: int, budget: int, n_runs: int) -> bool:
    required = [
        root / "ligands" / "all_ligands.sdf",
        root / "tables" / "full_docking_scores.csv",
        root / "tables" / "adaptive_scores.csv",
        root / "tables" / "random_baseline_scores.csv",
        root / "metrics" / "adaptive_benchmark_metrics.json",
        root / "metrics" / "rdock_metrics.json",
        root / "poses" / f"best_ligand_{n_runs}.sdf",
    ]
    if not all(path.exists() for path in required):
        return False
    if _count_sdf(root / "ligands" / "all_ligands.sdf") != ligand_count:
        return False
    adaptive_rows = _read_result_rows(root / "tables" / "adaptive_scores.csv")
    random_rows = _read_result_rows(root / "tables" / "random_baseline_scores.csv")
    return len(adaptive_rows) >= budget and len(random_rows) >= budget


def _run_full_docking(
    engine: RDockEngine,
    target_config: TargetConfig,
    all_ligands_sdf: Path,
    target_root: Path,
    n_runs: int,
    jobs: str,
    resume: bool,
) -> tuple[dict[str, Any], list[dict[str, Any]], float]:
    start = time.time()
    artifacts = engine.dock_sdf(target_config, all_ligands_sdf, target_root, n_runs=n_runs, jobs=jobs, run_id=target_root.name, resume=resume)
    elapsed = time.time() - start
    full_rows = _augment_full_rows(_read_rows(artifacts.best_per_ligand_csv))
    write_rows_csv(full_rows, target_root / "tables" / "best_per_ligand.csv")
    write_rows_csv(full_rows, target_root / "tables" / "full_docking_scores.csv")
    metrics = {
        "library_size": len(full_rows),
        "successful_ligands": len(full_rows),
        "failed_ligands": max(0, _count_sdf(all_ligands_sdf) - len(full_rows)),
        "pose_count": _count_sdf(Path(artifacts.all_poses_sdf)),
        "best_SCORE": _float(full_rows[0]["SCORE"]) if full_rows else None,
        "full_docking_seconds": elapsed,
        "n_runs": int(n_runs),
        "best_ligand_id": full_rows[0]["ligand_id"] if full_rows else None,
    }
    _write_json(target_root / "metrics" / "rdock_metrics.json", metrics)
    return metrics, full_rows, elapsed


def _run_random_baseline(
    engine: RDockEngine,
    target_config: TargetConfig,
    target_root: Path,
    all_blocks: dict[str, str],
    rows: list[dict[str, Any]],
    budget: int,
    n_runs: int,
    jobs: str,
    resume: bool,
    seed: int = 42,
) -> tuple[list[dict[str, Any]], float]:
    random_root = target_root / "random_run"
    existing = _read_result_rows(random_root / "tables" / "best_per_ligand.csv")
    if resume and len(existing) >= budget:
        return [dict(row) for row in existing[:budget]], 0.0
    random_root.mkdir(parents=True, exist_ok=True)
    population = [str(row["ligand_id"]) for row in rows]
    selected_ids = random.Random(seed).sample(population, budget)
    _write_json(random_root / "selection.json", {"seed": seed, "ligand_ids": selected_ids})
    baseline_sdf = random_root / "ligands" / "random_baseline.sdf"
    _write_selected_sdf(all_blocks, selected_ids, baseline_sdf)
    start = time.time()
    engine.dock_sdf(target_config, baseline_sdf, random_root, n_runs=n_runs, jobs=jobs, run_id=f"{target_root.name}_random", resume=resume)
    elapsed = time.time() - start
    random_rows = []
    selected_map = {ligand_id: idx + 1 for idx, ligand_id in enumerate(selected_ids)}
    for row in _read_rows(random_root / "tables" / "best_per_ligand.csv"):
        item: dict[str, Any] = dict(row)
        item["selection_order"] = selected_map.get(str(item["ligand_id"]), "")
        item["strategy"] = "random"
        random_rows.append(item)
    random_rows.sort(key=lambda row: int(row.get("selection_order", 0) or 0))
    write_rows_csv(random_rows, target_root / "tables" / "random_baseline_scores.csv")
    return random_rows, elapsed


def _run_adaptive_benchmark(
    engine: RDockEngine,
    target_config: TargetConfig,
    target_root: Path,
    all_blocks: dict[str, str],
    rows: list[dict[str, Any]],
    budget: int,
    batch_size: int,
    n_runs: int,
    jobs: str,
    resume: bool,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], float, float]:
    adaptive_root = target_root / "adaptive_run"
    adaptive_root.mkdir(parents=True, exist_ok=True)
    scheduler = AdaptiveSurrogateScheduler(rows, budget=budget, batch_size=batch_size)
    adaptive_rows: list[dict[str, Any]] = []
    batch_metrics: list[dict[str, Any]] = []
    docking_seconds = 0.0
    model_seconds = 0.0
    batch_index = 0
    while True:
        batch_ids = scheduler.next_batch()
        if not batch_ids:
            break
        batch_dir = adaptive_root / "rdock" / f"batch_{batch_index:03d}"
        selection_path = batch_dir / "selection.json"
        if resume and selection_path.exists():
            payload = json.loads(selection_path.read_text(encoding="utf-8"))
            batch_ids = [str(x) for x in payload.get("ligand_ids", batch_ids)]
        else:
            batch_dir.mkdir(parents=True, exist_ok=True)
            selection_payload = {
                "batch_index": batch_index,
                "ligand_ids": batch_ids,
                "selection_state": [
                    {
                        "ligand_id": ligand_id,
                        "model_score": scheduler.by_id[ligand_id]["model_score"],
                        "adaptive_priority": scheduler.by_id[ligand_id]["adaptive_priority"],
                    }
                    for ligand_id in batch_ids
                ],
            }
            _write_json(selection_path, selection_payload)
        batch_sdf = adaptive_root / "ligands" / f"batch_{batch_index:03d}.sdf"
        if not (resume and batch_sdf.exists() and _count_sdf(batch_sdf) == len(batch_ids)):
            _write_selected_sdf(all_blocks, batch_ids, batch_sdf)
        batch_start = time.time()
        engine.dock_sdf(target_config, batch_sdf, batch_dir, n_runs=n_runs, jobs=jobs, run_id=f"{target_root.name}_adaptive_batch_{batch_index:03d}", resume=resume)
        batch_docking_seconds = time.time() - batch_start
        docking_seconds += batch_docking_seconds
        batch_best = _read_rows(batch_dir / "tables" / "best_per_ligand.csv")
        selection_meta = json.loads(selection_path.read_text(encoding="utf-8"))
        selection_lookup = {str(item["ligand_id"]): item for item in selection_meta.get("selection_state", [])}
        batch_rows: list[dict[str, Any]] = []
        for local_index, row in enumerate(batch_best, start=1):
            ligand_id = str(row["ligand_id"])
            selection_item = selection_lookup.get(ligand_id, {})
            item: dict[str, Any] = dict(row)
            item["batch"] = batch_index
            item["selection_order"] = (batch_index * batch_size) + local_index
            item["model_score"] = selection_item.get("model_score", scheduler.by_id[ligand_id]["model_score"])
            item["adaptive_priority"] = selection_item.get("adaptive_priority", scheduler.by_id[ligand_id]["adaptive_priority"])
            item["strategy"] = "adaptive"
            batch_rows.append(item)
        adaptive_rows.extend(batch_rows)
        update_seconds = scheduler.update(batch_ids, batch_best)
        model_seconds += update_seconds
        batch_metrics.append(
            {
                "batch": batch_index,
                "selected_count": len(batch_ids),
                "successful_count": len(batch_best),
                "failed_count": max(0, len(batch_ids) - len(batch_best)),
                "docking_seconds": batch_docking_seconds,
                "model_seconds": update_seconds,
                "best_score_after_batch": min(_float(row.get("SCORE"), float("inf")) for row in adaptive_rows) if adaptive_rows else "",
            }
        )
        batch_index += 1
    write_rows_csv(adaptive_rows, target_root / "tables" / "adaptive_scores.csv")
    write_rows_csv(batch_metrics, target_root / "tables" / "adaptive_batches.csv")
    return adaptive_rows, batch_metrics, docking_seconds, model_seconds


def _build_metrics(
    target_id: str,
    library_size: int,
    full_rows: list[dict[str, Any]],
    adaptive_rows: list[dict[str, Any]],
    random_rows: list[dict[str, Any]],
    full_seconds: float,
    adaptive_docking_seconds: float,
    adaptive_model_seconds: float,
    random_seconds: float,
) -> dict[str, Any]:
    full_rank_map = {str(row["ligand_id"]): int(row["full_rank"]) for row in full_rows}
    adaptive_ranked = _append_rank_metrics(adaptive_rows, full_rank_map, len(full_rows))
    random_ranked = _append_rank_metrics(random_rows, full_rank_map, len(full_rows))
    adaptive_best = min(adaptive_ranked, key=lambda row: _float(row.get("SCORE"), float("inf"))) if adaptive_ranked else None
    random_best = min(random_ranked, key=lambda row: _float(row.get("SCORE"), float("inf"))) if random_ranked else None
    full_best = full_rows[0] if full_rows else None
    failed = max(0, library_size - len(full_rows))
    return {
        "target_id": target_id,
        "total_candidate_library_size": library_size,
        "full_success_count": len(full_rows),
        "adaptive_success_count": len(adaptive_ranked),
        "random_success_count": len(random_ranked),
        "failed_docking_count": failed,
        "success_rate": (len(full_rows) / library_size) if library_size else 0.0,
        "best_full_SCORE": _float(full_best.get("SCORE")) if full_best else None,
        "best_adaptive_SCORE": _float(adaptive_best.get("SCORE")) if adaptive_best else None,
        "best_random_SCORE": _float(random_best.get("SCORE")) if random_best else None,
        "full_best_percentile_of_full": 100.0 if full_best else None,
        "adaptive_best_percentile_of_full": _float(adaptive_best.get("full_percentile")) if adaptive_best else None,
        "random_best_percentile_of_full": _float(random_best.get("full_percentile")) if random_best else None,
        "adaptive_over_random_best_score_delta": (_float(random_best.get("SCORE")) - _float(adaptive_best.get("SCORE"))) if adaptive_best and random_best else None,
        "adaptive_over_random_percentile_delta": (_float(adaptive_best.get("full_percentile")) - _float(random_best.get("full_percentile"))) if adaptive_best and random_best else None,
        "top1_overlap_with_full": _top_overlap(full_rows, adaptive_ranked, 1),
        "top5_overlap_with_full": _top_overlap(full_rows, adaptive_ranked, 5),
        "top10_overlap_with_full": _top_overlap(full_rows, adaptive_ranked, 10),
        "random_top1_overlap_with_full": _top_overlap(full_rows, random_ranked, 1),
        "random_top5_overlap_with_full": _top_overlap(full_rows, random_ranked, 5),
        "random_top10_overlap_with_full": _top_overlap(full_rows, random_ranked, 10),
        "full_docking_seconds": full_seconds,
        "adaptive_docking_seconds": adaptive_docking_seconds,
        "adaptive_model_seconds": adaptive_model_seconds,
        "random_docking_seconds": random_seconds,
        "ligands_docked_by_adaptive": len(adaptive_ranked),
        "ligands_docked_by_random": len(random_ranked),
    }


def _merge_commands(target_root: Path) -> None:
    dst = target_root / "commands.log"
    existing = dst.read_text(encoding="utf-8", errors="ignore") if dst.exists() else ""
    with dst.open("w", encoding="utf-8") as out:
        if existing:
            out.write(existing)
        for candidate in [
            target_root / "prep_commands.log",
            target_root / "adaptive_run" / "commands.log",
            target_root / "random_run" / "commands.log",
        ]:
            if candidate.exists():
                out.write(candidate.read_text(encoding="utf-8", errors="ignore"))
    if not dst.exists():
        dst.write_text("", encoding="utf-8")


def _write_target_report(target_root: Path, target: dict[str, str], metrics: dict[str, Any], plots: list[str], notes: list[str]) -> None:
    report = [
        f"# Adaptive + rDock Benchmark: {target['target_id']}",
        "",
        "## Input Summary",
        f"- PDB: `{target['pdb_id']}`",
        f"- Receptor chain: `{target['receptor_chain']}`",
        f"- Reference ligand: `{target['reference_ligand_resname']}` chain `{target['reference_ligand_chain']}`",
        f"- Ligand CSV: `{target['ligands_csv']}`",
        f"- Library size: `{metrics['total_candidate_library_size']}`",
        "",
        "## Metrics",
    ]
    for key in [
        "best_full_SCORE",
        "best_adaptive_SCORE",
        "best_random_SCORE",
        "adaptive_best_percentile_of_full",
        "random_best_percentile_of_full",
        "adaptive_over_random_best_score_delta",
        "adaptive_over_random_percentile_delta",
        "full_docking_seconds",
        "adaptive_docking_seconds",
        "adaptive_model_seconds",
        "random_docking_seconds",
        "ligands_docked_by_adaptive",
        "ligands_docked_by_random",
        "failed_docking_count",
        "success_rate",
    ]:
        report.append(f"- {key}: `{metrics.get(key)}`")
    report.extend(["", "## Plots"])
    report.extend([f"- `{path}`" for path in plots] or ["- No plots generated"])
    report.extend(["", "## Notes"])
    report.extend([f"- {note}" for note in notes] or ["- No extra notes"])
    (target_root / "report.md").write_text("\n".join(report) + "\n", encoding="utf-8")


def _sanity_checks(target_root: Path, ligand_count: int, budget: int, n_runs: int) -> list[str]:
    checks: list[str] = []
    all_ligands = target_root / "ligands" / "all_ligands.sdf"
    if _count_sdf(all_ligands) != ligand_count:
        raise RDockPipelineError(f"{all_ligands} does not contain {ligand_count} ligands")
    checks.append(f"all_ligands.sdf has {ligand_count} ligands")
    full_rows = _read_rows(target_root / "tables" / "full_docking_scores.csv")
    if len(full_rows) != ligand_count:
        checks.append(f"full docking deviation: expected {ligand_count}, got {len(full_rows)}")
    else:
        checks.append("full docking returned expected ligand count")
    best_ligand = require_file(target_root / "poses" / f"best_ligand_{n_runs}.sdf", f"best_ligand_{n_runs}.sdf")
    if _count_sdf(best_ligand) != n_runs:
        checks.append(f"best_ligand_{n_runs}.sdf deviation: expected {n_runs}, got {_count_sdf(best_ligand)}")
    else:
        checks.append(f"best_ligand_{n_runs}.sdf contains {n_runs} poses")
    adaptive_rows = _read_rows(target_root / "tables" / "adaptive_scores.csv")
    random_rows = _read_rows(target_root / "tables" / "random_baseline_scores.csv")
    if len(adaptive_rows) < budget:
        checks.append(f"adaptive deviation: budget {budget}, successful {len(adaptive_rows)}")
    if len(random_rows) < budget:
        checks.append(f"random deviation: budget {budget}, successful {len(random_rows)}")
    if len(adaptive_rows) >= budget and len(random_rows) >= budget:
        checks.append("adaptive and random produced budget-sized result tables")
    return checks


def run_target(target: dict[str, str], args: argparse.Namespace, out_root: Path) -> dict[str, Any]:
    target_root = out_root / target["target_id"]
    if args.resume and _target_complete(target_root, args.ligands_per_target, args.adaptive_budget, args.n_runs):
        metrics = json.loads((target_root / "metrics" / "adaptive_benchmark_metrics.json").read_text(encoding="utf-8"))
        return {"target_id": target["target_id"], "status": "resumed_complete", "metrics": metrics, "run_dir": str(target_root)}

    if target_root.exists() and args.force and not args.resume:
        shutil.rmtree(target_root)
    target_root.mkdir(parents=True, exist_ok=True)
    runner = CommandRunner(target_root / "prep_commands.log")
    pdb = require_file(target["pdb_path"], f"PDB file for {target['target_id']}")
    receptor, ligand_pdb = _extract_receptor_and_ligand(
        pdb,
        target["receptor_chain"],
        target["reference_ligand_resname"],
        target["reference_ligand_chain"],
        target_root / "target_inputs",
    )
    reference_ligand_sdf = target_root / "target_inputs" / "reference_ligand.sdf"
    if not (args.resume and reference_ligand_sdf.exists()):
        _obabel_convert(runner, "reference_ligand_to_sdf", ligand_pdb, reference_ligand_sdf, [], target_root)

    engine = RDockEngine(
        RDockRunConfig(
            n_runs=args.n_runs,
            jobs=args.jobs,
            cpu_fraction=args.cpu_fraction,
            timeout_seconds=3600,
        )
    )
    prepared_root = target_root / "target_prepared"
    if args.resume and (prepared_root / "target_config.yaml").exists():
        from docking_pipeline.rdock import load_target_config

        target_config = load_target_config(prepared_root / "target_config.yaml")
    else:
        target_config = engine.prepare_target(receptor, reference_ligand_sdf, prepared_root)

    rows, all_ligands_sdf = _prepare_library(runner, Path(target["ligands_csv"]), args.ligands_per_target, target_root, args.resume)
    all_block_map = _load_input_block_map(all_ligands_sdf)
    model_rows = _build_model_rows(rows)

    rdock_metrics, full_rows, full_seconds = _run_full_docking(engine, target_config, all_ligands_sdf, target_root, args.n_runs, args.jobs, args.resume)
    _copy_full_aliases(target_root, target_config, full_rows, args.n_runs)
    adaptive_rows, batch_rows, adaptive_docking_seconds, adaptive_model_seconds = _run_adaptive_benchmark(
        engine,
        target_config,
        target_root,
        all_block_map,
        model_rows,
        args.adaptive_budget,
        args.batch_size,
        args.n_runs,
        args.jobs,
        args.resume,
    )
    random_rows, random_seconds = _run_random_baseline(
        engine,
        target_config,
        target_root,
        all_block_map,
        model_rows,
        args.adaptive_budget,
        args.n_runs,
        args.jobs,
        args.resume,
    )

    full_rank_map = {str(row["ligand_id"]): int(row["full_rank"]) for row in full_rows}
    adaptive_ranked = _append_rank_metrics(adaptive_rows, full_rank_map, len(full_rows))
    random_ranked = _append_rank_metrics(random_rows, full_rank_map, len(full_rows))
    write_rows_csv(adaptive_ranked, target_root / "tables" / "adaptive_scores.csv")
    write_rows_csv(random_ranked, target_root / "tables" / "random_baseline_scores.csv")
    write_rows_csv(batch_rows, target_root / "tables" / "adaptive_batches.csv")

    metrics = _build_metrics(
        target["target_id"],
        args.ligands_per_target,
        full_rows,
        adaptive_ranked,
        random_ranked,
        full_seconds,
        adaptive_docking_seconds,
        adaptive_model_seconds,
        random_seconds,
    )
    _write_json(target_root / "metrics" / "adaptive_benchmark_metrics.json", metrics)
    _write_json(target_root / "metrics" / "validation_metrics.json", metrics)

    plots = []
    plots.extend(plot_score_outputs(target_root / "tables" / "full_docking_scores.csv", target_root / "plots", title_prefix=f"{target['target_id']} full"))
    plots.extend(
        plot_adaptive_benchmark_outputs(
            target_root / "tables" / "full_docking_scores.csv",
            target_root / "tables" / "adaptive_scores.csv",
            target_root / "tables" / "random_baseline_scores.csv",
            target_root / "metrics" / "adaptive_benchmark_metrics.json",
            target_root / "plots",
        )
    )
    checks = _sanity_checks(target_root, args.ligands_per_target, args.adaptive_budget, args.n_runs)
    _merge_commands(target_root)

    manifest = {
        "target_id": target["target_id"],
        "engine": "adaptive-plus-rdock",
        "target": target,
        "rdock_metrics": rdock_metrics,
        "adaptive_metrics": metrics,
        "plots": plots,
        "artifacts": {
            "target_dir": str(target_root / "target"),
            "ligands_sdf": str(target_root / "ligands" / "all_ligands.sdf"),
            "all_poses_sdf": str(target_root / "poses" / "all_poses.sdf"),
            "best_per_ligand_sdf": str(target_root / "poses" / "best_per_ligand.sdf"),
            "best_ligand_all_poses_sdf": str(target_root / "poses" / f"best_ligand_{args.n_runs}.sdf"),
            "full_scores": str(target_root / "tables" / "full_docking_scores.csv"),
            "adaptive_scores": str(target_root / "tables" / "adaptive_scores.csv"),
            "random_scores": str(target_root / "tables" / "random_baseline_scores.csv"),
            "report": str(target_root / "report.md"),
            "commands_log": str(target_root / "commands.log"),
        },
        "sanity_checks": checks,
        "executables": {
            "rbdock": probe_version(require_executable("rbdock")),
            "rbcavity": probe_version(require_executable("rbcavity")),
            "obabel": probe_version(require_executable("obabel")),
        },
    }
    _write_json(target_root / "manifest.json", manifest)
    notes = [
        f"Prepared target from {target['pdb_path']}.",
        f"Library source: {target['ligands_csv']}.",
        f"Resume mode: {args.resume}.",
    ]
    _write_target_report(target_root, target, metrics, plots, notes)
    return {"target_id": target["target_id"], "status": "completed", "metrics": metrics, "run_dir": str(target_root), "sanity_checks": checks}


def _write_aggregate_report(out_root: Path, results: list[dict[str, Any]], args: argparse.Namespace) -> None:
    lines = [
        "# Adaptive + rDock Benchmark on 3 Targets",
        "",
        "## Command",
        f"- targets: `{args.targets}`",
        f"- ligands_per_target: `{args.ligands_per_target}`",
        f"- n_runs: `{args.n_runs}`",
        f"- adaptive_budget: `{args.adaptive_budget}`",
        f"- batch_size: `{args.batch_size}`",
        f"- jobs: `{args.jobs}`",
        f"- cpu_fraction: `{args.cpu_fraction}`",
        f"- resume: `{args.resume}`",
        "",
        "## Target Status",
    ]
    for result in results:
        metrics = result.get("metrics", {})
        lines.extend(
            [
                f"- {result['target_id']}: `{result['status']}`",
                f"  best full SCORE `{metrics.get('best_full_SCORE')}`, adaptive `{metrics.get('best_adaptive_SCORE')}`, random `{metrics.get('best_random_SCORE')}`",
                f"  adaptive percentile `{metrics.get('adaptive_best_percentile_of_full')}`, random percentile `{metrics.get('random_best_percentile_of_full')}`",
                f"  full seconds `{metrics.get('full_docking_seconds')}`, adaptive docking `{metrics.get('adaptive_docking_seconds')}`, random `{metrics.get('random_docking_seconds')}`",
                f"  run dir `{result.get('run_dir')}`",
            ]
        )
    (out_root / "report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    _write_json(out_root / "manifest.json", {"results": results})


def main() -> int:
    parser = argparse.ArgumentParser(description="Production adaptive + rDock benchmark on 3 PDB targets with 1000 ligands each.")
    parser.add_argument("--targets", required=True)
    parser.add_argument("--ligands-per-target", type=int, default=1000)
    parser.add_argument("--n-runs", type=int, default=50)
    parser.add_argument("--adaptive-budget", type=int, default=250)
    parser.add_argument("--batch-size", type=int, default=50)
    parser.add_argument("--jobs", default="auto")
    parser.add_argument("--cpu-fraction", type=float, default=0.85)
    parser.add_argument("--out", required=True)
    parser.add_argument("--resume", action="store_true")
    parser.add_argument("--force", action="store_true")
    args = parser.parse_args()

    if args.ligands_per_target != 1000:
        raise RDockPipelineError("This production benchmark is configured for 1000 ligands per target; do not reduce without explicit approval.")
    out_root = Path(args.out)
    out_root.mkdir(parents=True, exist_ok=True)
    targets = _load_targets(Path(args.targets))
    results = []
    for target in targets:
        results.append(run_target(target, args, out_root))
        _write_aggregate_report(out_root, results, args)
    print(json.dumps({"results": results, "out": str(out_root)}, indent=2))
    return 0


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