File size: 28,951 Bytes
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
from __future__ import annotations

import csv
import gzip
import json
import os
import re
import shutil
import tarfile
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass
from pathlib import Path
from statistics import median
from typing import Iterable

from .metrics import enrichment_rows, validation_metrics_from_rows
from .provenance import (
    CommandRecord,
    CommandRunner,
    RDockPipelineError,
    fail_if_bad_command,
    require_executable,
    require_file,
    resolve_dock_prm_path,
    resolve_rbt_root,
)
from .reports.plots import plot_astex_outputs, plot_dud_outputs
from .sdf import best_per_ligand, parse_rdock_sdf_records, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records

VALIDATION_URL = "https://rdock.github.io/validation-sets/"


@dataclass(frozen=True)
class ValidationSystem:
    system_id: str
    path: str
    receptor_prm: str
    dock_prm: str
    ligand_sdf: str = ""
    ligprep_sdf: str = ""
    crystal_sdf: str = ""


def resolve_jobs(jobs: int | str = "auto", cpu_fraction: float = 0.85) -> int:
    if str(jobs).lower() == "auto":
        cpus = os.cpu_count() or 1
        reserve = 1 if cpus <= 4 else 2
        return max(1, min(cpus - reserve, int(cpus * float(cpu_fraction))))
    return max(1, int(jobs))


def _rdock_env() -> dict[str, str]:
    root = resolve_rbt_root(executable="rbdock")
    if root:
        return {"RBT_ROOT": root, "RBT_HOME": root}
    return {}


def _system_id_from_prm(path: Path) -> str:
    name = path.stem
    return re.sub(r"_?rdock$", "", name, flags=re.IGNORECASE)


def _find_first(candidates: Iterable[Path]) -> Path | None:
    for p in candidates:
        if p.exists() and p.is_file() and p.stat().st_size > 0:
            return p
    return None


def _find_dock_prm(system_dir: Path) -> Path | None:
    candidates = [system_dir / "dock.prm"] + [parent / "dock.prm" for parent in list(system_dir.parents)[:3]]
    resolved = resolve_dock_prm_path(executable="rbdock")
    if resolved is not None:
        candidates.append(resolved)
    return _find_first(candidates)


def discover_validation_systems(data_dir: str | Path, set_name: str) -> list[ValidationSystem]:
    root = Path(data_dir)
    if not root.exists():
        return []
    systems: dict[str, ValidationSystem] = {}
    for prm in sorted(root.rglob("*_rdock.prm")):
        system_dir = prm.parent
        system_id = _system_id_from_prm(prm)
        dock_prm = _find_dock_prm(system_dir)
        if dock_prm is None:
            local = list(system_dir.rglob("dock.prm"))
            dock_prm = local[0] if local else None
        sdf_files = sorted(list(system_dir.glob("*.sd")) + list(system_dir.glob("*.sdf")))
        gz_sdfs = sorted(list(system_dir.glob("*.sd.gz")) + list(system_dir.glob("*.sdf.gz")))
        ligand_sdf = _find_first(
            [
                system_dir / f"{system_id}_ligand.sd",
                system_dir / f"{system_id}_ligand.sdf",
                system_dir / "ligand.sd",
                system_dir / "ligand.sdf",
            ]
            + [p for p in sdf_files if "ligand" in p.name.lower() or "crystal" in p.name.lower()]
            + sdf_files
        )
        ligprep_sdf = _find_first(
            [
                system_dir / f"{system_id}_ligprep.sdf",
                system_dir / f"{system_id}_ligprep.sd",
            ]
            + [p for p in sdf_files if "ligprep" in p.name.lower()]
            + [p for p in gz_sdfs if "ligprep" in p.name.lower()]
        )
        if set_name.lower() == "dud" and ligprep_sdf is None:
            continue
        systems[system_id] = ValidationSystem(
            system_id=system_id,
            path=str(system_dir),
            receptor_prm=str(prm),
            dock_prm=str(dock_prm or ""),
            ligand_sdf=str(ligand_sdf or ""),
            ligprep_sdf=str(ligprep_sdf or ""),
            crystal_sdf=str(ligand_sdf or ""),
        )
    return [systems[k] for k in sorted(systems)]


def _actionable_missing_system(data_dir: Path, set_name: str, system: str | None) -> RDockPipelineError:
    expected = data_dir / (system or "<system>")
    return RDockPipelineError(
        "Missing rDock validation data.\n"
        f"Expected path or discoverable system files under: {expected}\n"
        f"Validation set: {set_name}\n"
        f"Official validation sets: {VALIDATION_URL}\n"
        "Use one of:\n"
        f"  python -m docking_pipeline validate-rdock --set {set_name} --data-dir {data_dir} --list-systems\n"
        f"  python -m docking_pipeline validate-rdock --set {set_name} --system {system or '<id>'} --data-dir {data_dir} --out results/benchmarks/{set_name}_{system or '<id>'} --download-url <official_tar.gz> --download-if-missing\n"
        "or manually download/extract the official rDock validation set and pass its extracted directory via --data-dir."
    )


def download_validation_set(download_url: str, data_dir: str | Path, force: bool = False) -> Path:
    target = Path(data_dir)
    if target.exists() and any(target.iterdir()) and not force:
        return target
    target.mkdir(parents=True, exist_ok=True)
    archive = target / Path(download_url).name
    urllib.request.urlretrieve(download_url, archive)
    with tarfile.open(archive, "r:*") as tar:
        tar.extractall(target)
    return target


def ensure_validation_data(data_dir: str | Path, set_name: str, download_url: str | None, download_if_missing: bool, force: bool = False) -> Path:
    root = Path(data_dir)
    if root.exists() and discover_validation_systems(root, set_name):
        return root
    if download_if_missing:
        if not download_url:
            raise RDockPipelineError(
                f"--download-if-missing was set but --download-url was not provided. Official validation sets: {VALIDATION_URL}"
            )
        download_validation_set(download_url, root, force=force)
    return root


def resolve_systems(
    data_dir: str | Path,
    set_name: str,
    system: str | None = None,
    system_list: str | Path | None = None,
    max_systems: int | None = None,
) -> list[ValidationSystem]:
    root = Path(data_dir)
    systems = discover_validation_systems(root, set_name)
    if not systems:
        raise _actionable_missing_system(root, set_name, system)
    wanted: set[str] | None = None
    if system:
        wanted = {system}
    if system_list:
        ids = [line.strip() for line in Path(system_list).read_text(encoding="utf-8").splitlines() if line.strip()]
        wanted = (wanted or set()) | set(ids)
    if wanted is not None:
        systems = [s for s in systems if s.system_id in wanted]
        if not systems:
            raise _actionable_missing_system(root, set_name, system or ",".join(sorted(wanted)))
    if max_systems is not None:
        systems = systems[: int(max_systems)]
    return systems


def _copy_system(src: Path, out_dir: Path, force: bool) -> Path:
    dst = out_dir / "rdock" / src.name
    if dst.exists():
        if not force:
            return dst
        shutil.rmtree(dst)
    shutil.copytree(src, dst)
    return dst


def _gunzip_if_needed(path: Path) -> Path:
    if path.exists() and path.suffix != ".gz":
        return path
    if path.suffix == ".gz":
        out = path.with_suffix("")
        if not out.exists():
            with gzip.open(path, "rb") as src, out.open("wb") as dst:
                shutil.copyfileobj(src, dst)
        return out
    gz = path.with_suffix(path.suffix + ".gz")
    if gz.exists():
        return _gunzip_if_needed(gz)
    return require_file(path, "ligand-prepped SDF")


def _run_rbdock_parallel(
    runner: CommandRunner,
    work: Path,
    prm: Path,
    dock_prm: Path,
    ligand_sdf: Path,
    out_prefix: str,
    n_runs: int,
    jobs: int,
) -> tuple[Path, list[CommandRecord]]:
    rbdock = require_executable("rbdock")
    blocks = split_sdf_file(ligand_sdf)
    chunk_dir = work / "chunks"
    chunk_dir.mkdir(exist_ok=True)
    chunk_count = min(max(1, jobs), len(blocks))
    chunks: list[Path] = []
    for idx in range(chunk_count):
        chunk_blocks = blocks[idx::chunk_count]
        chunk = chunk_dir / f"chunk_{idx:03d}.sdf"
        write_sdf_blocks(chunk_blocks, chunk)
        chunks.append(chunk)

    def run_one(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]:
        prefix = work / f"{out_prefix}_chunk_{idx:03d}"
        rec = runner.run(
            f"rbdock_chunk_{idx:03d}",
            [rbdock, "-r", str(prm.name), "-p", str(dock_prm), "-n", str(int(n_runs)), "-i", str(chunk.relative_to(work)), "-o", str(prefix.name)],
            work,
            work / f"{out_prefix}_chunk_{idx:03d}.stdout.log",
            work / f"{out_prefix}_chunk_{idx:03d}.stderr.log",
            env=_rdock_env(),
        )
        return idx, rec, prefix.with_suffix(".sd")

    outputs: dict[int, Path] = {}
    records: list[CommandRecord] = []
    with ThreadPoolExecutor(max_workers=chunk_count) as pool:
        futures = [pool.submit(run_one, idx, chunk) for idx, chunk in enumerate(chunks)]
        for fut in as_completed(futures):
            idx, rec, out_sd = fut.result()
            fail_if_bad_command(rec, f"rbdock chunk {idx}")
            require_file(out_sd, f"rDock output chunk {idx}")
            outputs[idx] = out_sd
            records.append(rec)
    merged = work / f"{out_prefix}.sd"
    all_blocks: list[str] = []
    for idx in sorted(outputs):
        all_blocks.extend(split_sdf_file(outputs[idx]))
    write_sdf_blocks(all_blocks, merged)
    return merged, records


def _parse_rmsd_stdout(text: str) -> list[float]:
    vals: list[float] = []
    for token in re.findall(r"[-+]?(?:\d+\.\d+|\d+)", text):
        try:
            value = float(token)
        except Exception:
            continue
        if 0.0 <= value < 100.0:
            vals.append(value)
    return vals


def _sdf_pose_coords(path: Path) -> list[list[list[float]]]:
    poses: list[list[list[float]]] = []
    for block in split_sdf_file(path):
        lines = block.splitlines()
        if len(lines) < 4:
            continue
        try:
            atom_count = int(lines[3][0:3])
        except Exception:
            continue
        coords: list[list[float]] = []
        for line in lines[4 : 4 + atom_count]:
            try:
                coords.append([float(line[0:10]), float(line[10:20]), float(line[20:30])])
            except Exception:
                parts = line.split()
                if len(parts) >= 3:
                    try:
                        coords.append([float(parts[0]), float(parts[1]), float(parts[2])])
                    except Exception:
                        continue
        if coords:
            poses.append(coords)
    return poses


def _rmsd_same_order(a: list[list[float]], b: list[list[float]]) -> float:
    n = min(len(a), len(b))
    if n == 0:
        return float("nan")
    return (sum((a[i][0] - b[i][0]) ** 2 + (a[i][1] - b[i][1]) ** 2 + (a[i][2] - b[i][2]) ** 2 for i in range(n)) / n) ** 0.5


def _internal_rmsds(reference_sdf: Path, poses_sdf: Path) -> list[float]:
    ref = _sdf_pose_coords(reference_sdf)
    poses = _sdf_pose_coords(poses_sdf)
    if not ref:
        return []
    return [_rmsd_same_order(ref[0], pose) for pose in poses]


def _write_csv(path: Path, rows: list[dict[str, object]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fields: list[str] = []
    for row in rows:
        for k in row:
            if k not in fields:
                fields.append(k)
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def _empty_standard_outputs(root: Path) -> None:
    for name in ("target", "ligands", "rdock", "poses", "tables", "metrics", "plots"):
        (root / name).mkdir(parents=True, exist_ok=True)


def _copy_receptor_to_target(work: Path, system: ValidationSystem, root: Path) -> Path | None:
    target_dir = root / "target"
    target_dir.mkdir(parents=True, exist_ok=True)
    prm_stem = Path(system.receptor_prm).stem
    candidates = [
        work / f"{prm_stem}.mol2",
        work / f"{system.system_id}_rdock.mol2",
        work / f"{system.system_id}.mol2",
    ]
    candidates.extend(sorted(work.glob("*.mol2")))
    receptor = _find_first(candidates)
    if receptor is None:
        return None
    dst = target_dir / receptor.name
    shutil.copy2(receptor, dst)
    return dst


def validate_astex_system(
    system: ValidationSystem,
    root: Path,
    n_runs: int,
    jobs: int,
    force: bool = False,
) -> dict[str, object]:
    _empty_standard_outputs(root)
    work = _copy_system(Path(system.path), root, force=force)
    _copy_receptor_to_target(work, system, root)
    runner = CommandRunner(root / "commands.log")
    for exe in ("rbcavity", "rbdock", "sdsort", "sdrmsd"):
        require_executable(exe)
    prm = require_file(work / Path(system.receptor_prm).name, "ASTEX rDock receptor prm")
    dock_prm = require_file(system.dock_prm, "ASTEX dock.prm")
    ligand = require_file(work / Path(system.ligand_sdf).name, "ASTEX ligand SDF")
    rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env())
    fail_if_bad_command(rec, "ASTEX rbcavity")
    out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligand, f"{system.system_id}_docking_out", n_runs, jobs)
    rec = runner.run(
        "sdsort",
        ["/bin/sh", "-c", f"sdsort -n -f'SCORE' {out_sd.name} > {system.system_id}_docking_out_sorted.sd"],
        work,
        work / "sdsort.stdout.log",
        work / "sdsort.stderr.log",
        env=_rdock_env(),
    )
    fail_if_bad_command(rec, "ASTEX sdsort")
    sorted_sd = require_file(work / f"{system.system_id}_docking_out_sorted.sd", "ASTEX sorted SDF")
    rmsd_source = "sdrmsd"
    rmsd_diagnostic = ""
    rec = runner.run("sdrmsd", ["sdrmsd", ligand.name, sorted_sd.name], work, work / "sdrmsd.stdout.log", work / "sdrmsd.stderr.log", env=_rdock_env())
    try:
        fail_if_bad_command(rec, "ASTEX sdrmsd")
        rmsds = _parse_rmsd_stdout(Path(rec.stdout_log).read_text(encoding="utf-8", errors="ignore"))
    except RDockPipelineError as exc:
        rmsd_source = "internal_same_atom_order_sdf_rmsd_after_sdrmsd_failure"
        rmsd_diagnostic = str(exc)
        rmsds = _internal_rmsds(ligand, sorted_sd)
    top1 = rmsds[0] if rmsds else float("nan")
    best = min(rmsds) if rmsds else float("nan")
    shutil.copy2(out_sd, root / "poses" / "all_poses.sdf")
    shutil.copy2(sorted_sd, root / "poses" / "best_per_ligand.sdf")
    records = parse_rdock_sdf_records(out_sd)
    sorted_records = parse_rdock_sdf_records(sorted_sd)
    best_records = best_per_ligand(records)
    write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv")
    write_rows_csv(records_to_rows(best_records), root / "tables" / "best_per_ligand.csv")
    top1_score = sorted_records[0].numeric_tags.get("SCORE") if sorted_records else None
    row = {
        "system_id": system.system_id,
        "top1_rmsd": top1,
        "best_of_n_rmsd": best,
        "top1_SCORE": top1_score,
        "success_top1_rmsd_le_2A": bool(top1 <= 2.0),
        "success_best_rmsd_le_2A": bool(best <= 2.0),
        "n_poses": len(records),
        "status": "success",
        "rmsd_source": rmsd_source,
        "rmsd_diagnostic": rmsd_diagnostic,
    }
    _write_csv(root / "tables" / "astex_system_summary.csv", [row])
    metrics = {
        **row,
        "median_top1_rmsd": top1,
        "median_best_rmsd": best,
        "n_systems_total": 1,
        "n_systems_successful": 1,
        "n_systems_failed": 0,
        "n_poses_total": len(records),
    }
    (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
    (root / "metrics" / "enrichment.csv").write_text("", encoding="utf-8")
    plots = plot_astex_outputs(root / "tables" / "astex_system_summary.csv", root / "plots")
    _write_validation_report(root, "ASTEX", [system], runner.records, metrics, plots)
    return metrics


def _read_dud_labels(work: Path) -> dict[str, int]:
    labels: dict[str, int] = {}
    for name, value in (("ligands.txt", 1), ("actives.txt", 1), ("decoys.txt", 0)):
        p = work / name
        if not p.exists():
            continue
        for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
            parts = line.strip().split()
            if parts:
                labels[parts[0]] = value
    return labels


def validate_dud_system(system: ValidationSystem, root: Path, n_runs: int, jobs: int, force: bool = False) -> dict[str, object]:
    _empty_standard_outputs(root)
    work = _copy_system(Path(system.path), root, force=force)
    _copy_receptor_to_target(work, system, root)
    runner = CommandRunner(root / "commands.log")
    for exe in ("rbcavity", "rbdock", "sdsort", "sdfilter", "sdreport"):
        require_executable(exe)
    prm = require_file(work / Path(system.receptor_prm).name, "DUD rDock receptor prm")
    dock_prm = require_file(system.dock_prm, "DUD dock.prm")
    ligprep = _gunzip_if_needed(work / Path(system.ligprep_sdf).name)
    labels = _read_dud_labels(work)
    if not labels:
        raise RDockPipelineError(
            "Missing DUD active/decoy label files for enrichment metrics.\n"
            f"Expected `ligands.txt`/`actives.txt` and `decoys.txt` in: {work}\n"
            "The official rDock ROC workflow requires these files to assign IsActive labels.\n"
            "Add the label files for this DUD system, then rerun the same validate-rdock command."
        )
    rec = runner.run("rbcavity", ["rbcavity", "-r", prm.name, "-was"], work, work / "rbcavity.stdout.log", work / "rbcavity.stderr.log", env=_rdock_env())
    fail_if_bad_command(rec, "DUD rbcavity")
    out_sd, _ = _run_rbdock_parallel(runner, work, prm, dock_prm, ligprep, f"{system.system_id}_docking_out", n_runs, jobs)
    records = parse_rdock_sdf_records(out_sd, require_score=True)
    best_records = best_per_ligand(records)
    best_sd = write_sdf_records(best_records, work / f"{system.system_id}_1poseperlig.sd")
    rows = records_to_rows(best_records)
    for row in rows:
        row["label"] = labels.get(str(row["ligand_id"]), 0)
    duplicate_count = len(records) - len({r.ligand_id for r in records})
    metrics = validation_metrics_from_rows(rows)
    metrics.update(
        {
            "active_count": sum(int(row.get("label", 0)) for row in rows),
            "decoy_count": sum(1 - int(row.get("label", 0)) for row in rows),
            "attempted_ligands": len(split_sdf_file(ligprep)),
            "successful_ligands": len(rows),
            "failed_ligands": max(0, len(split_sdf_file(ligprep)) - len(rows)),
            "duplicate_ligand_ids": duplicate_count,
            "missing_SCORE_count": 0,
        }
    )
    shutil.copy2(out_sd, root / "poses" / "all_poses.sdf")
    shutil.copy2(best_sd, root / "poses" / "best_per_ligand.sdf")
    write_rows_csv(records_to_rows(records), root / "tables" / "scores_long.csv")
    write_rows_csv(rows, root / "tables" / "best_per_ligand.csv")
    _write_csv(root / "metrics" / "enrichment.csv", enrichment_rows([float(r["SCORE"]) for r in rows], [int(r["label"]) for r in rows]))
    (root / "metrics" / "validation_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
    plots = plot_dud_outputs(root / "tables" / "best_per_ligand.csv", root / "metrics" / "enrichment.csv", root / "plots")
    _write_validation_report(root, "DUD", [system], runner.records, metrics, plots)
    return metrics


def plan_validation(
    set_name: str,
    data_dir: str | Path,
    systems: list[ValidationSystem],
    out_dir: str | Path,
    n_runs: int,
    jobs: int | str,
    cpu_fraction: float,
) -> dict[str, object]:
    resolved_jobs = resolve_jobs(jobs, cpu_fraction)
    return {
        "set": set_name,
        "data_dir": str(data_dir),
        "out": str(out_dir),
        "n_runs": int(n_runs),
        "jobs": resolved_jobs,
        "system_count": len(systems),
        "systems": [asdict(s) for s in systems],
        "commands": [
            f"rbcavity -r <system>_rdock.prm -was",
            f"rbdock -r <system>_rdock.prm -p dock.prm -n {int(n_runs)} -i <ligands>.sd -o <out>",
            "sdsort/sdrmsd for ASTEX or best-pose/enrichment reporting for DUD",
        ],
    }


def validate_many(
    set_name: str,
    data_dir: str | Path,
    out_dir: str | Path,
    system: str | None = None,
    system_list: str | Path | None = None,
    max_systems: int | None = None,
    n_runs: int = 100,
    jobs: int | str = "auto",
    cpu_fraction: float = 0.85,
    download_url: str | None = None,
    download_if_missing: bool = False,
    force: bool = False,
    dry_run: bool = False,
    plan_only: bool = False,
) -> dict[str, object]:
    root_data = ensure_validation_data(data_dir, set_name, download_url, download_if_missing, force=force)
    systems = resolve_systems(root_data, set_name, system, system_list, max_systems)
    plan = plan_validation(set_name, root_data, systems, out_dir, n_runs, jobs, cpu_fraction)
    out = Path(out_dir)
    if dry_run or plan_only:
        out.mkdir(parents=True, exist_ok=True)
        (out / "validation_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
        return {"dry_run": bool(dry_run), "plan": plan}
    if out.exists() and force:
        shutil.rmtree(out)
    out.mkdir(parents=True, exist_ok=True)
    resolved_jobs = int(plan["jobs"])
    rows: list[dict[str, object]] = []
    failures: list[dict[str, object]] = []
    metrics_by_system: list[dict[str, object]] = []
    per_system_jobs = resolved_jobs if len(systems) == 1 else 1
    system_order = {s.system_id: idx for idx, s in enumerate(systems)}

    def run_system(s: ValidationSystem) -> tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]:
        run_root = out / s.system_id if len(systems) > 1 else out
        try:
            if set_name.lower() == "astex":
                metrics = validate_astex_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force)
                row = {
                    "system_id": s.system_id,
                        "top1_rmsd": metrics.get("top1_rmsd"),
                        "best_of_n_rmsd": metrics.get("best_of_n_rmsd"),
                        "top1_SCORE": metrics.get("top1_SCORE"),
                        "success_top1_rmsd_le_2A": metrics.get("success_top1_rmsd_le_2A"),
                        "success_best_rmsd_le_2A": metrics.get("success_best_rmsd_le_2A"),
                    "n_poses": metrics.get("n_poses"),
                    "status": "success",
                }
            elif set_name.lower() == "dud":
                metrics = validate_dud_system(s, run_root, n_runs=n_runs, jobs=per_system_jobs, force=force)
                row = {"system_id": s.system_id, "status": "success", **metrics}
            else:
                raise RDockPipelineError(f"Unsupported validation set: {set_name}")
            return system_order[s.system_id], s, metrics, row, None
        except Exception as exc:
            return system_order[s.system_id], s, None, {"system_id": s.system_id, "status": "failed", "error": str(exc)}, exc

    max_system_workers = min(resolved_jobs, len(systems))
    results: list[tuple[int, ValidationSystem, dict[str, object] | None, dict[str, object], Exception | None]] = []
    if max_system_workers > 1:
        with ThreadPoolExecutor(max_workers=max_system_workers) as pool:
            futures = [pool.submit(run_system, s) for s in systems]
            for fut in as_completed(futures):
                results.append(fut.result())
    else:
        results = [run_system(s) for s in systems]

    for _, s, metrics, row, exc in sorted(results, key=lambda item: item[0]):
        rows.append(row)
        if exc is not None:
            failures.append({"system_id": s.system_id, "error": str(exc)})
            continue
        if metrics is not None:
            metrics_by_system.append({"system_id": s.system_id, **metrics})

    # Per-system outputs are written by each worker. The root directory stores
    # aggregate summaries, plots, manifests, and reports.
    _empty_standard_outputs(out)
    _write_csv(out / "tables" / f"{set_name.lower()}_system_summary.csv", rows)
    if set_name.lower() == "astex":
        top1 = [float(r["top1_rmsd"]) for r in rows if r.get("status") == "success"]
        best_vals = [float(r["best_of_n_rmsd"]) for r in rows if r.get("status") == "success"]
        aggregate = {
            "n_systems_total": len(systems),
            "n_systems_successful": len(top1),
            "n_systems_failed": len(failures),
            "median_top1_rmsd": median(top1) if top1 else None,
            "median_best_rmsd": median(best_vals) if best_vals else None,
            "success_top1_rmsd_le_2A": sum(1 for x in top1 if x <= 2.0),
            "success_best_rmsd_le_2A": sum(1 for x in best_vals if x <= 2.0),
            "n_poses_total": sum(int(r.get("n_poses", 0) or 0) for r in rows),
            "failures": failures,
        }
        plots = plot_astex_outputs(out / "tables" / f"{set_name.lower()}_system_summary.csv", out / "plots")
    else:
        aggregate = {
            "n_systems_total": len(systems),
            "n_systems_successful": len(metrics_by_system),
            "n_systems_failed": len(failures),
            "failures": failures,
        }
        plots = []
    (out / "metrics" / "validation_metrics.json").write_text(json.dumps(aggregate, indent=2), encoding="utf-8")
    _write_validation_report(out, set_name.upper(), systems, [], aggregate, plots)
    return {"metrics": aggregate, "systems": rows}


def validate_astex(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]:
    result = validate_many("astex", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs)
    return dict(result.get("metrics", {}))


def validate_dud(data_dir: str | Path, system: str, out_dir: str | Path, n_runs: int = 100, jobs: int | str = 1) -> dict[str, object]:
    result = validate_many("dud", data_dir, out_dir, system=system, n_runs=n_runs, jobs=jobs)
    return dict(result.get("metrics", {}))


def _write_validation_report(
    root: Path,
    set_name: str,
    systems: list[ValidationSystem],
    commands: list[CommandRecord],
    metrics: dict[str, object],
    plots: list[str],
) -> None:
    manifest = {
        "validation_set": set_name,
        "engine": "real-rdock-official-workflow",
        "systems": [asdict(s) for s in systems],
        "commands": [c.to_dict() for c in commands],
        "metrics": metrics,
        "plots": plots,
        "artifacts": {
            "report": str(root / "report.md"),
            "manifest": str(root / "manifest.json"),
            "config": str(root / "config.yaml"),
            "commands": str(root / "commands.log"),
            "tables": str(root / "tables"),
            "metrics": str(root / "metrics"),
            "plots": str(root / "plots"),
        },
    }
    (root / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    (root / "config.yaml").write_text(f"validation_set: {set_name}\nsystems: {[s.system_id for s in systems]}\n", encoding="utf-8")
    top_lines = []
    for item in list(metrics.items())[:20]:
        top_lines.append(f"- {item[0]}: `{item[1]}`")
    plot_lines = [f"- `{p}`" for p in plots] or ["- No plots generated; see `plots/skipped_plots.json` if present."]
    (root / "report.md").write_text(
        "\n".join(
            [
                f"# {set_name} rDock Validation",
                "",
                "## Input Summary",
                f"- Systems: `{', '.join(s.system_id for s in systems)}`",
                f"- System count: `{len(systems)}`",
                "",
                "## Metrics",
                *top_lines,
                "",
                "## Commands",
                f"- Command log: `{root / 'commands.log'}`",
                "- Per-system command logs are stored under each system run directory for multi-system runs.",
                "",
                "## Plots",
                *plot_lines,
                "",
                "## Skipped Steps",
                "- Browser bundle export was removed from the production pipeline.",
                "- No mock docking or surrogate scores are used.",
                "",
                "## Diagnostics",
                f"- Failures: `{json.dumps(metrics.get('failures', []))}`",
            ]
        ),
        encoding="utf-8",
    )