Download libs/docking/backend_smina.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/docking/backend_smina.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/libs/docking/backend_smina.py
-
curl -L -o backend_smina.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/docking/backend_smina.py
13.8 kB
| 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") | |
| 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 [] | |