Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
33 changes: 32 additions & 1 deletion docs/03-m3-fold.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
22 changes: 22 additions & 0 deletions s2f/common/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand All @@ -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"]},
},
Expand Down
23 changes: 22 additions & 1 deletion s2f/full_report/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -583,6 +583,8 @@ def tab_structures(report: dict[str, Any]) -> str:
value = row.get(key)
if key == "pockets":
cells.append(f"<td>{_pocket_cell(row)}</td>")
elif key == "receptor":
cells.append(f"<td>{_receptor_cell(row)}</td>")
elif isinstance(value, (dict, list)):
cells.append(f"<td>{esc(json.dumps(value)[:120])}</td>")
else:
Expand Down Expand Up @@ -879,3 +881,22 @@ def _pocket_cell(structure: dict[str, Any]) -> str:
line += "&hellip;</span>" if len(residues) > 6 else "</span>"
parts.append(line)
return "<div>" + "</div><div>".join(parts) + "</div>"


#: 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"<b>{esc(label)}</b> &middot; {prepared_by}"
f"<br><span class='muted'>{esc(note)}</span>")
39 changes: 38 additions & 1 deletion s2f/m3_fold/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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")}
Expand Down Expand Up @@ -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


Expand Down
56 changes: 56 additions & 0 deletions s2f/m3_fold/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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))
4 changes: 4 additions & 0 deletions s2f/m3_fold/mmcif.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
Loading
Loading