From 35c4ed28d755a762918b8c59444b647a19e7585f Mon Sep 17 00:00:00 2001 From: AJPreto Date: Fri, 25 Sep 2026 16:12:46 +0000 Subject: [PATCH 1/4] Diffdock on the same chains of the other PLBP methods --- Makefile | 7 +- README.md | 27 + build_sweep_table.py | 27 + guild/analysis/posebusters.py | 23 +- guild/bulk.py | 25 +- guild/constants/diffdock.py | 37 ++ guild/docking/diffdock.py | 741 +++++++++++++------------ guild/docking/gnina.py | 5 +- guild/docking/vina.py | 10 +- guild/support/diffdock_model_args.yaml | 6 +- guild/tools/bulk.py | 88 +-- guild/transformers/converters.py | 13 +- pyproject.toml | 2 +- run_native_rmsd.py | 231 ++++++++ run_posebusters.py | 39 ++ scripts/run_guild.py | 15 + tests/bulk_run/test_diffdock_pocket.py | 285 ++++++++++ uv.lock | 2 +- 18 files changed, 1139 insertions(+), 444 deletions(-) create mode 100644 build_sweep_table.py create mode 100644 run_native_rmsd.py create mode 100644 run_posebusters.py create mode 100644 tests/bulk_run/test_diffdock_pocket.py diff --git a/Makefile b/Makefile index 3cd8f16..9f3a471 100644 --- a/Makefile +++ b/Makefile @@ -112,6 +112,11 @@ _POSEBUSTERS_CONFIG_FLAG = $(if $(POSEBUSTERS_CONFIG),--posebusters-config $(POS EXCLUDE_NON_PHYSICAL ?= _EXCLUDE_NON_PHYSICAL_FLAG = $(if $(EXCLUDE_NON_PHYSICAL),--exclude-non-physical,) +# DiffDock pocket restriction: auto (default; pocket box when available, blind +# otherwise), box (pocket required), or blind (ignore any box). +DIFFDOCK_POCKET ?= +_DIFFDOCK_POCKET_FLAG = $(if $(DIFFDOCK_POCKET),--diffdock-pocket $(DIFFDOCK_POCKET),) + # Internal docker run flags reused across targets. # Mounts a generated /etc/passwd so pwd.getpwuid() works for the host UID # (required by PyTorch / boltz inside the container). @@ -140,7 +145,7 @@ _NO_DECOYS_FLAG = $(if $(NO_DECOYS),--no-decoys,) _BOX_FLAG = $(if $(BOX),--box $(BOX),) _N_WORKERS_FLAG = $(if $(N_WORKERS),--n-workers $(N_WORKERS),) _VINA_EXHAUSTIVENESS_FLAG = $(if $(VINA_EXHAUSTIVENESS),--vina-exhaustiveness $(VINA_EXHAUSTIVENESS),) -_OPTIONAL_FLAGS = $(_CLEAN_FLAG) $(_KNOWN_BINDERS_FLAG) $(_HEAD_FLAG) $(_DECOYS_FLAG) $(_NO_DECOYS_FLAG) $(_BOX_FLAG) $(_N_WORKERS_FLAG) $(_NO_GPU_FLAG) $(_GNINA_INPUT_MODE_FLAG) $(_FLEXIBLE_DOCKING_FLAG) $(_FLEXRES_GNINA_FLAG) $(_VINA_EXHAUSTIVENESS_FLAG) $(_POSES_DIR_FLAG) $(_POSE_MODE_FLAG) $(_NO_POSEBUSTERS_FLAG) $(_POSEBUSTERS_CONFIG_FLAG) $(_EXCLUDE_NON_PHYSICAL_FLAG) +_OPTIONAL_FLAGS = $(_CLEAN_FLAG) $(_KNOWN_BINDERS_FLAG) $(_HEAD_FLAG) $(_DECOYS_FLAG) $(_NO_DECOYS_FLAG) $(_BOX_FLAG) $(_N_WORKERS_FLAG) $(_NO_GPU_FLAG) $(_GNINA_INPUT_MODE_FLAG) $(_FLEXIBLE_DOCKING_FLAG) $(_FLEXRES_GNINA_FLAG) $(_VINA_EXHAUSTIVENESS_FLAG) $(_POSES_DIR_FLAG) $(_POSE_MODE_FLAG) $(_NO_POSEBUSTERS_FLAG) $(_POSEBUSTERS_CONFIG_FLAG) $(_EXCLUDE_NON_PHYSICAL_FLAG) $(_DIFFDOCK_POCKET_FLAG) # Generate an /etc/passwd that includes the container's original entries plus # the host user. This fixes pwd.getpwuid() failures for LDAP/SSSD users diff --git a/README.md b/README.md index 46fb82f..1717c83 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ make run-vina \ | `NO_POSEBUSTERS` | *(empty)* | Set to `1` to skip the PoseBusters pose-validity step. On by default (mirrors PLIP): ~400ms/pose, and adds `_pb_valid`/`_pb_pose` to `guild_scores.txt`. See [PoseBusters](#posebusters). | | `POSEBUSTERS_CONFIG` | *(empty → `dock`)* | `dock` \| `dock_fast`. `dock_fast` skips the `internal_energy` conformer-ensemble check — a lever worth trying on large/very flexible ligand sets. | | `EXCLUDE_NON_PHYSICAL` | *(empty)* | Set to `1` to null non-physical Vina-family raw scores (e.g. a positive binding energy) before ranking, for a **new** run. Off by default — see [Raw score plausibility](#raw-score-plausibility). | +| `DIFFDOCK_POCKET` | *(empty → `auto`)* | `auto` \| `box` \| `blind`. How DiffDock's pose is restricted to the pocket. `auto` keeps the highest-confidence sample whose centroid lies inside the combination's pocket box, and falls back to blind selection when no pocket exists; `box` requires a pocket (no box, or no sample inside it, scores NaN); `blind` ignores any box. DiffDock always docks into the prepared receptor chain(s), in every mode. See [DiffDock pocket restriction](#diffdock-pocket-restriction). | | `MIN_MOL_WT` | `250` | Minimum molecular weight filter for known-binder expansion | | `MAX_MOL_WT` | `450` | Maximum molecular weight filter for known-binder expansion | | `CHEMBL_VERSION` | `chembl_36` | ChEMBL version string used for known-binder lookup | @@ -458,6 +459,32 @@ All four are in kcal/mol (lower = stronger predicted binding), independently ran protein. The gnina tracks also emit `gnina_rescore_*_cnn_score` as a confidence side channel, which is not ranked. +DiffDock poses are locally minimised before both rescores (Vina `optimize()`, gnina +`--local_only`), against the same prepared receptor DiffDock docked into, with hydrogens added +to the heavy-atom-only ligand. A DiffDock pose with no receptor heavy atom within 4 Å scores +NaN instead of the near-zero energy an empty grid would return. + +### DiffDock pocket restriction + +DiffDock is a blind docker with no pocket argument. Guild gives it the same prepared receptor +as Vina and gnina (`proteins/_single_chain_clean.pdb`: the receptor chain(s) only), so +partner chains in the deposited file (G proteins, antibodies, fusion domains) are never +searched. Whether the chosen pose must lie in the pocket is set by `DIFFDOCK_POCKET` +(`--diffdock-pocket`): + +| Mode | Pocket box present | No pocket box | +|------|--------------------|---------------| +| `auto` (default) | highest-confidence sample whose heavy-atom centroid is inside the box | highest-confidence sample | +| `box` | as `auto` | failure (NaN) | +| `blind` | highest-confidence sample | highest-confidence sample | + +A combination whose samples all fall outside the box scores NaN (`no_sample_in_box`). The +outcome is recorded per combination in the `diffdock_pose_selection` column (`box`, `blind`, +`no_sample_in_box`, `no_box`, `no_samples`) and in +`batches//diffdock/results//selected_pose.json`. The DiffDock confidence +score, both rescores, the complex PDB and PoseBusters all use that same pose. Use `box` for +benchmarks, so a missing pocket can never silently become blind docking. + > **Rank-percentile orientation.** Every `rp_*_score` and the `global_rp_score` is bounded to > `(0, 1]` with **0 = best**. A ligand that is uniquely best for a protein scores `1 / n` and the > uniquely worst `1.0`, but ties share their average rank, so tied extremes fall short of those diff --git a/build_sweep_table.py b/build_sweep_table.py new file mode 100644 index 0000000..dc30687 --- /dev/null +++ b/build_sweep_table.py @@ -0,0 +1,27 @@ +import pandas as pd + +TARGETS = [ + "7l1v-R-XGD-R", "7v3z-A-9GF-A", "4ea3-A-0NN-A", "6ot0-R-CO1-R", "6me6-A-JEY-A", + "8gdc-R-P2E-R", "6ds0-A-H8M-A", "5o9h-A-9P2-A", "5tud-A-ERM-A", "7jvr-R-08Y-R", +] +N_PER_TARGET = 100 +SEED = 42 + +df = pd.read_csv("vinarun_all_combinations.csv", low_memory=False) +df = df[df.protein_config_id.isin(TARGETS)].copy() + +# Deterministic: sort by ligand_id first so the sample does not depend on row order. +picked = ( + df.sort_values(["protein_config_id", "ligand_id"]) + .groupby("protein_config_id", group_keys=False) + .apply(lambda g: g.sample(n=min(N_PER_TARGET, len(g)), random_state=SEED)) + .sort_values(["protein_config_id", "ligand_id"]) +) + +# Repoint protein_path at this machine's mount. +picked["protein_path"] = "/workspace/data/" + picked["protein_id"] + ".pdb" + +picked.to_csv("combinations.csv", index=False) +print(f"rows: {len(picked)} targets: {picked.protein_config_id.nunique()}") +print(picked.groupby("protein_config_id").size().to_string()) +print(picked.ligand_category.value_counts().to_string()) diff --git a/guild/analysis/posebusters.py b/guild/analysis/posebusters.py index df4d7ee..eb1ce80 100644 --- a/guild/analysis/posebusters.py +++ b/guild/analysis/posebusters.py @@ -15,7 +15,6 @@ not check". """ -import glob import logging import multiprocessing as mp import os @@ -65,6 +64,7 @@ POSEBUSTERS_MAX_POSES, POSEBUSTERS_REPORT_ID_COLUMNS, ) +from guild.docking.diffdock import _diffdock_samples, read_selected_pose from guild.tools.pose_molecules import ( mol_from_pdb_block, mols_from_sdf, @@ -112,19 +112,16 @@ def _pose_mols( poses = [mol_from_pdb_block(b, smiles) for b in split_pdbqt_models(pdbqt_path)] elif docking_method == DIFFDOCK_PREFIX: - # Confidence from the filename matches how the complex PDB picked its - # pose, and avoids the rank lexicographic trap (rank10 < rank2). + # The recorded selection (the pose in the complex PDB and behind every + # DiffDock score) comes first; the remaining samples follow by + # confidence for the escalate/all scopes. results_dir = f"{method_folder}/results/{combination_id}" - scored = [] - for path in glob.glob(f"{results_dir}/*_confidence*.sdf"): - try: - confidence = float( - os.path.basename(path).split("_confidence")[1].replace(".sdf", "") - ) - except (IndexError, ValueError): - continue - scored.append((confidence, path)) - for _, path in sorted(scored, key=lambda item: item[0], reverse=True): + ordered = [path for _, path in _diffdock_samples(results_dir)] + selection = read_selected_pose(results_dir) + if selection and selection.get("sdf") in ordered: + ordered.remove(selection["sdf"]) + ordered.insert(0, selection["sdf"]) + for path in ordered: poses.extend(mols_from_sdf(path, smiles)) if not poses: diff --git a/guild/bulk.py b/guild/bulk.py index ba576ac..81aed1f 100644 --- a/guild/bulk.py +++ b/guild/bulk.py @@ -43,7 +43,10 @@ SMILES_NAMES_DICTIONARY_KEY, ) from guild.constants.diffdock import ( + DEFAULT_DIFFDOCK_POCKET, DIFFDOCK_COMBINATIONS_FILE, + DIFFDOCK_POCKET_KEY, + DIFFDOCK_POCKET_MODES, DIFFDOCK_RESULTS_FOLDER, ) from guild.constants.guild import ( @@ -337,6 +340,7 @@ def __init__( pose_mode=DEFAULT_POSE_MODE, flexible_docking: bool = False, flexres_gnina: str = None, + diffdock_pocket: str = DEFAULT_DIFFDOCK_POCKET, ): """ BulkRun class for running multiple docking simulations and performing guild scoring. @@ -384,6 +388,12 @@ def __init__( gnina's ``--flexres`` flag (e.g. ``"A:88,91"`` or ``"A:88,91_B:7"``). Applied to every row; when set it takes precedence over the automatic box/flexdist selection that ``flexible_docking`` uses. + :param diffdock_pocket: How DiffDock's pose is restricted to the pocket. + ``"auto"`` (default) keeps the highest-confidence sample inside the + pocket box when the combination has one and falls back to blind + selection when it does not; ``"box"`` requires a pocket box (no box, + or no sample inside it, is a failure); ``"blind"`` ignores any box. + DiffDock always docks into the prepared receptor chain(s). """ # Pathing variables @@ -402,6 +412,11 @@ def __init__( self.n_workers = n_workers if n_workers is not None else mp.cpu_count() self.vina_exhaustiveness = vina_exhaustiveness self.predict_binding_pocket = predict_binding_pocket + if diffdock_pocket not in DIFFDOCK_POCKET_MODES: + raise ValueError( + f"Invalid diffdock_pocket={diffdock_pocket!r}; expected one of {DIFFDOCK_POCKET_MODES}." + ) + self.diffdock_pocket = diffdock_pocket if "_" in project_name: raise ValueError("Project name cannot contain underscores!") @@ -478,10 +493,7 @@ def __init__( self.methods_to_run = list(self.methods_to_run) + [GNINA_RESCORE_BOLTZ_PREFIX] # boltz_affinity isn't a docking method (no docking step of its own, # like the rescore tracks above) — listed only so scoring ranks/votes it. - if ( - BOLTZ_PREFIX in self.methods_to_run - and BOLTZ_AFFINITY_PREFIX not in self.methods_to_run - ): + if BOLTZ_PREFIX in self.methods_to_run and BOLTZ_AFFINITY_PREFIX not in self.methods_to_run: self.methods_to_run = list(self.methods_to_run) + [BOLTZ_AFFINITY_PREFIX] # Resolve gnina_input_mode against the (now auto-extended) methods @@ -692,6 +704,7 @@ def _generate_batched_dictionary(self, input_table, batch_size=1000): current_batch_table=current_batch_table, batch_folder=batch_folder, ) + self.batched_dictionary[current_batch][DIFFDOCK_POCKET_KEY] = self.diffdock_pocket self.batched_dictionary[current_batch] = identify_previously_ran_combinations( current_batch=current_batch, @@ -2125,7 +2138,7 @@ def run_interactions_analysis(self, methods_to_analyze=None): logger.info( f"PLIP/ProLIF coverage: {sorted(unsupported)} produce no complex " f"PDB by design and are excluded from interaction analysis — " - f"structurally not applicable, not \"analyzed and found nothing\"." + f'structurally not applicable, not "analyzed and found nothing".' ) logger.info("Starting interactions analysis") @@ -2431,7 +2444,7 @@ def run_pose_validity_analysis( logger.info( f"PoseBusters coverage: {unsupported} produce no complex PDB by " f"design and are excluded from pose validity — structurally not " - f"applicable, not \"checked and passed\". Validating: {supported}." + f'applicable, not "checked and passed". Validating: {supported}.' ) logger.info( diff --git a/guild/constants/diffdock.py b/guild/constants/diffdock.py index 2042161..146d179 100644 --- a/guild/constants/diffdock.py +++ b/guild/constants/diffdock.py @@ -21,3 +21,40 @@ COMPLEX_NAME = "complex_name" LIGAND_DESCRIPTION = "ligand_description" PROTEIN_SEQUENCE = "protein_sequence" + +""" +Pocket restriction +""" +# auto: restrict to the pocket box when one exists, otherwise blind. +# box: a pocket box is required; no box or no sample inside it is a failure. +# blind: ignore any box and keep DiffDock's top-confidence sample. +DIFFDOCK_POCKET_AUTO = "auto" +DIFFDOCK_POCKET_BOX = "box" +DIFFDOCK_POCKET_BLIND = "blind" +DIFFDOCK_POCKET_MODES = (DIFFDOCK_POCKET_AUTO, DIFFDOCK_POCKET_BOX, DIFFDOCK_POCKET_BLIND) +DEFAULT_DIFFDOCK_POCKET = DIFFDOCK_POCKET_AUTO + +# Batch-dictionary key carrying the pocket mode to the scoring/complex helpers. +DIFFDOCK_POCKET_KEY = "diffdock_pocket" + +# Per-combination record of which sample was chosen and why, so the score, +# both rescores, the complex PDB and PoseBusters all describe the same pose. +SELECTED_POSE_FILE = "selected_pose.json" + +# Outcomes written to the diffdock_pose_selection column. +POSE_SELECTED_BOX = "box" +POSE_SELECTED_BLIND = "blind" +POSE_NO_SAMPLE_IN_BOX = "no_sample_in_box" +POSE_NO_BOX = "no_box" +POSE_NO_SAMPLES = "no_samples" + +# A rescored pose with no receptor heavy atom within this distance (Å) is not +# bound to the receptor; its score is reported as NaN rather than ~0. +RECEPTOR_CONTACT_CUTOFF = 4.0 + +# Side-channel column in the scores table; not a score, never ranked. +DIFFDOCK_POSE_SELECTION = "diffdock_pose_selection" + +# Prepared receptor written by Guild prep (receptor chain(s), altlocs +# collapsed, Vina/box frame): {proteins}/{protein_conf_id}{suffix}.pdb/.pdbqt +CLEAN_RECEPTOR_SUFFIX = "_single_chain_clean" diff --git a/guild/docking/diffdock.py b/guild/docking/diffdock.py index 6509c66..b4bc93a 100644 --- a/guild/docking/diffdock.py +++ b/guild/docking/diffdock.py @@ -2,12 +2,15 @@ Diffdock support functions """ +import glob +import json import logging import os import subprocess import numpy as np import pandas as pd +from rdkit import Chem from tqdm import tqdm from guild.constants.bulk import ( @@ -16,17 +19,33 @@ COMBINATIONS_TO_RUN_KEY, ) from guild.constants.diffdock import ( + CLEAN_RECEPTOR_SUFFIX, COMPLEX_NAME, + DEFAULT_DIFFDOCK_POCKET, DIFFDOCK_ARGS_FILE, DIFFDOCK_COMBINATIONS_FILE, DIFFDOCK_DIRECTORY, + DIFFDOCK_POCKET_AUTO, + DIFFDOCK_POCKET_BLIND, + DIFFDOCK_POCKET_BOX, + DIFFDOCK_POCKET_KEY, + DIFFDOCK_POCKET_MODES, + DIFFDOCK_POSE_SELECTION, DIFFDOCK_RESULTS_FOLDER, LIGAND_DESCRIPTION, + POSE_NO_BOX, + POSE_NO_SAMPLE_IN_BOX, + POSE_NO_SAMPLES, + POSE_SELECTED_BLIND, + POSE_SELECTED_BOX, PROTEIN_PATH, PROTEIN_SEQUENCE, + RECEPTOR_CONTACT_CUTOFF, + SELECTED_POSE_FILE, ) from guild.constants.general import RANDOM_SEED from guild.constants.guild import ( + BOXES_FOLDER, DIFFDOCK_FOLDER, DIFFDOCK_SCORE, GNINA_RESCORE_DIFFDOCK_CNN_SCORE, @@ -43,13 +62,14 @@ PYTHON_EXECUTABLE, SUPPORT_FOLDER, ) +from guild.constants.vina import VINA_BOXES_FOLDER from guild.docking.gnina import gnina_score_pose from guild.docking.vina import ( compute_box_from_sdf, + get_center_and_size_from_box_file, vina_score_pose, ) -from guild.tools.preparation import _normalize_chain_list -from guild.transformers.converters import sdf_to_pdbqt +from guild.transformers.converters import protein_pdb_to_pdbqt, sdf_to_pdbqt logger = logging.getLogger(__name__) @@ -71,33 +91,167 @@ def generate_diffdock_table( return output_csv -def process_diffdock_files(combination, diffdock_folder): +def clean_receptor_path(batch_folder: str, protein_conf_id: str, extension: str = "pdb") -> str: + """Prepared receptor Guild writes during prep, in the Vina/pocket-box frame.""" + return os.path.join( + batch_folder, PROTEINS_FOLDER, f"{protein_conf_id}{CLEAN_RECEPTOR_SUFFIX}.{extension}" + ) + + +def _diffdock_samples(combo_dir: str) -> list: + """``(confidence, sdf_path)`` for every DiffDock sample, highest confidence first. + + Confidence comes from the ``rank_confidence.sdf`` filename, which + avoids the lexicographic rank trap (``rank10`` sorts before ``rank2``). """ - Process the diffdock csv files to retrieve the highest scores for each pdb - :param input_combination: combination to process - :param diffdock_folder: folder containing the diffdock results - :param mode: single or bulk, depending on the input. If single, the ligand and protein names are the same for all rows. If bulk, the ligand and protein names are extracted from the pdb_id + if not os.path.isdir(combo_dir): + return [] + samples = [] + for fname in os.listdir(combo_dir): + if "_confidence" not in fname or not fname.endswith(".sdf"): + continue + try: + confidence = float(fname.split("_confidence")[1].replace(".sdf", "")) + except ValueError: + continue + samples.append((confidence, os.path.join(combo_dir, fname))) + return sorted(samples, key=lambda item: item[0], reverse=True) + + +def _heavy_atom_coordinates(sdf_path: str): + """Heavy-atom coordinates of the first molecule in an SDF, or ``None`` if unreadable.""" + supplier = Chem.SDMolSupplier(sdf_path, sanitize=False, removeHs=False) + mol = next((m for m in supplier if m is not None), None) + if mol is None or mol.GetNumConformers() == 0: + return None + positions = mol.GetConformer().GetPositions() + heavy = [atom.GetIdx() for atom in mol.GetAtoms() if atom.GetAtomicNum() > 1] + return positions[heavy] if heavy else None + + +def _inside_box(point, center, size) -> bool: + return all(abs(p - c) <= s / 2.0 for p, c, s in zip(point, center, size, strict=True)) + + +def find_pocket_box(batch_folder: str, protein_conf_id: str, ligand_id: str): + """Pocket box for a combination, or ``None`` when no pocket was defined. + + Every pocket source (user box, P2Rank, co-crystal ligand) ends up in + ``boxes/vina_boxes/.txt``. That file is written per ligand + during Vina prep, so when it is missing another ligand's box for the same + protein is used: the pocket centre is per protein. """ - folder_name = combination[0] + "_" + combination[1] - full_folder = os.path.join(diffdock_folder, folder_name) + boxes_dir = os.path.join(batch_folder, BOXES_FOLDER, VINA_BOXES_FOLDER) + exact = os.path.join(boxes_dir, f"{protein_conf_id}_{ligand_id}.txt") + if os.path.isfile(exact): + return exact + siblings = sorted( + glob.glob(os.path.join(glob.escape(boxes_dir), f"{glob.escape(protein_conf_id)}_*.txt")) + ) + return siblings[0] if siblings else None - # Extract IDs - protein_conf, ligand_id = combination - scores = [ - float(i.split("_confidence")[1].replace(".sdf", "")) - for i in os.listdir(full_folder) - if "_confidence" in i - ] +def select_diffdock_pose(combo_dir: str, box_file, mode: str = DEFAULT_DIFFDOCK_POCKET) -> dict: + """Choose which DiffDock sample represents a combination. - best_score = max(scores) if scores else 0.0 + - ``box`` (or ``auto`` with a box): the highest-confidence sample whose + heavy-atom centroid lies inside the pocket box. + - ``blind`` (or ``auto`` without a box): the highest-confidence sample. - return { - COMBINATION_ID: folder_name, - PROTEIN_CONF_ID: protein_conf, - LIGAND_ID: ligand_id, - DIFFDOCK_SCORE: best_score, + :return: dict with ``sdf`` (path or ``None``), ``confidence`` (NaN when no + pose), ``reason`` (one of the ``POSE_*`` outcomes), ``mode``, + ``box_file`` and ``n_samples``. + """ + if mode not in DIFFDOCK_POCKET_MODES: + raise ValueError( + f"Invalid DiffDock pocket mode {mode!r}; expected one of {DIFFDOCK_POCKET_MODES}." + ) + + samples = _diffdock_samples(combo_dir) + selection = { + "mode": mode, + "box_file": box_file, + "n_samples": len(samples), + "sdf": None, + "confidence": np.nan, + "reason": POSE_NO_SAMPLES, } + if not samples: + return selection + + use_box = mode == DIFFDOCK_POCKET_BOX or (mode == DIFFDOCK_POCKET_AUTO and box_file is not None) + if not use_box: + confidence, sdf_path = samples[0] + return { + **selection, + "sdf": sdf_path, + "confidence": confidence, + "reason": POSE_SELECTED_BLIND, + } + + if box_file is None: + return {**selection, "reason": POSE_NO_BOX} + + center, size = get_center_and_size_from_box_file(box_file) + for confidence, sdf_path in samples: + coordinates = _heavy_atom_coordinates(sdf_path) + if coordinates is not None and _inside_box(coordinates.mean(axis=0), center, size): + return { + **selection, + "sdf": sdf_path, + "confidence": confidence, + "reason": POSE_SELECTED_BOX, + } + return {**selection, "reason": POSE_NO_SAMPLE_IN_BOX} + + +def diffdock_combo_dir(batch_folder: str, protein_conf_id: str, ligand_id: str) -> str: + return os.path.join( + batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER, f"{protein_conf_id}_{ligand_id}" + ) + + +def resolve_diffdock_pose( + batch_folder: str, protein_conf_id: str, ligand_id: str, mode: str = DEFAULT_DIFFDOCK_POCKET +) -> dict: + """Select the pose for a combination and record the choice next to its samples. + + The record (``selected_pose.json``) is what PoseBusters reads, so every + consumer of "the DiffDock pose" agrees without re-deriving the rule. + """ + combo_dir = diffdock_combo_dir(batch_folder, protein_conf_id, ligand_id) + box_file = ( + None + if mode == DIFFDOCK_POCKET_BLIND + else find_pocket_box(batch_folder, protein_conf_id, ligand_id) + ) + selection = select_diffdock_pose(combo_dir, box_file, mode) + + if os.path.isdir(combo_dir): + record = { + **selection, + "sdf": os.path.basename(selection["sdf"]) if selection["sdf"] else None, + "confidence": None if pd.isna(selection["confidence"]) else selection["confidence"], + } + with open(os.path.join(combo_dir, SELECTED_POSE_FILE), "w") as handle: + json.dump(record, handle, indent=2) + return selection + + +def read_selected_pose(combo_dir: str): + """The recorded selection for a combination, with ``sdf`` as a full path, or ``None``.""" + path = os.path.join(combo_dir, SELECTED_POSE_FILE) + if not os.path.isfile(path): + return None + with open(path) as handle: + record = json.load(handle) + if record.get("sdf"): + record["sdf"] = os.path.join(combo_dir, record["sdf"]) + return record + + +def pocket_mode(batch_dictionary: dict) -> str: + return batch_dictionary.get(DIFFDOCK_POCKET_KEY, DEFAULT_DIFFDOCK_POCKET) def deploy_diffdock_single( @@ -235,14 +389,19 @@ def write_diffdock_combinations_table(input_table, output_dir): """ Write the combinations table to the project directory for DiffDock. + DiffDock docks into the same prepared receptor as Vina and gnina + (``proteins/_single_chain_clean.pdb``: the receptor chain(s) only, in + the pocket-box frame), not the deposited file, which can carry G proteins, + antibodies or fusion partners that a blind docker would search too. + :param input_table: Table to write the combinations table for. - :param output_dir: Path to the project directory. + :param output_dir: Path to the batch directory. """ diffdock_combinations_table = input_table.copy() diffdock_combinations_table[PROTEIN_PATH] = diffdock_combinations_table[PROTEIN_CONF_ID].apply( - lambda x: f"{output_dir}/{PROTEINS_FOLDER}/{x}_raw.pdb" + lambda x: clean_receptor_path(output_dir, x) ) diffdock_combinations_table[COMPLEX_NAME] = ( @@ -261,263 +420,187 @@ def write_diffdock_combinations_table(input_table, output_dir): def diffdock_guild_scoring(batch_dictionary): """ - Perform the scoring of the dockinf results for DiffDock + DiffDock confidence of the selected pose for each combination in a batch. + + A combination with no selectable pose scores NaN (not 0.0, which is a + mid-range confidence). ``diffdock_pose_selection`` records which rule + chose the pose, or why none was chosen. :param batch_dictionary: Dictionary containing the batch information. :return: DataFrame containing the docking scores. """ - diffdock_scores_data = [] - diffdock_folder = ( - f"{batch_dictionary[BATCH_FOLDER]}/{DIFFDOCK_FOLDER}/{DIFFDOCK_RESULTS_FOLDER}/" - ) - for current_combination in tqdm( + batch_folder = batch_dictionary[BATCH_FOLDER] + mode = pocket_mode(batch_dictionary) + rows = [] + for protein_conf_id, ligand_id in tqdm( batch_dictionary[COMBINATIONS_TO_RUN_KEY], desc="DiffDock scoring", ): - diffdock_scores_data.append(process_diffdock_files(current_combination, diffdock_folder)) - - return pd.DataFrame(diffdock_scores_data) + selection = resolve_diffdock_pose(batch_folder, protein_conf_id, ligand_id, mode) + rows.append( + { + COMBINATION_ID: f"{protein_conf_id}_{ligand_id}", + PROTEIN_CONF_ID: protein_conf_id, + LIGAND_ID: ligand_id, + DIFFDOCK_SCORE: selection["confidence"], + DIFFDOCK_POSE_SELECTION: selection["reason"], + } + ) + return pd.DataFrame( + rows, + columns=[ + COMBINATION_ID, + PROTEIN_CONF_ID, + LIGAND_ID, + DIFFDOCK_SCORE, + DIFFDOCK_POSE_SELECTION, + ], + ) # ──────────────────────────────────────────────────────────────────────────── -# Vina score-only re-scoring of DiffDock poses +# Rescoring of DiffDock poses (Vina and gnina) # -# DiffDock returns a relative confidence score, not a physics-based ΔG. For a -# comparable energy estimate we apply Vina's scoring function to the highest- -# confidence pose (no re-docking). DiffDock writes poses in the coordinate -# frame of the *raw* input PDB, so the rescore receptor must be derived from -# that same raw PDB — the cleaned/centred receptor used by Vina docking is in -# a different frame. +# DiffDock's confidence is not a binding energy, so the selected pose is also +# scored with Vina and gnina. Both use the receptor DiffDock docked into +# (Guild's prepared receptor, so the frames already agree), and the pose is +# locally minimised first: raw DiffDock poses routinely carry heavy-atom +# clashes that would otherwise dominate the score. A pose that touches no +# receptor atom is reported as NaN rather than the ~0 an empty grid returns. # ──────────────────────────────────────────────────────────────────────────── -def _find_best_diffdock_sdf(diffdock_results_dir: str, protein_conf_id: str, ligand_id: str) -> str: - """ - Locate the highest-confidence SDF file for a combination in a DiffDock - results directory. DiffDock names output files like - ``rank1_confidence-1.23.sdf``. - - :return: Absolute path to the best-confidence SDF. - :raises FileNotFoundError: If no SDF files are found for the combination. - """ - folder_name = f"{protein_conf_id}_{ligand_id}" - combo_dir = os.path.join(diffdock_results_dir, folder_name) - - if not os.path.isdir(combo_dir): - raise FileNotFoundError(f"DiffDock results folder not found: {combo_dir}") - - sdf_scores = {} - for fname in os.listdir(combo_dir): - if "_confidence" in fname and fname.endswith(".sdf"): - try: - score = float(fname.split("_confidence")[1].replace(".sdf", "")) - sdf_scores[fname] = score - except ValueError: - continue - - if not sdf_scores: - raise FileNotFoundError(f"No DiffDock SDF files found in {combo_dir}") - - best_fname = max(sdf_scores, key=sdf_scores.get) - return os.path.join(combo_dir, best_fname) - - -def _extract_receptor_pdb_from_raw( - raw_pdb: str, - chain_id, - output_pdb: str, -) -> str: - """ - Extract one or more chains (ATOM records only) from a raw PDB into a new - PDB, preserving the original crystal coordinates so the receptor is in - the same frame as DiffDock's output SDF files. No format conversion — the - result is still a plain PDB. - - ``chain_id`` may be a single chain ID, a list of IDs, or a comma-separated - string (e.g. ``"A,B"``) so a multi-chain receptor is kept intact. - """ - if not os.path.isfile(raw_pdb): - raise FileNotFoundError(f"Raw PDB not found: {raw_pdb}") - - chain_ids = _normalize_chain_list(chain_id) - kept = 0 - with open(raw_pdb) as fin, open(output_pdb, "w") as fout: - for line in fin: - if line.startswith("ATOM") and len(line) > 21 and line[21] in chain_ids: - fout.write(line) - kept += 1 - fout.write("END\n") - - if kept == 0: - raise ValueError(f"No ATOM records found for chain(s) {chain_ids} in {raw_pdb}") - - logger.info( - f"Extracted receptor PDB from raw PDB chain(s) {chain_ids}: " f"{kept} atoms → {output_pdb}" - ) - return output_pdb - - -def _prepare_receptor_pdbqt_from_raw( - raw_pdb: str, - chain_id, - output_pdbqt: str, -) -> str: - """ - Extract one or more chains from a raw PDB (see - :func:`_extract_receptor_pdb_from_raw`) and convert them to PDBQT via - OpenBabel. Used by the Vina rescore track — gnina's rescore track - (:func:`rescore_diffdock_pose_gnina`) passes the extracted PDB straight - to gnina instead, since gnina's receptor argument accepts plain PDB. - """ - chain_pdb = output_pdbqt.replace(".pdbqt", "_chain.pdb") - _extract_receptor_pdb_from_raw(raw_pdb, chain_id, chain_pdb) - - result = subprocess.run( - ["obabel", "-ipdb", chain_pdb, "-opdbqt", "-O", output_pdbqt, "-xr"], - capture_output=True, - text=True, - ) - if not os.path.isfile(output_pdbqt) or os.path.getsize(output_pdbqt) == 0: - raise RuntimeError(f"obabel PDB→PDBQT failed for {chain_pdb}: {result.stderr}") - - logger.info(f"Prepared receptor PDBQT from {chain_pdb} → {output_pdbqt}") - return output_pdbqt +def _has_receptor_contact( + sdf_path: str, receptor_pdb: str, cutoff: float = RECEPTOR_CONTACT_CUTOFF +) -> bool: + ligand = _heavy_atom_coordinates(sdf_path) + if ligand is None: + return False + receptor = [] + with open(receptor_pdb) as handle: + for line in handle: + if line.startswith(("ATOM", "HETATM")) and line[76:78].strip().upper() != "H": + receptor.append((float(line[30:38]), float(line[38:46]), float(line[46:54]))) + if not receptor: + return False + distances = np.linalg.norm(ligand[:, None, :] - np.asarray(receptor)[None, :, :], axis=-1) + return bool((distances < cutoff).any()) + + +def _rescorable_pose( + batch_folder: str, protein_conf_id: str, ligand_id: str, mode: str, track: str +): + """The selected pose's SDF when it can be rescored, else ``None`` (reason logged).""" + combination_id = f"{protein_conf_id}_{ligand_id}" + selection = resolve_diffdock_pose(batch_folder, protein_conf_id, ligand_id, mode) + if selection["sdf"] is None: + logger.info(f"{track}: no DiffDock pose for {combination_id} ({selection['reason']})") + return None + + receptor_pdb = clean_receptor_path(batch_folder, protein_conf_id) + if not os.path.isfile(receptor_pdb): + logger.warning(f"{track}: prepared receptor {receptor_pdb} not found for {combination_id}") + return None + if not _has_receptor_contact(selection["sdf"], receptor_pdb): + logger.warning( + f"{track}: DiffDock pose for {combination_id} has no receptor heavy atom within " + f"{RECEPTOR_CONTACT_CUTOFF} Å; reporting NaN" + ) + return None + return selection["sdf"] def rescore_diffdock_pose( receptor_pdbqt: str, - diffdock_results_dir: str, - protein_conf_id: str, - ligand_id: str, - output_dir: str = None, - box_padding: float = 4.0, + sdf_path: str, + output_dir: str, + combination_id: str, + box_padding: float = 6.0, seed: int = RANDOM_SEED, -) -> dict: +) -> float: """ - Re-score a single DiffDock pose with Vina's physics-based scoring function. + Vina energy of a DiffDock pose after local minimisation (no re-docking). - Pipeline: - 1. Find the highest-confidence SDF in ``diffdock_results_dir/{protein}_{ligand}/``. - 2. Convert SDF → PDBQT (preserving 3D coordinates). - 3. Compute a Vina box centred on the SDF pose. - 4. Call :func:`guild.docking.vina.vina_score_pose` (score-only). + The grid is a box around the pose itself; the pocket restriction has + already been applied when the pose was selected. - :return: Dict with ``combination``, ``protein_config_id``, ``ligand_id``, - ``vina_rescore_diffdock_score``, ``diffdock_sdf``. + :return: Vina energy in kcal/mol (lower = better). """ - sdf_path = _find_best_diffdock_sdf(diffdock_results_dir, protein_conf_id, ligand_id) - - if output_dir is None: - output_dir = os.path.dirname(sdf_path) - - ligand_pdbqt = os.path.join(output_dir, f"{protein_conf_id}_{ligand_id}_rescore.pdbqt") - sdf_to_pdbqt(sdf_path, pdbqt=ligand_pdbqt) + ligand_pdbqt = os.path.join(output_dir, f"{combination_id}_rescore.pdbqt") + # DiffDock writes heavy atoms only; Vina needs polar hydrogens to type donors. + sdf_to_pdbqt(sdf_path, pdbqt=ligand_pdbqt, add_hydrogens=True) center, size = compute_box_from_sdf(sdf_path, padding=box_padding) - score = vina_score_pose( receptor_pdbqt=receptor_pdbqt, ligand_pdbqt=ligand_pdbqt, center=center, size=size, seed=seed, + minimize=True, + output_pdbqt=os.path.join(output_dir, f"{combination_id}_rescore_minimized.pdbqt"), ) - - combination_id = f"{protein_conf_id}_{ligand_id}" logger.info(f"Vina rescore (DiffDock pose): {combination_id} → {score:.3f} kcal/mol") + return score - return { - COMBINATION_ID: combination_id, - PROTEIN_CONF_ID: protein_conf_id, - LIGAND_ID: ligand_id, - VINA_RESCORE_DIFFDOCK_SCORE: score, - "diffdock_sdf": sdf_path, - } + +def _prepared_receptor_pdbqt(batch_folder: str, protein_conf_id: str) -> str: + """Vina's receptor PDBQT, prepared the way Vina docking prepares it when Vina did not run.""" + receptor_pdbqt = clean_receptor_path(batch_folder, protein_conf_id, "pdbqt") + if not os.path.isfile(receptor_pdbqt): + protein_pdb_to_pdbqt( + input_pdb=clean_receptor_path(batch_folder, protein_conf_id), + output_pdbqt=receptor_pdbqt, + allow_bad_res=True, + ) + return receptor_pdbqt def vina_rescore_diffdock_batch( batch_folder: str, combinations: list, - receptor_pdbqt_dir: str = None, - box_padding: float = 4.0, + mode: str = DEFAULT_DIFFDOCK_POCKET, + box_padding: float = 6.0, seed: int = RANDOM_SEED, ) -> pd.DataFrame: - """ - Batch re-score DiffDock poses for all combinations in a batch. - - Receptor PDBQT resolution order: - - 1. ``{receptor_pdbqt_dir}/{protein_conf_id}_raw.pdbqt`` — single-chain - PDBQT already in the raw (crystal) coordinate frame. - 2. Auto-generated from ``{protein_conf_id}_raw.pdb`` by extracting the - chain letter encoded in *protein_conf_id* and converting via OpenBabel. - """ - diffdock_results_dir = os.path.join(batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER) - if receptor_pdbqt_dir is None: - receptor_pdbqt_dir = os.path.join(batch_folder, PROTEINS_FOLDER) + """Vina-rescore the selected DiffDock pose of every combination in a batch.""" + output_dir = os.path.join(batch_folder, VINA_RESCORE_DIFFDOCK_FOLDER) + os.makedirs(output_dir, exist_ok=True) - rescore_output_dir = os.path.join(batch_folder, VINA_RESCORE_DIFFDOCK_FOLDER) - os.makedirs(rescore_output_dir, exist_ok=True) - - results = [] + rows = [] for protein_conf_id, ligand_id in combinations: - receptor_pdbqt = os.path.join(receptor_pdbqt_dir, f"{protein_conf_id}_raw.pdbqt") - if not os.path.exists(receptor_pdbqt): - raw_pdb = os.path.join(receptor_pdbqt_dir, f"{protein_conf_id}_raw.pdb") - if os.path.isfile(raw_pdb): - parts = protein_conf_id.split("-") - chain_id = parts[1] if len(parts) >= 2 else "A" - try: - _prepare_receptor_pdbqt_from_raw(raw_pdb, chain_id, receptor_pdbqt) - except Exception as e: - logger.warning( - f"Could not prepare receptor PDBQT from raw PDB " - f"for {protein_conf_id}: {e}" - ) - receptor_pdbqt = None - else: - logger.warning( - f"Neither {receptor_pdbqt} nor {raw_pdb} found for " - f"{protein_conf_id}, skipping combination" - ) - receptor_pdbqt = None - - if receptor_pdbqt is None or not os.path.exists(receptor_pdbqt): - results.append( - { - COMBINATION_ID: f"{protein_conf_id}_{ligand_id}", - PROTEIN_CONF_ID: protein_conf_id, - LIGAND_ID: ligand_id, - VINA_RESCORE_DIFFDOCK_SCORE: np.nan, - "diffdock_sdf": None, - } - ) - continue - + combination_id = f"{protein_conf_id}_{ligand_id}" + row = { + COMBINATION_ID: combination_id, + PROTEIN_CONF_ID: protein_conf_id, + LIGAND_ID: ligand_id, + VINA_RESCORE_DIFFDOCK_SCORE: np.nan, + } try: - result = rescore_diffdock_pose( - receptor_pdbqt=receptor_pdbqt, - diffdock_results_dir=diffdock_results_dir, - protein_conf_id=protein_conf_id, - ligand_id=ligand_id, - output_dir=rescore_output_dir, - box_padding=box_padding, - seed=seed, + sdf_path = _rescorable_pose( + batch_folder, protein_conf_id, ligand_id, mode, "Vina rescore" ) - results.append(result) + if sdf_path is not None: + row[VINA_RESCORE_DIFFDOCK_SCORE] = rescore_diffdock_pose( + receptor_pdbqt=_prepared_receptor_pdbqt(batch_folder, protein_conf_id), + sdf_path=sdf_path, + output_dir=output_dir, + combination_id=combination_id, + box_padding=box_padding, + seed=seed, + ) except Exception as e: - logger.warning(f"Vina rescore failed for {protein_conf_id}_{ligand_id}: {e}") - results.append( - { - COMBINATION_ID: f"{protein_conf_id}_{ligand_id}", - PROTEIN_CONF_ID: protein_conf_id, - LIGAND_ID: ligand_id, - VINA_RESCORE_DIFFDOCK_SCORE: np.nan, - "diffdock_sdf": None, - } - ) + logger.warning(f"Vina rescore failed for {combination_id}: {e}") + rows.append(row) - return pd.DataFrame(results) + return pd.DataFrame( + rows, columns=[COMBINATION_ID, PROTEIN_CONF_ID, LIGAND_ID, VINA_RESCORE_DIFFDOCK_SCORE] + ) + + +def _diffdock_outputs_present(batch_folder: str) -> bool: + diffdock_root = os.path.join(batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER) + return os.path.isdir(diffdock_root) and len(os.listdir(diffdock_root)) > 0 def vina_rescore_diffdock_guild_scoring(batch_dictionary): @@ -529,62 +612,40 @@ def vina_rescore_diffdock_guild_scoring(batch_dictionary): empty frame (with those columns) if no DiffDock outputs are found. """ batch_folder = batch_dictionary[BATCH_FOLDER] - combinations = batch_dictionary[COMBINATIONS_TO_RUN_KEY] - - diffdock_root = os.path.join(batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER) - diffdock_present = os.path.isdir(diffdock_root) and len(os.listdir(diffdock_root)) > 0 - if not diffdock_present: + columns = [COMBINATION_ID, PROTEIN_CONF_ID, LIGAND_ID, VINA_RESCORE_DIFFDOCK_SCORE] + if not _diffdock_outputs_present(batch_folder): logger.warning( "vina_rescore_diffdock: no DiffDock outputs found in %s — returning empty score table", batch_folder, ) - return pd.DataFrame( - columns=[COMBINATION_ID, PROTEIN_CONF_ID, LIGAND_ID, VINA_RESCORE_DIFFDOCK_SCORE] - ) - - df = vina_rescore_diffdock_batch(batch_folder=batch_folder, combinations=combinations) - keep = [COMBINATION_ID, PROTEIN_CONF_ID, LIGAND_ID, VINA_RESCORE_DIFFDOCK_SCORE] - return df[[c for c in keep if c in df.columns]] - + return pd.DataFrame(columns=columns) -# ──────────────────────────────────────────────────────────────────────────── -# gnina score-only re-scoring of DiffDock poses -# -# Same rationale as the Vina rescore track above, but via gnina's CNN-backed -# scoring function instead. Needs no PDBQT conversion at all: DiffDock already -# writes its poses as SDF (gnina reads ligand SDF directly), and gnina's -# receptor argument accepts a plain PDB — so the chain-filtered raw PDB is -# passed straight through with no OpenBabel step. -# ──────────────────────────────────────────────────────────────────────────── + return vina_rescore_diffdock_batch( + batch_folder=batch_folder, + combinations=batch_dictionary[COMBINATIONS_TO_RUN_KEY], + mode=pocket_mode(batch_dictionary), + ) def rescore_diffdock_pose_gnina( receptor_pdb: str, - diffdock_results_dir: str, - protein_conf_id: str, - ligand_id: str, - output_dir: str = None, - box_padding: float = 4.0, + sdf_path: str, + output_dir: str, + combination_id: str, + box_padding: float = 6.0, seed: int = RANDOM_SEED, use_gpu: bool = False, subprocess_log_path: str = None, -) -> dict: - """ - Re-score a single DiffDock pose with gnina's score-only mode (no PDBQT - conversion for either receptor or ligand — see module note above). - - :return: Dict with ``combination``, ``protein_config_id``, ``ligand_id``, - ``gnina_rescore_diffdock_score``, ``gnina_rescore_diffdock_cnn_score``, - ``diffdock_sdf``. +) -> tuple[float, float]: """ - sdf_path = _find_best_diffdock_sdf(diffdock_results_dir, protein_conf_id, ligand_id) + gnina energy and CNN score of a DiffDock pose after local minimisation. - if output_dir is None: - output_dir = os.path.dirname(sdf_path) + gnina reads the SDF and the plain-PDB receptor directly, so no PDBQT + conversion is involved. + :return: ``(affinity, cnn_score)``. + """ center, size = compute_box_from_sdf(sdf_path, padding=box_padding) - - combination_id = f"{protein_conf_id}_{ligand_id}" score, cnn_score = gnina_score_pose( receptor=receptor_pdb, ligand=sdf_path, @@ -595,86 +656,67 @@ def rescore_diffdock_pose_gnina( seed=seed, use_gpu=use_gpu, subprocess_log_path=subprocess_log_path, + minimize=True, ) - logger.info(f"gnina rescore (DiffDock pose): {combination_id} → {score:.3f} kcal/mol") - - return { - COMBINATION_ID: combination_id, - PROTEIN_CONF_ID: protein_conf_id, - LIGAND_ID: ligand_id, - GNINA_RESCORE_DIFFDOCK_SCORE: score, - GNINA_RESCORE_DIFFDOCK_CNN_SCORE: cnn_score, - "diffdock_sdf": sdf_path, - } + return score, cnn_score def gnina_rescore_diffdock_batch( batch_folder: str, combinations: list, - receptor_pdb_dir: str = None, - box_padding: float = 4.0, + mode: str = DEFAULT_DIFFDOCK_POCKET, + box_padding: float = 6.0, seed: int = RANDOM_SEED, use_gpu: bool = False, ) -> pd.DataFrame: - """ - Batch re-score DiffDock poses with gnina for all combinations in a batch. + """gnina-rescore the selected DiffDock pose of every combination in a batch.""" + output_dir = os.path.join(batch_folder, GNINA_RESCORE_DIFFDOCK_FOLDER) + os.makedirs(output_dir, exist_ok=True) - Receptor resolution mirrors :func:`vina_rescore_diffdock_batch` but stops - at a plain chain-filtered PDB — no PDBQT conversion needed since gnina - reads ``.pdb`` receptors directly. - """ - diffdock_results_dir = os.path.join(batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER) - if receptor_pdb_dir is None: - receptor_pdb_dir = os.path.join(batch_folder, PROTEINS_FOLDER) - - rescore_output_dir = os.path.join(batch_folder, GNINA_RESCORE_DIFFDOCK_FOLDER) - os.makedirs(rescore_output_dir, exist_ok=True) - - results = [] + rows = [] for protein_conf_id, ligand_id in combinations: combination_id = f"{protein_conf_id}_{ligand_id}" - empty_result = { + row = { COMBINATION_ID: combination_id, PROTEIN_CONF_ID: protein_conf_id, LIGAND_ID: ligand_id, GNINA_RESCORE_DIFFDOCK_SCORE: np.nan, GNINA_RESCORE_DIFFDOCK_CNN_SCORE: np.nan, - "diffdock_sdf": None, } - - raw_pdb = os.path.join(receptor_pdb_dir, f"{protein_conf_id}_raw.pdb") - if not os.path.isfile(raw_pdb): - logger.warning(f"{raw_pdb} not found for {protein_conf_id}, skipping combination") - results.append(empty_result) - continue - try: - parts = protein_conf_id.split("-") - chain_id = parts[1] if len(parts) >= 2 else "A" - receptor_pdb = os.path.join(rescore_output_dir, f"{protein_conf_id}_raw_chain.pdb") - _extract_receptor_pdb_from_raw(raw_pdb, chain_id, receptor_pdb) - - subprocess_log_path = os.path.join( - rescore_output_dir, f"{combination_id}.subprocess.log" + sdf_path = _rescorable_pose( + batch_folder, protein_conf_id, ligand_id, mode, "gnina rescore" ) - result = rescore_diffdock_pose_gnina( - receptor_pdb=receptor_pdb, - diffdock_results_dir=diffdock_results_dir, - protein_conf_id=protein_conf_id, - ligand_id=ligand_id, - output_dir=rescore_output_dir, - box_padding=box_padding, - seed=seed, - use_gpu=use_gpu, - subprocess_log_path=subprocess_log_path, - ) - results.append(result) + if sdf_path is not None: + score, cnn_score = rescore_diffdock_pose_gnina( + receptor_pdb=clean_receptor_path(batch_folder, protein_conf_id), + sdf_path=sdf_path, + output_dir=output_dir, + combination_id=combination_id, + box_padding=box_padding, + seed=seed, + use_gpu=use_gpu, + subprocess_log_path=os.path.join( + output_dir, f"{combination_id}.subprocess.log" + ), + ) + row[GNINA_RESCORE_DIFFDOCK_SCORE] = score + row[GNINA_RESCORE_DIFFDOCK_CNN_SCORE] = cnn_score except Exception as e: logger.warning(f"gnina rescore failed for {combination_id}: {e}") - results.append(empty_result) - - return pd.DataFrame(results) + rows.append(row) + + return pd.DataFrame( + rows, + columns=[ + COMBINATION_ID, + PROTEIN_CONF_ID, + LIGAND_ID, + GNINA_RESCORE_DIFFDOCK_SCORE, + GNINA_RESCORE_DIFFDOCK_CNN_SCORE, + ], + ) def gnina_rescore_diffdock_guild_scoring(batch_dictionary, use_gpu: bool = False): @@ -687,33 +729,24 @@ def gnina_rescore_diffdock_guild_scoring(batch_dictionary, use_gpu: bool = False frame (with those columns) if no DiffDock outputs are found. """ batch_folder = batch_dictionary[BATCH_FOLDER] - combinations = batch_dictionary[COMBINATIONS_TO_RUN_KEY] - - diffdock_root = os.path.join(batch_folder, DIFFDOCK_FOLDER, DIFFDOCK_RESULTS_FOLDER) - diffdock_present = os.path.isdir(diffdock_root) and len(os.listdir(diffdock_root)) > 0 - if not diffdock_present: + columns = [ + COMBINATION_ID, + PROTEIN_CONF_ID, + LIGAND_ID, + GNINA_RESCORE_DIFFDOCK_SCORE, + GNINA_RESCORE_DIFFDOCK_CNN_SCORE, + ] + if not _diffdock_outputs_present(batch_folder): logger.warning( "gnina_rescore_diffdock: no DiffDock outputs found in %s — returning empty score table", batch_folder, ) - return pd.DataFrame( - columns=[ - COMBINATION_ID, - PROTEIN_CONF_ID, - LIGAND_ID, - GNINA_RESCORE_DIFFDOCK_SCORE, - GNINA_RESCORE_DIFFDOCK_CNN_SCORE, - ] - ) + return pd.DataFrame(columns=columns) df = gnina_rescore_diffdock_batch( - batch_folder=batch_folder, combinations=combinations, use_gpu=use_gpu + batch_folder=batch_folder, + combinations=batch_dictionary[COMBINATIONS_TO_RUN_KEY], + mode=pocket_mode(batch_dictionary), + use_gpu=use_gpu, ) - keep = [ - COMBINATION_ID, - PROTEIN_CONF_ID, - LIGAND_ID, - GNINA_RESCORE_DIFFDOCK_SCORE, - GNINA_RESCORE_DIFFDOCK_CNN_SCORE, - ] - return df[[c for c in keep if c in df.columns]] + return df.reindex(columns=columns) diff --git a/guild/docking/gnina.py b/guild/docking/gnina.py index 39b1041..93cf7af 100644 --- a/guild/docking/gnina.py +++ b/guild/docking/gnina.py @@ -421,6 +421,7 @@ def gnina_score_pose( seed: int = RANDOM_SEED, use_gpu: bool = False, subprocess_log_path: str | None = None, + minimize: bool = False, ) -> tuple[float, float]: """ Score a single pre-docked ligand pose with gnina (score-only, no re-docking). @@ -443,6 +444,8 @@ def gnina_score_pose( :param use_gpu: When False (default — rescoring commonly runs alongside CPU-only batch scoring), passes ``--no_gpu`` to gnina. :param subprocess_log_path: Optional path for the gnina stdout/stderr transcript. + :param minimize: Locally minimise the pose first (``--local_only``) instead + of scoring it as-is (``--score_only``). :return: ``(affinity, cnn_score)`` — affinity in kcal/mol (lower = better). """ output_pdbqt = os.path.join(output_dir, f"{run_id}_gnina_score.pdbqt") @@ -457,7 +460,7 @@ def gnina_score_pose( output_scores=output_scores, seed=seed, use_gpu=use_gpu, - pose_mode=POSE_MODE_SCORE, + pose_mode=POSE_MODE_LOCAL if minimize else POSE_MODE_SCORE, subprocess_log_path=subprocess_log_path, ) return float(result["scores"][0]), float(result["cnn_scores"][0]) diff --git a/guild/docking/vina.py b/guild/docking/vina.py index f51ae98..fdef0bf 100644 --- a/guild/docking/vina.py +++ b/guild/docking/vina.py @@ -434,6 +434,8 @@ def vina_score_pose( center: tuple[float, float, float], size: tuple[float, float, float], seed: int = RANDOM_SEED, + minimize: bool = False, + output_pdbqt: str | None = None, ) -> float: """ Score a single pre-docked ligand pose with Vina (no re-docking). @@ -447,6 +449,10 @@ def vina_score_pose( :param center: Box center (x, y, z). :param size: Box size (x, y, z). :param seed: Random seed (for reproducibility). + :param minimize: Locally minimise the pose (``Vina.optimize()``) before + reporting the energy, so steric clashes in an externally generated + pose do not dominate the score. The pose stays in place otherwise. + :param output_pdbqt: Optional path to write the (minimised) pose. :return: Vina binding energy in kcal/mol. """ _validate_pdbqt(receptor_pdbqt, "receptor") @@ -465,7 +471,9 @@ def vina_score_pose( raise RuntimeError(f"Failed to set ligand from {ligand_pdbqt}: {e}") from e v.compute_vina_maps(center=center, box_size=size) - energy = v.score() + energy = v.optimize() if minimize else v.score() + if output_pdbqt is not None: + v.write_pose(output_pdbqt, overwrite=True) return float(energy[0]) diff --git a/guild/support/diffdock_model_args.yaml b/guild/support/diffdock_model_args.yaml index 30ff890..3d9a8fe 100644 --- a/guild/support/diffdock_model_args.yaml +++ b/guild/support/diffdock_model_args.yaml @@ -2,9 +2,9 @@ ckpt: best_ema_inference_epoch_model.pt model_dir: ./workdir/v1.1/score_model confidence_ckpt: best_model_epoch75.pt confidence_model_dir: ./workdir/v1.1/confidence_model -samples_per_complex: 7 -inference_steps: 10 -actual_steps: 9 +samples_per_complex: 10 +inference_steps: 20 +actual_steps: 19 different_schedules: false sigma_schedule: expbeta inf_sched_alpha: 1 diff --git a/guild/tools/bulk.py b/guild/tools/bulk.py index a09a451..f10bc8a 100644 --- a/guild/tools/bulk.py +++ b/guild/tools/bulk.py @@ -36,7 +36,6 @@ UNIQUE_PROTEIN_IDS_KEY, ) from guild.constants.decoys import DECOYS_CATEGORY -from guild.constants.diffdock import DIFFDOCK_RESULTS_FOLDER from guild.constants.guild import ( BOLTZ_FOLDER, COVALENT_REC_ATOM, @@ -54,7 +53,6 @@ VINA_FOLDER, ) from guild.tools.binders import collect_known_binders -from guild.tools.preparation import _normalize_chain_list from guild.transformers.converters import cif_to_pdb, sdf_to_pdb from guild.transformers.pdb import ( add_covalent_conect, @@ -395,20 +393,28 @@ def generate_diffdock_complex_pdbs(batch_dictionary): """ Generate PLIP-ready complex PDB files for DiffDock docking results. - For each combination, finds the highest-confidence DiffDock SDF pose, - converts it to PDB, extracts the matching chain from the raw protein PDB - (preserving the crystal coordinate frame), and merges them into a single - complex PDB suitable for PLIP analysis. + For each combination, takes the pose chosen by + :func:`guild.docking.diffdock.resolve_diffdock_pose` (the same pose the + DiffDock score and both rescores use), converts it to PDB and merges it + with the prepared receptor DiffDock docked into. A combination with no + selectable pose gets no complex. An existing complex is rebuilt when the + selected pose has changed since it was written. :param batch_dictionary: Dictionary containing batch information including BATCH_FOLDER, COMBINATIONS_TABLE_KEY, etc. """ from guild.constants.guild import DIFFDOCK_FOLDER + from guild.docking.diffdock import ( + clean_receptor_path, + diffdock_combo_dir, + pocket_mode, + read_selected_pose, + resolve_diffdock_pose, + ) batch_folder = batch_dictionary[BATCH_FOLDER] - diffdock_results = f"{batch_folder}/{DIFFDOCK_FOLDER}/{DIFFDOCK_RESULTS_FOLDER}" - proteins_folder = f"{batch_folder}/proteins" diffdock_folder = f"{batch_folder}/{DIFFDOCK_FOLDER}" + mode = pocket_mode(batch_dictionary) combinations_df = batch_dictionary[COMBINATIONS_TABLE_KEY] @@ -419,39 +425,23 @@ def generate_diffdock_complex_pdbs(batch_dictionary): protein_conf_id = row[PROTEIN_CONF_ID] ligand_id = row[LIGAND_ID] run_id = f"{protein_conf_id}_{ligand_id}" - complex_pdb = f"{diffdock_folder}/{run_id}_complex.pdb" - # Skip if complex already exists - if os.path.exists(complex_pdb): - complexes_created += 1 - continue + previous = read_selected_pose(diffdock_combo_dir(batch_folder, protein_conf_id, ligand_id)) + selection = resolve_diffdock_pose(batch_folder, protein_conf_id, ligand_id, mode) + best_sdf = selection["sdf"] - # --- Find best DiffDock SDF --- - combo_dir = os.path.join(diffdock_results, run_id) - if not os.path.isdir(combo_dir): - logger.warning(f"DiffDock results folder not found: {combo_dir}") + if best_sdf is None: + if os.path.exists(complex_pdb): + os.remove(complex_pdb) + logger.warning(f"No DiffDock pose selected for {run_id} ({selection['reason']})") complexes_failed += 1 continue - sdf_scores = {} - for fname in os.listdir(combo_dir): - if "_confidence" in fname and fname.endswith(".sdf"): - try: - score = float(fname.split("_confidence")[1].replace(".sdf", "")) - sdf_scores[fname] = score - except ValueError: - continue - - if not sdf_scores: - logger.warning(f"No DiffDock SDF files found in {combo_dir}") - complexes_failed += 1 + if os.path.exists(complex_pdb) and previous and previous.get("sdf") == best_sdf: + complexes_created += 1 continue - best_fname = max(sdf_scores, key=sdf_scores.get) - best_sdf = os.path.join(combo_dir, best_fname) - - # --- Convert SDF → PDB (preserving 3D coordinates) --- ligand_pdb = os.path.join(diffdock_folder, f"{run_id}_ligand.pdb") try: sdf_to_pdb(best_sdf, ligand_pdb) @@ -460,39 +450,15 @@ def generate_diffdock_complex_pdbs(batch_dictionary): complexes_failed += 1 continue - # --- Get protein PDB in raw coordinate frame --- - # DiffDock outputs are in the raw PDB frame, so we must use the raw PDB. - # Extract the single chain to match what DiffDock used. - raw_pdb = f"{proteins_folder}/{protein_conf_id}_raw.pdb" - if not os.path.exists(raw_pdb): - logger.warning(f"Raw PDB not found for {protein_conf_id}: {raw_pdb}") + receptor_pdb = clean_receptor_path(batch_folder, protein_conf_id) + if not os.path.exists(receptor_pdb): + logger.warning(f"Prepared receptor not found for {protein_conf_id}: {receptor_pdb}") complexes_failed += 1 continue - # Extract chain(s) from protein_conf_id. Single chain ("8gut-R-KO8-R" → - # "R") or a comma-joined set for a multi-chain pocket ("8gut-A,B-..." → - # ["A", "B"]); every listed chain is kept so the receptor stays intact. - parts = protein_conf_id.split("-") - chain_ids = _normalize_chain_list(parts[1]) if len(parts) >= 2 else ["A"] - - chain_pdb = os.path.join(diffdock_folder, f"{protein_conf_id}_chain.pdb") - if not os.path.exists(chain_pdb): - kept = 0 - with open(raw_pdb) as fin, open(chain_pdb, "w") as fout: - for line in fin: - if line.startswith("ATOM") and len(line) > 21 and line[21] in chain_ids: - fout.write(line) - kept += 1 - fout.write("END\n") - if kept == 0: - logger.warning(f"No ATOM records for chain(s) {chain_ids} in {raw_pdb}") - complexes_failed += 1 - continue - - # --- Build complex PDB --- try: build_complex_pdb( - protein_pdb=chain_pdb, + protein_pdb=receptor_pdb, ligand_file=ligand_pdb, out_complex_pdb=complex_pdb, ligand_is_pdbqt=False, diff --git a/guild/transformers/converters.py b/guild/transformers/converters.py index 9210b3e..d926ebf 100644 --- a/guild/transformers/converters.py +++ b/guild/transformers/converters.py @@ -329,7 +329,12 @@ def ligand_pdb_to_pdbqt(pdb: str, timeout: int = 300): raise RuntimeError(f"OpenBabel conversion failed for {pdb}: {e.stderr}") from e -def sdf_to_pdbqt(sdf: str, pdbqt: str = None, timeout: int = OBABEL_CONVERSION_TIMEOUT): +def sdf_to_pdbqt( + sdf: str, + pdbqt: str = None, + timeout: int = OBABEL_CONVERSION_TIMEOUT, + add_hydrogens: bool = False, +): """ Convert an SDF file (with existing 3D coordinates) directly to PDBQT. This preserves the 3D pose — no --gen3d is used. @@ -338,6 +343,9 @@ def sdf_to_pdbqt(sdf: str, pdbqt: str = None, timeout: int = OBABEL_CONVERSION_T :param sdf: Path to the input SDF file (must have 3D coords) :param pdbqt: Path to the output PDBQT file. Defaults to replacing .sdf with .pdbqt. :param timeout: Maximum time in seconds for conversion + :param add_hydrogens: Add hydrogens (``obabel -h``, keeping the input's + formal charges) for poses written heavy-atom-only, e.g. by DiffDock; + without them Vina cannot type hydrogen-bond donors. :return: Path to the generated PDBQT file """ if not os.path.exists(sdf): @@ -346,7 +354,8 @@ def sdf_to_pdbqt(sdf: str, pdbqt: str = None, timeout: int = OBABEL_CONVERSION_T if pdbqt is None: pdbqt = sdf.replace(".sdf", ".pdbqt") - obabel_cmd = f'obabel "{sdf}" -O "{pdbqt}" {SHELL_SILENCER}' + hydrogen_flag = "-h " if add_hydrogens else "" + obabel_cmd = f'obabel "{sdf}" -O "{pdbqt}" {hydrogen_flag}{SHELL_SILENCER}' try: subprocess.run( diff --git a/pyproject.toml b/pyproject.toml index 7a2506f..6018266 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "guild" -version = "1.4.0" +version = "1.4.1" description = "A unified framework for multi-method molecular docking and scoring" license = "MIT" authors = [ diff --git a/run_native_rmsd.py b/run_native_rmsd.py new file mode 100644 index 0000000..f71f5d2 --- /dev/null +++ b/run_native_rmsd.py @@ -0,0 +1,231 @@ +import os +from pathlib import Path + +os.environ.setdefault("UV_CACHE_DIR", "/tmp/uv-cache") +os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/tmp/torchinductor") + +import numpy as np +import pandas as pd +from posebusters import PoseBusters + +from guild.constants.interactions import LIGAND_RESNAME +from guild.analysis.posebusters import _pose_mols +from guild.tools.pose_molecules import split_complex_records, mol_from_pdb_block + +PROJECT_ROOT = Path("/workspace") +DATA_ROOT = PROJECT_ROOT / "data" / "small-example-all-methods" + +TARGETS = [ + { + "protein_config_id": "7v3z-A-9GF-A", + "raw_pdb": PROJECT_ROOT / "data" / "7v3z.pdb", + "raw_chain": "A", + "resname": "9GF", + "combination_id": "7v3z-A-9GF-A_9GF_native", + "smiles": "CCCCCCC(C)(C)c1ccc([C@@H]2C[C@H](O)CC[C@H]2CCCO)c(O)c1", + "batch_folder": str(DATA_ROOT / "batches" / "batch_83"), + }, + { + "protein_config_id": "6ot0-R-CO1-R", + "raw_pdb": PROJECT_ROOT / "data" / "6ot0.pdb", + "raw_chain": "R", + "resname": "CO1", + "combination_id": "6ot0-R-CO1-R_CO1_native", + "smiles": "C[C@H](CC[C@@H]1OC1(C)C)[C@H]2CC[C@H]3[C@@H]4CC=C5C[C@@H](O)CC[C@]5(C)[C@H]4CC[C@]23C", + "batch_folder": str(DATA_ROOT / "batches" / "batch_84"), + }, + { + "protein_config_id": "8gdc-R-P2E-R", + "raw_pdb": PROJECT_ROOT / "data" / "8gdc.pdb", + "raw_chain": "R", + "resname": "P2E", + "combination_id": "8gdc-R-P2E-R_P2E_native", + "smiles": "CCCCC[C@H](O)/C=C/[C@H]1[C@H](O)CC(=O)[C@@H]1C\\C=C/CCCC(O)=O", + "batch_folder": str(DATA_ROOT / "batches" / "batch_84"), + }, +] + +METHODS = ["vina", "gnina", "karmadock", "diffdock", "boltz"] + + +def read_ca_coords(path, chain_filter=None): + # Dedupe by residue number, keeping the first occurrence (guild's own prep + # collapses alternate side-chain conformers to a single one, preferring + # altloc 'A' -- confirmed against the run's own logged warning about + # 8gdc R:163 HIS having an A/B altloc; the raw PDB still carries both). + coords = [] + seen_resnum = set() + with open(path) as f: + for line in f: + if line.startswith("ATOM") and line[12:16].strip() == "CA": + if chain_filter and line[21] != chain_filter: + continue + resnum = line[22:27] # includes insertion code + if resnum in seen_resnum: + continue + seen_resnum.add(resnum) + coords.append((float(line[30:38]), float(line[38:46]), float(line[46:54]))) + return np.array(coords) + + +def kabsch_transform(mobile, target): + """Rotation+translation that maps `mobile` (N,3) onto `target` (N,3), in + residue-sequence order (robust to residue renumbering across guild's + receptor-prep stages, since chain length/order is preserved even when the + numbering isn't -- confirmed empirically: same atom count, sequential). + """ + assert mobile.shape == target.shape, f"CA count mismatch: {mobile.shape} vs {target.shape}" + mobile_c = mobile - mobile.mean(axis=0) + target_c = target - target.mean(axis=0) + H = mobile_c.T @ target_c + U, S, Vt = np.linalg.svd(H) + d = np.sign(np.linalg.det(Vt.T @ U.T)) + D = np.diag([1, 1, d]) + R = Vt.T @ D @ U.T + t = target.mean(axis=0) - R @ mobile.mean(axis=0) + return R, t + + +def apply_transform_to_pdb_block(lines, R, t): + out = [] + for line in lines: + if line.startswith(("ATOM", "HETATM")) and len(line) >= 54: + x, y, z = float(line[30:38]), float(line[38:46]), float(line[46:54]) + xyz = R @ np.array([x, y, z]) + t + newline = f"{line[:30]}{xyz[0]:8.3f}{xyz[1]:8.3f}{xyz[2]:8.3f}{line[54:]}" + out.append(newline) + else: + out.append(line) + return out + + +def crystal_ligand_lines(raw_pdb_path, resname): + lines = [] + with open(raw_pdb_path) as fh: + for line in fh: + if line.startswith("HETATM") and line[17:20].strip() == resname: + lines.append(line) + if not lines: + raise ValueError(f"no HETATM lines for {resname} in {raw_pdb_path}") + return lines + + +def complex_pdb_path(batch_folder, method, combination_id): + return f"{batch_folder}/{method}/{combination_id}_complex.pdb" + + +def receptor_path_from_complex(complex_pdb, out_path, ligand_resname=LIGAND_RESNAME): + text = Path(complex_pdb).read_text(encoding="utf-8", errors="replace") + _, protein_lines = split_complex_records(text, ligand_resname) + if not protein_lines: + raise ValueError(f"no protein atoms left in {complex_pdb} after excluding {ligand_resname}") + with open(out_path, "w") as fh: + fh.writelines(protein_lines) + fh.write("END\n") + return out_path + + +def main(): + buster = PoseBusters(config="redock") + rows = [] + printed_columns = False + + for target in TARGETS: + raw_ca = read_ca_coords(target["raw_pdb"], chain_filter=target["raw_chain"]) + raw_ligand_lines = crystal_ligand_lines(target["raw_pdb"], target["resname"]) + + for method in METHODS: + combo_id = target["combination_id"] + cpdb = complex_pdb_path(target["batch_folder"], method, combo_id) + record = {"protein_config_id": target["protein_config_id"], "method": method} + + if not os.path.exists(cpdb): + rows.append({**record, "status": "missing_complex_pdb", "path_checked": cpdb}) + continue + + complex_ca = read_ca_coords(cpdb) + if complex_ca.shape != raw_ca.shape: + rows.append({ + **record, "status": "ca_count_mismatch", + "reason": f"raw has {raw_ca.shape[0]} CA, complex has {complex_ca.shape[0]}", + }) + continue + + R, t = kabsch_transform(raw_ca, complex_ca) + rmsd_fit = float(np.sqrt(np.mean(np.sum((raw_ca @ R.T + t - complex_ca) ** 2, axis=1)))) + transformed_ligand_lines = apply_transform_to_pdb_block(raw_ligand_lines, R, t) + ligand_block = "".join(transformed_ligand_lines) + "END\n" + + mol_true, true_reason, true_fallback = mol_from_pdb_block(ligand_block, target["smiles"]) + if mol_true is None: + rows.append({**record, "status": "crystal_ligand_build_failed", "reason": true_reason}) + continue + + poses = _pose_mols( + complex_pdb_path=cpdb, + batch_folder=target["batch_folder"], + docking_method=method, + combination_id=combo_id, + smiles=target["smiles"], + ligand_resname=LIGAND_RESNAME, + max_poses=1, + ) + if not poses or poses[0][0] is None: + reason = poses[0][1] if poses else "no pose records found" + rows.append({**record, "status": "no_usable_pose", "reason": reason}) + continue + + mol_pred, pose_reason, pred_fallback = poses[0] + receptor_tmp = f"/tmp/{target['protein_config_id']}_{method}_receptor.pdb" + try: + receptor_path_from_complex(cpdb, receptor_tmp) + except Exception as error: + rows.append({**record, "status": "receptor_build_failed", "reason": str(error)}) + continue + + try: + frame = buster.bust( + mol_pred=mol_pred, mol_true=mol_true, mol_cond=receptor_tmp, full_report=True + ) + except Exception as error: + rows.append({**record, "status": "posebusters_raised", "reason": str(error)}) + continue + + if frame is None or frame.empty: + rows.append({**record, "status": "posebusters_empty_frame"}) + continue + + raw = frame.reset_index(drop=True).iloc[0].to_dict() + if not printed_columns: + print("PoseBusters redock columns:", sorted(raw.keys())) + printed_columns = True + + rmsd = raw.get("rmsd") + within_2A = raw.get("rmsd_≤_2å") + + rows.append({ + **record, + "status": "ok", + "kabsch_fit_rmsd_ca": rmsd_fit, # sanity check: should be ~0 + "pred_template_fallback": pred_fallback, + "true_template_fallback": true_fallback, + "mol_true_loaded": raw.get("mol_true_loaded"), + "mol_pred_loaded": raw.get("mol_pred_loaded"), + "mol_cond_loaded": raw.get("mol_cond_loaded"), + "inchi_crystal_valid": raw.get("inchi_crystal_valid"), + "inchi_docked_valid": raw.get("inchi_docked_valid"), + "rmsd": rmsd, + "kabsch_rmsd": raw.get("kabsch_rmsd"), + "within_2A": within_2A, + "stereochemistry_preserved": raw.get("stereochemistry_preserved"), + }) + + df = pd.DataFrame(rows) + out_path = DATA_ROOT / "native_ligand_rmsd.tsv" + df.to_csv(out_path, sep="\t", index=False) + print(f"Wrote {out_path}") + print(df.to_string()) + + +if __name__ == "__main__": + main() diff --git a/run_posebusters.py b/run_posebusters.py new file mode 100644 index 0000000..bc4825e --- /dev/null +++ b/run_posebusters.py @@ -0,0 +1,39 @@ +import os +from pathlib import Path + +import pandas as pd + +os.environ.setdefault("UV_CACHE_DIR", "/tmp/uv-cache") +os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/tmp/torchinductor") + +PROJECT_ROOT = Path("/workspace") + +import guild.constants.system as _sys_const +import guild.bulk as _bulk_mod + +_sys_const.WORKING_DIR_PATH = PROJECT_ROOT +_sys_const.PROJECTS_FOLDER = str(PROJECT_ROOT / "data") +_bulk_mod.WORKING_DIR_PATH = PROJECT_ROOT +_bulk_mod.PROJECTS_FOLDER = str(PROJECT_ROOT / "data") + +from guild.bulk import BulkRun + +runs_table = pd.read_csv("/workspace/combinations.csv") + +# Must match the run-guild invocation exactly: project name, methods, batch_size, and +# the decoy/known-binder flags. BulkRun reconstructs the batch folder layout from them, +# and a mismatch silently finds no poses and writes empty TSVs rather than erroring. +# This run used NO_DECOYS=1 (decoys were explicit rows) and the Makefile's default +# BATCH_SIZE=2, confirmed against batch_progress.log (83 batches for 165 combos). +BATCH_SIZE = 2 + +bulk = BulkRun( + runs_table, + "small-example-all-methods", + methods_to_run=["vina", "gnina", "karmadock", "diffdock", "boltz"], + batch_size=BATCH_SIZE, + use_decoys=False, + use_known_binders=False, +) +bulk.run_pose_validity_analysis() +print(f"Wrote {bulk.posebusters_path} and {bulk.posebusters_report_path}") diff --git a/scripts/run_guild.py b/scripts/run_guild.py index 9a3b1f1..e8a7256 100644 --- a/scripts/run_guild.py +++ b/scripts/run_guild.py @@ -39,6 +39,7 @@ import numpy as np import pandas as pd +from guild.constants.diffdock import DEFAULT_DIFFDOCK_POCKET, DIFFDOCK_POCKET_MODES from guild.constants.posebusters import DEFAULT_POSEBUSTERS_CONFIG, POSEBUSTERS_CONFIGS # --------------------------------------------------------------------------- @@ -317,6 +318,19 @@ def parse_args() -> argparse.Namespace: "Ignored by Vina, Boltz, DiffDock, and KarmaDock." ), ) + parser.add_argument( + "--diffdock-pocket", + choices=DIFFDOCK_POCKET_MODES, + default=DEFAULT_DIFFDOCK_POCKET, + help=( + "How DiffDock's pose is restricted to the pocket. 'auto': keep the " + "highest-confidence sample inside the pocket box when the combination " + "has one, blind selection otherwise. 'box': require a pocket box; no " + "box, or no sample inside it, is a failure. 'blind': ignore any box " + "and keep the top-confidence sample. DiffDock always docks into the " + "prepared receptor chain(s), in every mode." + ), + ) return parser.parse_args() @@ -474,6 +488,7 @@ def _normalize_workspace_path(p): pose_mode=args.pose_mode, flexible_docking=args.flexible_docking, flexres_gnina=args.flexres_gnina, + diffdock_pocket=args.diffdock_pocket, ) skip_docking_and_scoring, run_plip, run_posebusters = resolve_pipeline_steps(args) diff --git a/tests/bulk_run/test_diffdock_pocket.py b/tests/bulk_run/test_diffdock_pocket.py new file mode 100644 index 0000000..59e6b18 --- /dev/null +++ b/tests/bulk_run/test_diffdock_pocket.py @@ -0,0 +1,285 @@ +""" +Tests for DiffDock pose selection (auto / box / blind), the shared selection +record, and the DiffDock rescore inputs (prepared receptor, ligand hydrogens, +minimisation, no-contact guard). +""" + +import subprocess +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from rdkit import Chem +from rdkit.Chem import AllChem + +from guild.constants.bulk import BATCH_FOLDER, COMBINATIONS_TO_RUN_KEY +from guild.constants.diffdock import ( + DIFFDOCK_POCKET_AUTO, + DIFFDOCK_POCKET_BLIND, + DIFFDOCK_POCKET_BOX, + DIFFDOCK_POCKET_KEY, + DIFFDOCK_POSE_SELECTION, + POSE_NO_BOX, + POSE_NO_SAMPLE_IN_BOX, + POSE_NO_SAMPLES, + POSE_SELECTED_BLIND, + POSE_SELECTED_BOX, + SELECTED_POSE_FILE, +) +from guild.constants.guild import DIFFDOCK_SCORE, LIGAND_ID, PROTEIN_CONF_ID, SMILES +from guild.docking.diffdock import ( + _has_receptor_contact, + diffdock_combo_dir, + diffdock_guild_scoring, + find_pocket_box, + read_selected_pose, + resolve_diffdock_pose, + select_diffdock_pose, + write_diffdock_combinations_table, +) +from guild.docking.vina import compute_box_from_sdf, vina_score_pose +from guild.transformers.converters import sdf_to_pdbqt + +TEST_DATA_DIR = Path(__file__).parent.parent / "test_data" +PROTEIN = "prot-A-LIG-A" +LIGAND = "lig1" +COMBO = f"{PROTEIN}_{LIGAND}" + + +def _write_sample(combo_dir: Path, rank: int, confidence: float, centroid) -> Path: + """An ethanol pose translated so its heavy-atom centroid sits at ``centroid``.""" + mol = Chem.AddHs(Chem.MolFromSmiles("CCO")) + AllChem.EmbedMolecule(mol, randomSeed=0xC0FFEE) + mol = Chem.RemoveHs(mol) + conformer = mol.GetConformer() + shift = np.asarray(centroid) - conformer.GetPositions().mean(axis=0) + for idx in range(mol.GetNumAtoms()): + conformer.SetAtomPosition(idx, (conformer.GetPositions()[idx] + shift).tolist()) + path = combo_dir / f"rank{rank}_confidence{confidence:.2f}.sdf" + with Chem.SDWriter(str(path)) as writer: + writer.write(mol) + return path + + +def _write_box(path: Path, center=(0.0, 0.0, 0.0), size=(10.0, 10.0, 10.0)) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "".join(f"center_{a} = {c}\n" for a, c in zip("xyz", center, strict=True)) + + "".join(f"size_{a} = {s}\n" for a, s in zip("xyz", size, strict=True)) + ) + return path + + +@pytest.fixture +def batch(tmp_path): + """A batch with one combination: a high-confidence sample outside the box + and a lower-confidence one inside it.""" + combo_dir = Path(diffdock_combo_dir(str(tmp_path), PROTEIN, LIGAND)) + combo_dir.mkdir(parents=True) + outside = _write_sample(combo_dir, 1, 0.80, (30.0, 0.0, 0.0)) + inside = _write_sample(combo_dir, 2, -0.40, (1.0, 0.0, 0.0)) + box = _write_box(tmp_path / "boxes" / "vina_boxes" / f"{COMBO}.txt") + return { + "folder": tmp_path, + "combo_dir": combo_dir, + "outside": outside, + "inside": inside, + "box": box, + } + + +class TestSelectDiffdockPose: + def test_box_mode_prefers_in_box_sample_over_higher_confidence(self, batch): + selection = select_diffdock_pose( + str(batch["combo_dir"]), str(batch["box"]), DIFFDOCK_POCKET_BOX + ) + assert selection["sdf"] == str(batch["inside"]) + assert selection["confidence"] == pytest.approx(-0.40) + assert selection["reason"] == POSE_SELECTED_BOX + + def test_auto_with_box_behaves_like_box(self, batch): + selection = select_diffdock_pose( + str(batch["combo_dir"]), str(batch["box"]), DIFFDOCK_POCKET_AUTO + ) + assert selection["sdf"] == str(batch["inside"]) + assert selection["reason"] == POSE_SELECTED_BOX + + def test_auto_without_box_falls_back_to_blind(self, batch): + selection = select_diffdock_pose(str(batch["combo_dir"]), None, DIFFDOCK_POCKET_AUTO) + assert selection["sdf"] == str(batch["outside"]) + assert selection["reason"] == POSE_SELECTED_BLIND + + def test_blind_ignores_box(self, batch): + selection = select_diffdock_pose( + str(batch["combo_dir"]), str(batch["box"]), DIFFDOCK_POCKET_BLIND + ) + assert selection["sdf"] == str(batch["outside"]) + assert selection["confidence"] == pytest.approx(0.80) + assert selection["reason"] == POSE_SELECTED_BLIND + + def test_box_mode_without_box_is_a_failure(self, batch): + selection = select_diffdock_pose(str(batch["combo_dir"]), None, DIFFDOCK_POCKET_BOX) + assert selection["sdf"] is None + assert np.isnan(selection["confidence"]) + assert selection["reason"] == POSE_NO_BOX + + def test_no_sample_in_box_is_a_failure(self, batch): + batch["inside"].unlink() + selection = select_diffdock_pose( + str(batch["combo_dir"]), str(batch["box"]), DIFFDOCK_POCKET_BOX + ) + assert selection["sdf"] is None + assert np.isnan(selection["confidence"]) + assert selection["reason"] == POSE_NO_SAMPLE_IN_BOX + + def test_no_samples(self, tmp_path): + selection = select_diffdock_pose(str(tmp_path / "missing"), None, DIFFDOCK_POCKET_BLIND) + assert selection["sdf"] is None + assert selection["reason"] == POSE_NO_SAMPLES + + def test_invalid_mode_raises(self, batch): + with pytest.raises(ValueError): + select_diffdock_pose(str(batch["combo_dir"]), None, "pocket") + + +class TestPocketBoxAndRecord: + def test_find_pocket_box_exact(self, batch): + assert find_pocket_box(str(batch["folder"]), PROTEIN, LIGAND) == str(batch["box"]) + + def test_find_pocket_box_falls_back_to_same_protein(self, batch): + sibling = batch["box"].with_name(f"{PROTEIN}_other.txt") + batch["box"].rename(sibling) + assert find_pocket_box(str(batch["folder"]), PROTEIN, LIGAND) == str(sibling) + + def test_find_pocket_box_none_when_no_pocket(self, tmp_path): + assert find_pocket_box(str(tmp_path), PROTEIN, LIGAND) is None + + def test_resolve_writes_record_that_round_trips(self, batch): + selection = resolve_diffdock_pose( + str(batch["folder"]), PROTEIN, LIGAND, DIFFDOCK_POCKET_AUTO + ) + assert (batch["combo_dir"] / SELECTED_POSE_FILE).is_file() + record = read_selected_pose(str(batch["combo_dir"])) + assert record["sdf"] == selection["sdf"] == str(batch["inside"]) + assert record["reason"] == POSE_SELECTED_BOX + + def test_resolve_records_failures_with_null_pose(self, batch): + batch["inside"].unlink() + resolve_diffdock_pose(str(batch["folder"]), PROTEIN, LIGAND, DIFFDOCK_POCKET_BOX) + record = read_selected_pose(str(batch["combo_dir"])) + assert record["sdf"] is None + assert record["confidence"] is None + assert record["reason"] == POSE_NO_SAMPLE_IN_BOX + + +class TestDiffdockScoring: + def _batch_dictionary(self, folder, mode): + return { + BATCH_FOLDER: str(folder), + COMBINATIONS_TO_RUN_KEY: [(PROTEIN, LIGAND)], + DIFFDOCK_POCKET_KEY: mode, + } + + def test_score_is_confidence_of_selected_pose(self, batch): + scores = diffdock_guild_scoring( + self._batch_dictionary(batch["folder"], DIFFDOCK_POCKET_BOX) + ) + assert scores[DIFFDOCK_SCORE].iloc[0] == pytest.approx(-0.40) + assert scores[DIFFDOCK_POSE_SELECTION].iloc[0] == POSE_SELECTED_BOX + + def test_blind_score_is_top_confidence(self, batch): + scores = diffdock_guild_scoring( + self._batch_dictionary(batch["folder"], DIFFDOCK_POCKET_BLIND) + ) + assert scores[DIFFDOCK_SCORE].iloc[0] == pytest.approx(0.80) + assert scores[DIFFDOCK_POSE_SELECTION].iloc[0] == POSE_SELECTED_BLIND + + def test_failure_scores_nan_not_zero(self, batch): + batch["inside"].unlink() + scores = diffdock_guild_scoring( + self._batch_dictionary(batch["folder"], DIFFDOCK_POCKET_BOX) + ) + assert np.isnan(scores[DIFFDOCK_SCORE].iloc[0]) + assert scores[DIFFDOCK_POSE_SELECTION].iloc[0] == POSE_NO_SAMPLE_IN_BOX + + +def test_combinations_table_points_at_prepared_receptor(tmp_path): + table = pd.DataFrame({PROTEIN_CONF_ID: [PROTEIN], LIGAND_ID: [LIGAND], SMILES: ["CCO"]}) + write_diffdock_combinations_table(table, str(tmp_path)) + written = pd.read_csv(tmp_path / "diffdock_combinations.csv") + assert written["protein_path"].iloc[0] == str( + tmp_path / "proteins" / f"{PROTEIN}_single_chain_clean.pdb" + ) + + +def _split_complex(tmp_path): + receptor = tmp_path / "receptor.pdb" + ligand_pdb = tmp_path / "ligand.pdb" + lines = (TEST_DATA_DIR / "3pbl_lig_complex.pdb").read_text().splitlines(keepends=True) + receptor.write_text("".join(line for line in lines if line.startswith("ATOM")) + "END\n") + ligand_pdb.write_text("".join(line for line in lines if line.startswith("HETATM")) + "END\n") + return receptor, ligand_pdb + + +def test_receptor_contact_guard(tmp_path): + receptor, ligand_pdb = _split_complex(tmp_path) + bound = tmp_path / "bound.sdf" + subprocess.run(["obabel", str(ligand_pdb), "-O", str(bound)], check=True, capture_output=True) + assert _has_receptor_contact(str(bound), str(receptor)) + + far = Chem.MolFromMolFile(str(bound), sanitize=False) + conformer = far.GetConformer() + for idx in range(far.GetNumAtoms()): + conformer.SetAtomPosition(idx, (conformer.GetPositions()[idx] + 200.0).tolist()) + far_path = tmp_path / "far.sdf" + Chem.MolToMolFile(far, str(far_path), kekulize=False) + assert not _has_receptor_contact(str(far_path), str(receptor)) + + +def test_sdf_to_pdbqt_adds_polar_hydrogens_on_request(tmp_path): + mol = Chem.AddHs(Chem.MolFromSmiles("CCO")) + AllChem.EmbedMolecule(mol, randomSeed=0xC0FFEE) + sdf = tmp_path / "ethanol.sdf" + Chem.MolToMolFile(Chem.RemoveHs(mol), str(sdf)) + + without = sdf_to_pdbqt(str(sdf), pdbqt=str(tmp_path / "without.pdbqt")) + with_h = sdf_to_pdbqt(str(sdf), pdbqt=str(tmp_path / "with.pdbqt"), add_hydrogens=True) + + def atom_types(path): + lines = Path(path).read_text().splitlines() + return [line.split()[-1] for line in lines if line.startswith(("ATOM", "HETATM"))] + + assert "HD" not in atom_types(without) + assert "HD" in atom_types(with_h) + + +def test_vina_minimised_score_is_not_worse_than_raw(tmp_path): + receptor, ligand_pdb = _split_complex(tmp_path) + receptor_pdbqt = tmp_path / "receptor.pdbqt" + subprocess.run( + ["obabel", str(receptor), "-xr", "-h", "-O", str(receptor_pdbqt)], + check=True, + capture_output=True, + ) + ligand_sdf = tmp_path / "ligand.sdf" + subprocess.run( + ["obabel", str(ligand_pdb), "-O", str(ligand_sdf)], check=True, capture_output=True + ) + ligand_pdbqt = sdf_to_pdbqt( + str(ligand_sdf), pdbqt=str(tmp_path / "ligand.pdbqt"), add_hydrogens=True + ) + + center, size = compute_box_from_sdf(str(ligand_sdf), padding=6.0) + raw = vina_score_pose(str(receptor_pdbqt), ligand_pdbqt, center, size) + minimised_pose = tmp_path / "minimised.pdbqt" + minimised = vina_score_pose( + str(receptor_pdbqt), + ligand_pdbqt, + center, + size, + minimize=True, + output_pdbqt=str(minimised_pose), + ) + assert minimised <= raw + 1e-6 + assert minimised_pose.is_file() and minimised_pose.stat().st_size > 0 diff --git a/uv.lock b/uv.lock index 1db08ff..c843fc0 100644 --- a/uv.lock +++ b/uv.lock @@ -982,7 +982,7 @@ wheels = [ [[package]] name = "guild" -version = "1.4.0" +version = "1.4.1" source = { editable = "." } dependencies = [ { name = "boltz", extra = ["cuda"] }, From 290721b6bdf955dd81f7a25f7bf237346892ad08 Mon Sep 17 00:00:00 2001 From: AJPreto Date: Fri, 25 Sep 2026 16:17:15 +0000 Subject: [PATCH 2/4] Keep reviewer-response scratch scripts out of the DiffDock change --- build_sweep_table.py | 27 ----- run_native_rmsd.py | 231 ------------------------------------------- run_posebusters.py | 39 -------- 3 files changed, 297 deletions(-) delete mode 100644 build_sweep_table.py delete mode 100644 run_native_rmsd.py delete mode 100644 run_posebusters.py diff --git a/build_sweep_table.py b/build_sweep_table.py deleted file mode 100644 index dc30687..0000000 --- a/build_sweep_table.py +++ /dev/null @@ -1,27 +0,0 @@ -import pandas as pd - -TARGETS = [ - "7l1v-R-XGD-R", "7v3z-A-9GF-A", "4ea3-A-0NN-A", "6ot0-R-CO1-R", "6me6-A-JEY-A", - "8gdc-R-P2E-R", "6ds0-A-H8M-A", "5o9h-A-9P2-A", "5tud-A-ERM-A", "7jvr-R-08Y-R", -] -N_PER_TARGET = 100 -SEED = 42 - -df = pd.read_csv("vinarun_all_combinations.csv", low_memory=False) -df = df[df.protein_config_id.isin(TARGETS)].copy() - -# Deterministic: sort by ligand_id first so the sample does not depend on row order. -picked = ( - df.sort_values(["protein_config_id", "ligand_id"]) - .groupby("protein_config_id", group_keys=False) - .apply(lambda g: g.sample(n=min(N_PER_TARGET, len(g)), random_state=SEED)) - .sort_values(["protein_config_id", "ligand_id"]) -) - -# Repoint protein_path at this machine's mount. -picked["protein_path"] = "/workspace/data/" + picked["protein_id"] + ".pdb" - -picked.to_csv("combinations.csv", index=False) -print(f"rows: {len(picked)} targets: {picked.protein_config_id.nunique()}") -print(picked.groupby("protein_config_id").size().to_string()) -print(picked.ligand_category.value_counts().to_string()) diff --git a/run_native_rmsd.py b/run_native_rmsd.py deleted file mode 100644 index f71f5d2..0000000 --- a/run_native_rmsd.py +++ /dev/null @@ -1,231 +0,0 @@ -import os -from pathlib import Path - -os.environ.setdefault("UV_CACHE_DIR", "/tmp/uv-cache") -os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/tmp/torchinductor") - -import numpy as np -import pandas as pd -from posebusters import PoseBusters - -from guild.constants.interactions import LIGAND_RESNAME -from guild.analysis.posebusters import _pose_mols -from guild.tools.pose_molecules import split_complex_records, mol_from_pdb_block - -PROJECT_ROOT = Path("/workspace") -DATA_ROOT = PROJECT_ROOT / "data" / "small-example-all-methods" - -TARGETS = [ - { - "protein_config_id": "7v3z-A-9GF-A", - "raw_pdb": PROJECT_ROOT / "data" / "7v3z.pdb", - "raw_chain": "A", - "resname": "9GF", - "combination_id": "7v3z-A-9GF-A_9GF_native", - "smiles": "CCCCCCC(C)(C)c1ccc([C@@H]2C[C@H](O)CC[C@H]2CCCO)c(O)c1", - "batch_folder": str(DATA_ROOT / "batches" / "batch_83"), - }, - { - "protein_config_id": "6ot0-R-CO1-R", - "raw_pdb": PROJECT_ROOT / "data" / "6ot0.pdb", - "raw_chain": "R", - "resname": "CO1", - "combination_id": "6ot0-R-CO1-R_CO1_native", - "smiles": "C[C@H](CC[C@@H]1OC1(C)C)[C@H]2CC[C@H]3[C@@H]4CC=C5C[C@@H](O)CC[C@]5(C)[C@H]4CC[C@]23C", - "batch_folder": str(DATA_ROOT / "batches" / "batch_84"), - }, - { - "protein_config_id": "8gdc-R-P2E-R", - "raw_pdb": PROJECT_ROOT / "data" / "8gdc.pdb", - "raw_chain": "R", - "resname": "P2E", - "combination_id": "8gdc-R-P2E-R_P2E_native", - "smiles": "CCCCC[C@H](O)/C=C/[C@H]1[C@H](O)CC(=O)[C@@H]1C\\C=C/CCCC(O)=O", - "batch_folder": str(DATA_ROOT / "batches" / "batch_84"), - }, -] - -METHODS = ["vina", "gnina", "karmadock", "diffdock", "boltz"] - - -def read_ca_coords(path, chain_filter=None): - # Dedupe by residue number, keeping the first occurrence (guild's own prep - # collapses alternate side-chain conformers to a single one, preferring - # altloc 'A' -- confirmed against the run's own logged warning about - # 8gdc R:163 HIS having an A/B altloc; the raw PDB still carries both). - coords = [] - seen_resnum = set() - with open(path) as f: - for line in f: - if line.startswith("ATOM") and line[12:16].strip() == "CA": - if chain_filter and line[21] != chain_filter: - continue - resnum = line[22:27] # includes insertion code - if resnum in seen_resnum: - continue - seen_resnum.add(resnum) - coords.append((float(line[30:38]), float(line[38:46]), float(line[46:54]))) - return np.array(coords) - - -def kabsch_transform(mobile, target): - """Rotation+translation that maps `mobile` (N,3) onto `target` (N,3), in - residue-sequence order (robust to residue renumbering across guild's - receptor-prep stages, since chain length/order is preserved even when the - numbering isn't -- confirmed empirically: same atom count, sequential). - """ - assert mobile.shape == target.shape, f"CA count mismatch: {mobile.shape} vs {target.shape}" - mobile_c = mobile - mobile.mean(axis=0) - target_c = target - target.mean(axis=0) - H = mobile_c.T @ target_c - U, S, Vt = np.linalg.svd(H) - d = np.sign(np.linalg.det(Vt.T @ U.T)) - D = np.diag([1, 1, d]) - R = Vt.T @ D @ U.T - t = target.mean(axis=0) - R @ mobile.mean(axis=0) - return R, t - - -def apply_transform_to_pdb_block(lines, R, t): - out = [] - for line in lines: - if line.startswith(("ATOM", "HETATM")) and len(line) >= 54: - x, y, z = float(line[30:38]), float(line[38:46]), float(line[46:54]) - xyz = R @ np.array([x, y, z]) + t - newline = f"{line[:30]}{xyz[0]:8.3f}{xyz[1]:8.3f}{xyz[2]:8.3f}{line[54:]}" - out.append(newline) - else: - out.append(line) - return out - - -def crystal_ligand_lines(raw_pdb_path, resname): - lines = [] - with open(raw_pdb_path) as fh: - for line in fh: - if line.startswith("HETATM") and line[17:20].strip() == resname: - lines.append(line) - if not lines: - raise ValueError(f"no HETATM lines for {resname} in {raw_pdb_path}") - return lines - - -def complex_pdb_path(batch_folder, method, combination_id): - return f"{batch_folder}/{method}/{combination_id}_complex.pdb" - - -def receptor_path_from_complex(complex_pdb, out_path, ligand_resname=LIGAND_RESNAME): - text = Path(complex_pdb).read_text(encoding="utf-8", errors="replace") - _, protein_lines = split_complex_records(text, ligand_resname) - if not protein_lines: - raise ValueError(f"no protein atoms left in {complex_pdb} after excluding {ligand_resname}") - with open(out_path, "w") as fh: - fh.writelines(protein_lines) - fh.write("END\n") - return out_path - - -def main(): - buster = PoseBusters(config="redock") - rows = [] - printed_columns = False - - for target in TARGETS: - raw_ca = read_ca_coords(target["raw_pdb"], chain_filter=target["raw_chain"]) - raw_ligand_lines = crystal_ligand_lines(target["raw_pdb"], target["resname"]) - - for method in METHODS: - combo_id = target["combination_id"] - cpdb = complex_pdb_path(target["batch_folder"], method, combo_id) - record = {"protein_config_id": target["protein_config_id"], "method": method} - - if not os.path.exists(cpdb): - rows.append({**record, "status": "missing_complex_pdb", "path_checked": cpdb}) - continue - - complex_ca = read_ca_coords(cpdb) - if complex_ca.shape != raw_ca.shape: - rows.append({ - **record, "status": "ca_count_mismatch", - "reason": f"raw has {raw_ca.shape[0]} CA, complex has {complex_ca.shape[0]}", - }) - continue - - R, t = kabsch_transform(raw_ca, complex_ca) - rmsd_fit = float(np.sqrt(np.mean(np.sum((raw_ca @ R.T + t - complex_ca) ** 2, axis=1)))) - transformed_ligand_lines = apply_transform_to_pdb_block(raw_ligand_lines, R, t) - ligand_block = "".join(transformed_ligand_lines) + "END\n" - - mol_true, true_reason, true_fallback = mol_from_pdb_block(ligand_block, target["smiles"]) - if mol_true is None: - rows.append({**record, "status": "crystal_ligand_build_failed", "reason": true_reason}) - continue - - poses = _pose_mols( - complex_pdb_path=cpdb, - batch_folder=target["batch_folder"], - docking_method=method, - combination_id=combo_id, - smiles=target["smiles"], - ligand_resname=LIGAND_RESNAME, - max_poses=1, - ) - if not poses or poses[0][0] is None: - reason = poses[0][1] if poses else "no pose records found" - rows.append({**record, "status": "no_usable_pose", "reason": reason}) - continue - - mol_pred, pose_reason, pred_fallback = poses[0] - receptor_tmp = f"/tmp/{target['protein_config_id']}_{method}_receptor.pdb" - try: - receptor_path_from_complex(cpdb, receptor_tmp) - except Exception as error: - rows.append({**record, "status": "receptor_build_failed", "reason": str(error)}) - continue - - try: - frame = buster.bust( - mol_pred=mol_pred, mol_true=mol_true, mol_cond=receptor_tmp, full_report=True - ) - except Exception as error: - rows.append({**record, "status": "posebusters_raised", "reason": str(error)}) - continue - - if frame is None or frame.empty: - rows.append({**record, "status": "posebusters_empty_frame"}) - continue - - raw = frame.reset_index(drop=True).iloc[0].to_dict() - if not printed_columns: - print("PoseBusters redock columns:", sorted(raw.keys())) - printed_columns = True - - rmsd = raw.get("rmsd") - within_2A = raw.get("rmsd_≤_2å") - - rows.append({ - **record, - "status": "ok", - "kabsch_fit_rmsd_ca": rmsd_fit, # sanity check: should be ~0 - "pred_template_fallback": pred_fallback, - "true_template_fallback": true_fallback, - "mol_true_loaded": raw.get("mol_true_loaded"), - "mol_pred_loaded": raw.get("mol_pred_loaded"), - "mol_cond_loaded": raw.get("mol_cond_loaded"), - "inchi_crystal_valid": raw.get("inchi_crystal_valid"), - "inchi_docked_valid": raw.get("inchi_docked_valid"), - "rmsd": rmsd, - "kabsch_rmsd": raw.get("kabsch_rmsd"), - "within_2A": within_2A, - "stereochemistry_preserved": raw.get("stereochemistry_preserved"), - }) - - df = pd.DataFrame(rows) - out_path = DATA_ROOT / "native_ligand_rmsd.tsv" - df.to_csv(out_path, sep="\t", index=False) - print(f"Wrote {out_path}") - print(df.to_string()) - - -if __name__ == "__main__": - main() diff --git a/run_posebusters.py b/run_posebusters.py deleted file mode 100644 index bc4825e..0000000 --- a/run_posebusters.py +++ /dev/null @@ -1,39 +0,0 @@ -import os -from pathlib import Path - -import pandas as pd - -os.environ.setdefault("UV_CACHE_DIR", "/tmp/uv-cache") -os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", "/tmp/torchinductor") - -PROJECT_ROOT = Path("/workspace") - -import guild.constants.system as _sys_const -import guild.bulk as _bulk_mod - -_sys_const.WORKING_DIR_PATH = PROJECT_ROOT -_sys_const.PROJECTS_FOLDER = str(PROJECT_ROOT / "data") -_bulk_mod.WORKING_DIR_PATH = PROJECT_ROOT -_bulk_mod.PROJECTS_FOLDER = str(PROJECT_ROOT / "data") - -from guild.bulk import BulkRun - -runs_table = pd.read_csv("/workspace/combinations.csv") - -# Must match the run-guild invocation exactly: project name, methods, batch_size, and -# the decoy/known-binder flags. BulkRun reconstructs the batch folder layout from them, -# and a mismatch silently finds no poses and writes empty TSVs rather than erroring. -# This run used NO_DECOYS=1 (decoys were explicit rows) and the Makefile's default -# BATCH_SIZE=2, confirmed against batch_progress.log (83 batches for 165 combos). -BATCH_SIZE = 2 - -bulk = BulkRun( - runs_table, - "small-example-all-methods", - methods_to_run=["vina", "gnina", "karmadock", "diffdock", "boltz"], - batch_size=BATCH_SIZE, - use_decoys=False, - use_known_binders=False, -) -bulk.run_pose_validity_analysis() -print(f"Wrote {bulk.posebusters_path} and {bulk.posebusters_report_path}") From aedaa2e55c2743fdeee757daeaeb7cd9f52783d2 Mon Sep 17 00:00:00 2001 From: "A. J. Preto" Date: Fri, 25 Sep 2026 18:27:29 +0100 Subject: [PATCH 3/4] Handle exceptions when returning energy value Add error handling for energy return value. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- guild/docking/vina.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/guild/docking/vina.py b/guild/docking/vina.py index fdef0bf..5e1b53b 100644 --- a/guild/docking/vina.py +++ b/guild/docking/vina.py @@ -475,7 +475,10 @@ def vina_score_pose( if output_pdbqt is not None: v.write_pose(output_pdbqt, overwrite=True) - return float(energy[0]) + try: + return float(energy[0]) + except (TypeError, IndexError): + return float(energy) # ── Vina score-only re-scoring of Boltz-predicted complexes ───────────────── From fbe6f65f4ef4dd6316ff1bd7f6178c3c7e5f4208 Mon Sep 17 00:00:00 2001 From: AJPreto Date: Fri, 25 Sep 2026 18:13:14 +0000 Subject: [PATCH 4/4] Fixing boltz --- guild/docking/boltz.py | 89 +++++++++---- guild/transformers/converters.py | 84 ++++++++++++- tests/bulk_run/test_boltz_rescore_prep.py | 144 ++++++++++++++++++++++ 3 files changed, 289 insertions(+), 28 deletions(-) create mode 100644 tests/bulk_run/test_boltz_rescore_prep.py diff --git a/guild/docking/boltz.py b/guild/docking/boltz.py index 3e77504..7eaae7c 100644 --- a/guild/docking/boltz.py +++ b/guild/docking/boltz.py @@ -11,6 +11,7 @@ import numpy as np import pandas as pd import yaml +from rdkit import Chem from tqdm import tqdm from guild.constants.boltz import ( @@ -23,6 +24,7 @@ COMBINATIONS_TABLE_KEY, COMBINATIONS_TO_RUN_KEY, OUTPUT_LOG_FILE, + SMILES_NAMES_DICTIONARY_KEY, ) from guild.constants.general import RANDOM_SEED from guild.constants.guild import ( @@ -45,10 +47,11 @@ _validate_connected_ligand_pdbqt, vina_score_pose, ) +from guild.tools.pose_molecules import mol_from_pdb_block from guild.transformers.converters import ( cif_to_pdb, - ligand_pdb_to_pdbqt, protein_pdb_to_pdbqt, + sdf_to_pdbqt, ) logger = logging.getLogger(__name__) @@ -504,10 +507,38 @@ def _ensure_boltz_complex_pdb(boltz_folder: str, run_id: str) -> str: return complex_pdb +def _prepare_boltz_ligand(complex_pdb: str, ligand_pdb: str, smiles: str): + """ + Build the Boltz ligand for rescoring: bond orders from ``smiles``, + hydrogens added in place, written next to ``ligand_pdb`` as an SDF. + + Boltz writes heavy atoms with no bond orders; inferring bonds from that + geometry and adding hydrogens to the guess can mis-protonate the ligand. + A pose whose geometry does not match its SMILES (e.g. an atom Boltz put + too close to another) is not the ligand and is not rescored. + + :return: ``(sdf_path, heavy_atom_coordinates)``. + :raises ValueError: when the pose cannot be matched to ``smiles``. + """ + _extract_ligand_records(complex_pdb, ligand_pdb, resname="LIG") + with open(ligand_pdb) as handle: + block = handle.read() + mol, reason, used_fallback = mol_from_pdb_block(block, smiles) + if mol is None or used_fallback: + raise ValueError(f"Boltz ligand pose does not match its SMILES ({reason}); not rescoring") + + heavy_coordinates = mol.GetConformer().GetPositions() + mol = Chem.AddHs(mol, addCoords=True) + sdf_path = ligand_pdb.replace(".pdb", ".sdf") + Chem.MolToMolFile(mol, sdf_path) + return sdf_path, heavy_coordinates + + def rescore_boltz_pose( boltz_folder: str, protein_conf_id: str, ligand_id: str, + smiles: str, output_dir: str = None, box_padding: float = 4.0, seed: int = RANDOM_SEED, @@ -519,12 +550,14 @@ def rescore_boltz_pose( Pipeline (all in Boltz's predicted coordinate frame): 1. Ensure the relabelled complex PDB exists (regenerate from CIF if needed). - 2. Extract the receptor (everything that is not the ligand resname) → PDBQT. - 3. Extract the ligand (resname ``LIG``) → PDBQT. - 4. Validate the ligand PDBQT is a single connected molecule — Boltz - occasionally predicts physically implausible ligand geometry, which - leaves OpenBabel's distance-based bond inference unable to connect - the ligand's own atoms (see :func:`guild.docking.vina._validate_connected_ligand_pdbqt`). + 2. Extract the ligand (resname ``LIG``), assign bond orders from its + SMILES and add hydrogens (:func:`_prepare_boltz_ligand`) → PDBQT. + 3. Validate the ligand PDBQT is a single connected molecule (see + :func:`guild.docking.vina._validate_connected_ligand_pdbqt`). + 4. Extract the receptor (everything that is not the ligand resname) → + PDBQT. Predicted receptors sometimes place two residues close enough + that Meeko reads a bond; those residues are dropped and preparation + retried, unless they lie within 8 Å of the ligand. 5. Compute the Vina box from the ligand's bounding box. 6. Call :func:`guild.docking.vina.vina_score_pose` (score-only). @@ -532,6 +565,7 @@ def rescore_boltz_pose( (``{batch_folder}/boltz``). :param protein_conf_id: Protein configuration ID. :param ligand_id: Ligand identifier. + :param smiles: The ligand's SMILES, used for bond orders and hydrogens. :param output_dir: Where to write intermediate PDB/PDBQT files. Defaults to ``boltz_folder``. :param box_padding: Padding around the ligand bounding box (Å). @@ -546,7 +580,13 @@ def rescore_boltz_pose( output_dir = boltz_folder os.makedirs(output_dir, exist_ok=True) - # Per-pose receptor in Boltz's frame + # Ligand in Boltz's frame + ligand_pdb = os.path.join(output_dir, f"{run_id}_ligand_rescore.pdb") + ligand_sdf, ligand_coordinates = _prepare_boltz_ligand(complex_pdb, ligand_pdb, smiles) + ligand_pdbqt = sdf_to_pdbqt(ligand_sdf, pdbqt=ligand_pdb.replace(".pdb", ".pdbqt")) + _validate_connected_ligand_pdbqt(ligand_pdbqt) + + # Per-pose receptor in the same frame receptor_pdb = os.path.join(output_dir, f"{run_id}_receptor_rescore.pdb") _extract_protein_from_complex(complex_pdb, receptor_pdb, ligand_resname="LIG") receptor_pdbqt = receptor_pdb.replace(".pdb", ".pdbqt") @@ -554,15 +594,10 @@ def rescore_boltz_pose( input_pdb=receptor_pdb, output_pdbqt=receptor_pdbqt, allow_bad_res=True, + delete_clashing_residues=True, + protected_coordinates=ligand_coordinates, ) - # Ligand in the same frame - ligand_pdb = os.path.join(output_dir, f"{run_id}_ligand_rescore.pdb") - _extract_ligand_records(complex_pdb, ligand_pdb, resname="LIG") - ligand_pdb_to_pdbqt(pdb=ligand_pdb) - ligand_pdbqt = ligand_pdb.replace(".pdb", ".pdbqt") - _validate_connected_ligand_pdbqt(ligand_pdbqt) - center, size = _compute_box_from_pdb_atoms(ligand_pdb, padding=box_padding) score = vina_score_pose( @@ -602,6 +637,7 @@ def _append_progress_log(progress_log_path, message): def vina_rescore_boltz_batch( batch_folder: str, combinations: list, + smiles_by_ligand: dict, box_padding: float = 4.0, seed: int = RANDOM_SEED, progress_log_path: str = None, @@ -611,6 +647,7 @@ def vina_rescore_boltz_batch( :param batch_folder: Path to the batch folder. :param combinations: List of ``(protein_conf_id, ligand_id)`` tuples. + :param smiles_by_ligand: ``ligand_id → SMILES`` for the batch. :param box_padding: Padding around the ligand bounding box (Å). :param seed: Random seed for Vina. :param progress_log_path: Optional path to the batch's persisted @@ -634,6 +671,7 @@ def vina_rescore_boltz_batch( boltz_folder=boltz_folder, protein_conf_id=protein_conf_id, ligand_id=ligand_id, + smiles=smiles_by_ligand[ligand_id], output_dir=rescore_output_dir, box_padding=box_padding, seed=seed, @@ -692,6 +730,7 @@ def vina_rescore_boltz_guild_scoring(batch_dictionary): df = vina_rescore_boltz_batch( batch_folder=batch_folder, combinations=combinations, + smiles_by_ligand=batch_dictionary[SMILES_NAMES_DICTIONARY_KEY], progress_log_path=progress_log_path, ) keep = [COMBINATION_ID, PROTEIN_CONF_ID, LIGAND_ID, VINA_RESCORE_BOLTZ_SCORE] @@ -706,9 +745,8 @@ def vina_rescore_boltz_guild_scoring(batch_dictionary): # pose), but scored with gnina's CNN-backed function instead. The receptor is # passed to gnina as a plain PDB — gnina reads ``.pdb`` receptors directly, # so no protein_pdb_to_pdbqt / mk_prepare_receptor.py step is needed here. -# The ligand still goes through ligand_pdb_to_pdbqt: Boltz's raw coordinates -# carry no bond-order information, so OpenBabel bond inference (and the -# single-connected-fragment validation) is unavoidable regardless of engine. +# The ligand is the same SMILES-templated, hydrogenated SDF the Vina track +# uses; gnina reads SDF directly. # ──────────────────────────────────────────────────────────────────────────── @@ -716,6 +754,7 @@ def rescore_boltz_pose_gnina( boltz_folder: str, protein_conf_id: str, ligand_id: str, + smiles: str, output_dir: str = None, box_padding: float = 4.0, seed: int = RANDOM_SEED, @@ -729,6 +768,7 @@ def rescore_boltz_pose_gnina( :param boltz_folder: Directory containing Boltz outputs for this batch. :param protein_conf_id: Protein configuration ID. :param ligand_id: Ligand identifier. + :param smiles: The ligand's SMILES, used for bond orders and hydrogens. :param output_dir: Where to write intermediate PDB/PDBQT files. Defaults to ``boltz_folder``. :param box_padding: Padding around the ligand bounding box (Å). @@ -749,20 +789,15 @@ def rescore_boltz_pose_gnina( receptor_pdb = os.path.join(output_dir, f"{run_id}_gnina_receptor_rescore.pdb") _extract_protein_from_complex(complex_pdb, receptor_pdb, ligand_resname="LIG") - # Ligand: bond order must still be inferred, so this goes through the - # same OpenBabel + connectivity-validation pipeline as the Vina track. ligand_pdb = os.path.join(output_dir, f"{run_id}_gnina_ligand_rescore.pdb") - _extract_ligand_records(complex_pdb, ligand_pdb, resname="LIG") - ligand_pdb_to_pdbqt(pdb=ligand_pdb) - ligand_pdbqt = ligand_pdb.replace(".pdb", ".pdbqt") - _validate_connected_ligand_pdbqt(ligand_pdbqt) + ligand_sdf, _ = _prepare_boltz_ligand(complex_pdb, ligand_pdb, smiles) center, size = _compute_box_from_pdb_atoms(ligand_pdb, padding=box_padding) combination_id = f"{protein_conf_id}_{ligand_id}" score, cnn_score = gnina_score_pose( receptor=receptor_pdb, - ligand=ligand_pdbqt, + ligand=ligand_sdf, center=center, size=size, output_dir=output_dir, @@ -786,6 +821,7 @@ def rescore_boltz_pose_gnina( def gnina_rescore_boltz_batch( batch_folder: str, combinations: list, + smiles_by_ligand: dict, box_padding: float = 4.0, seed: int = RANDOM_SEED, use_gpu: bool = False, @@ -796,6 +832,7 @@ def gnina_rescore_boltz_batch( :param batch_folder: Path to the batch folder. :param combinations: List of ``(protein_conf_id, ligand_id)`` tuples. + :param smiles_by_ligand: ``ligand_id → SMILES`` for the batch. :param box_padding: Padding around the ligand bounding box (Å). :param seed: Random seed for gnina. :param use_gpu: When False (default), passes ``--no_gpu`` to gnina. @@ -821,6 +858,7 @@ def gnina_rescore_boltz_batch( boltz_folder=boltz_folder, protein_conf_id=protein_conf_id, ligand_id=ligand_id, + smiles=smiles_by_ligand[ligand_id], output_dir=rescore_output_dir, box_padding=box_padding, seed=seed, @@ -890,6 +928,7 @@ def gnina_rescore_boltz_guild_scoring(batch_dictionary, use_gpu: bool = False): df = gnina_rescore_boltz_batch( batch_folder=batch_folder, combinations=combinations, + smiles_by_ligand=batch_dictionary[SMILES_NAMES_DICTIONARY_KEY], use_gpu=use_gpu, progress_log_path=progress_log_path, ) diff --git a/guild/transformers/converters.py b/guild/transformers/converters.py index d926ebf..1c9bb53 100644 --- a/guild/transformers/converters.py +++ b/guild/transformers/converters.py @@ -6,10 +6,13 @@ - PDB to SDF """ +import logging import os +import re import shutil import subprocess +import numpy as np from rdkit import Chem from rdkit.Chem import AllChem, rdMolAlign @@ -17,6 +20,8 @@ from guild.constants.poses import POSE_FILE_EXTENSION from guild.constants.system import SHELL_SILENCER +logger = logging.getLogger(__name__) + # warnings.filterwarnings("ignore", category=DeprecationWarning) @@ -387,20 +392,65 @@ def sdf_to_pdbqt( return pdbqt +# Meeko reports two residues it could not template because a steric clash was +# read as a covalent bond (typical of predicted structures) as e.g. +# "matched with excess inter-residue bond(s): A:69". +_EXCESS_BOND_RESIDUE = re.compile(r"excess inter-residue bond\(s\): (\w+):(-?\d+[A-Za-z]?)") + + +def _residue_spec(residues) -> str: + """Meeko ``--delete_residues`` spec for ``[(chain, resnum), ...]``, e.g. ``A:69,72,B:5``.""" + by_chain = {} + for chain, resnum in residues: + by_chain.setdefault(chain, []).append(resnum) + return ",".join(f"{chain}:{','.join(nums)}" for chain, nums in sorted(by_chain.items())) + + +def _residues_near(pdb_path: str, residues, coordinates, cutoff: float) -> list: + """The subset of ``residues`` with any atom within ``cutoff`` Å of ``coordinates``.""" + wanted = set(residues) + points = np.asarray(coordinates, dtype=float).reshape(-1, 3) + near = set() + with open(pdb_path) as handle: + for line in handle: + if not line.startswith(("ATOM", "HETATM")): + continue + key = (line[21].strip(), line[22:27].strip()) + if key not in wanted or key in near: + continue + atom = np.array([float(line[30:38]), float(line[38:46]), float(line[46:54])]) + if np.linalg.norm(points - atom, axis=1).min() < cutoff: + near.add(key) + return sorted(near) + + def protein_pdb_to_pdbqt( input_pdb: str, output_pdbqt: str | None = None, default_altloc: str = "A", allow_bad_res: bool = False, + delete_clashing_residues: bool = False, + protected_coordinates=None, + protected_cutoff: float = 8.0, ): """ - Convert a PDB file to a PDBQT file. + Convert a PDB file to a PDBQT file with Meeko. :param input_pdb: PDB file to be converted :param output_pdbqt: PDBQT file to be written :param default_altloc: Default alternate location :param allow_bad_res: Allow bad residues - return: PDBQT file + :param delete_clashing_residues: When Meeko rejects the receptor because + two residues sit close enough that it reads the contact as a bond + (typical of predicted structures), retry once with those residues + deleted. For predicted complexes only; crystal receptors should fail. + :param protected_coordinates: Coordinates (e.g. the ligand's atoms) that + a deleted residue must stay clear of, so the deletion cannot change a + score computed around them. + :param protected_cutoff: Minimum distance (Å) between a deleted residue + and ``protected_coordinates``; 8 Å is Vina's interaction cutoff. + :return: PDBQT file + :raises RuntimeError: with Meeko's output when preparation fails. """ output_pdbqt = output_pdbqt or input_pdb.replace(".pdb", ".pdbqt") cmd = [ @@ -415,7 +465,35 @@ def protein_pdb_to_pdbqt( if allow_bad_res: cmd += ["--allow_bad_res"] - subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode == 0: + return output_pdbqt + + output = f"{result.stdout}\n{result.stderr}" + residues = sorted(set(_EXCESS_BOND_RESIDUE.findall(output))) + if not (delete_clashing_residues and residues): + raise RuntimeError( + f"mk_prepare_receptor.py failed for {input_pdb}: {output.strip()[-1500:]}" + ) + + if protected_coordinates is not None: + near = _residues_near(input_pdb, residues, protected_coordinates, protected_cutoff) + if near: + raise RuntimeError( + f"mk_prepare_receptor.py failed for {input_pdb} on clashing residue(s) " + f"{_residue_spec(near)} within {protected_cutoff} Å of the ligand; not deleting them" + ) + + spec = _residue_spec(residues) + logger.warning( + f"Meeko read a steric clash as a bond in {input_pdb}; retrying without residue(s) {spec}" + ) + retry = subprocess.run(cmd + ["--delete_residues", spec], capture_output=True, text=True) + if retry.returncode != 0: + raise RuntimeError( + f"mk_prepare_receptor.py failed for {input_pdb} even without residue(s) {spec}: " + f"{(retry.stdout + retry.stderr).strip()[-1500:]}" + ) return output_pdbqt diff --git a/tests/bulk_run/test_boltz_rescore_prep.py b/tests/bulk_run/test_boltz_rescore_prep.py new file mode 100644 index 0000000..c3435c8 --- /dev/null +++ b/tests/bulk_run/test_boltz_rescore_prep.py @@ -0,0 +1,144 @@ +""" +Tests for Boltz rescore input preparation: Meeko's clash-residue retry and the +SMILES-templated, hydrogenated ligand. +""" + +import subprocess +from pathlib import Path +from unittest.mock import patch + +import numpy as np +import pytest +from rdkit import Chem +from rdkit.Chem import AllChem + +from guild.docking.boltz import _prepare_boltz_ligand +from guild.transformers.converters import ( + _residue_spec, + _residues_near, + protein_pdb_to_pdbqt, +) + +MEEKO_CLASH = ( + "matched with excess inter-residue bond(s): A:69\n" + "matched with excess inter-residue bond(s): A:72\n" + "RuntimeError: Expected 2 paddings for (A:69, A:72) with bonds [(1, 18)], but got 0\n" +) + + +def _pdb_line(serial, name, resname, chain, resnum, xyz, element="C", record="ATOM"): + x, y, z = xyz + return ( + f"{record:<6}{serial:>5} {name:<4} {resname:>3} {chain}{resnum:>4} " + f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 {element:>2}\n" + ) + + +@pytest.fixture +def receptor(tmp_path): + lines = [ + _pdb_line(1, "CA", "ASN", "A", 69, (30.0, 0.0, 0.0)), + _pdb_line(2, "CA", "ARG", "A", 72, (31.0, 0.0, 0.0)), + _pdb_line(3, "CA", "GLY", "A", 10, (2.0, 0.0, 0.0)), + ] + path = tmp_path / "receptor.pdb" + path.write_text("".join(lines) + "END\n") + return path + + +def _completed(returncode, stdout=""): + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="") + + +def test_residue_spec_groups_by_chain(): + assert _residue_spec([("A", "69"), ("A", "72"), ("B", "5")]) == "A:69,72,B:5" + + +def test_residues_near_uses_any_atom(receptor): + ligand = np.array([[0.0, 0.0, 0.0]]) + residues = [("A", "69"), ("A", "10")] + assert _residues_near(str(receptor), residues, ligand, 8.0) == [("A", "10")] + + +def test_success_needs_no_retry(receptor): + with patch("guild.transformers.converters.subprocess.run", return_value=_completed(0)) as run: + protein_pdb_to_pdbqt(str(receptor), delete_clashing_residues=True) + assert run.call_count == 1 + + +def test_failure_raises_meeko_output_by_default(receptor): + with patch( + "guild.transformers.converters.subprocess.run", return_value=_completed(1, MEEKO_CLASH) + ): + with pytest.raises(RuntimeError, match="excess inter-residue bond"): + protein_pdb_to_pdbqt(str(receptor)) + + +def test_clash_retry_deletes_reported_residues(receptor): + calls = [_completed(1, MEEKO_CLASH), _completed(0)] + with patch("guild.transformers.converters.subprocess.run", side_effect=calls) as run: + protein_pdb_to_pdbqt( + str(receptor), + delete_clashing_residues=True, + protected_coordinates=np.array([[0.0, 0.0, 0.0]]), + ) + retry_cmd = run.call_args_list[1].args[0] + assert retry_cmd[-2:] == ["--delete_residues", "A:69,72"] + + +def test_clash_near_ligand_is_not_deleted(receptor): + ligand_next_to_clash = np.array([[30.5, 0.0, 0.0]]) + with patch( + "guild.transformers.converters.subprocess.run", return_value=_completed(1, MEEKO_CLASH) + ) as run: + with pytest.raises(RuntimeError, match="within 8.0 Å of the ligand"): + protein_pdb_to_pdbqt( + str(receptor), + delete_clashing_residues=True, + protected_coordinates=ligand_next_to_clash, + ) + assert run.call_count == 1 + + +def test_failed_retry_raises(receptor): + calls = [_completed(1, MEEKO_CLASH), _completed(1, "still broken")] + with patch("guild.transformers.converters.subprocess.run", side_effect=calls): + with pytest.raises(RuntimeError, match="even without residue"): + protein_pdb_to_pdbqt(str(receptor), delete_clashing_residues=True) + + +def _complex_with_ligand(tmp_path: Path, smiles: str, squash: bool = False) -> Path: + mol = Chem.AddHs(Chem.MolFromSmiles(smiles)) + AllChem.EmbedMolecule(mol, randomSeed=0xC0FFEE) + mol = Chem.RemoveHs(mol) + positions = mol.GetConformer().GetPositions() + if squash: + # Put two non-bonded heavy atoms on top of each other, as a distorted + # prediction would; bond inference then disagrees with the SMILES. + positions[-1] = positions[0] + 0.3 + lines = [_pdb_line(1, "CA", "GLY", "A", 1, (20.0, 20.0, 20.0))] + for idx, atom in enumerate(mol.GetAtoms(), start=2): + name = f"{atom.GetSymbol()}{idx}" + lines.append( + _pdb_line(idx, name, "LIG", "L", 1, positions[idx - 2], atom.GetSymbol(), "HETATM") + ) + path = tmp_path / "complex.pdb" + path.write_text("".join(lines) + "END\n") + return path + + +def test_boltz_ligand_gets_smiles_bond_orders_and_hydrogens(tmp_path): + smiles = "OC(=O)c1ccccc1" + complex_pdb = _complex_with_ligand(tmp_path, smiles) + sdf, heavy = _prepare_boltz_ligand(str(complex_pdb), str(tmp_path / "ligand.pdb"), smiles) + mol = Chem.MolFromMolFile(sdf, removeHs=False) + assert heavy.shape == (9, 3) + assert sum(atom.GetAtomicNum() == 1 for atom in mol.GetAtoms()) == 6 + assert Chem.MolToSmiles(Chem.RemoveHs(mol)) == Chem.MolToSmiles(Chem.MolFromSmiles(smiles)) + + +def test_boltz_ligand_that_does_not_match_smiles_is_rejected(tmp_path): + smiles = "OCCCCCCO" + complex_pdb = _complex_with_ligand(tmp_path, smiles, squash=True) + with pytest.raises(ValueError, match="does not match its SMILES"): + _prepare_boltz_ligand(str(complex_pdb), str(tmp_path / "ligand.pdb"), smiles)