| 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)}") |
|
|
| |
| 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)) |
|
|