Datasets:
Download verify_bundle.py from genesisml/PocketWatch: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/genesisml/PocketWatch/resolve/main/verify_bundle.py
- Command line
-
hf download hf://datasets/genesisml/PocketWatch/verify_bundle.py
-
curl -L -o verify_bundle.py https://huggingface.co/datasets/genesisml/PocketWatch/resolve/main/verify_bundle.py
12.2 kB
| """Rebuild `data/site_centroids.parquet` from the files in this repository, and check it matches. | |
| Standalone. It needs Python 3.10+ and two packages, and nothing else from this project: | |
| pip install numpy polars | |
| python verify_bundle.py --sample 0 # every site (4,466) | |
| python verify_bundle.py --sample 300 # a random 300 | |
| `site_centroids.parquet` is the localization ground truth, in the frame of the folds in | |
| `structures/`. This script rebuilds it from the frame-independent inputs in `projection/` and | |
| the folds alone. For each site, it takes every member observation and: | |
| 1. reads the observation's contact-residue CA coordinates in its own deposited-entry frame, each | |
| tagged with the canonical sequence position it maps to (`projection/contact_residues.parquet`); | |
| 2. reads the fold's CA at those same positions, dropping positions outside 1..L or with no CA; | |
| 3. finds the least-squares rigid transform (Kabsch, with the reflection correction) carrying the | |
| entry CAs onto the fold CAs, provided at least 3 positions matched; | |
| 4. applies that transform to the observation's entry-frame ligand centroid | |
| (`projection/ligand_centroids.parquet`). | |
| The site centroid is the mean of its members' transformed centroids. The script checks the | |
| rebuilt centroid, member count, spread and median fit RMSD of every sampled site against the | |
| shipped table, and each member's fit RMSD against `projection/ligand_centroids.parquet`. | |
| The fold reader is a minimal mmCIF `_atom_site` parser. It reads the first model, requires a | |
| single chain whose residues are numbered exactly 1..L against `data/sequences.parquet`, and | |
| keeps each residue's first CA as float32, matching how the centroids were built. | |
| """ | |
| import argparse | |
| import gzip | |
| import logging | |
| import pathlib | |
| import re | |
| import numpy as np | |
| import polars as pl | |
| logger = logging.getLogger("verify") | |
| HERE = pathlib.Path(__file__).resolve().parent | |
| # Below three matched CA atoms a rigid transform is underdetermined in at least one axis. | |
| MIN_MATCHED_CA = 3 | |
| _TOKEN = re.compile(r"'[^']*'|\"[^\"]*\"|\S+") | |
| _HYDROGEN = {"H", "D"} | |
| def parse_args(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--sample", type=int, default=300, help="sites to check; 0 for all") | |
| parser.add_argument("--seed", type=int, default=0) | |
| parser.add_argument("--tolerance", type=float, default=1e-4, help="angstrom") | |
| return parser.parse_args(argv) | |
| def _atom_site_rows(text: str) -> tuple[list[str], list[list[str]]]: | |
| """Column names and rows of the `_atom_site` loop.""" | |
| lines = text.splitlines() | |
| for start, line in enumerate(lines): | |
| if line.startswith("_atom_site."): | |
| break | |
| else: | |
| raise ValueError("no _atom_site loop") | |
| columns = [] | |
| index = start | |
| while index < len(lines) and lines[index].startswith("_atom_site."): | |
| columns.append(lines[index].strip()[len("_atom_site."):]) | |
| index += 1 | |
| tokens: list[str] = [] | |
| for line in lines[index:]: | |
| if not line.strip(): | |
| continue | |
| if line.startswith(("#", "loop_", "_", "data_")): | |
| break | |
| tokens.extend(line.split() if "'" not in line and '"' not in line else _TOKEN.findall(line)) | |
| if len(tokens) % len(columns): | |
| raise ValueError("_atom_site loop has a ragged final row") | |
| width = len(columns) | |
| rows = [tokens[i:i + width] for i in range(0, len(tokens), width)] | |
| return columns, rows | |
| def _value(token: str) -> str: | |
| return token[1:-1] if len(token) >= 2 and token[0] == token[-1] and token[0] in "'\"" else token | |
| def read_ca(path: pathlib.Path, expected_length: int) -> np.ndarray: | |
| """Per-residue CA coordinates of a fold, indexed by canonical position. | |
| Args: | |
| path: The fold's mmCIF, gzipped or not. | |
| expected_length: Canonical sequence length. | |
| Returns: | |
| ``(L, 3)`` float32, NaN where the fold has no CA for a position. | |
| Raises: | |
| ValueError: If the first model is not one chain numbered 1..`expected_length`. | |
| """ | |
| opener = gzip.open if path.suffix == ".gz" else open | |
| with opener(path, "rt") as handle: | |
| columns, rows = _atom_site_rows(handle.read()) | |
| col = {name: i for i, name in enumerate(columns)} | |
| seq_col = col.get("auth_seq_id", col.get("label_seq_id")) | |
| chain_col = col.get("auth_asym_id", col.get("label_asym_id")) | |
| model_col = col.get("pdbx_PDB_model_num") | |
| ins_col = col.get("pdbx_PDB_ins_code") | |
| alt_col = col.get("label_alt_id") | |
| comp_col = col["label_comp_id"] | |
| name_col = col.get("label_atom_id", col.get("auth_atom_id")) | |
| element_col = col.get("type_symbol") | |
| first_model = rows[0][model_col] if model_col is not None and rows else None | |
| chains = [] | |
| residues = [] # (seq_num, ins_code, comp_id) of consecutive atom groups, in file order | |
| ca = np.full((expected_length, 3), np.nan, dtype=np.float32) | |
| seen_ca = set() | |
| first_alt: dict[tuple, str] = {} | |
| for row in rows: | |
| if model_col is not None and row[model_col] != first_model: | |
| continue | |
| if element_col is not None and _value(row[element_col]).upper() in _HYDROGEN: | |
| continue | |
| chain = _value(row[chain_col]) | |
| if chain not in chains: | |
| chains.append(chain) | |
| key = ( | |
| int(_value(row[seq_col])), | |
| _value(row[ins_col]) if ins_col is not None else "?", | |
| _value(row[comp_col]), | |
| ) | |
| if not residues or residues[-1] != key: | |
| residues.append(key) | |
| # Keep one conformer: the first alternate location seen for each residue. | |
| if alt_col is not None: | |
| alt = _value(row[alt_col]) | |
| if alt not in (".", "?"): | |
| if first_alt.setdefault(key, alt) != alt: | |
| continue | |
| if _value(row[name_col]) == "CA" and key not in seen_ca: | |
| seen_ca.add(key) | |
| position = key[0] | |
| if 1 <= position <= expected_length: | |
| ca[position - 1] = [float(row[col["Cartn_x"]]), float(row[col["Cartn_y"]]), | |
| float(row[col["Cartn_z"]])] | |
| if len(chains) != 1: | |
| raise ValueError(f"{path}: expected one chain in the first model, found {len(chains)}") | |
| numbers = [r[0] for r in residues] | |
| if numbers != list(range(1, expected_length + 1)): | |
| raise ValueError( | |
| f"{path}: numbered {numbers[:3]}..{numbers[-3:]} over {len(numbers)} residues, " | |
| f"expected 1..{expected_length}" | |
| ) | |
| return ca | |
| def kabsch(source: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, np.ndarray]: | |
| """Rotation and translation with ``source @ rotation.T + translation`` closest to `target`.""" | |
| source = np.asarray(source, dtype=np.float64) | |
| target = np.asarray(target, dtype=np.float64) | |
| source_centre, target_centre = source.mean(axis=0), target.mean(axis=0) | |
| covariance = (source - source_centre).T @ (target - target_centre) | |
| u, _, vt = np.linalg.svd(covariance) | |
| # Flip the least significant axis when the naive solution is a reflection. | |
| sign = np.sign(np.linalg.det(vt.T @ u.T)) | |
| rotation = vt.T @ np.diag([1.0, 1.0, sign]) @ u.T | |
| return rotation, target_centre - rotation @ source_centre | |
| def project(source_ca: np.ndarray, fold_ca: np.ndarray, centroid: np.ndarray): | |
| """Carry one ligand centroid from its entry's frame into the fold's. | |
| Returns: | |
| ``(centroid, fit_rmsd_angstrom)``, or None when fewer than 3 positions matched. | |
| """ | |
| if len(source_ca) < MIN_MATCHED_CA: | |
| return None | |
| rotation, translation = kabsch(source_ca, fold_ca) | |
| fitted = source_ca @ rotation.T + translation | |
| rmsd = float(np.sqrt(((fitted - np.asarray(fold_ca, dtype=np.float64)) ** 2).sum(axis=1).mean())) | |
| return rotation @ np.asarray(centroid, dtype=np.float64) + translation, rmsd | |
| def main(argv=None) -> None: | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| args = parse_args(argv) | |
| truth = pl.read_parquet(HERE / "data/site_centroids.parquet") | |
| centroids = pl.read_parquet(HERE / "projection/ligand_centroids.parquet") | |
| residues = pl.read_parquet(HERE / "projection/contact_residues.parquet") | |
| lengths = dict( | |
| pl.read_parquet(HERE / "data/sequences.parquet") | |
| .select("normalized_uniprot_id", "sequence_length") | |
| .iter_rows() | |
| ) | |
| if args.sample: | |
| truth = truth.sample(min(args.sample, truth.height), seed=args.seed, shuffle=True) | |
| logger.info("checking %d sites", truth.height) | |
| by_observation = {key[0]: part for key, part in residues.group_by(["pocket_observation_id"])} | |
| members = {key[0]: part for key, part in centroids.group_by(["pocket_site_id"])} | |
| folds: dict[str, np.ndarray] = {} | |
| worst = {"centroid": 0.0, "spread": 0.0, "median_fit_rmsd": 0.0, "member_fit_rmsd": 0.0} | |
| count_mismatch = checked = skipped = 0 | |
| for row in truth.iter_rows(named=True): | |
| site, uniprot = row["pocket_site_id"], row["normalized_uniprot_id"] | |
| path = HERE / f"structures/{uniprot}.cif.gz" | |
| if not path.exists() or site not in members: | |
| skipped += 1 | |
| continue | |
| if uniprot not in folds: | |
| folds[uniprot] = read_ca(path, lengths[uniprot]) | |
| fold_ca = folds[uniprot] | |
| projected, fits = [], [] | |
| for member in members[site].iter_rows(named=True): | |
| part = by_observation.get(member["pocket_observation_id"]) | |
| if part is None: | |
| continue | |
| positions = part["canonical_position"].to_numpy() | |
| source = np.stack( | |
| [part["ca_x"].to_numpy(), part["ca_y"].to_numpy(), part["ca_z"].to_numpy()], axis=1 | |
| ) | |
| inside = (positions >= 1) & (positions <= len(fold_ca)) | |
| positions, source = positions[inside], source[inside] | |
| target = fold_ca[positions - 1] | |
| usable = ~np.isnan(target).any(axis=1) | |
| result = project( | |
| source[usable], | |
| target[usable], | |
| np.array([member["ligand_centroid_x"], member["ligand_centroid_y"], | |
| member["ligand_centroid_z"]]), | |
| ) | |
| if result is not None: | |
| projected.append(result[0]) | |
| fits.append(result[1]) | |
| worst["member_fit_rmsd"] = max( | |
| worst["member_fit_rmsd"], abs(result[1] - member["fit_rmsd_angstrom"])) | |
| if not projected: | |
| skipped += 1 | |
| continue | |
| stacked = np.stack(projected) | |
| rebuilt = stacked.mean(axis=0) | |
| shipped = np.array([row["ligand_centroid_x"], row["ligand_centroid_y"], | |
| row["ligand_centroid_z"]]) | |
| worst["centroid"] = max(worst["centroid"], float(np.abs(rebuilt - shipped).max())) | |
| spread = float(np.linalg.norm(stacked - rebuilt, axis=1).max()) | |
| worst["spread"] = max(worst["spread"], abs(spread - row["centroid_spread_angstrom"])) | |
| worst["median_fit_rmsd"] = max( | |
| worst["median_fit_rmsd"], abs(float(np.median(fits)) - row["median_fit_rmsd_angstrom"])) | |
| count_mismatch += len(projected) != row["centroid_member_count"] | |
| checked += 1 | |
| logger.info("checked %d sites over %d folds, skipped %d", checked, len(folds), skipped) | |
| logger.info("worst coordinate disagreement: %.6f A", worst["centroid"]) | |
| logger.info( | |
| "worst spread / median fit RMSD / member fit RMSD disagreement: %.6f / %.6f / %.6f A", | |
| worst["spread"], worst["median_fit_rmsd"], worst["member_fit_rmsd"], | |
| ) | |
| logger.info("sites whose member count differs: %d", count_mismatch) | |
| failures = [f"{name} {value:.6f} A" for name, value in worst.items() if value > args.tolerance] | |
| if count_mismatch: | |
| failures.append(f"{count_mismatch} member-count mismatches") | |
| if skipped: | |
| failures.append(f"{skipped} sites skipped") | |
| if failures: | |
| raise SystemExit(f"FAILED (tolerance {args.tolerance} A): " + "; ".join(failures)) | |
| logger.info("OK: the shipped files reproduce site_centroids.parquet") | |
| if __name__ == "__main__": | |
| main() | |