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

import math
import re
import shutil
import json
from dataclasses import dataclass
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Any, Dict, Sequence

import numpy as np
from concurrent.futures import ThreadPoolExecutor

from libs.utils.subprocess_utils import run_command

from .base import BackendCapability, DockingBackend, DockingError, DockingResult
from .pocket import (
    PocketSpec,
    centroid_from_pdbqt,
    is_pose_in_pocket,
    pose_distance_to_center,
    resolve_pocket_spec,
    write_pocket_spec,
)
from .prep import prepare_ligand_sdf

_FLOAT_RE = re.compile(r"[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?")


def _resolve_executable(name: str) -> str | None:
    direct = shutil.which(name)
    if direct:
        return direct
    candidates = [
        Path.home() / "miniconda3" / "envs" / "docking_diag" / "bin" / name,
        Path.home() / "miniconda3" / "bin" / name,
    ]
    for c in candidates:
        if c.exists():
            return str(c)
    return None


def parse_smina_score(text: str) -> float:
    """
    Parse smina score from combined output text.

    Supported patterns:
    - `REMARK minimizedAffinity -7.6`
    - `REMARK VINA RESULT: -7.6 ...`
    - score table lines: `1 -7.6 ...`
    """
    best = math.nan
    for ln in text.splitlines():
        low = ln.lower()
        if "minimizedaffinity" in low or "vina result" in low or low.startswith("affinity:"):
            nums = _FLOAT_RE.findall(ln)
            for tok in nums:
                try:
                    val = float(tok)
                except Exception:
                    continue
                if math.isfinite(val):
                    if (not math.isfinite(best)) or val < best:
                        best = val
                    break
            continue
        stripped = ln.strip()
        if not stripped or stripped.startswith("#"):
            continue
        cols = stripped.split()
        if len(cols) >= 2 and cols[0].isdigit():
            try:
                val = float(cols[1])
            except Exception:
                continue
            if math.isfinite(val):
                if (not math.isfinite(best)) or val < best:
                    best = val
    return float(best) if math.isfinite(best) else float("nan")


@dataclass
class SminaConfig:
    smina_bin: str = "smina"
    obabel_bin: str = "obabel"
    command_timeout_seconds: int = 120
    exhaustiveness: int = 8
    num_modes: int = 5
    cpu: int = 1
    parallel_jobs: int = 1
    seed: int = 20260419
    pocket_mode: str = "reference_complex_pocket"
    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


class SminaBackend(DockingBackend):
    """
    Minimal smina backend used for fixed-pocket diagnostics.

    It intentionally keeps logic compact and explicit:
    success is true only when command succeeds, output pose exists and score is finite.
    """

    def __init__(self, config: SminaConfig | None = None) -> None:
        self.config = config or SminaConfig()

    def check_capability(self) -> BackendCapability:
        bins = {
            "smina": _resolve_executable(self.config.smina_bin),
            "obabel": _resolve_executable(self.config.obabel_bin),
        }
        return BackendCapability(
            backend_name="smina",
            available=bool(bins["smina"] and bins["obabel"]),
            details=bins,
        )

    def prepare_target(self, target_path: str | Path, work_dir: str | Path) -> Dict[str, Path]:
        src = Path(target_path)
        if not src.exists():
            raise DockingError(f"Missing target file: {src}")
        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)

        receptor_pdbqt = wd / "receptor.pdbqt"
        obabel = _resolve_executable(self.config.obabel_bin)
        if obabel is None:
            raise DockingError("obabel is required for smina receptor preparation")
        conv = run_command([obabel, str(src), "-O", str(receptor_pdbqt)], cwd=wd, timeout=self.config.command_timeout_seconds)
        if conv.returncode != 0 or (not receptor_pdbqt.exists()) or receptor_pdbqt.stat().st_size == 0:
            raise DockingError(f"Failed to prepare receptor.pdbqt for smina: rc={conv.returncode}")

        pocket = resolve_pocket_spec(
            target_path=src,
            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=6.0,
        )
        write_pocket_spec(wd / "pocket.json", pocket)
        return {
            "receptor_pdbqt": receptor_pdbqt,
            "target_prepared": src,
            "target_work_dir": wd,
            "pocket_json": wd / "pocket.json",
        }

    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)
        sdf = prepare_ligand_sdf(ligand_id, smiles, wd / f"{ligand_id}.sdf")
        out = wd / f"{ligand_id}.pdbqt"
        obabel = _resolve_executable(self.config.obabel_bin)
        if obabel is None:
            raise DockingError("obabel is required for smina ligand preparation")
        conv = run_command([obabel, str(sdf), "-O", str(out)], cwd=wd, timeout=self.config.command_timeout_seconds)
        if conv.returncode != 0 or (not out.exists()) or out.stat().st_size == 0:
            raise DockingError(f"Failed to prepare ligand pdbqt for smina `{ligand_id}`: rc={conv.returncode}")
        return out

    def build_site_or_constraints(self, target_context: Dict[str, Path], reference_ligand: Path, work_dir: str | Path) -> Path:
        _ = (target_context, reference_ligand, work_dir)
        return Path()

    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]:
        _ = (allow_mock, require_real_backend)
        cap = self.check_capability()
        if not cap.available:
            raise DockingError(f"smina backend unavailable: {cap.details}")

        wd = Path(work_dir)
        wd.mkdir(parents=True, exist_ok=True)
        receptor = target_context.get("receptor_pdbqt")
        if receptor is None:
            raise DockingError("Missing receptor_pdbqt in target context")

        pocket_json = target_context.get("pocket_json")
        if pocket_json is not None and Path(pocket_json).exists():
            pocket = PocketSpec.from_dict(json.loads(Path(pocket_json).read_text(encoding="utf-8")))
        else:
            pocket = resolve_pocket_spec(
                target_path=target_context.get("target_prepared", receptor),
                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=6.0,
            )
        results: list[DockingResult] = []
        smina = _resolve_executable(self.config.smina_bin)
        if smina is None:
            raise DockingError("smina executable not found")

        def _dock_single(lig: Path) -> DockingResult:
            lid = lig.stem
            out_pose = wd / f"{lid}_smina_out.pdbqt"
            cmd = [
                smina,
                "--receptor",
                str(receptor),
                "--ligand",
                str(lig),
                "--center_x",
                f"{pocket.center[0]:.4f}",
                "--center_y",
                f"{pocket.center[1]:.4f}",
                "--center_z",
                f"{pocket.center[2]:.4f}",
                "--size_x",
                f"{pocket.box_size[0]:.4f}",
                "--size_y",
                f"{pocket.box_size[1]:.4f}",
                "--size_z",
                f"{pocket.box_size[2]:.4f}",
                "--exhaustiveness",
                str(self.config.exhaustiveness),
                "--num_modes",
                str(self.config.num_modes),
                "--cpu",
                str(self.config.cpu),
                "--seed",
                str(self.config.seed),
                "--out",
                str(out_pose),
            ]
            try:
                res = run_command(cmd, cwd=wd, timeout=self.config.command_timeout_seconds)
            except TimeoutExpired as exc:
                return DockingResult(
                    ligand_id=lid,
                    docking_score=float("nan"),
                    pose_path=None,
                    backend_name="smina",
                    backend_mode="real-smina",
                    score_source="smina_timeout",
                    raw_output_file=str(out_pose),
                    parsed_from="timeout",
                    fallback_used=False,
                    success=False,
                    message=f"smina_timeout:{exc}",
                    command=" ".join(cmd),
                    extra={"pocket_spec": pocket.to_dict(), "pose_distance_to_pocket_center": float("nan"), "pose_in_fixed_pocket": False},
                )
            except Exception as exc:
                return DockingResult(
                    ligand_id=lid,
                    docking_score=float("nan"),
                    pose_path=None,
                    backend_name="smina",
                    backend_mode="real-smina",
                    score_source="smina_error",
                    raw_output_file=str(out_pose),
                    parsed_from="exception",
                    fallback_used=False,
                    success=False,
                    message=f"smina_exception:{exc}",
                    command=" ".join(cmd),
                    extra={"pocket_spec": pocket.to_dict(), "pose_distance_to_pocket_center": float("nan"), "pose_in_fixed_pocket": False},
                )
            text = "\n".join([res.stdout or "", res.stderr or ""])
            if out_pose.exists():
                text = f"{text}\n{out_pose.read_text(encoding='utf-8', errors='ignore')}"
            score = parse_smina_score(text)
            centroid = centroid_from_pdbqt(out_pose) if out_pose.exists() else np.asarray([np.nan, np.nan, np.nan], dtype=float)
            distance = pose_distance_to_center(centroid, pocket)
            inside = is_pose_in_pocket(centroid, pocket)
            success = bool(res.returncode == 0 and out_pose.exists() and np.isfinite(score))
            parsed_from = "stdout+stderr+pose::minimizedAffinity_or_vina_result_or_table"
            return DockingResult(
                ligand_id=lid,
                docking_score=float(score) if np.isfinite(score) else float("nan"),
                pose_path=out_pose if out_pose.exists() else None,
                backend_name="smina",
                backend_mode="real-smina",
                score_source="smina_affinity",
                raw_output_file=str(out_pose),
                parsed_from=parsed_from,
                fallback_used=False,
                success=success,
                message="" if success else f"smina_rc={res.returncode}",
                command=" ".join(cmd),
                extra={
                    "pocket_spec": pocket.to_dict(),
                    "pose_distance_to_pocket_center": distance,
                    "pose_in_fixed_pocket": inside,
                },
            )

        jobs = max(1, int(self.config.parallel_jobs))
        if jobs <= 1 or len(ligand_files) <= 1:
            for lig in ligand_files:
                results.append(_dock_single(lig))
        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, Any]]:
        rows: list[dict[str, Any]] = []
        for r in results:
            rows.append(
                {
                    "ligand_id": r.ligand_id,
                    "docking_score": float(r.docking_score),
                    "backend_name": r.backend_name,
                    "backend_mode": r.backend_mode,
                    "score_source": r.score_source,
                    "raw_output_file": r.raw_output_file,
                    "parsed_from": r.parsed_from,
                    "fallback_used": bool(r.fallback_used),
                    "success": bool(r.success),
                    "message": r.message,
                    "command": r.command,
                    "pose_distance_to_pocket_center": float((r.extra or {}).get("pose_distance_to_pocket_center", np.nan)),
                    "pose_in_fixed_pocket": bool((r.extra or {}).get("pose_in_fixed_pocket", False)),
                    "quantity_type": "docking_score",
                }
            )
        return rows

    def extract_interface_features(self, parsed_results: Sequence[dict[str, Any]]) -> list[dict[str, float]]:
        _ = parsed_results
        return []