File size: 12,570 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
from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
from rdkit import Chem

POCKET_MODE_USER_FIXED = "user_fixed_pocket"
POCKET_MODE_REFERENCE = "reference_complex_pocket"
POCKET_MODE_REFERENCE_RELAXED = "reference_complex_pocket_relaxed"
SUPPORTED_POCKET_MODES = {
    POCKET_MODE_USER_FIXED,
    POCKET_MODE_REFERENCE,
    POCKET_MODE_REFERENCE_RELAXED,
}


@dataclass(frozen=True)
class PocketSpec:
    mode: str
    center: tuple[float, float, float]
    radius: float
    box_size: tuple[float, float, float]
    reference_ligand_id: str | None = None
    relaxation_margin: float = 0.0
    source: str = "unknown"
    notes: str = ""

    def to_dict(self) -> dict[str, Any]:
        return {
            "mode": self.mode,
            "center": list(self.center),
            "radius": float(self.radius),
            "box_size": list(self.box_size),
            "reference_ligand_id": self.reference_ligand_id or "",
            "relaxation_margin": float(self.relaxation_margin),
            "source": self.source,
            "notes": self.notes,
        }

    @classmethod
    def from_dict(cls, payload: dict[str, Any]) -> "PocketSpec":
        center = _parse_vector3(payload.get("center"), field_name="center")
        box = _parse_vector3(payload.get("box_size"), field_name="box_size")
        return cls(
            mode=str(payload.get("mode", POCKET_MODE_REFERENCE)),
            center=center,
            radius=float(payload.get("radius", 6.0)),
            box_size=box,
            reference_ligand_id=str(payload.get("reference_ligand_id", "")).strip() or None,
            relaxation_margin=float(payload.get("relaxation_margin", 0.0)),
            source=str(payload.get("source", "unknown")),
            notes=str(payload.get("notes", "")),
        )


def _parse_vector3(value: Any, field_name: str) -> tuple[float, float, float]:
    if value is None:
        raise ValueError(f"{field_name} is required")
    if isinstance(value, str):
        text = value.replace(";", ",").replace(" ", "")
        parts = [x for x in text.split(",") if x]
        if len(parts) != 3:
            raise ValueError(f"{field_name} must contain 3 values, got: {value}")
        return (float(parts[0]), float(parts[1]), float(parts[2]))

    if isinstance(value, (tuple, list)) and len(value) == 3:
        return (float(value[0]), float(value[1]), float(value[2]))

    raise ValueError(f"{field_name} must be a length-3 sequence")


def _derive_center_radius_box(
    coords: np.ndarray,
    relaxation_margin: float,
    fallback_radius: float,
) -> tuple[tuple[float, float, float], float, tuple[float, float, float]]:
    if coords.size == 0:
        raise ValueError("cannot derive pocket from empty coordinates")
    center = coords.mean(axis=0)
    max_dist = float(np.linalg.norm(coords - center, axis=1).max()) if coords.shape[0] > 0 else 0.0
    radius = max(float(fallback_radius), max_dist + 2.0 + float(relaxation_margin))
    half_box = max(radius, 8.0)
    box = (2.0 * half_box, 2.0 * half_box, 2.0 * half_box)
    return (float(center[0]), float(center[1]), float(center[2])), float(radius), box


def _extract_receptor_atom_coords(target_path: str | Path) -> np.ndarray:
    coords: list[list[float]] = []
    for ln in Path(target_path).read_text(encoding="utf-8", errors="ignore").splitlines():
        if not ln.startswith("ATOM"):
            continue
        try:
            x = float(ln[30:38])
            y = float(ln[38:46])
            z = float(ln[46:54])
        except Exception:
            continue
        coords.append([x, y, z])
    return np.asarray(coords, dtype=float)


def extract_reference_ligand_coords(
    target_path: str | Path,
    pocket_reference_ligand_id: str | None,
) -> tuple[np.ndarray, dict[str, Any]]:
    path = Path(target_path)
    ligand_filter = (pocket_reference_ligand_id or "").strip().upper()
    grouped: dict[tuple[str, str, str, str], list[list[float]]] = {}
    residues: dict[tuple[str, str, str, str], str] = {}
    for ln in path.read_text(encoding="utf-8", errors="ignore").splitlines():
        if not ln.startswith("HETATM"):
            continue
        resn = ln[17:20].strip().upper()
        if not resn or resn in {"HOH", "WAT", "DOD", "SO4"}:
            continue
        if ligand_filter and resn != ligand_filter:
            continue
        try:
            x = float(ln[30:38])
            y = float(ln[38:46])
            z = float(ln[46:54])
        except Exception:
            continue
        chain = ln[21:22].strip()
        resseq = ln[22:26].strip()
        ins = ln[26:27].strip()
        key = (resn, chain, resseq, ins)
        grouped.setdefault(key, []).append([x, y, z])
        residues[key] = resn

    if not grouped:
        return np.asarray([], dtype=float), {
            "selected_resname": "",
            "selected_chain": "",
            "selected_resseq": "",
            "selected_atom_count": 0,
        }

    selected = max(grouped, key=lambda k: len(grouped[k]))
    coords = np.asarray(grouped[selected], dtype=float)
    return coords, {
        "selected_resname": residues[selected],
        "selected_chain": selected[1],
        "selected_resseq": selected[2],
        "selected_atom_count": int(coords.shape[0]),
    }


def resolve_pocket_spec(
    *,
    target_path: str | Path,
    pocket_mode: str | None = None,
    pocket_center: Any = None,
    pocket_box_size: Any = None,
    pocket_radius: float | None = None,
    pocket_reference_ligand_id: str | None = None,
    pocket_relaxation_margin: float = 0.0,
    fallback_radius: float = 6.0,
) -> PocketSpec:
    mode = str(pocket_mode or POCKET_MODE_REFERENCE).strip()
    if mode not in SUPPORTED_POCKET_MODES:
        raise ValueError(f"Unsupported pocket_mode `{mode}`. Supported: {sorted(SUPPORTED_POCKET_MODES)}")

    # Explicit center + shape always wins over inferred modes.
    if pocket_center is not None and (pocket_radius is not None or pocket_box_size is not None):
        center = _parse_vector3(pocket_center, field_name="pocket_center")
        radius = float(pocket_radius) if pocket_radius is not None else float(max(_parse_vector3(pocket_box_size, "pocket_box_size")) / 2.0)
        box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius)
        return PocketSpec(
            mode=POCKET_MODE_USER_FIXED,
            center=center,
            radius=float(radius),
            box_size=box,
            reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None,
            relaxation_margin=0.0,
            source="user_explicit_override",
            notes="Explicit pocket center/size provided by user; inferred modes skipped.",
        )

    if mode == POCKET_MODE_USER_FIXED:
        center = _parse_vector3(pocket_center, field_name="pocket_center")
        if pocket_radius is None and pocket_box_size is None:
            raise ValueError("user_fixed_pocket requires pocket_radius or pocket_box_size")
        radius = float(pocket_radius) if pocket_radius is not None else float(max(_parse_vector3(pocket_box_size, "pocket_box_size")) / 2.0)
        box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius)
        return PocketSpec(
            mode=POCKET_MODE_USER_FIXED,
            center=center,
            radius=float(radius),
            box_size=box,
            reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None,
            relaxation_margin=0.0,
            source="user_fixed_pocket",
            notes="Fixed pocket from explicit user configuration.",
        )

    margin = float(pocket_relaxation_margin if mode == POCKET_MODE_REFERENCE_RELAXED else 0.0)
    coords, meta = extract_reference_ligand_coords(target_path=target_path, pocket_reference_ligand_id=pocket_reference_ligand_id)
    if coords.size > 0:
        center, derived_radius, box = _derive_center_radius_box(coords, relaxation_margin=margin, fallback_radius=fallback_radius)
        radius = float(pocket_radius) if pocket_radius is not None else float(derived_radius)
        if pocket_box_size is not None:
            box = _parse_vector3(pocket_box_size, "pocket_box_size")
        return PocketSpec(
            mode=mode,
            center=center,
            radius=float(radius),
            box_size=box,
            reference_ligand_id=meta.get("selected_resname") or (str(pocket_reference_ligand_id).strip() if pocket_reference_ligand_id else None),
            relaxation_margin=float(margin),
            source="reference_complex_ligand",
            notes=(
                "Fixed pocket from crystal ligand coordinates "
                f"(resname={meta.get('selected_resname', '')}, atoms={meta.get('selected_atom_count', 0)})."
            ),
        )

    receptor_coords = _extract_receptor_atom_coords(target_path)
    if receptor_coords.size == 0:
        raise ValueError("Cannot resolve fixed pocket: no reference ligand and no receptor atom coordinates found")
    center = receptor_coords.mean(axis=0)
    radius = float(pocket_radius) if pocket_radius is not None else float(fallback_radius)
    box = _parse_vector3(pocket_box_size, "pocket_box_size") if pocket_box_size is not None else (2.0 * radius, 2.0 * radius, 2.0 * radius)
    return PocketSpec(
        mode=mode,
        center=(float(center[0]), float(center[1]), float(center[2])),
        radius=float(radius),
        box_size=box,
        reference_ligand_id=str(pocket_reference_ligand_id or "").strip() or None,
        relaxation_margin=float(margin),
        source="receptor_centroid_fallback",
        notes="Reference ligand not found; deterministic receptor-centroid fixed pocket fallback used.",
    )


def write_pocket_spec(path: str | Path, spec: PocketSpec) -> Path:
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(json.dumps(spec.to_dict(), indent=2), encoding="utf-8")
    return p


def load_pocket_spec(path: str | Path) -> PocketSpec:
    payload = json.loads(Path(path).read_text(encoding="utf-8"))
    return PocketSpec.from_dict(payload)


def centroid_from_sdf(path: str | Path) -> np.ndarray:
    mols = Chem.SDMolSupplier(str(path), removeHs=False)
    mol = mols[0] if mols and len(mols) > 0 else None
    if mol is None or mol.GetNumConformers() == 0:
        return np.asarray([np.nan, np.nan, np.nan], dtype=float)
    conf = mol.GetConformer()
    pts = []
    for i in range(mol.GetNumAtoms()):
        p = conf.GetAtomPosition(i)
        pts.append([p.x, p.y, p.z])
    if not pts:
        return np.asarray([np.nan, np.nan, np.nan], dtype=float)
    return np.asarray(pts, dtype=float).mean(axis=0)


def centroid_from_pdbqt(path: str | Path) -> np.ndarray:
    pts: list[list[float]] = []
    text = Path(path).read_text(encoding="utf-8", errors="ignore")
    has_models = "MODEL" in text
    in_model = False
    for ln in text.splitlines():
        if ln.startswith("MODEL"):
            in_model = True
            continue
        if ln.startswith("ENDMDL"):
            break
        if has_models and (not in_model):
            continue
        if not ln.startswith(("ATOM", "HETATM")):
            continue
        try:
            x = float(ln[30:38])
            y = float(ln[38:46])
            z = float(ln[46:54])
        except Exception:
            continue
        pts.append([x, y, z])
    if not pts:
        return np.asarray([np.nan, np.nan, np.nan], dtype=float)
    return np.asarray(pts, dtype=float).mean(axis=0)


def pose_distance_to_center(centroid: np.ndarray, spec: PocketSpec) -> float:
    if centroid.size != 3 or not np.isfinite(centroid).all():
        return float("nan")
    center = np.asarray(spec.center, dtype=float)
    return float(np.linalg.norm(centroid - center))


def is_pose_in_pocket(centroid: np.ndarray, spec: PocketSpec) -> bool:
    if centroid.size != 3 or not np.isfinite(centroid).all():
        return False
    center = np.asarray(spec.center, dtype=float)
    box = np.asarray(spec.box_size, dtype=float)
    if box.size == 3 and np.isfinite(box).all():
        inside_box = bool(np.all(np.abs(centroid - center) <= (box / 2.0)))
    else:
        inside_box = False
    if inside_box:
        return True
    dist = float(np.linalg.norm(centroid - center))
    return bool(np.isfinite(dist) and dist <= float(spec.radius))