File size: 36,116 Bytes
c289d87
 
 
 
504d922
c289d87
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
504d922
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import threading
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Dict, Sequence

import numpy as np

from libs.utils.logging_utils import get_logger
from libs.utils.subprocess_utils import CommandResult, run_command

from .base import BackendCapability, BackendUnavailableError, DockingBackend, DockingError, DockingResult
from .constraints import write_receptor_prm, write_receptor_prm_sphere
from .interface_features import extract_simple_interface_features
from .pocket import (
    POCKET_MODE_REFERENCE,
    POCKET_MODE_REFERENCE_RELAXED,
    POCKET_MODE_USER_FIXED,
    PocketSpec,
    centroid_from_sdf,
    is_pose_in_pocket,
    pose_distance_to_center,
    resolve_pocket_spec,
    write_pocket_spec,
)
from .pose_parsing import parse_rdock_sdf
from .prep import prepare_ligand_sdf
from .plip_interactions import analyze_pose_with_plip, plip_import_available


@dataclass
class RDockConfig:
    rbdock_bin: str = "rbdock"
    rbcavity_bin: str = "rbcavity"
    sdtether_bin: str = "sdtether"
    n_runs: int = 5
    seed: int | None = None
    protocol_prm: str | None = None
    rbt_root: str | None = None
    command_log_path: str | None = None
    mapper_radius: float = 6.0
    command_timeout_seconds: int = 180
    parallel_jobs: int = 1
    auto_batch_memory: bool = True
    memory_safety_fraction: float = 0.85
    min_memory_per_job_mb: int = 256
    memory_probe_ligands: int = 2
    enable_plip_interactions: bool = True
    plip_timeout_seconds: int = 120
    allow_partial_failures: bool = False
    pocket_mode: str = POCKET_MODE_REFERENCE
    pocket_center: tuple[float, float, float] | str | list[float] | None = None
    pocket_box_size: tuple[float, float, float] | str | list[float] | None = None
    pocket_radius: float | None = None
    pocket_reference_ligand_id: str | None = None
    pocket_relaxation_margin: float = 0.0
    allow_legacy_generated_pocket: bool = False


class RDockBackend(DockingBackend):
    """rDock adapter with strict backend validation and explicit provenance."""

    def __init__(self, config: RDockConfig | None = None) -> None:
        self.config = config or RDockConfig()
        self.logger = get_logger("rdock_backend")
        self.default_rbt_root = Path("/opt/homebrew/opt/rdock/share")
        self.command_history: list[dict[str, str | int]] = []
        self._log_lock = threading.Lock()

    def _ensure_runtime_env(self) -> None:
        if self.config.rbt_root:
            os.environ["RBT_ROOT"] = self.config.rbt_root
            return

        if "RBT_ROOT" not in os.environ and self.default_rbt_root.exists():
            os.environ["RBT_ROOT"] = str(self.default_rbt_root)

    def _resolve_protocol_prm(self) -> Path:
        if self.config.protocol_prm:
            prm = Path(self.config.protocol_prm).expanduser().resolve()
            if prm.exists():
                return prm
            raise DockingError(f"Configured protocol file does not exist: {prm}")

        rbt_root = os.environ.get("RBT_ROOT")
        if not rbt_root:
            raise DockingError("RBT_ROOT is not set and protocol_prm is not configured")

        prm = Path(rbt_root) / "data" / "scripts" / "dock.prm"
        if not prm.exists():
            raise DockingError(f"Default rDock protocol file not found: {prm}")
        return prm

    def _append_command_log(self, payload: dict[str, str | int]) -> None:
        with self._log_lock:
            self.command_history.append(payload)
            if self.config.command_log_path:
                log_path = Path(self.config.command_log_path)
                log_path.parent.mkdir(parents=True, exist_ok=True)
                line = (
                    f"[{payload['timestamp']}] stage={payload['stage']} rc={payload['returncode']} cwd={payload['cwd']}\n"
                    f"  command: {payload['command']}\n"
                    f"  stdout: {payload['stdout_log']}\n"
                    f"  stderr: {payload['stderr_log']}\n"
                )
                with log_path.open("a", encoding="utf-8") as handle:
                    handle.write(line)

    def _record_command(
        self,
        stage: str,
        result: CommandResult,
        cwd: Path,
        stdout_log: Path,
        stderr_log: Path,
    ) -> None:
        stdout_log.write_text(result.stdout, encoding="utf-8")
        stderr_log.write_text(result.stderr, encoding="utf-8")
        self._append_command_log(
            {
                "timestamp": datetime.now(UTC).isoformat(),
                "stage": stage,
                "command": " ".join(result.command),
                "cwd": str(cwd),
                "returncode": result.returncode,
                "stdout_log": str(stdout_log),
                "stderr_log": str(stderr_log),
            }
        )

    @staticmethod
    def _indicates_failure(result: CommandResult) -> bool:
        if result.returncode != 0:
            return True

        text = f"{result.stdout}\n{result.stderr}".lower()
        known_error_markers = [
            "rbt_file_read_error",
            "bad_receptor_file",
            "cavity file",
            "inappropriate molecular file type",
            "fatal",
        ]
        return any(marker in text for marker in known_error_markers)

    @staticmethod
    def _available_memory_bytes() -> int | None:
        try:
            pages = os.sysconf("SC_AVPHYS_PAGES")
            page_size = os.sysconf("SC_PAGE_SIZE")
            value = int(pages) * int(page_size)
            return value if value > 0 else None
        except Exception:
            pass
        try:
            proc = subprocess.run(["vm_stat"], check=False, capture_output=True, text=True, timeout=5)
            if proc.returncode != 0:
                return None
            page_size = 4096
            first = proc.stdout.splitlines()[0] if proc.stdout.splitlines() else ""
            match = re.search(r"page size of (\d+) bytes", first)
            if match:
                page_size = int(match.group(1))
            page_counts: dict[str, int] = {}
            for line in proc.stdout.splitlines()[1:]:
                if ":" not in line:
                    continue
                key, value = line.split(":", 1)
                text = value.strip().rstrip(".").replace(",", "")
                try:
                    page_counts[key.strip()] = int(text)
                except Exception:
                    continue
            available_pages = (
                page_counts.get("Pages free", 0)
                + page_counts.get("Pages inactive", 0)
                + page_counts.get("Pages speculative", 0)
                + page_counts.get("File-backed pages", 0)
            )
            value = int(available_pages) * int(page_size)
            return value if value > 0 else None
        except Exception:
            return None

    @staticmethod
    def _cavity_volume_from_text(text: str) -> float | None:
        for pattern in (r"total\s+volume\s*[:=]?\s*([0-9]+(?:\.[0-9]+)?)", r"volume\s*[:=]\s*([0-9]+(?:\.[0-9]+)?)"):
            match = re.search(pattern, text, flags=re.IGNORECASE)
            if match:
                try:
                    return float(match.group(1))
                except Exception:
                    return None
        return None

    def _cavity_artifact_usable(self, cavity_file: Path, log_path: Path | None = None) -> bool:
        if not cavity_file.exists() or cavity_file.stat().st_size <= 0:
            return False
        if log_path is not None and log_path.exists():
            volume = self._cavity_volume_from_text(log_path.read_text(encoding="utf-8", errors="ignore"))
            if volume is not None and volume <= 0.0:
                return False
        return True

    def _estimate_memory_bytes_per_job(self, ligand_files: Sequence[Path]) -> int:
        sample_n = max(1, int(self.config.memory_probe_ligands))
        sample = list(ligand_files[:sample_n])
        sizes = [path.stat().st_size for path in sample if path.exists()]
        avg_size = float(sum(sizes) / len(sizes)) if sizes else 0.0
        static_estimate = int(avg_size * 80.0 * max(1, int(self.config.n_runs)))
        floor_estimate = int(max(1, int(self.config.min_memory_per_job_mb)) * 1024 * 1024)
        return max(static_estimate, floor_estimate)

    def _resolve_memory_limited_jobs(self, ligand_files: Sequence[Path], work_dir: Path) -> int:
        configured_jobs = max(1, int(self.config.parallel_jobs))
        requested_jobs = min(configured_jobs, max(1, len(ligand_files)))
        available = self._available_memory_bytes()
        per_job = self._estimate_memory_bytes_per_job(ligand_files)
        memory_jobs = requested_jobs
        if self.config.auto_batch_memory and available is not None and per_job > 0:
            usable = max(1, int(float(available) * max(0.1, min(1.0, float(self.config.memory_safety_fraction)))))
            memory_jobs = max(1, usable // per_job)
        resolved = max(1, min(requested_jobs, memory_jobs))
        plan = {
            "parallel_jobs_configured": configured_jobs,
            "parallel_jobs_requested_for_batch": requested_jobs,
            "parallel_jobs_resolved": resolved,
            "ligand_count": len(ligand_files),
            "sampled_ligand_count": min(len(ligand_files), max(1, int(self.config.memory_probe_ligands))),
            "available_memory_bytes": available,
            "estimated_memory_bytes_per_job": per_job,
            "memory_safety_fraction": float(self.config.memory_safety_fraction),
            "auto_batch_memory": bool(self.config.auto_batch_memory),
            "batching_policy": "memory_limited_parallel_jobs",
        }
        (work_dir / "memory_batch_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
        return resolved

    @staticmethod
    def _post_docking_confidence(extra: dict[str, object], score: float, success: bool) -> float:
        if not success or not np.isfinite(score):
            return 0.0
        native = dict(extra.get("rdock_native", {}))
        pose_count = float(native.get("n_generated_poses", extra.get("pose_count", 0)) or 0)
        std_top5 = native.get("std_top5_pose_score", np.nan)
        gap = native.get("pose_score_gap_1_2", np.nan)
        pose_inside = bool(extra.get("pose_in_fixed_pocket", False))
        pose_term = min(1.0, pose_count / 5.0)
        variance_term = 0.5
        try:
            std_value = abs(float(std_top5))
            if np.isfinite(std_value):
                variance_term = 1.0 / (1.0 + std_value)
        except Exception:
            pass
        gap_term = 0.5
        try:
            gap_value = abs(float(gap))
            if np.isfinite(gap_value):
                gap_term = min(1.0, gap_value / 2.0)
        except Exception:
            pass
        pocket_term = 1.0 if pose_inside else 0.25
        return float(max(0.0, min(1.0, 0.25 * pose_term + 0.25 * variance_term + 0.20 * gap_term + 0.30 * pocket_term)))

    @staticmethod
    def _biological_interaction_proxy(native: dict[str, object], derived: dict[str, object], pose_inside: bool) -> float:
        def _finite(value: object, default: float = 0.0) -> float:
            try:
                out = float(value)
            except Exception:
                return default
            return out if np.isfinite(out) else default

        polar = abs(_finite(native.get("rdock_polar_term"), 0.0))
        vdw = abs(_finite(native.get("rdock_vdw_term"), 0.0))
        overlap = max(0.0, min(1.0, _finite(derived.get("contact_overlap_consistency"), 0.0)))
        hotspot = max(0.0, min(1.0, _finite(derived.get("hotspot_contact_frequency"), 0.0)))
        energetic = max(0.0, min(1.0, (0.04 * polar) + (0.01 * vdw)))
        pocket_bonus = 0.15 if pose_inside else 0.0
        return float(max(0.0, min(1.0, 0.45 * energetic + 0.20 * overlap + 0.20 * hotspot + pocket_bonus)))

    def check_capability(self) -> BackendCapability:
        bins = {
            "rbdock": shutil.which(self.config.rbdock_bin),
            "rbcavity": shutil.which(self.config.rbcavity_bin),
            "sdtether": shutil.which(self.config.sdtether_bin),
            "obabel": shutil.which("obabel"),
        }
        available = bins["rbdock"] is not None and bins["rbcavity"] is not None and bins["obabel"] is not None
        return BackendCapability(backend_name="rdock", available=available, details=bins)

    def _resolve_target_pocket(self, target_path: Path, work_dir: Path) -> PocketSpec:
        spec = resolve_pocket_spec(
            target_path=target_path,
            pocket_mode=self.config.pocket_mode,
            pocket_center=self.config.pocket_center,
            pocket_box_size=self.config.pocket_box_size,
            pocket_radius=self.config.pocket_radius,
            pocket_reference_ligand_id=self.config.pocket_reference_ligand_id,
            pocket_relaxation_margin=self.config.pocket_relaxation_margin,
            fallback_radius=self.config.mapper_radius,
        )
        write_pocket_spec(work_dir / "pocket_spec.json", spec)
        return spec

    def prepare_target(self, target_path: str | Path, work_dir: str | Path) -> Dict[str, Path]:
        source = Path(target_path)
        if not source.exists():
            raise DockingError(f"Target file does not exist: {source}")

        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)

        prepared = wd / f"target_prepared{source.suffix.lower()}"
        prepared.write_bytes(source.read_bytes())

        receptor_mol2 = wd / "receptor.mol2"
        suffix = source.suffix.lower()
        if suffix == ".mol2":
            receptor_mol2.write_bytes(source.read_bytes())
        else:
            obabel = shutil.which("obabel")
            if obabel is None:
                raise DockingError("Open Babel executable `obabel` is required for receptor preparation")

            try:
                result = run_command([obabel, str(prepared), "-O", str(receptor_mol2)], cwd=wd, timeout=120)
            except TimeoutExpired as exc:
                raise DockingError(f"obabel timed out while preparing receptor: {exc}") from exc
            self._record_command(
                stage="prepare_target_obabel",
                result=result,
                cwd=wd,
                stdout_log=wd / "prepare_target_obabel.stdout.log",
                stderr_log=wd / "prepare_target_obabel.stderr.log",
            )
            if self._indicates_failure(result) or not receptor_mol2.exists() or receptor_mol2.stat().st_size == 0:
                raise DockingError(
                    "Failed to produce receptor.mol2 from target structure. "
                    f"Return code: {result.returncode}, stderr: {result.stderr.strip()}"
                )

        pocket = self._resolve_target_pocket(source, wd)
        self.logger.info(
            "Resolved pocket mode=%s source=%s center=(%.3f, %.3f, %.3f) radius=%.3f",
            pocket.mode,
            pocket.source,
            pocket.center[0],
            pocket.center[1],
            pocket.center[2],
            pocket.radius,
        )

        plip_receptor_pdb: Path | None = wd / "receptor_plip.pdb"
        if suffix == ".pdb":
            plip_receptor_pdb.write_bytes(prepared.read_bytes())
        else:
            obabel = shutil.which("obabel")
            if obabel is not None:
                try:
                    result = run_command([obabel, str(receptor_mol2), "-O", str(plip_receptor_pdb)], cwd=wd, timeout=120)
                    self._record_command(
                        stage="prepare_target_plip_pdb",
                        result=result,
                        cwd=wd,
                        stdout_log=wd / "prepare_target_plip_pdb.stdout.log",
                        stderr_log=wd / "prepare_target_plip_pdb.stderr.log",
                    )
                    if result.returncode != 0 or not plip_receptor_pdb.exists() or plip_receptor_pdb.stat().st_size == 0:
                        plip_receptor_pdb = prepared if prepared.suffix.lower() == ".pdb" else None
                except Exception:
                    plip_receptor_pdb = prepared if prepared.suffix.lower() == ".pdb" else None

        context = {
            "target_prepared": prepared,
            "receptor_mol2": receptor_mol2,
            "target_work_dir": wd,
            "pocket_spec_json": wd / "pocket_spec.json",
        }
        if plip_receptor_pdb is not None:
            context["plip_receptor_pdb"] = plip_receptor_pdb
        return context

    def prepare_ligand(self, ligand_id: str, smiles: str, work_dir: str | Path) -> Path:
        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)
        return prepare_ligand_sdf(ligand_id, smiles, wd / f"{ligand_id}.sdf")

    def build_site_or_constraints(
        self,
        target_context: Dict[str, Path],
        reference_ligand: Path,
        work_dir: str | Path,
    ) -> Path:
        receptor_mol2 = target_context.get("receptor_mol2")
        if receptor_mol2 is None or not receptor_mol2.exists():
            raise DockingError("Missing receptor_mol2 in target context")

        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)

        prm = wd / "receptor.prm"
        pocket_json = target_context.get("pocket_spec_json")
        if pocket_json and Path(pocket_json).exists():
            pocket = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8")))
            write_receptor_prm_sphere(
                receptor_mol2=receptor_mol2,
                center=pocket.center,
                radius=pocket.radius,
                out_path=prm,
            )
            return prm

        if not self.config.allow_legacy_generated_pocket:
            raise DockingError(
                "Missing pocket_spec_json while strict fixed-pocket mode is active. "
                "Provide user_fixed_pocket or reference_complex_pocket settings."
            )

        write_receptor_prm(
            receptor_mol2=receptor_mol2,
            reference_ligand_sdf=reference_ligand,
            out_path=prm,
            radius=self.config.mapper_radius,
        )
        return prm

    @staticmethod
    def _failed_real_result(ligand_id: str, message: str, command: Sequence[str] | None = None) -> DockingResult:
        return DockingResult(
            ligand_id=ligand_id,
            docking_score=float("nan"),
            pose_path=None,
            backend_name="rdock",
            backend_mode="real-rdock",
            score_source="rdock_error",
            raw_output_file="",
            parsed_from="",
            fallback_used=False,
            success=False,
            message=message,
            command=" ".join(command) if command else "",
            extra={},
        )

    def dock(
        self,
        target_context: Dict[str, Path],
        ligand_files: Sequence[Path],
        work_dir: str | Path,
        allow_mock: bool = False,
        require_real_backend: bool = False,
    ) -> list[DockingResult]:
        self._ensure_runtime_env()
        capability = self.check_capability()
        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)

        if allow_mock:
            raise DockingError(
                "Mock rDock fallback has been removed. Install/configure rDock and OpenBabel, "
                "or call with allow_mock=False to receive the actionable real-backend error."
            )

        if not capability.available:
            msg = f"rDock capability check failed: {capability.details}"
            raise BackendUnavailableError(msg)

        if not ligand_files:
            return []

        pocket_spec: PocketSpec | None = None
        pocket_json = target_context.get("pocket_spec_json")
        if pocket_json is not None and Path(pocket_json).exists():
            pocket_spec = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8")))
        else:
            target_prepared = target_context.get("target_prepared")
            if target_prepared is not None and Path(target_prepared).exists():
                resolved = self._resolve_target_pocket(Path(target_prepared), Path(target_context.get("target_work_dir", wd)))
                write_pocket_spec(Path(target_context.get("target_work_dir", wd)) / "pocket_spec.json", resolved)
                target_context["pocket_spec_json"] = Path(target_context.get("target_work_dir", wd)) / "pocket_spec.json"
                pocket_spec = resolved

        site_dir = Path(target_context.get("target_work_dir", wd))
        site_dir.mkdir(parents=True, exist_ok=True)
        cached_prm = Path(target_context["site_prm"]) if "site_prm" in target_context else None
        cached_cavity = Path(target_context["site_cavity"]) if "site_cavity" in target_context else None
        if (
            cached_prm is not None
            and cached_cavity is not None
            and cached_prm.exists()
            and cached_cavity.exists()
            and self._cavity_artifact_usable(cached_cavity, site_dir / "rbcavity.stdout.log")
        ):
            prm_file = cached_prm
            cavity_file = cached_cavity
        else:
            prm_file = self.build_site_or_constraints(target_context, ligand_files[0], site_dir)
            try:
                cavity = run_command(
                    [self.config.rbcavity_bin, "-was", "-r", str(prm_file)],
                    cwd=site_dir,
                    timeout=self.config.command_timeout_seconds,
                )
            except TimeoutExpired as exc:
                raise DockingError(f"rbcavity timed out: {exc}") from exc
            self._record_command(
                stage="rbcavity",
                result=cavity,
                cwd=site_dir,
                stdout_log=site_dir / "rbcavity.stdout.log",
                stderr_log=site_dir / "rbcavity.stderr.log",
            )

            cavity_file = site_dir / f"{prm_file.stem}.as"
            cavity_ok = self._cavity_artifact_usable(cavity_file, site_dir / "rbcavity.stdout.log")
            if self._indicates_failure(cavity) or not cavity_ok:
                msg = (
                    "rbcavity failed or did not produce cavity file. "
                    f"expected={cavity_file}, rc={cavity.returncode}, stderr={cavity.stderr.strip()}"
                )
                raise DockingError(msg)
            target_context["site_prm"] = prm_file
            target_context["site_cavity"] = cavity_file

        # Keep batch-local cavity artifact for compatibility with existing validation/tests.
        local_prm = wd / prm_file.name
        if prm_file.exists() and prm_file != local_prm and not local_prm.exists():
            shutil.copy2(prm_file, local_prm)
        local_cavity = wd / cavity_file.name
        if cavity_file.exists() and cavity_file != local_cavity and not local_cavity.exists():
            shutil.copy2(cavity_file, local_cavity)

        protocol_prm = self._resolve_protocol_prm()

        def _dock_single(ligand_file: Path) -> DockingResult:
            ligand_id = ligand_file.stem
            out_prefix = wd / f"{ligand_id}_rdock"
            cmd = [
                self.config.rbdock_bin,
                "-i",
                str(ligand_file),
                "-o",
                str(out_prefix),
                "-r",
                str(prm_file),
                "-p",
                str(protocol_prm),
                "-n",
                str(self.config.n_runs),
            ]
            if self.config.seed is not None:
                cmd.extend(["-s", str(int(self.config.seed))])
            try:
                proc = run_command(cmd, cwd=wd, timeout=self.config.command_timeout_seconds)
            except TimeoutExpired as exc:
                msg = f"rbdock timed out for {ligand_id}: {exc}"
                if self.config.allow_partial_failures:
                    return self._failed_real_result(ligand_id, msg, cmd)
                raise DockingError(msg) from exc
            self._record_command(
                stage=f"rbdock:{ligand_id}",
                result=proc,
                cwd=wd,
                stdout_log=wd / f"{ligand_id}.rbdock.stdout.log",
                stderr_log=wd / f"{ligand_id}.rbdock.stderr.log",
            )

            if self._indicates_failure(proc):
                msg = f"rbdock failed for {ligand_id}: rc={proc.returncode}, stderr={proc.stderr.strip()}"
                if self.config.allow_partial_failures:
                    return self._failed_real_result(ligand_id, msg, cmd)
                raise DockingError(msg)

            pose_candidates = sorted(wd.glob(f"{ligand_id}_rdock*.sd"))
            if not pose_candidates:
                msg = f"rbdock produced no .sd output for {ligand_id} in {wd}"
                if self.config.allow_partial_failures:
                    return self._failed_real_result(ligand_id, msg, cmd)
                raise DockingError(msg)

            pose_file = pose_candidates[0]
            try:
                parsed = parse_rdock_sdf(pose_file)
            except Exception as exc:
                msg = f"Failed parsing rDock output for {ligand_id}: {exc}"
                if self.config.allow_partial_failures:
                    return self._failed_real_result(ligand_id, msg, cmd)
                raise DockingError(msg) from exc

            pose_centroid = centroid_from_sdf(pose_file)
            pocket_distance = pose_distance_to_center(pose_centroid, pocket_spec) if pocket_spec is not None else float("nan")
            pose_inside = is_pose_in_pocket(pose_centroid, pocket_spec) if pocket_spec is not None else False
            native_features = dict(parsed.get("native_features", {}))
            derived_features = dict(parsed.get("derived_features", {}))
            fallback_interaction_proxy = self._biological_interaction_proxy(native_features, derived_features, pose_inside)
            plip_summary = None
            plip_receptor = target_context.get("plip_receptor_pdb")
            if (
                self.config.enable_plip_interactions
                and plip_receptor is not None
                and Path(plip_receptor).exists()
                and plip_import_available()
            ):
                plip_summary = analyze_pose_with_plip(
                    receptor_pdb=Path(plip_receptor),
                    pose_sdf=pose_file,
                    ligand_id=ligand_id,
                    work_dir=wd / "plip",
                    timeout_seconds=int(self.config.plip_timeout_seconds),
                )
            plip_payload = plip_summary.to_dict() if plip_summary is not None else {
                "available": plip_import_available(),
                "success": False,
                "source": "plip",
                "interaction_score": 0.0,
                "interaction_count": 0,
                "message": "PLIP disabled or receptor PDB unavailable",
            }
            interaction_score = (
                float(plip_payload.get("interaction_score", 0.0))
                if bool(plip_payload.get("success", False))
                else fallback_interaction_proxy
            )
            interaction_source = "plip" if bool(plip_payload.get("success", False)) else "rdock_energy_pose_proxy"
            extra = {
                "all_scores": parsed.get("all_scores", []),
                "pose_count": parsed.get("pose_count"),
                "rdock_native": native_features,
                "rdock_derived": derived_features,
                "rdock_feature_provenance": parsed.get("feature_provenance", []),
                "pocket_spec": pocket_spec.to_dict() if pocket_spec is not None else {},
                "pose_centroid": pose_centroid.tolist() if pose_centroid.size == 3 and np.isfinite(pose_centroid).all() else [],
                "pose_distance_to_pocket_center": pocket_distance,
                "pose_in_fixed_pocket": pose_inside,
                "plip_interactions": plip_payload,
                "biological_interaction_proxy_score": interaction_score,
                "biological_interaction_source": interaction_source,
            }
            extra["post_docking_confidence_score"] = self._post_docking_confidence(extra, float(parsed["score"]), True)

            return DockingResult(
                ligand_id=ligand_id,
                docking_score=float(parsed["score"]),
                pose_path=pose_file,
                backend_name="rdock",
                backend_mode="real-rdock",
                score_source=f"rdock_tag:{parsed['score_tag']}",
                raw_output_file=str(pose_file),
                parsed_from=f"{pose_file}::{parsed['score_tag']}",
                fallback_used=False,
                success=True,
                command=" ".join(cmd),
                extra=extra,
            )

        results: list[DockingResult] = []
        jobs = self._resolve_memory_limited_jobs(ligand_files, wd)
        if jobs <= 1 or len(ligand_files) <= 1:
            for ligand_file in ligand_files:
                results.append(_dock_single(ligand_file))
        else:
            with ThreadPoolExecutor(max_workers=min(jobs, len(ligand_files))) as ex:
                for res in ex.map(_dock_single, ligand_files):
                    results.append(res)

        return results

    def parse_results(self, results: Sequence[DockingResult]) -> list[dict[str, object]]:
        parsed: list[dict[str, object]] = []
        nan = float("nan")
        for result in results:
            native = dict((result.extra or {}).get("rdock_native", {}))
            derived = dict((result.extra or {}).get("rdock_derived", {}))
            pocket = dict((result.extra or {}).get("pocket_spec", {}))
            center = pocket.get("center", [nan, nan, nan])
            box = pocket.get("box_size", [nan, nan, nan])
            confidence = float((result.extra or {}).get("post_docking_confidence_score", 0.0))
            interaction_proxy = float((result.extra or {}).get("biological_interaction_proxy_score", 0.0))
            interaction_weighted_score = float(result.docking_score) - (0.5 * interaction_proxy) if result.success else nan
            plip_payload = dict((result.extra or {}).get("plip_interactions", {}))
            parsed.append(
                {
                    "ligand_id": result.ligand_id,
                    "docking_score": float(result.docking_score),
                    "backend_name": result.backend_name,
                    "backend_mode": result.backend_mode,
                    "score_source": result.score_source,
                    "raw_output_file": result.raw_output_file,
                    "parsed_from": result.parsed_from,
                    "fallback_used": bool(result.fallback_used),
                    "success": bool(result.success),
                    "message": result.message,
                    "pose_path": str(result.pose_path) if result.pose_path else "",
                    "command": result.command,
                    "quantity_type": "docking_score",
                    "rdock_total_score": native.get("rdock_total_score", float(result.docking_score)),
                    "rdock_pose_rank": native.get("rdock_pose_rank", 1),
                    "n_generated_poses": native.get("n_generated_poses", (result.extra or {}).get("pose_count", 1)),
                    "best_pose_score": native.get("best_pose_score", float(result.docking_score)),
                    "mean_top3_pose_score": native.get("mean_top3_pose_score", float(result.docking_score)),
                    "mean_top5_pose_score": native.get("mean_top5_pose_score", float(result.docking_score)),
                    "std_top5_pose_score": native.get("std_top5_pose_score", nan),
                    "pose_score_gap_1_2": native.get("pose_score_gap_1_2", nan),
                    "rdock_restraint_term": native.get("rdock_restraint_term", nan),
                    "rdock_internal_ligand_term": native.get("rdock_internal_ligand_term", nan),
                    "rdock_polar_term": native.get("rdock_polar_term", nan),
                    "rdock_vdw_term": native.get("rdock_vdw_term", nan),
                    "top_pose_rmsd_consistency": derived.get("top_pose_rmsd_consistency", nan),
                    "contact_overlap_consistency": derived.get("contact_overlap_consistency", nan),
                    "hotspot_contact_frequency": derived.get("hotspot_contact_frequency", nan),
                    "subpocket_match_score": derived.get("subpocket_match_score", nan),
                    "replicate_mean_score": nan,
                    "replicate_score_variance": nan,
                    "replicate_consensus_score": nan,
                    "rdock_feature_provenance": json.dumps((result.extra or {}).get("rdock_feature_provenance", [])),
                    "pocket_mode": pocket.get("mode", ""),
                    "pocket_source": pocket.get("source", ""),
                    "pocket_center_x": float(center[0]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan,
                    "pocket_center_y": float(center[1]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan,
                    "pocket_center_z": float(center[2]) if isinstance(center, (list, tuple)) and len(center) == 3 else nan,
                    "pocket_radius": float(pocket.get("radius", nan)),
                    "pocket_box_size_x": float(box[0]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan,
                    "pocket_box_size_y": float(box[1]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan,
                    "pocket_box_size_z": float(box[2]) if isinstance(box, (list, tuple)) and len(box) == 3 else nan,
                    "pose_distance_to_pocket_center": float((result.extra or {}).get("pose_distance_to_pocket_center", nan)),
                    "pose_in_fixed_pocket": bool((result.extra or {}).get("pose_in_fixed_pocket", False)),
                    "post_docking_confidence_score": confidence,
                    "biological_interaction_proxy_score": interaction_proxy,
                    "interaction_weighted_docking_score": interaction_weighted_score,
                    "interaction_filter_pass": bool(interaction_proxy > 0.0),
                    "interaction_feature_source": str((result.extra or {}).get("biological_interaction_source", "")),
                    "plip_available": bool(plip_payload.get("available", False)),
                    "plip_success": bool(plip_payload.get("success", False)),
                    "plip_interaction_count": int(plip_payload.get("interaction_count", 0) or 0),
                    "plip_hydrophobic_count": int(plip_payload.get("hydrophobic_count", 0) or 0),
                    "plip_hbond_count": int(plip_payload.get("hbond_count", 0) or 0),
                    "plip_saltbridge_count": int(plip_payload.get("saltbridge_count", 0) or 0),
                    "plip_pistacking_count": int(plip_payload.get("pistacking_count", 0) or 0),
                    "plip_pication_count": int(plip_payload.get("pication_count", 0) or 0),
                    "plip_halogen_count": int(plip_payload.get("halogen_count", 0) or 0),
                    "plip_waterbridge_count": int(plip_payload.get("waterbridge_count", 0) or 0),
                    "plip_metal_count": int(plip_payload.get("metal_count", 0) or 0),
                    "plip_message": str(plip_payload.get("message", "")),
                }
            )
        return parsed

    def extract_interface_features(self, parsed_results: Sequence[dict[str, object]]) -> list[dict[str, float]]:
        normalized = [{"docking_score": float(row.get("docking_score", 0.0))} for row in parsed_results]
        return extract_simple_interface_features(normalized)