From 11d9c08c661564a762d3dc2c28190a9b48c008b2 Mon Sep 17 00:00:00 2001 From: Jiahui Chen Date: Wed, 18 Nov 2026 22:46:24 -0600 Subject: [PATCH] M3: prepare receptors and search boxes for M4 (#14, part B) Completes #14. Two of the three things M4 needs can be produced exactly with nothing installed, and the third cannot. - The receptor: our entity's polymer chains, no waters, no ligands, no hydrogens. The collected structure file is never modified, so the bound components are not lost; docking into a site that still holds its ligand finds the ligand. - The search box, per pocket, drawn round the site's own atoms rather than as a fixed cube at its centre, which either clips an elongated site or spends the search on empty volume. A Vina config beside it. - The PDBQT is the part that cannot be faked. Adding polar hydrogens and assigning atom types is what Meeko, OpenBabel and PDB2PQR exist for, and a homemade substitute that merely parses is a receptor that docks and lies about it. A tool on PATH is used and recorded as fidelity 'full'; with none, the default writes the receptor PDB and no PDBQT rather than approximating one. --pdbqt-fallback turns on the built-in converter adapted from Ping Hu's bacteria_structure_docking.py, which is recorded as 'reduced' with its own caveat in every record: it is a smoke test, not a reported result. Receptors are prepared only for structures that passed the quality gate; preparing one M3 already called unusable would hand M4 something to dock that M3 said not to. Path.with_suffix would have eaten the .463 of fig|243273.25.peg.463, so the filename helper appends instead. A test pins it. Co-Authored-By: Claude Opus 5 --- README.md | 2 +- docs/03-m3-fold.md | 33 +++- s2f/common/schema.py | 22 +++ s2f/full_report/render.py | 23 ++- s2f/m3_fold/__main__.py | 39 ++++- s2f/m3_fold/collect.py | 56 +++++++ s2f/m3_fold/mmcif.py | 4 + s2f/m3_fold/receptor.py | 335 ++++++++++++++++++++++++++++++++++++++ tests/test_m3_dry_run.py | 29 ++++ tests/test_m3_receptor.py | 155 ++++++++++++++++++ 10 files changed, 694 insertions(+), 4 deletions(-) create mode 100644 s2f/m3_fold/receptor.py create mode 100644 tests/test_m3_receptor.py diff --git a/README.md b/README.md index dc3a1ab..ca168c1 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Project page: https://niaid-brc-codeathons.github.io/projects/structure-to-funct | --- | --- | --- | | M1 genome | `s2f.m1_genome` | taxon call, CGA submit/poll/parse, quality gate, BV-BRC Data API route, priority ranking, interactive report | | M2 triage | `s2f.m2_triage` | PDB evidence, AlphaFold, knowledge graph, functional annotation, triage scoring with selectable profiles (`--profile`) | -| M3 fold | `s2f.m3_fold` | Collects existing PDB/AFDB structures and applies preliminary quality checks; Pending: new structure prediction, pocket detection, receptor preparation | +| M3 fold | `s2f.m3_fold` | Collects existing PDB/AFDB structures, quality-gates them, defines binding sites from what the homolog binds, and prepares receptors and search boxes; Pending: new structure prediction, pockets for apo structures | | M4 ligands | - | not started | | M5 disease | - | not started | | M6 report | `s2f.m6_report`, `s2f.full_report` | one self-contained HTML report from `report.json`; the full report covers the whole run directory | diff --git a/docs/03-m3-fold.md b/docs/03-m3-fold.md index 94b62cd..2c91eac 100644 --- a/docs/03-m3-fold.md +++ b/docs/03-m3-fold.md @@ -51,13 +51,44 @@ reason — uncovered, not "no pocket exists", the distinction issue #90 draws. T are what a detector such as P2Rank is for; `find_pockets` is where it plugs in, discovered on `PATH` like M2's annotation providers rather than required. +## Receptors and search boxes (issue #14, part B) + +Two of the three things M4 needs can be produced exactly, with nothing installed: + +- **The receptor.** Our entity's polymer chains, first model, no waters, no ligands, no + hydrogens, written as PDB. The bound components stay in the collected structure file, + which is never modified — docking into a site that still holds its ligand finds the ligand. +- **The search box**, per pocket, drawn round the site's *own* atoms (the lining residues and + the bound component together) with 4 Å of padding and a 16 Å floor on each axis. A fixed + cube at the pocket centre is the usual shortcut, and it either clips an elongated site or + spends the search on empty volume. A Vina config is written beside it; M3 runs no docking. + +**The PDBQT is the part that cannot be faked.** Assigning atom types and adding the polar +hydrogens Vina needs is what Meeko, OpenBabel and PDB2PQR exist for, and a homemade +substitute that merely parses is a receptor that docks and lies about it. So: + +| `receptor.fidelity` | When | What M4 should do | +| --- | --- | --- | +| `full` | a preparation tool was on `PATH` (`mk_prepare_receptor.py`, then `obabel`) | use it | +| `pdb_only` | no tool, the default | prepare it yourself; M3 wrote no PDBQT rather than approximating one | +| `reduced` | `--pdbqt-fallback` was passed | smoke test only, never a reported result | +| `none` | no polymer atoms could be read | nothing to dock | + +`--pdbqt-fallback` turns on the built-in converter adapted from Ping Hu's +`bacteria_structure_docking.py`: AutoDock atom types, no added hydrogens, zero partial +charges. Every record it writes says so. `--no-receptors` skips this step entirely. + +Receptors are prepared only for structures that passed the quality gate. Preparing one M3 +has already called unusable would hand M4 something to dock that M3 said not to. + ## Steps 1. `collect_existing()` — copy or download PDB/AFDB structures; prefer experimental, prefer holo. 2. `predict_missing()` — one job per protein; record model, version, seed. 3. `quality_gate()` — mean pLDDT and per-region confidence; trim or mask low-confidence tails; if the whole model is poor, set `usable_for_docking: false`. 4. `find_pockets()` — read the holo template's own site (above). P2Rank for the rest, and superposition for a site held in an entry other than the collected one, are not built yet. -5. `prep_receptors()` — protonation and PDBQT for M4, saved per protein. +5. `prep_receptors()` — receptor PDB and search box per pocket, always; PDBQT where a + preparation tool exists (above). Protonation and PDB2PQR are not built yet. ## Acceptance checks diff --git a/s2f/common/schema.py b/s2f/common/schema.py index 453b888..e90d6aa 100644 --- a/s2f/common/schema.py +++ b/s2f/common/schema.py @@ -283,6 +283,9 @@ }, }, "score": {"type": ["number", "null"]}, + # The search box M4 docks in, drawn round the site's own atoms. + "box": {"type": ["object", "null"]}, + "vina_config": {"type": ["string", "null"]}, "center": { "type": ["array", "null"], "items": {"type": "number"}, @@ -300,6 +303,25 @@ }, }, "pocket_search": {"type": ["object", "null"]}, + # The prepared receptor (#14 part B). `fidelity` is the honesty flag M4 must + # read: "full" came from a real preparation tool, "reduced" from the + # built-in converter and is not fit for a reported result, "pdb_only" means + # no PDBQT was written rather than one being approximated. + "receptor": { + "type": ["object", "null"], + "properties": { + "pdb_path": {"type": ["string", "null"]}, + "pdbqt_path": {"type": ["string", "null"]}, + "prepared_by": {"type": "string"}, + "fidelity": { + "type": "string", + "enum": ["full", "reduced", "pdb_only", "none"], + }, + "reason": {"type": "string"}, + }, + "required": ["prepared_by", "fidelity"], + "additionalProperties": True, + }, "usable_for_docking": {"type": ["boolean", "null"]}, "reason": {"type": ["string", "null"]}, }, diff --git a/s2f/full_report/render.py b/s2f/full_report/render.py index 175c9ec..a3fa7e1 100644 --- a/s2f/full_report/render.py +++ b/s2f/full_report/render.py @@ -553,7 +553,7 @@ def tab_structures(report: dict[str, Any]) -> str: keys: list[str] = [] for preferred in ("feature_id", "source", "accession", "entry_id", "method", "resolution", "confidence", "plddt", "coverage", "quality", - "usable", "reason", "pockets", "pocket_count", "path"): + "usable", "reason", "pockets", "pocket_count", "receptor", "path"): if any(preferred in row for row in structures): keys.append(preferred) for row in structures: @@ -583,6 +583,8 @@ def tab_structures(report: dict[str, Any]) -> str: value = row.get(key) if key == "pockets": cells.append(f"{_pocket_cell(row)}") + elif key == "receptor": + cells.append(f"{_receptor_cell(row)}") elif isinstance(value, (dict, list)): cells.append(f"{esc(json.dumps(value)[:120])}") else: @@ -879,3 +881,22 @@ def _pocket_cell(structure: dict[str, Any]) -> str: line += "…" if len(residues) > 6 else "" parts.append(line) return "
" + "
".join(parts) + "
" + + +#: What each receptor fidelity means to someone reading the report (#14 part B). +_FIDELITY = { + "full": ("ready", "prepared by a docking tool"), + "reduced": ("smoke test only", "built-in converter: no added hydrogens, zero charges"), + "pdb_only": ("no PDBQT", "no preparation tool was available; none was approximated"), + "none": ("none", "no receptor could be built"), +} + + +def _receptor_cell(structure: dict[str, Any]) -> str: + receptor = _mapping(structure.get("receptor")) + if not receptor: + return "" + label, note = _FIDELITY.get(str(receptor.get("fidelity")), ("", "")) + prepared_by = esc(str(receptor.get("prepared_by") or "")) + return (f"{esc(label)} · {prepared_by}" + f"
{esc(note)}") diff --git a/s2f/m3_fold/__main__.py b/s2f/m3_fold/__main__.py index 6415d43..bedbf31 100644 --- a/s2f/m3_fold/__main__.py +++ b/s2f/m3_fold/__main__.py @@ -80,7 +80,13 @@ def fetch(candidate: StructureCandidate) -> DownloadedFile: min_local_plddt=args.min_local_plddt, ) summary = collect_existing( - report, run_dir, fetch, limit=args.limit, quality_thresholds=quality_thresholds + report, + run_dir, + fetch, + limit=args.limit, + quality_thresholds=quality_thresholds, + receptors=args.receptors, + pdbqt_fallback=args.pdbqt_fallback, ) update_section(run_dir, "structures", summary.structures) _write_manifest( @@ -190,6 +196,22 @@ def _write_manifest( "holo_template_preferred": sum( 1 for record in summary.structures if record.get("template_preference") ), + "receptors_prepared": sum( + 1 + for record in summary.structures + if (record.get("receptor") or {}).get("pdb_path") + ), + "receptors_docking_ready": sum( + 1 + for record in summary.structures + if (record.get("receptor") or {}).get("fidelity") == "full" + ), + "search_boxes": sum( + 1 + for record in summary.structures + for pocket in record.get("pockets") or [] + if pocket.get("box") + ), }, "failures": [ {"feature_id": record["feature_id"], "reason": record.get("reason")} @@ -267,6 +289,21 @@ def build_parser() -> argparse.ArgumentParser: default=70.0, help="mask AFDB residues below this pLDDT (default: 70)", ) + + docking = parser.add_argument_group("receptor preparation (#14)") + docking.add_argument( + "--no-receptors", + dest="receptors", + action="store_false", + help="skip receptor and search-box preparation for M4", + ) + docking.add_argument( + "--pdbqt-fallback", + action="store_true", + help="write a PDBQT with the built-in converter when no preparation tool is on " + "PATH: AutoDock types but no added hydrogens and zero charges, so the result " + "is recorded as reduced fidelity and is a smoke test, not a docking result", + ) return parser diff --git a/s2f/m3_fold/collect.py b/s2f/m3_fold/collect.py index 26c4bb3..54a0a4b 100644 --- a/s2f/m3_fold/collect.py +++ b/s2f/m3_fold/collect.py @@ -15,6 +15,7 @@ from ..common.http import DownloadedFile from .pockets import find_pockets +from .receptor import available_tool, docking_box, prepare_receptor, vina_config from .quality import QualityThresholds, assess_structure PDB_DOWNLOAD_URL = "https://files.rcsb.org/download/{entry_id}.cif" @@ -155,6 +156,9 @@ def collect_existing( *, limit: int = 0, quality_thresholds: QualityThresholds | None = None, + receptors: bool = True, + pdbqt_fallback: bool = False, + find_tool: Callable[[], str | None] = available_tool, clock: Callable[[], float] = time.monotonic, now: Callable[[], datetime] = _utc_now, ) -> CollectionSummary: @@ -212,6 +216,16 @@ def collect_existing( ) record["pockets"] = pockets record["pocket_search"] = pocket_summary + if receptors and quality.usable_for_docking: + _prepare_for_docking( + record, + payload, + candidate=candidate, + run_dir=run_dir, + pockets=pockets, + allow_fallback=pdbqt_fallback, + find_tool=find_tool, + ) record.update( path=str(destination.relative_to(run_dir)), sha256=hashlib.sha256(payload).hexdigest(), @@ -352,3 +366,45 @@ def _atomic_write(path: Path, payload: bytes) -> None: except BaseException: Path(handle.name).unlink(missing_ok=True) raise + + +def _prepare_for_docking( + record: dict[str, Any], + payload: bytes, + *, + candidate: StructureCandidate, + run_dir: Path, + pockets: list[dict[str, Any]], + allow_fallback: bool, + find_tool: Callable[[], str | None], +) -> None: + """Write the receptor and a search box per pocket (#14 part B). + + Only for a structure that passed the quality gate: preparing a receptor M3 has already + called unusable would hand M4 something to dock that M3 said not to. + """ + stem = run_dir / "receptors" / _safe_name(candidate.feature_id) + entity = candidate.accession.split("_", 1)[1] if "_" in candidate.accession else "" + prepared = prepare_receptor( + payload, + entity_id=entity if candidate.source == "pdb" else "", + destination_stem=stem, + run_dir=run_dir, + allow_fallback=allow_fallback, + find_tool=find_tool, + ) + record["receptor"] = prepared.as_dict() + + docking_target = prepared.pdbqt_path or prepared.pdb_path + for index, pocket in enumerate(pockets, 1): + box = docking_box(payload, pocket) + if box is None: + continue + pocket["box"] = box + if not pocket.get("usable") or not docking_target: + continue + config = stem.parent / f"{stem.name}_pocket_{index:02d}.vina.txt" + config.write_text( + vina_config(box, Path(docking_target).name), encoding="utf-8" + ) + pocket["vina_config"] = str(config.relative_to(run_dir)) diff --git a/s2f/m3_fold/mmcif.py b/s2f/m3_fold/mmcif.py index 7002fc9..44a3fef 100644 --- a/s2f/m3_fold/mmcif.py +++ b/s2f/m3_fold/mmcif.py @@ -101,6 +101,10 @@ class Atom: def has_coordinates(self) -> bool: return None not in (self.x, self.y, self.z) + def b_iso_value(self) -> float: + """The B_iso column for writing out, 0.0 when the file carried none.""" + return 0.0 if self.b_factor is None else self.b_factor + def read_atoms(payload: bytes, *, first_model_only: bool = True) -> list[Atom]: """Every atom of the first model, or an empty list if the file cannot be read.""" diff --git a/s2f/m3_fold/receptor.py b/s2f/m3_fold/receptor.py new file mode 100644 index 0000000..34d9dbd --- /dev/null +++ b/s2f/m3_fold/receptor.py @@ -0,0 +1,335 @@ +"""Docking-ready receptors and search boxes for M4 (issue #14, part B). + +Two of the three things M4 needs can be produced exactly, with no external tool: a cleaned +receptor and a search box drawn around the site M3 defined. The third, a PDBQT, cannot — +assigning atom types and adding the polar hydrogens Vina needs is what Meeko, OpenBabel and +PDB2PQR exist for, and a homemade substitute that merely *parses* is a receptor that docks +and lies about it. + +So the default is: always write the receptor PDB and the box; write a PDBQT when a real +preparation tool is on PATH; otherwise say so and write none. `--pdbqt-fallback` turns on the +built-in converter adapted from Ping Hu's `bacteria_structure_docking.py`, which produces a +geometrically valid PDBQT with AutoDock atom types, no added hydrogens and zero charges. That +is enough for a smoke test and not enough for a result; every record it writes carries +`fidelity: "reduced"` and the reason, and M4 is expected to refuse it unless asked. +""" + +from __future__ import annotations + +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Iterable + +from .mmcif import Atom, entity_chains, read_atoms + +#: Padding added around the site's own atoms to give a ligand room to move. Vina's own +#: guidance is a box a little larger than the ligand; 4 A each side is the usual starting +#: point and is recorded in every box record rather than assumed. +BOX_PADDING = 4.0 + +#: No box smaller than this on any axis: a tight site would otherwise leave no room to search. +MIN_BOX_EDGE = 16.0 + +#: Preparation tools, best first. Meeko is AutoDock's own; OpenBabel is the common fallback. +PDBQT_TOOLS = ("mk_prepare_receptor.py", "obabel") + + +@dataclass(frozen=True) +class PreparedReceptor: + """What was written for one structure, and what it is fit for.""" + + pdb_path: str | None + pdbqt_path: str | None + prepared_by: str + fidelity: str + reason: str + chains: list[str] + atoms: int + + def as_dict(self) -> dict[str, Any]: + return { + "pdb_path": self.pdb_path, + "pdbqt_path": self.pdbqt_path, + "prepared_by": self.prepared_by, + "fidelity": self.fidelity, + "reason": self.reason, + "chains": self.chains, + "atoms": self.atoms, + } + + +def available_tool() -> str | None: + """The first receptor-preparation tool on PATH, or None. + + Discovery only: nothing here is installed, and no path is hard-coded, the same contract + M2's annotation providers keep. + """ + for tool in PDBQT_TOOLS: + if shutil.which(tool): + return tool + return None + + +def receptor_atoms(payload: bytes, entity_id: str = "") -> list[Atom]: + """The polymer atoms a receptor is built from: our entity, first model, no solvent. + + Ligands and waters are dropped because docking into a site that still contains its + ligand finds the ligand. The bound components stay in the collected structure file, + which is never modified, so nothing is lost. + """ + chains = entity_chains(payload, entity_id) if entity_id else set() + return [ + atom + for atom in read_atoms(payload) + if not atom.is_hetatm + and atom.has_coordinates + and (not chains or atom.chain in chains) + and not _is_hydrogen(atom) + ] + + +def _is_hydrogen(atom: Atom) -> bool: + name = atom.atom_id.strip() + return name.startswith("H") or (len(name) > 1 and name[0].isdigit() and name[1] == "H") + + +def write_receptor_pdb(atoms: Iterable[Atom], destination: Path) -> int: + """Write the receptor as PDB, the format every preparation tool reads. Returns atoms.""" + destination.parent.mkdir(parents=True, exist_ok=True) + lines = [] + for serial, atom in enumerate(atoms, 1): + name = atom.atom_id[:4] + # PDB column rules: a one- or two-letter element starts in column 14, not 13. + padded = f" {name:<3}" if len(name) < 4 else name + element = _element(atom) + lines.append( + f"ATOM {serial:>5} {padded}{'':1}{atom.comp_id[:3]:>3} " + f"{(atom.auth_chain or atom.chain)[:1]:>1}" + f"{(atom.auth_seq_id or atom.seq_id or 0):>4}{'':1} " + f"{atom.x:>8.3f}{atom.y:>8.3f}{atom.z:>8.3f}" + f"{1.00:>6.2f}{(atom.b_iso_value()):>6.2f}{'':10}{element:>2}" + ) + lines.append("END") + destination.write_text("\n".join(lines) + "\n", encoding="utf-8") + return len(lines) - 1 + + +def _with_extension(stem: Path, extension: str) -> Path: + """Append an extension. `Path.with_suffix` would eat the `.463` of a feature id.""" + return stem.with_name(stem.name + extension) + + +def _element(atom: Atom) -> str: + name = atom.atom_id.strip() + for character in name: + if character.isalpha(): + return character.upper() + return "C" + + +# --- AutoDock typing, adapted from Ping Hu's bacteria_structure_docking.py ---------------- + +#: Carbons in aromatic rings are type A, not C; AutoDock scores them differently. +_AROMATIC_CARBONS = { + "PHE": {"CG", "CD1", "CD2", "CE1", "CE2", "CZ"}, + "TYR": {"CG", "CD1", "CD2", "CE1", "CE2", "CZ"}, + "HIS": {"CG", "CD2", "CE1"}, + "TRP": {"CG", "CD1", "CD2", "CE2", "CE3", "CZ2", "CZ3", "CH2"}, +} + + +def autodock_type(atom_name: str, residue: str, element: str) -> str: + if element == "C": + return "A" if atom_name in _AROMATIC_CARBONS.get(residue, ()) else "C" + if element == "N": + return "NA" if residue == "HIS" and atom_name in {"ND1", "NE2"} else "N" + return {"O": "OA", "S": "SA", "P": "P"}.get(element, element or "C") + + +def write_pdbqt_fallback(atoms: Iterable[Atom], destination: Path) -> int: + """A PDBQT with AutoDock types, no hydrogens and zero charges. Reduced fidelity, stated.""" + destination.parent.mkdir(parents=True, exist_ok=True) + lines = [] + for serial, atom in enumerate(atoms, 1): + element = _element(atom) + name = atom.atom_id.strip()[:4] + padded = f" {name:<3}" if len(name) < 4 else name + lines.append( + f"ATOM {serial:>5} {padded}{'':1}{atom.comp_id[:3]:>3} " + f"{(atom.auth_chain or atom.chain)[:1]:>1}" + f"{(atom.auth_seq_id or atom.seq_id or 0):>4}{'':1} " + f"{atom.x:>8.3f}{atom.y:>8.3f}{atom.z:>8.3f}" + f"{1.00:>6.2f}{atom.b_iso_value():>6.2f} +0.000 " + f"{autodock_type(name, atom.comp_id[:3], element):<2}" + ) + lines.append("END") + destination.write_text("\n".join(lines) + "\n", encoding="utf-8") + return len(lines) - 1 + + +def run_preparation_tool(tool: str, pdb_path: Path, destination: Path) -> tuple[bool, str]: + """Convert with a real preparation tool. Returns (wrote_a_file, message).""" + if tool == "obabel": + command = ["obabel", str(pdb_path), "-O", str(destination), "-xr"] + else: + base = str(destination)[: -len(".pdbqt")] if str(destination).endswith(".pdbqt") else str(destination) + command = [tool, "--read_pdb", str(pdb_path), "-o", base, "-p"] + try: + finished = subprocess.run(command, capture_output=True, text=True, timeout=300) + except (OSError, subprocess.SubprocessError) as exc: + return False, f"{tool} failed: {exc}" + stem = destination.name[: -len(".pdbqt")] if destination.name.endswith(".pdbqt") else destination.name + candidates = [destination, destination.with_name(stem + "_rigid.pdbqt")] + for candidate in candidates: + if candidate.exists() and candidate.stat().st_size: + if candidate != destination: + candidate.replace(destination) + return True, f"prepared with {tool}" + detail = (finished.stderr or finished.stdout or "").strip().splitlines() + return False, f"{tool} produced no PDBQT" + (f": {detail[-1]}" if detail else "") + + +def prepare_receptor( + payload: bytes, + *, + entity_id: str, + destination_stem: Path, + run_dir: Path, + allow_fallback: bool = False, + find_tool: Callable[[], str | None] = available_tool, +) -> PreparedReceptor: + """Write the receptor for one structure, and a PDBQT where that can be done honestly.""" + atoms = receptor_atoms(payload, entity_id) + if not atoms: + return PreparedReceptor( + pdb_path=None, + pdbqt_path=None, + prepared_by="none", + fidelity="none", + reason="no polymer atoms could be read for this entity", + chains=[], + atoms=0, + ) + + pdb_path = _with_extension(destination_stem, ".pdb") + written = write_receptor_pdb(atoms, pdb_path) + chains = sorted({atom.auth_chain or atom.chain for atom in atoms}) + relative = str(pdb_path.relative_to(run_dir)) + + pdbqt_path = _with_extension(destination_stem, ".pdbqt") + tool = find_tool() + if tool: + ok, message = run_preparation_tool(tool, pdb_path, pdbqt_path) + if ok: + return PreparedReceptor( + pdb_path=relative, + pdbqt_path=str(pdbqt_path.relative_to(run_dir)), + prepared_by=tool, + fidelity="full", + reason=message, + chains=chains, + atoms=written, + ) + reason = message + else: + reason = ( + "no receptor preparation tool on PATH (" + ", ".join(PDBQT_TOOLS) + ")" + ) + + if not allow_fallback: + return PreparedReceptor( + pdb_path=relative, + pdbqt_path=None, + prepared_by="none", + fidelity="pdb_only", + reason=reason + "; receptor PDB written, PDBQT skipped rather than approximated", + chains=chains, + atoms=written, + ) + + write_pdbqt_fallback(atoms, pdbqt_path) + return PreparedReceptor( + pdb_path=relative, + pdbqt_path=str(pdbqt_path.relative_to(run_dir)), + prepared_by="builtin_fallback", + fidelity="reduced", + reason=( + reason + "; built-in converter used: AutoDock atom types, but no added " + "hydrogens and zero partial charges. Fit for a pipeline smoke test, not for a " + "reported docking result" + ), + chains=chains, + atoms=written, + ) + + +# --- search boxes ------------------------------------------------------------------------- + + +def docking_box( + payload: bytes, + pocket: dict[str, Any], + *, + padding: float = BOX_PADDING, + minimum_edge: float = MIN_BOX_EDGE, +) -> dict[str, Any] | None: + """A search box around one pocket's own atoms, not a fixed cube at its centre. + + Drawn from the lining residues and the bound component together, so the box follows the + shape of the real site. A cube centred on the ligand is the usual shortcut and it either + clips an elongated site or wastes search volume on a compact one. + """ + residues = pocket.get("residues") or [] + if not residues: + return None + wanted = { + (str(residue.get("chain")), str(residue.get("auth_seq_id"))) + for residue in residues + if isinstance(residue, dict) + } + if not wanted: + return None + + component = str(pocket.get("component") or "") + points = [ + atom + for atom in read_atoms(payload) + if atom.has_coordinates + and ( + ((atom.auth_chain or atom.chain), str(atom.auth_seq_id)) in wanted + or (atom.is_hetatm and component and atom.comp_id == component) + ) + ] + if not points: + return None + + box: dict[str, Any] = {"padding": padding, "minimum_edge": minimum_edge} + for axis, values in ( + ("x", [atom.x for atom in points]), + ("y", [atom.y for atom in points]), + ("z", [atom.z for atom in points]), + ): + low, high = min(values), max(values) + size = max((high - low) + 2 * padding, minimum_edge) + box[f"center_{axis}"] = round((low + high) / 2, 3) + box[f"size_{axis}"] = round(size, 3) + box["atoms"] = len(points) + return box + + +def vina_config(box: dict[str, Any], receptor: str, *, exhaustiveness: int = 8, + num_modes: int = 9) -> str: + """The box as an AutoDock Vina config file. + + Written for M4 to use or ignore; M3 runs no docking. Exhaustiveness and the mode count + are Vina's own defaults, recorded here so a run states them rather than inheriting them. + """ + return ( + f"receptor = {receptor}\n" + f"center_x = {box['center_x']}\ncenter_y = {box['center_y']}\n" + f"center_z = {box['center_z']}\n" + f"size_x = {box['size_x']}\nsize_y = {box['size_y']}\nsize_z = {box['size_z']}\n" + f"exhaustiveness = {exhaustiveness}\nnum_modes = {num_modes}\n" + ) diff --git a/tests/test_m3_dry_run.py b/tests/test_m3_dry_run.py index 3ab4fd3..d21c034 100644 --- a/tests/test_m3_dry_run.py +++ b/tests/test_m3_dry_run.py @@ -75,3 +75,32 @@ def test_the_dry_run_defines_a_site_from_the_holo_fixture(tmp_path: Path) -> Non assert counts["with_pocket"] == 1 assert counts["usable_pockets"] == 1 assert counts["cofactor_required_pockets"] == 0 + + +def test_the_dry_run_prepares_a_receptor_and_a_box(tmp_path: Path) -> None: + """#14 part B, offline and with no preparation tool required.""" + run_dir = tmp_path / "run" + assert main(["--dry-run", "--run", str(run_dir), "--no-receptors"]) == 0 + assert not (run_dir / "receptors").exists() + + run_dir = tmp_path / "with" + assert main(["--dry-run", "--run", str(run_dir)]) == 0 + + holo = [r for r in read_report(run_dir)["structures"] if r["accession"] == "6MU0_1"][0] + receptor = holo["receptor"] + assert receptor["chains"] == ["A"] + assert receptor["atoms"] > 100 + # The feature id ends in a number, which must survive the filename. + assert receptor["pdb_path"].endswith("peg.463.pdb") + assert (run_dir / receptor["pdb_path"]).exists() + # Fidelity depends on what is installed, so assert the honesty rule, not the tool. + assert receptor["fidelity"] in {"full", "pdb_only", "reduced"} + if receptor["fidelity"] == "pdb_only": + assert receptor["pdbqt_path"] is None + + box = holo["pockets"][0]["box"] + assert {"center_x", "size_x", "atoms"} <= set(box) + + counts = json.loads((run_dir / "m3_fold" / "run.json").read_text())["counts"] + assert counts["receptors_prepared"] == 1 + assert counts["search_boxes"] == 1 diff --git a/tests/test_m3_receptor.py b/tests/test_m3_receptor.py new file mode 100644 index 0000000..e2c69c8 --- /dev/null +++ b/tests/test_m3_receptor.py @@ -0,0 +1,155 @@ +"""Receptors and search boxes for M4 (issue #14, part B). + +No test here depends on a preparation tool being installed: `find_tool` is injected, so the +suite behaves the same on a node with OpenBabel and on CI without it. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from s2f.m3_fold.receptor import (autodock_type, docking_box, prepare_receptor, + receptor_atoms, vina_config) +from s2f.m3_fold.pockets import find_pockets + +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures/m3/6MU0.cif" +NO_TOOL = lambda: None # noqa: E731 - a stand-in for a node with nothing installed +FAKE_TOOL = lambda: "obabel" # noqa: E731 + + +@pytest.fixture +def payload() -> bytes: + return FIXTURE.read_bytes() + + +@pytest.fixture +def pocket(payload: bytes) -> dict: + pockets, _ = find_pockets( + payload, + source="pdb", + holo_template={"pdb_entity": "6MU0_1", "ligands": ["5RP"], "metals": []}, + structure_accession="6MU0_1", + ) + return pockets[0] + + +def test_the_receptor_is_our_entity_without_solvent_or_ligand(payload: bytes) -> None: + atoms = receptor_atoms(payload, "1") + + assert atoms + assert {atom.auth_chain for atom in atoms} == {"A"} + # Docking into a site that still holds its ligand finds the ligand. + assert not any(atom.comp_id == "5RP" for atom in atoms) + assert not any(atom.comp_id == "HOH" for atom in atoms) + assert not any(atom.atom_id.startswith("H") for atom in atoms) + + +def test_without_a_preparation_tool_no_pdbqt_is_invented(tmp_path: Path, payload: bytes) -> None: + prepared = prepare_receptor( + payload, entity_id="1", destination_stem=tmp_path / "p", run_dir=tmp_path, + find_tool=NO_TOOL) + + assert prepared.pdb_path == "p.pdb" + assert prepared.pdbqt_path is None + assert prepared.fidelity == "pdb_only" + assert "skipped rather than approximated" in prepared.reason + assert (tmp_path / "p.pdb").exists() + + +def test_the_fallback_converter_says_what_it_is(tmp_path: Path, payload: bytes) -> None: + prepared = prepare_receptor( + payload, entity_id="1", destination_stem=tmp_path / "p", run_dir=tmp_path, + find_tool=NO_TOOL, allow_fallback=True) + + assert prepared.fidelity == "reduced" + assert prepared.prepared_by == "builtin_fallback" + assert "no added" in prepared.reason and "hydrogens" in prepared.reason + assert "not for a reported docking result" in prepared.reason + line = (tmp_path / "p.pdbqt").read_text().splitlines()[0] + assert line.startswith("ATOM") + assert "+0.000" in line + + +def test_a_feature_id_ending_in_a_number_keeps_it(tmp_path: Path, payload: bytes) -> None: + """`Path.with_suffix` treats the `.463` of fig|...peg.463 as an extension and eats it.""" + prepared = prepare_receptor( + payload, entity_id="1", destination_stem=tmp_path / "fig_243273.25.peg.463", + run_dir=tmp_path, find_tool=NO_TOOL) + + assert prepared.pdb_path == "fig_243273.25.peg.463.pdb" + assert (tmp_path / "fig_243273.25.peg.463.pdb").exists() + + +def test_a_structure_with_no_readable_atoms_prepares_nothing(tmp_path: Path) -> None: + prepared = prepare_receptor( + b"data_X\n#\n", entity_id="1", destination_stem=tmp_path / "p", run_dir=tmp_path, + find_tool=NO_TOOL) + + assert prepared.pdb_path is None + assert prepared.fidelity == "none" + assert not list(tmp_path.iterdir()) + + +def test_a_tool_that_writes_nothing_is_not_reported_as_success( + tmp_path: Path, payload: bytes, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "s2f.m3_fold.receptor.run_preparation_tool", lambda *_, **__: (False, "obabel broke")) + + prepared = prepare_receptor( + payload, entity_id="1", destination_stem=tmp_path / "p", run_dir=tmp_path, + find_tool=FAKE_TOOL) + + assert prepared.pdbqt_path is None + assert prepared.fidelity == "pdb_only" + assert "obabel broke" in prepared.reason + + +# --- search boxes ------------------------------------------------------------------------- + + +def test_the_box_is_drawn_round_the_site_not_a_cube_at_its_centre( + payload: bytes, pocket: dict +) -> None: + box = docking_box(payload, pocket) + + assert box is not None + # A real site is not a cube: the axes differ, which a fixed-size box cannot express. + assert len({box["size_x"], box["size_y"], box["size_z"]}) > 1 + assert all(box[f"size_{axis}"] >= 16.0 for axis in "xyz") + # The ligand sits inside the box it defines. + centre = pocket["center"] + for value, axis in zip(centre, "xyz"): + assert abs(value - box[f"center_{axis}"]) <= box[f"size_{axis}"] / 2 + + +def test_a_tight_site_still_gets_a_searchable_box(payload: bytes) -> None: + single = {"component": "", "residues": [ + {"chain": "A", "auth_seq_id": "11", "comp_id": "HIS"}]} + + box = docking_box(payload, single, padding=0.0) + + assert box is not None + assert box["size_x"] == box["size_y"] == box["size_z"] == 16.0 + + +def test_a_pocket_with_no_residues_has_no_box(payload: bytes) -> None: + assert docking_box(payload, {"residues": []}) is None + + +def test_the_vina_config_states_its_own_parameters(payload: bytes, pocket: dict) -> None: + config = vina_config(docking_box(payload, pocket), "receptor.pdbqt") + + assert "receptor = receptor.pdbqt" in config + assert "exhaustiveness = 8" in config + assert "num_modes = 9" in config + + +def test_aromatic_carbons_are_typed_apart_from_aliphatic_ones() -> None: + assert autodock_type("CG", "PHE", "C") == "A" + assert autodock_type("CB", "PHE", "C") == "C" + assert autodock_type("ND1", "HIS", "N") == "NA" + assert autodock_type("N", "ALA", "N") == "N" + assert autodock_type("OD1", "ASP", "O") == "OA"