""" Per-residue comparison of two observations of the same sequence. Both chains share an identical SEQRES, so residues are paired by label_seq_id (no alignment needed). Coordinates come from the RCSB ModelServer (one chain, first model). Chain B is superposed onto chain A on their largest rigid core, so moving regions stand out rather than being averaged away. Each SEQRES position is then classified by its Cα deviation, or as resolved in only one of the two structures. """ from __future__ import annotations import re import urllib.request from functools import lru_cache from typing import Dict, List, Optional, Tuple import numpy as np MODELSERVER = "https://models.rcsb.org/v1/{pdb}/atoms?auth_asym_id={chain}&model_nums=1&encoding=cif©_all_categories=false" # Cα deviation classes (Å): < LOW green, LOW..HIGH yellow, >= HIGH red LOW, HIGH = 1.0, 3.0 _TOKEN = re.compile(r"'[^']*'|\"[^\"]*\"|\S+") Atom = Tuple[str, str, str, float, float, float] # atom name, element, residue name, x, y, z class StructureUnavailable(Exception): pass @lru_cache(maxsize=64) def _chain_atoms(pdb_id: str, chain: str) -> Dict[int, List[Atom]]: """label_seq_id -> atoms of one polymer chain (first model, first altloc).""" url = MODELSERVER.format(pdb=pdb_id.lower(), chain=urllib.request.quote(chain)) try: with urllib.request.urlopen(url, timeout=60) as r: text = r.read().decode("utf-8", "replace") except Exception as exc: raise StructureUnavailable(f"could not fetch {pdb_id.upper()}.{chain} from RCSB: {exc}") from exc cols: List[str] = [] residues: Dict[int, List[Atom]] = {} seen_alt: Dict[Tuple[int, str], str] = {} in_loop = False for line in text.splitlines(): if line.startswith("_atom_site."): cols.append(line.split(".", 1)[1].strip()) in_loop = True continue if not in_loop or not cols: continue if line.startswith(("ATOM", "HETATM")): f = dict(zip(cols, _TOKEN.findall(line))) seq = f.get("label_seq_id", ".") if not seq.isdigit() or f.get("group_PDB") != "ATOM": continue name = f["label_atom_id"].strip("\"'") alt = f.get("label_alt_id", ".") key = (int(seq), name) if alt not in (".", "?"): first = seen_alt.setdefault(key, alt) if alt != first: continue residues.setdefault(int(seq), []).append( (name, f.get("type_symbol", ""), f["label_comp_id"], float(f["Cartn_x"]), float(f["Cartn_y"]), float(f["Cartn_z"])) ) elif line.startswith(("#", "loop_", "_")) and residues: break if not residues: raise StructureUnavailable(f"no protein atoms for {pdb_id.upper()}.{chain}") return residues def _ca(residues: Dict[int, List[Atom]]) -> Dict[int, np.ndarray]: out = {} for seq, atoms in residues.items(): for a in atoms: if a[0] == "CA": out[seq] = np.array(a[3:6]) break return out def _kabsch(P: np.ndarray, Q: np.ndarray, w: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Rotation R and translation t minimising sum w |R q + t - p|^2.""" w = w / w.sum() pc = (w[:, None] * P).sum(0) qc = (w[:, None] * Q).sum(0) H = ((Q - qc) * w[:, None]).T @ (P - pc) U, _, Vt = np.linalg.svd(H) d = np.sign(np.linalg.det(Vt.T @ U.T)) D = np.diag([1.0, 1.0, d]) R = Vt.T @ D @ U.T return R, pc - R @ qc # Rigid-core search scale (Å). TM-score's length-dependent d0 (~7 Å at 370 residues) # happily spreads a hinge motion over both domains; a small fixed scale instead # locks onto the largest rigid part, which is what a per-region comparison needs. CORE_D0 = 2.0 CORE_SEARCH = 3.0 def _superpose(P: np.ndarray, Q: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Superposition of Q onto P on the largest rigid core (TM-score-style seed search). Seeds are contiguous windows of L, L/2, L/4 and L/8 residues; from each seed the fit is refined on residues within CORE_SEARCH until the set stops changing, and the fit maximising sum 1/(1+(d/CORE_D0)^2) wins. """ n = len(P) d0 = CORE_D0 d_search = CORE_SEARCH ones = np.ones(n) best_score, best = -1.0, _kabsch(P, Q, ones) lengths = sorted({n, n // 2, n // 4, max(n // 8, 4)}, reverse=True) for win in lengths: if win < 3: continue for s in range(0, n - win + 1, max(1, win // 2)): idx = np.arange(s, s + win) for _ in range(20): R, t = _kabsch(P[idx], Q[idx], ones[: len(idx)]) d = np.linalg.norm(Q @ R.T + t - P, axis=1) score = float(np.sum(1.0 / (1.0 + (d / d0) ** 2))) if score > best_score: best_score, best = score, (R, t) cut = d_search new = np.where(d < cut)[0] while len(new) < 3 and cut < 50: cut += 0.5 new = np.where(d < cut)[0] if np.array_equal(new, idx): break idx = new return best def _pdb_lines(residues: Dict[int, List[Atom]], chain: str, R=None, t=None, devs=None, start=1) -> List[str]: lines, serial = [], start for seq in sorted(residues): b = devs.get(seq, 0.0) if devs else 0.0 for name, element, resname, x, y, z in residues[seq]: xyz = np.array([x, y, z]) if R is not None: xyz = R @ xyz + t atom = name if len(name) == 4 else f" {name:<3}" lines.append( f"ATOM {serial % 100000:>5} {atom:<4} {resname[:3]:>3} {chain}{seq % 10000:>4} " f"{xyz[0]:>8.3f}{xyz[1]:>8.3f}{xyz[2]:>8.3f}{1.0:>6.2f}{min(b, 999.99):>6.2f} " f"{element[:2]:>2}" ) serial += 1 return lines @lru_cache(maxsize=32) def compare(pdb_a: str, chain_a: str, pdb_b: str, chain_b: str) -> Dict[str, object]: """Superpose B onto A and classify every SEQRES position.""" A = _chain_atoms(pdb_a, chain_a) B = _chain_atoms(pdb_b, chain_b) ca_a, ca_b = _ca(A), _ca(B) common = sorted(set(ca_a) & set(ca_b)) if len(common) < 3: raise StructureUnavailable("the two structures share fewer than 3 resolved residues") P = np.stack([ca_a[s] for s in common]) Q = np.stack([ca_b[s] for s in common]) R, t = _superpose(P, Q) dev = np.linalg.norm(Q @ R.T + t - P, axis=1) devs = {s: float(d) for s, d in zip(common, dev)} residues = [] for seq in sorted(set(A) | set(B)): in_a, in_b = seq in ca_a, seq in ca_b d = devs.get(seq) cls = ( "only_a" if in_a and not in_b else "only_b" if in_b and not in_a else "low" if d is not None and d < LOW else "medium" if d is not None and d < HIGH else "high" if d is not None else "missing" ) resname = (A.get(seq) or B.get(seq))[0][2] residues.append({"pos": seq, "res": resname, "dev": None if d is None else round(d, 2), "class": cls}) counts = {c: sum(1 for r in residues if r["class"] == c) for c in ("low", "medium", "high", "only_a", "only_b")} core = dev[dev < LOW] pdb_text = "\n".join( ["REMARK MuSProt comparison: chain A = %s.%s, chain B = %s.%s superposed onto A" % (pdb_a.upper(), chain_a, pdb_b.upper(), chain_b)] + _pdb_lines(A, "A", devs=devs) + ["TER"] + _pdb_lines(B, "B", R, t, devs=devs, start=sum(len(v) for v in A.values()) + 2) + ["TER", "END"] ) return { "a": {"pdb_id": pdb_a.lower(), "auth_asym_id": chain_a}, "b": {"pdb_id": pdb_b.lower(), "auth_asym_id": chain_b}, "thresholds": {"low": LOW, "high": HIGH}, "n_common": len(common), "rmsd_all": round(float(np.sqrt((dev**2).mean())), 2), "rmsd_core": round(float(np.sqrt((core**2).mean())), 2) if len(core) else None, "max_dev": round(float(dev.max()), 2), "counts": counts, "residues": residues, "pdb": pdb_text, } def compare_json(pdb_a: str, chain_a: str, pdb_b: str, chain_b: str) -> Dict[str, object]: out = dict(compare(pdb_a, chain_a, pdb_b, chain_b)) out.pop("pdb") return out def compare_pdb(pdb_a: str, chain_a: str, pdb_b: str, chain_b: str, show: Optional[str] = None) -> str: text = compare(pdb_a, chain_a, pdb_b, chain_b)["pdb"] if show in ("A", "B"): keep = [l for l in text.splitlines() if not l.startswith("ATOM") or l[21] == show] return "\n".join(keep) return text