Download libs/docking/plip_interactions.py from QPromaQ/Docking_project: direct link, hf CLI and curl.
- Browser
- Download file 7.16 kB
-
https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/docking/plip_interactions.py
- Command line
-
hf download hf://datasets/QPromaQ/Docking_project/libs/docking/plip_interactions.py
-
curl -L -o plip_interactions.py https://huggingface.co/datasets/QPromaQ/Docking_project/resolve/main/libs/docking/plip_interactions.py
7.16 kB
| from __future__ import annotations | |
| import json | |
| import shutil | |
| from dataclasses import dataclass, asdict | |
| from pathlib import Path | |
| from subprocess import TimeoutExpired | |
| from typing import Any | |
| from libs.utils.subprocess_utils import run_command | |
| class PLIPInteractionSummary: | |
| available: bool | |
| success: bool | |
| source: str | |
| interaction_score: float | |
| interaction_count: int | |
| hydrophobic_count: int = 0 | |
| hbond_count: int = 0 | |
| saltbridge_count: int = 0 | |
| pistacking_count: int = 0 | |
| pication_count: int = 0 | |
| halogen_count: int = 0 | |
| waterbridge_count: int = 0 | |
| metal_count: int = 0 | |
| ligand_key: str = "" | |
| complex_pdb: str = "" | |
| message: str = "" | |
| def to_dict(self) -> dict[str, Any]: | |
| return asdict(self) | |
| def plip_import_available() -> bool: | |
| try: | |
| from plip.structure.preparation import PDBComplex # noqa: F401 | |
| return True | |
| except Exception: | |
| return False | |
| def _failed(message: str, *, available: bool | None = None) -> PLIPInteractionSummary: | |
| return PLIPInteractionSummary( | |
| available=plip_import_available() if available is None else bool(available), | |
| success=False, | |
| source="plip", | |
| interaction_score=0.0, | |
| interaction_count=0, | |
| message=message, | |
| ) | |
| def _rewrite_ligand_pdb_lines(text: str) -> list[str]: | |
| out: list[str] = [] | |
| atom_serial = 9000 | |
| for raw in text.splitlines(): | |
| if not raw.startswith(("ATOM", "HETATM")): | |
| continue | |
| line = raw.ljust(80) | |
| atom_serial += 1 | |
| rewritten = ( | |
| "HETATM" | |
| + f"{atom_serial:5d}" | |
| + line[11:17] | |
| + "LIG" | |
| + " Z" | |
| + f"{1:4d}" | |
| + line[26:] | |
| ) | |
| out.append(rewritten[:80]) | |
| return out | |
| def _receptor_pdb_lines(receptor_pdb: Path) -> list[str]: | |
| lines: list[str] = [] | |
| for raw in receptor_pdb.read_text(encoding="utf-8", errors="ignore").splitlines(): | |
| if raw.startswith(("ATOM", "TER")): | |
| lines.append(raw[:80]) | |
| return lines | |
| def _pose_sdf_to_pdb(pose_sdf: Path, out_pdb: Path, *, timeout_seconds: int) -> Path: | |
| obabel = shutil.which("obabel") | |
| if obabel is None: | |
| raise RuntimeError("obabel executable is required for PLIP ligand conversion") | |
| result = run_command([obabel, str(pose_sdf), "-O", str(out_pdb), "-f", "1", "-l", "1"], cwd=out_pdb.parent, timeout=timeout_seconds) | |
| if result.returncode != 0 or not out_pdb.exists() or out_pdb.stat().st_size == 0: | |
| raise RuntimeError(f"obabel SDF->PDB conversion failed: rc={result.returncode}, stderr={result.stderr.strip()}") | |
| return out_pdb | |
| def _build_complex_pdb(receptor_pdb: Path, ligand_pdb: Path, complex_pdb: Path) -> Path: | |
| receptor_lines = _receptor_pdb_lines(receptor_pdb) | |
| ligand_lines = _rewrite_ligand_pdb_lines(ligand_pdb.read_text(encoding="utf-8", errors="ignore")) | |
| if not receptor_lines: | |
| raise RuntimeError(f"PLIP receptor PDB has no ATOM/HETATM records: {receptor_pdb}") | |
| if not ligand_lines: | |
| raise RuntimeError(f"PLIP ligand PDB has no atom records: {ligand_pdb}") | |
| complex_pdb.write_text("\n".join(receptor_lines + ["TER"] + ligand_lines + ["END", ""]) , encoding="utf-8") | |
| return complex_pdb | |
| def _count_attr(interaction_set: Any, attr: str) -> int: | |
| return len(getattr(interaction_set, attr, []) or []) | |
| def _score_counts( | |
| *, | |
| hydrophobic_count: int, | |
| hbond_count: int, | |
| saltbridge_count: int, | |
| pistacking_count: int, | |
| pication_count: int, | |
| halogen_count: int, | |
| waterbridge_count: int, | |
| metal_count: int, | |
| ) -> float: | |
| raw = ( | |
| 0.05 * hydrophobic_count | |
| + 0.14 * hbond_count | |
| + 0.16 * saltbridge_count | |
| + 0.12 * pistacking_count | |
| + 0.12 * pication_count | |
| + 0.10 * halogen_count | |
| + 0.06 * waterbridge_count | |
| + 0.20 * metal_count | |
| ) | |
| return max(0.0, min(1.0, float(raw))) | |
| def analyze_pose_with_plip( | |
| *, | |
| receptor_pdb: Path, | |
| pose_sdf: Path, | |
| ligand_id: str, | |
| work_dir: Path, | |
| timeout_seconds: int = 120, | |
| ) -> PLIPInteractionSummary: | |
| if not plip_import_available(): | |
| return _failed("PLIP Python package is not importable", available=False) | |
| try: | |
| from plip.structure.preparation import PDBComplex | |
| except Exception as exc: # pragma: no cover | |
| return _failed(f"PLIP import failed: {exc}", available=False) | |
| try: | |
| work_dir.mkdir(parents=True, exist_ok=True) | |
| ligand_pdb = _pose_sdf_to_pdb(pose_sdf, work_dir / f"{ligand_id}_plip_ligand.pdb", timeout_seconds=timeout_seconds) | |
| complex_pdb = _build_complex_pdb(receptor_pdb, ligand_pdb, work_dir / f"{ligand_id}_plip_complex.pdb") | |
| complex_obj = PDBComplex() | |
| complex_obj.load_pdb(str(complex_pdb)) | |
| ligand = next((item for item in complex_obj.ligands if str(getattr(item, "hetid", "")).strip() == "LIG"), None) | |
| if ligand is None and complex_obj.ligands: | |
| ligand = complex_obj.ligands[0] | |
| if ligand is None: | |
| return _failed(f"PLIP found no ligand in generated complex {complex_pdb}", available=True) | |
| complex_obj.characterize_complex(ligand) | |
| interaction_set = next(iter(complex_obj.interaction_sets.values()), None) | |
| if interaction_set is None: | |
| return _failed(f"PLIP produced no interaction set for {ligand_id}", available=True) | |
| hbond_count = _count_attr(interaction_set, "hbonds_ldon") + _count_attr(interaction_set, "hbonds_pdon") | |
| saltbridge_count = _count_attr(interaction_set, "saltbridges_lneg") + _count_attr(interaction_set, "saltbridges_pneg") | |
| pication_count = _count_attr(interaction_set, "pication_laro") + _count_attr(interaction_set, "pication_paro") | |
| counts = { | |
| "hydrophobic_count": _count_attr(interaction_set, "hydrophobic_contacts"), | |
| "hbond_count": hbond_count, | |
| "saltbridge_count": saltbridge_count, | |
| "pistacking_count": _count_attr(interaction_set, "pistacking"), | |
| "pication_count": pication_count, | |
| "halogen_count": _count_attr(interaction_set, "halogen_bonds"), | |
| "waterbridge_count": _count_attr(interaction_set, "water_bridges"), | |
| "metal_count": _count_attr(interaction_set, "metal_complexes"), | |
| } | |
| interaction_count = int(sum(counts.values())) | |
| summary = PLIPInteractionSummary( | |
| available=True, | |
| success=True, | |
| source="plip", | |
| interaction_score=_score_counts(**counts), | |
| interaction_count=interaction_count, | |
| ligand_key=str(next(iter(complex_obj.interaction_sets.keys()), "")), | |
| complex_pdb=str(complex_pdb), | |
| **counts, | |
| ) | |
| (work_dir / f"{ligand_id}_plip_summary.json").write_text(json.dumps(summary.to_dict(), indent=2), encoding="utf-8") | |
| return summary | |
| except TimeoutExpired as exc: | |
| return _failed(f"PLIP ligand conversion timed out: {exc}", available=True) | |
| except Exception as exc: | |
| return _failed(f"PLIP analysis failed: {exc}", available=True) | |