File size: 35,072 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
c289d87
 
 
 
 
 
 
 
24f6204
 
c289d87
 
24f6204
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
c289d87
 
 
 
 
24f6204
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
 
 
24f6204
c289d87
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
 
 
 
 
24f6204
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
24f6204
 
 
 
 
c289d87
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
24f6204
c289d87
 
 
 
 
 
 
 
 
24f6204
c289d87
 
 
 
 
 
 
24f6204
c289d87
 
24f6204
c289d87
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
24f6204
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
c289d87
 
 
 
24f6204
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
c289d87
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
from __future__ import annotations

import json
import math
import os
import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

try:  # pragma: no cover
    from tqdm import tqdm
except Exception:  # pragma: no cover
    tqdm = None  # type: ignore[assignment]

from .provenance import (
    CommandRecord,
    CommandRunner,
    RDockPipelineError,
    fail_if_bad_command,
    probe_version,
    require_executable,
    require_file,
    resolve_dock_prm_path,
    resolve_rbt_root,
    sha256_file,
)
from .sdf import best_per_ligand, ligand_id_from_block, parse_rdock_sdf_records, parse_tags, records_to_rows, split_sdf_file, write_rows_csv, write_sdf_blocks, write_sdf_records


@dataclass
class TargetConfig:
    receptor: str
    reference_ligand: str
    target_dir: str
    receptor_mol2: str
    receptor_prm: str
    cavity_as: str
    pocket_center: list[float]
    pocket_radius: float
    diagnostics: dict[str, Any]


@dataclass
class RDockRunConfig:
    n_runs: int = 50
    jobs: int | str = "auto"
    cpu_fraction: float = 0.85
    timeout_seconds: int = 3600
    chunk_size: int | None = None
    rbdock_bin: str = "rbdock"
    rbcavity_bin: str = "rbcavity"
    obabel_bin: str = "obabel"
    sdsort_bin: str = "sdsort"
    sdfilter_bin: str = "sdfilter"
    sdreport_bin: str = "sdreport"
    sdrmsd_bin: str = "sdrmsd"
    sdsplit_bin: str = "sdsplit"
    dock_prm: str | None = None
    rbt_root: str | None = None
    require_reporting_tools: bool = False


@dataclass
class RunArtifacts:
    run_dir: str
    manifest: str
    config_yaml: str
    commands_log: str
    all_poses_sdf: str
    best_per_ligand_sdf: str
    scores_long_csv: str
    best_per_ligand_csv: str
    report_md: str
    command_records: list[dict[str, Any]] = field(default_factory=list)
    best_ligand_poses_sdf: str | None = None


def _tail_text(path: Path, limit: int = 2000) -> str:
    if not path.exists():
        return ""
    try:
        text = path.read_text(encoding="utf-8", errors="ignore")
    except Exception:
        return ""
    return text[-limit:]


def _classify_chunk_failure(
    rec: CommandRecord | None,
    out_sd: Path,
    stdout_log: Path,
    stderr_log: Path,
) -> str:
    combined = f"{_tail_text(stdout_log, 4000)}\n{_tail_text(stderr_log, 4000)}".lower()
    exit_code = int(rec.exit_code) if rec is not None else None
    if exit_code == 124 or "timeout after" in combined:
        return "rdock_timeout"
    if exit_code == -15 or "sigterm" in combined or "terminated" in combined:
        return "rdock_sigterm"
    if exit_code == -9 or "sigkill" in combined or "killed" in combined:
        return "rdock_sigkill"
    if not out_sd.exists():
        if exit_code not in (None, 0):
            return f"rdock_nonzero_exit_{exit_code}"
        return "missing_rdock_output_sdf"
    if "not enough diversity" in combined or "population failure" in combined:
        return "rdock_population_not_enough_diversity"
    if "explicit valence" in combined:
        return "rdkit_or_obabel_explicit_valence"
    if "2d" in combined and "record" in combined:
        return "rdock_2d_record"
    try:
        records = parse_rdock_sdf_records(out_sd, require_score=False)
    except Exception:
        return "rdock_unknown_failure"
    if not records:
        return "rdock_no_valid_scored_poses"
    valid_records = [record for record in records if record.score is not None]
    if not valid_records:
        return "rdock_missing_score"
    return "rdock_unknown_failure"


def _write_yaml_like(path: Path, payload: dict[str, Any]) -> None:
    try:
        import yaml

        text = yaml.safe_dump(payload, sort_keys=False)
    except Exception:
        text = json.dumps(payload, indent=2)
    path.write_text(text, encoding="utf-8")


def _sanitize_chunk_output_scores(path: Path) -> tuple[list[Any], int]:
    records = parse_rdock_sdf_records(path, require_score=False)
    valid_records = [record for record in records if record.score is not None]
    dropped = len(records) - len(valid_records)
    if dropped > 0:
        write_sdf_records(valid_records, path)
    return valid_records, dropped


def _normalize_receptor_prm_paths(prm_path: Path, config_dir: Path, dataset_target_dir: Path) -> bool:
    if not prm_path.exists():
        return False
    text = prm_path.read_text(encoding="utf-8", errors="ignore")
    updated_lines: list[str] = []
    changed = False
    receptor_candidate = config_dir / "receptor.mol2"
    reference_candidates = [
        config_dir / "reference_ligand.sdf",
        dataset_target_dir / "reference_ligand.sdf",
    ]
    for line in text.splitlines():
        stripped = line.strip()
        if stripped.startswith("RECEPTOR_FILE ") and receptor_candidate.exists():
            new_line = f"RECEPTOR_FILE {receptor_candidate.name}"
            if line != new_line:
                line = new_line
                changed = True
        elif stripped.startswith("REF_MOL "):
            for candidate in reference_candidates:
                if candidate.exists():
                    new_line = f"    REF_MOL {candidate.name}"
                    if line != new_line:
                        line = new_line
                        changed = True
                    break
        updated_lines.append(line)
    if changed:
        prm_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
    return changed


def _coords_from_pdb(path: Path, include_hetatm: bool) -> np.ndarray:
    coords: list[list[float]] = []
    for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
        if not line.startswith(("ATOM", "HETATM")):
            continue
        if line.startswith("HETATM") and not include_hetatm:
            continue
        try:
            coords.append([float(line[30:38]), float(line[38:46]), float(line[46:54])])
        except Exception:
            continue
    return coords  # type: ignore[return-value]


def _coords_from_mol2(path: Path) -> np.ndarray:
    coords: list[list[float]] = []
    in_atoms = False
    for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
        if line.startswith("@<TRIPOS>ATOM"):
            in_atoms = True
            continue
        if line.startswith("@<TRIPOS>") and in_atoms:
            break
        if not in_atoms:
            continue
        parts = line.split()
        if len(parts) >= 5:
            try:
                coords.append([float(parts[2]), float(parts[3]), float(parts[4])])
            except Exception:
                continue
    return coords  # type: ignore[return-value]


def _coords_from_sdf(path: Path) -> np.ndarray:
    first = path.read_text(encoding="utf-8", errors="ignore").split("$$$$", 1)[0]
    lines = first.splitlines()
    if len(lines) < 4:
        return []  # type: ignore[return-value]
    try:
        atom_count = int(lines[3][0:3])
    except Exception:
        atom_count = 0
    coords = []
    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
    return coords  # type: ignore[return-value]


def _coords_for_structure(path: Path, receptor: bool) -> np.ndarray:
    suffix = path.suffix.lower()
    if suffix == ".mol2":
        return _coords_from_mol2(path)
    if suffix in {".sdf", ".sd"}:
        return _coords_from_sdf(path)
    if suffix in {".pdb", ".ent", ".cif", ".mmcif"}:
        return _coords_from_pdb(path, include_hetatm=not receptor)
    raise RDockPipelineError(f"Unsupported structure format for coordinate validation: {path}")


def _validate_receptor_ligand_geometry(receptor: Path, ligand: Path) -> tuple[list[float], dict[str, Any]]:
    receptor_coords = _coords_for_structure(receptor, receptor=True)
    ligand_coords = _coords_for_structure(ligand, receptor=False)
    if not receptor_coords:
        raise RDockPipelineError(f"Missing receptor atoms or coordinates in {receptor}")
    if not ligand_coords:
        raise RDockPipelineError(f"Missing ligand coordinates in reference ligand {ligand}")
    n_lig = len(ligand_coords)
    center = [sum(coord[i] for coord in ligand_coords) / n_lig for i in range(3)]

    def dist(a: list[float], b: list[float]) -> float:
        return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5

    all_dists = [dist(r, l) for r in receptor_coords for l in ligand_coords]
    min_receptor_ligand_dist = min(all_dists)
    centroid_to_receptor = min(dist(r, center) for r in receptor_coords)
    severe_clashes = sum(1 for d in all_dists if d < 1.0)
    clash_fraction = severe_clashes / float(max(1, len(ligand_coords)))
    if centroid_to_receptor > 20.0:
        raise RDockPipelineError(
            f"Reference ligand centroid is {centroid_to_receptor:.2f} A from the nearest receptor atom; "
            "check receptor/reference ligand pairing and coordinate frames."
        )
    if clash_fraction > 1.0:
        raise RDockPipelineError(
            f"Severe receptor-ligand clashes before docking ({severe_clashes} atom pairs < 1.0 A). "
            "Check protonation, alternate locations, and coordinate consistency."
        )
    spread = max(dist(l, center) for l in ligand_coords)
    return [float(center[0]), float(center[1]), float(center[2])], {
        "receptor_atom_count": int(len(receptor_coords)),
        "reference_ligand_atom_count": int(len(ligand_coords)),
        "reference_ligand_centroid": [float(x) for x in center],
        "reference_ligand_radius": spread,
        "min_receptor_ligand_distance": min_receptor_ligand_dist,
        "reference_centroid_to_nearest_receptor_atom": centroid_to_receptor,
        "severe_clash_pairs_lt_1A": severe_clashes,
    }


class RDockEngine:
    def __init__(self, config: RDockRunConfig | None = None) -> None:
        self.config = config or RDockRunConfig()

    def _env(self) -> dict[str, str]:
        env: dict[str, str] = {}
        resolved = resolve_rbt_root(preferred=self.config.rbt_root, executable=self.config.rbdock_bin)
        if resolved:
            env["RBT_ROOT"] = resolved
            env["RBT_HOME"] = resolved
        return env

    def _dock_prm(self) -> Path:
        if self.config.dock_prm:
            return require_file(self.config.dock_prm, "rDock protocol dock.prm")
        candidate = resolve_dock_prm_path(preferred_rbt_root=self.config.rbt_root, executable=self.config.rbdock_bin)
        if candidate is not None:
            return candidate
        raise RDockPipelineError(
            "Could not locate rDock dock.prm. Pass --dock-prm or set RBT_ROOT so "
            "$RBT_ROOT/data/scripts/dock.prm exists."
        )

    def check_required_tools(self, validation: bool = False) -> dict[str, str]:
        needed = {
            "rbdock": self.config.rbdock_bin,
            "rbcavity": self.config.rbcavity_bin,
            "obabel": self.config.obabel_bin,
        }
        if validation or self.config.require_reporting_tools:
            needed.update(
                {
                    "sdsort": self.config.sdsort_bin,
                    "sdfilter": self.config.sdfilter_bin,
                    "sdreport": self.config.sdreport_bin,
                    "sdrmsd": self.config.sdrmsd_bin,
                }
            )
        return {key: require_executable(bin_name) for key, bin_name in needed.items()}

    def prepare_target(self, receptor: str | Path, reference_ligand: str | Path, out_dir: str | Path) -> TargetConfig:
        tools = self.check_required_tools(validation=False)
        receptor_path = require_file(receptor, "receptor structure")
        ref_path = require_file(reference_ligand, "reference ligand")
        out = Path(out_dir)
        out.mkdir(parents=True, exist_ok=True)
        command_log = out / "commands.log"
        runner = CommandRunner(command_log)

        receptor_copy = out / receptor_path.name
        reference_copy = out / ref_path.name
        if receptor_path.resolve() != receptor_copy.resolve():
            shutil.copy2(receptor_path, receptor_copy)
        if ref_path.resolve() != reference_copy.resolve():
            shutil.copy2(ref_path, reference_copy)

        center, diagnostics = _validate_receptor_ligand_geometry(receptor_copy, reference_copy)
        receptor_mol2 = out / "receptor.mol2"
        if receptor_copy.suffix.lower() == ".mol2":
            shutil.copy2(receptor_copy, receptor_mol2)
        else:
            rec = runner.run(
                "prepare_receptor_obabel",
                [tools["obabel"], str(receptor_copy.resolve()), "-O", str(receptor_mol2.resolve())],
                cwd=out,
                stdout_log=out / "prepare_receptor_obabel.stdout.log",
                stderr_log=out / "prepare_receptor_obabel.stderr.log",
                timeout=300,
                env=self._env(),
            )
            fail_if_bad_command(rec, "OpenBabel receptor conversion")
        require_file(receptor_mol2, "prepared receptor MOL2")

        prm = out / "receptor.prm"
        prm.write_text(
            "\n".join(
                [
                    "RBT_PARAMETER_FILE_V1.00",
                    "TITLE rdock_receptor_reference_ligand",
                    f"RECEPTOR_FILE {receptor_mol2.name}",
                    "",
                    "SECTION MAPPER",
                    "    SITE_MAPPER RbtLigandSiteMapper",
                    f"    REF_MOL {reference_copy.name}",
                    "    RADIUS 6.0",
                    "    SMALL_SPHERE 1.5",
                    "END_SECTION",
                    "",
                    "SECTION CAVITY",
                    "    SCORING_FUNCTION RbtCavityGridSF",
                    "END_SECTION",
                    "",
                ]
            ),
            encoding="utf-8",
        )
        _normalize_receptor_prm_paths(prm, out, out)

        rec = runner.run(
            "rbcavity",
            [tools["rbcavity"], "-r", prm.name, "-was"],
            cwd=out,
            stdout_log=out / "rbcavity.stdout.log",
            stderr_log=out / "rbcavity.stderr.log",
            timeout=self.config.timeout_seconds,
            env=self._env(),
        )
        fail_if_bad_command(rec, "rbcavity cavity generation")
        cavity = out / f"{prm.stem}.as"
        require_file(cavity, "rDock cavity .as file")
        if cavity.stat().st_size < 16:
            raise RDockPipelineError(f"rbcavity produced an invalid tiny cavity file: {cavity}")

        target_config = TargetConfig(
            receptor=str(receptor_copy),
            reference_ligand=str(reference_copy),
            target_dir=str(out),
            receptor_mol2=str(receptor_mol2),
            receptor_prm=str(prm),
            cavity_as=str(cavity),
            pocket_center=center,
            pocket_radius=float(max(6.0, diagnostics["reference_ligand_radius"] + 2.0)),
            diagnostics=diagnostics,
        )
        _write_yaml_like(out / "target_config.yaml", asdict(target_config))
        return target_config

    def _resolve_jobs(self, requested: int | str | None = None) -> int:
        value = self.config.jobs if requested is None else requested
        if isinstance(value, str) and value.lower() == "auto":
            cpus = os.cpu_count() or 1
            reserve = 1 if cpus <= 4 else 2
            return max(1, min(cpus - reserve, int(math.floor(cpus * self.config.cpu_fraction))))
        return max(1, int(value))

    def _split_input_sdf(self, ligands_sdf: Path, split_dir: Path, jobs: int, chunk_size: int | None = None) -> list[Path]:
        blocks = split_sdf_file(ligands_sdf)
        if jobs <= 1 or len(blocks) <= 1:
            target = split_dir / "chunk_000.sdf"
            write_sdf_blocks(blocks, target)
            return [target]
        max_chunk_records = int(chunk_size or 0)
        if max_chunk_records > 0:
            chunks = [blocks[idx : idx + max_chunk_records] for idx in range(0, len(blocks), max_chunk_records)]
        else:
            chunks = [[] for _ in range(min(jobs, len(blocks)))]
            for idx, block in enumerate(blocks):
                chunks[idx % len(chunks)].append(block)
        paths = []
        for idx, chunk in enumerate(chunks):
            path = split_dir / f"chunk_{idx:03d}.sdf"
            write_sdf_blocks(chunk, path)
            paths.append(path)
        return paths

    def dock_sdf(
        self,
        target_config: TargetConfig,
        ligands_sdf: str | Path,
        run_dir: str | Path,
        n_runs: int | None = None,
        jobs: int | str | None = None,
        run_id: str | None = None,
        validation_labels_csv: str | Path | None = None,
        resume: bool = False,
    ) -> RunArtifacts:
        self.check_required_tools(validation=False)
        ligands = require_file(ligands_sdf, "ligand SDF")
        dock_prm = self._dock_prm()
        run_root = Path(run_dir)
        run_root.mkdir(parents=True, exist_ok=True)
        for name in ("target", "ligands", "rdock", "poses", "tables", "metrics"):
            (run_root / name).mkdir(parents=True, exist_ok=True)
        commands_log = run_root / "commands.log"
        runner = CommandRunner(commands_log)
        progress_log = run_root / "rdock" / "progress.log"

        def _emit_progress(message: str, payload: dict[str, Any] | None = None) -> None:
            line = f"[rdock] {message}"
            print(line, flush=True)
            progress_log.parent.mkdir(parents=True, exist_ok=True)
            with progress_log.open("a", encoding="utf-8") as handle:
                handle.write(line + "\n")
            if payload is not None:
                (run_root / "rdock" / "progress.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")

        target_dir = run_root / "target"
        for src in (target_config.receptor, target_config.reference_ligand, target_config.receptor_mol2, target_config.receptor_prm, target_config.cavity_as):
            p = Path(src)
            if p.exists():
                shutil.copy2(p, target_dir / p.name)
        lig_copy = run_root / "ligands" / ligands.name
        if ligands.resolve() != lig_copy.resolve():
            shutil.copy2(ligands, lig_copy)
        shutil.copy2(dock_prm, run_root / "rdock" / "dock.prm")

        resolved_jobs = self._resolve_jobs(jobs)
        actual_n_runs = int(n_runs if n_runs is not None else self.config.n_runs)
        chunks = self._split_input_sdf(lig_copy, run_root / "rdock" / "chunks", resolved_jobs, self.config.chunk_size)
        rbdock = require_executable(self.config.rbdock_bin)
        failure_policy = os.environ.get("RDOCK_CHUNK_FAILURE_POLICY", "mark_failed").strip().lower() or "mark_failed"
        if failure_policy not in {"mark_failed", "fail"}:
            raise RDockPipelineError(f"Unsupported RDOCK_CHUNK_FAILURE_POLICY={failure_policy!r}")
        local_prm = require_file(target_dir / Path(target_config.receptor_prm).name, "copied receptor.prm for run")
        _normalize_receptor_prm_paths(local_prm, target_dir, target_dir)
        out_files: dict[int, Path] = {}
        failed_chunk_rows: list[dict[str, Any]] = []
        failed_ligand_rows: list[dict[str, Any]] = []
        records_without_score_dropped_total = 0
        _emit_progress(
            "dock:start",
            {
                "run_dir": str(run_root),
                "jobs": resolved_jobs,
                "n_runs": actual_n_runs,
                "chunk_count": len(chunks),
                "ligands_sdf": str(lig_copy),
                "failure_policy": failure_policy,
            },
        )

        def _run_chunk(idx: int, chunk: Path) -> tuple[int, CommandRecord, Path]:
            out_prefix = run_root / "rdock" / f"chunk_{idx:03d}_out"
            out_sd = out_prefix.with_suffix(".sd")
            if resume and out_sd.exists() and out_sd.stat().st_size > 0:
                try:
                    expected_ligand_ids = {
                        ligand_id_from_block(block, parse_tags(block), block_idx)
                        for block_idx, block in enumerate(split_sdf_file(chunk))
                    }
                    valid_records, _ = _sanitize_chunk_output_scores(out_sd)
                    if not valid_records:
                        raise RDockPipelineError(f"Resume chunk {idx} has no valid scored poses after sanitization")
                    observed_ligand_ids = {record.ligand_id for record in valid_records}
                    if not expected_ligand_ids.issubset(observed_ligand_ids):
                        missing = len(expected_ligand_ids - observed_ligand_ids)
                        raise RDockPipelineError(f"Resume chunk {idx} is incomplete; missing scored poses for {missing} input ligands")
                    stdout_log = run_root / "rdock" / f"chunk_{idx:03d}.stdout.log"
                    stderr_log = run_root / "rdock" / f"chunk_{idx:03d}.stderr.log"
                    stdout_log.touch(exist_ok=True)
                    stderr_log.touch(exist_ok=True)
                    rec = CommandRecord(
                        stage=f"rbdock_chunk_{idx:03d}_resume",
                        command=[rbdock, "-r", local_prm.name, "-p", str(dock_prm.resolve()), "-n", str(actual_n_runs), "-i", str(chunk.resolve()), "-o", str(out_prefix.resolve())],
                        cwd=str(target_dir),
                        start_time=datetime.now(UTC).isoformat(),
                        end_time=datetime.now(UTC).isoformat(),
                        exit_code=0,
                        stdout_log=str(stdout_log),
                        stderr_log=str(stderr_log),
                    )
                    return idx, rec, out_sd
                except RDockPipelineError:
                    try:
                        out_sd.unlink(missing_ok=True)
                    except Exception:
                        pass
            rec = runner.run(
                f"rbdock_chunk_{idx:03d}",
                [
                    rbdock,
                    "-r",
                    local_prm.name,
                    "-p",
                    str(dock_prm.resolve()),
                    "-n",
                    str(actual_n_runs),
                    "-i",
                    str(chunk.resolve()),
                    "-o",
                    str(out_prefix.resolve()),
                ],
                cwd=target_dir,
                stdout_log=run_root / "rdock" / f"chunk_{idx:03d}.stdout.log",
                stderr_log=run_root / "rdock" / f"chunk_{idx:03d}.stderr.log",
                timeout=self.config.timeout_seconds,
                env=self._env(),
            )
            return idx, rec, out_sd

        progress = tqdm(total=len(chunks), desc=f"rDock chunks ({actual_n_runs} runs)", unit="chunk") if tqdm is not None else None
        with ThreadPoolExecutor(max_workers=min(resolved_jobs, len(chunks))) as pool:
            futures = [pool.submit(_run_chunk, idx, chunk) for idx, chunk in enumerate(chunks)]
            completed = 0
            for fut in as_completed(futures):
                idx, rec, out_sd = fut.result()
                stdout_log = run_root / "rdock" / f"chunk_{idx:03d}.stdout.log"
                stderr_log = run_root / "rdock" / f"chunk_{idx:03d}.stderr.log"
                chunk_blocks = split_sdf_file(chunks[idx])
                failure_reason = ""
                dropped_records = 0
                try:
                    fail_if_bad_command(rec, f"rbdock chunk {idx}")
                    require_file(out_sd, f"rDock output SDF for chunk {idx}")
                    valid_records, dropped_records = _sanitize_chunk_output_scores(out_sd)
                    if not valid_records:
                        raise RDockPipelineError("rDock output had no valid scored poses")
                    out_files[idx] = out_sd
                    records_without_score_dropped_total += dropped_records
                except Exception as exc:
                    failure_reason = _classify_chunk_failure(rec, out_sd, stdout_log, stderr_log)
                    failed_chunk_rows.append(
                        {
                            "chunk_id": idx,
                            "input_sdf": str(chunks[idx]),
                            "expected_output_sdf": str(out_sd),
                            "stdout_log": str(stdout_log),
                            "stderr_log": str(stderr_log),
                            "n_input_ligands": len(chunk_blocks),
                            "failure_reason": failure_reason,
                            "exit_code": rec.exit_code,
                            "stdout_tail": _tail_text(stdout_log),
                            "stderr_tail": _tail_text(stderr_log),
                        }
                    )
                    for block_index, block in enumerate(chunk_blocks):
                        try:
                            tags = parse_tags(block)
                            ligand_id = ligand_id_from_block(block, tags, block_index)
                        except Exception:
                            ligand_id = f"ligand_{block_index:06d}"
                        failed_ligand_rows.append(
                            {
                                "ligand_id": ligand_id,
                                "chunk_id": idx,
                                "failure_reason": failure_reason,
                                "source_input_sdf": str(chunks[idx]),
                            }
                        )
                    if failure_policy == "fail":
                        raise RDockPipelineError(
                            f"rDock chunk {idx} failed with policy=fail: {failure_reason} ({exc})"
                        ) from exc
                completed += 1
                if progress is not None:
                    progress.update(1)
                    progress.set_postfix(last_chunk=idx, completed=f"{completed}/{len(chunks)}")
                _emit_progress(
                    "dock:chunk_complete",
                    {
                        "completed_chunks": completed,
                        "total_chunks": len(chunks),
                        "last_chunk": idx,
                        "output": str(out_sd),
                        "records_without_score_dropped": dropped_records,
                        "failure_reason": failure_reason,
                    },
                )
        if progress is not None:
            progress.close()

        all_blocks: list[str] = []
        for idx in sorted(out_files):
            all_blocks.extend(split_sdf_file(out_files[idx]))
        all_poses = run_root / "poses" / "all_poses.sdf"
        if all_blocks:
            write_sdf_blocks(all_blocks, all_poses)
            records = parse_rdock_sdf_records(all_poses, require_score=True)
            best = best_per_ligand(records)
        else:
            all_poses.write_text("", encoding="utf-8")
            records = []
            best = []
        best_sdf = write_sdf_records(best, run_root / "poses" / "best_per_ligand.sdf")
        best_ligand_poses_sdf: str | None = None
        if best:
            top_ligand_id = best[0].ligand_id
            best_ligand_records = [rec for rec in records if rec.ligand_id == top_ligand_id]
            best_ligand_path = run_root / "poses" / f"best_ligand_{actual_n_runs}.sdf"
            write_sdf_records(best_ligand_records, best_ligand_path)
            best_ligand_poses_sdf = str(best_ligand_path)
        scores_long = write_rows_csv(records_to_rows(records), run_root / "tables" / "scores_long.csv")
        best_csv = write_rows_csv(records_to_rows(best), run_root / "tables" / "best_per_ligand.csv")
        failed_chunks_csv = write_rows_csv(failed_chunk_rows, run_root / "tables" / "failed_chunks.csv")
        failed_ligands_csv = write_rows_csv(failed_ligand_rows, run_root / "tables" / "failed_ligands.csv")
        failure_summary = {
            "failure_policy": failure_policy,
            "total_chunks": len(chunks),
            "successful_chunks": len(out_files),
            "failed_chunks": len(failed_chunk_rows),
            "failed_ligands": len(failed_ligand_rows),
            "records_without_score_dropped": records_without_score_dropped_total,
        }
        (run_root / "metrics" / "rdock_failure_summary.json").write_text(json.dumps(failure_summary, indent=2), encoding="utf-8")

        labels_map: dict[str, int] = {}
        if validation_labels_csv:
            import pandas as pd

            label_df = pd.read_csv(validation_labels_csv)
            labels_map = dict(zip(label_df["ligand_id"].astype(str), label_df["label"].astype(int)))
            best_rows = records_to_rows(best)
            for row in best_rows:
                row["label"] = labels_map.get(str(row["ligand_id"]), 0)
            best_csv = write_rows_csv(best_rows, best_csv)

        manifest_path = run_root / "manifest.json"
        config_yaml = run_root / "config.yaml"
        report_md = run_root / "report.md"
        now = datetime.now(UTC).isoformat()
        file_inputs = {
            "ligands_sdf": str(lig_copy),
            "dock_prm": str(run_root / "rdock" / "dock.prm"),
            "receptor_prm": str(local_prm),
            "cavity_as": str(target_dir / Path(target_config.cavity_as).name),
        }
        manifest = {
            "run_id": run_id or run_root.name,
            "created_at": now,
            "engine": "real-rdock",
            "n_runs": actual_n_runs,
            "jobs": resolved_jobs,
            "input_hashes": {k: sha256_file(v) for k, v in file_inputs.items() if Path(v).exists()},
            "rdock_versions": {
                "rbdock": probe_version(rbdock),
                "rbcavity": probe_version(require_executable(self.config.rbcavity_bin)),
            },
            "target_config": asdict(target_config),
            "commands": [r.to_dict() for r in runner.records],
            "artifacts": {
                "all_poses_sdf": str(all_poses),
                "best_per_ligand_sdf": str(best_sdf),
                "best_ligand_poses_sdf": best_ligand_poses_sdf,
                "scores_long_csv": str(scores_long),
                "best_per_ligand_csv": str(best_csv),
                "failed_chunks_csv": str(failed_chunks_csv),
                "failed_ligands_csv": str(failed_ligands_csv),
                "rdock_failure_summary_json": str(run_root / "metrics" / "rdock_failure_summary.json"),
                "commands_log": str(commands_log),
            },
            "pose_count": len(records),
            "docked_ligand_count": len(best),
            "rdock_failure_summary": failure_summary,
        }
        manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
        _write_yaml_like(config_yaml, {"rdock": asdict(self.config), "run": {"n_runs": actual_n_runs, "jobs": resolved_jobs}})
        report_md.write_text(
            "\n".join(
                [
                    "# rDock Run Report",
                    "",
                    f"- Engine: `real-rdock`",
                    f"- Run ID: `{manifest['run_id']}`",
                    f"- n_runs per ligand: `{actual_n_runs}`",
                    f"- local jobs: `{resolved_jobs}`",
                    f"- poses parsed: `{len(records)}`",
                    f"- docked ligands: `{len(best)}`",
                    f"- failed chunks: `{failure_summary['failed_chunks']}`",
                    f"- failed ligands: `{failure_summary['failed_ligands']}`",
                    f"- all poses: `{all_poses}`",
                    f"- best per ligand: `{best_sdf}`",
                    f"- best ligand all poses: `{best_ligand_poses_sdf or ''}`",
                    f"- command log: `{commands_log}`",
                    "",
                    "No surrogate or undocked ligand is reported as a real rDock hit; hit tables are generated only from parsed rDock SDF records with native SCORE fields.",
                ]
            ),
            encoding="utf-8",
        )
        _emit_progress(
            "dock:done",
            {
                "run_dir": str(run_root),
                "pose_count": len(records),
                "docked_ligands": len(best),
                "all_poses_sdf": str(all_poses),
                "best_per_ligand_csv": str(best_csv),
                "failed_chunks": failure_summary["failed_chunks"],
                "failed_ligands": failure_summary["failed_ligands"],
            },
        )
        return RunArtifacts(
            run_dir=str(run_root),
            manifest=str(manifest_path),
            config_yaml=str(config_yaml),
            commands_log=str(commands_log),
            all_poses_sdf=str(all_poses),
            best_per_ligand_sdf=str(best_sdf),
            scores_long_csv=str(scores_long),
            best_per_ligand_csv=str(best_csv),
            report_md=str(report_md),
            command_records=[r.to_dict() for r in runner.records],
            best_ligand_poses_sdf=best_ligand_poses_sdf,
        )


def load_target_config(path: str | Path) -> TargetConfig:
    source = require_file(path, "target config")
    try:
        import yaml

        data = yaml.safe_load(source.read_text(encoding="utf-8"))
    except Exception:
        data = json.loads(source.read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise RDockPipelineError(f"Invalid target config payload in {source}")

    config_dir = source.parent.resolve()
    dataset_target_dir = config_dir.parent.resolve()

    def _rebase_file(value: object, *candidate_dirs: Path) -> str:
        text = str(value or "").strip()
        if not text:
            return text
        current = Path(text)
        if current.exists():
            return str(current.resolve())
        for base in candidate_dirs:
            candidate = (base / current.name).resolve()
            if candidate.exists():
                return str(candidate)
        return text

    data["target_dir"] = str(config_dir)
    data["receptor_prm"] = _rebase_file(data.get("receptor_prm", ""), config_dir)
    data["cavity_as"] = _rebase_file(data.get("cavity_as", ""), config_dir)
    data["receptor_mol2"] = _rebase_file(data.get("receptor_mol2", ""), config_dir, dataset_target_dir)
    data["reference_ligand"] = _rebase_file(data.get("reference_ligand", ""), config_dir, dataset_target_dir)
    data["receptor"] = _rebase_file(data.get("receptor", ""), config_dir, dataset_target_dir)
    if data.get("receptor_prm"):
        _normalize_receptor_prm_paths(Path(str(data["receptor_prm"])), config_dir, dataset_target_dir)
    return TargetConfig(**data)