#!/usr/bin/env python3 """ Layer 3: 3D Structural & Protein Interface Verification Plane (v0.8.0) ====================================================================== Computes deterministic atomic-level structural geometry directly from 10 experimental RCSB PDB structures (8 mmCIF: 3CDG, 1MHE, 3BZE, 2JJS, 4CMM, 4KJY, 4ZQK, 1IAU; plus 2 PDB: 1EFX, 1IM9) and 2 AlphaFold DB v6 models (AF-P50453-F1 SERPINB9, AF-P10144-F1 Granzyme B), consumes the exact processed polypeptide ledger from Layer 2 (`layer2_regulatory_and_perturbation_atlas.json`), and separates coordinate-computed geometry from literature-derived reference affinities and unresolved engineered-product hypotheses (closing V70-07, V70-08, and V70-09). Outputs: - data/extracted/layer3_structural_verification_atlas.json """ from __future__ import annotations import difflib import hashlib import io import json import math import re import sys from collections import defaultdict from numbers import Real from pathlib import Path from types import MappingProxyType from typing import Any, Dict, List, Mapping, Optional, Tuple import numpy as np _MMCIF_TOKEN_RE = re.compile(r"""'(?:[^']|'(?!\s|$))*'|"(?:[^"]|"(?!\s|$))*"|\S+""") REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from scripts.run_layer2_perturbation_and_regulatory_plane import validate_construct_fasta_binding STRUCT_DIR = REPO_ROOT / "data" / "structures" LAYER2_ATLAS_PATH = REPO_ROOT / "data" / "extracted" / "layer2_regulatory_and_perturbation_atlas.json" OUT_PATH = REPO_ROOT / "data" / "extracted" / "layer3_structural_verification_atlas.json" POLAR_ELEMENTS = {"N", "O", "S"} # Locked at 42.8005 pN*A per round-2/round-3 regression test pins (exact 2019 SI k_B*310.00K = 42.800119 pN*A; k_B*310.15K = 42.8208 pN*A) KBT_310K_PN_ANGSTROM = 42.8005 # k_B * 310 K = 4.28005 pN*nm = 42.8005 pN*Angstrom # Frozen reference inputs, independently checked against RCSB/AlphaFold on # 2026-10-26. PDB local copies use extended entry IDs; their parsed A/B-conformer # atom records match the RCSB copies exactly. AF models/PAE match byte for byte. # Hashing an arbitrary replacement and printing its hash is not source binding. STRUCTURAL_REFERENCE_SHA256 = { "pdb_00003cdg.cif": "36f9a9d45f9a3b7dbbf2d74e4c4d25e3edc66f5e02cafafac6acf5d6130b450a", "pdb_00001mhe.cif": "4f1bc39231d6ffb288cf85bb9322d264ceac92d6d427f755339a648e49d6227a", "pdb_00003bze.cif": "839b87df50ced664fa5c516d0836667176b64895677c87de737b3a6615fc802c", "pdb_00002jjs.cif": "84672a253e9c982dac16136cb76ae706eeafa2aa390cfdb2355ad68592cac10e", "pdb_00004cmm.cif": "13147521df35289b21488439170079c86286f58cdafe17544367ccf053d1f5fe", "pdb_00004kjy.cif": "6294d015c1c24d97558650dc98ef8bced967b3fd658da8b49dc51090e8b2ccaa", "pdb_00004zqk.cif": "ed7114a3c653cf964155c5491a5df30d5c5e4edfc6b09d399662c5764a1bad31", "pdb_00001iau.cif": "c1ffdeab80cc9ecaf06c9901c756b0f59259e178a45a4a33ffc949bd01123161", "pdb_00001bl4.cif": "ce142b747272c5fd3b7c0b5f5157750277614700bc32492f0eb7cb43056914d5", "pdb_00001jxq.cif": "4b7355537a8a81e90d5397cba398ff425dddc904a7748e3a25a0a9f57d1ff772", "pdb_00001nw9.cif": "89edc3aa4833b22c9604872d163e64d53755af6de1c9163204f2244ac1ce5da4", "AF-P50453-F1-model_v6.cif": "d0b27f7cc8317acd9cd59b76d3080b4019ffd38930dbfddf3bd2560814baf5b9", "AF-P10144-F1-model_v6.cif": "6362a677cc62d80b89229ea40a4c3ae81007a631d1c038a2e158541c8d40e9a5", "AF-P50453-F1-predicted_aligned_error_v6.json": "b88ea8a67dab0e5956f919c3205911d9d7d901973c3ff32e5277b81881b76f78", "AF-P10144-F1-predicted_aligned_error_v6.json": "cb5b42db914ceb00ef6d508fe800ad784e551236aa4d139c190a25ea41241121", "1EFX.pdb": "4e432fe894cc6b0390bab6071598f2f95249d5b6f0c4e5a9365c1ca110660fba", "1IM9.pdb": "4c21ebf9e5ba064ab65569079cb8d10a73b718bdc8c4cd1c298bec7a8e4f0013", "2WII.pdb": "93dc715a38124883028aea79a1e3a2715c1d82bed06f59e7889e9971f41543eb", "5O32.pdb": "26b9d9684e7b3fa1757f91a173c8423d583ca6df88eb11d1fa2ecdc059a803d3", } def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(65536), b""): h.update(chunk) return h.hexdigest() def verify_structural_reference_inputs(*names: str) -> Mapping[str, bytes]: """Return immutable, release-verified snapshots for parsing and provenance. Every consumer must use these bytes, never reopen the path after checking its hash. A concurrent replacement (including change then restore) cannot change the authenticated input consumed by an analysis. """ snapshots = {} for name in names: expected = STRUCTURAL_REFERENCE_SHA256.get(name) if expected is None: raise ValueError(f"Structural reference source identity mismatch: {name}") payload = (STRUCT_DIR / name).read_bytes() if hashlib.sha256(payload).hexdigest() != expected: raise ValueError(f"Structural reference source identity mismatch: {name}") snapshots[name] = payload return MappingProxyType(snapshots) def validate_processed_polypeptide_ledger(ledger: Dict[str, Any]) -> None: """Reject stale hashes and length labels before interpreting molecular identities.""" expected_ids = { "HLAE_0103_VMAPRTLVL_SCT_Arm1B_mature_surface", "HLAE_0103_VMAPRTLVL_SCT_Arm1A_mature_with_cytosolic_P2A_stub", "CD47_IgV_GPI_mature_cell_surface", "SERPINB9_cytosolic_with_21aa_GSG_P2A_stub", "PDL1_mature_cell_surface", "iCasp9_cytosolic_monomer", } if not isinstance(ledger, dict) or set(ledger) != expected_ids: raise ValueError("Complete six-product Layer-2 processed polypeptide ledger is required") for key, entry in ledger.items(): if not isinstance(entry, dict): raise TypeError(f"Processed polypeptide entry must be an object: {key}") seq = entry.get("sequence") if not isinstance(seq, str) or not seq or any(aa not in "ACDEFGHIKLMNPQRSTVWY" for aa in seq): raise ValueError(f"Invalid processed amino-acid sequence: {key}") if hashlib.sha256(seq.encode("utf-8")).hexdigest() != entry.get("sha256"): raise ValueError(f"Processed polypeptide SHA-256 mismatch: {key}") lengths = [entry[name] for name in ("mature_length_aa", "processed_length_aa") if name in entry] if not lengths or any(type(value) is not int or value != len(seq) for value in lengths): raise ValueError(f"Processed polypeptide length mismatch: {key}") cd47 = ledger["CD47_IgV_GPI_mature_cell_surface"] if hashlib.sha256(cd47["sequence"][:120].encode("utf-8")).hexdigest() != cd47.get("cd47_ectodomain_120aa_sha256"): raise ValueError("CD47 ectodomain SHA-256 mismatch") def validated_pae_matrix(payload: Any, expected_length: int, label: str) -> np.ndarray: """Require a full finite, nonnegative residue-pair matrix; missing rows are not zero confidence.""" if type(expected_length) is not int or expected_length <= 0: raise ValueError("AlphaFold PAE expected_length must be a positive integer") if isinstance(payload, list): if len(payload) != 1: raise ValueError(f"Expected one AlphaFold PAE record: {label}") payload = payload[0] if not isinstance(payload, dict) or "predicted_aligned_error" not in payload: raise ValueError(f"Missing AlphaFold PAE matrix: {label}") try: raw_matrix = np.asarray(payload["predicted_aligned_error"], dtype=object) if raw_matrix.shape != (expected_length, expected_length): raise ValueError("PAE shape does not match the declared residue count") if any(isinstance(value, (bool, np.bool_)) or not isinstance(value, Real) for value in raw_matrix.flat): raise ValueError("PAE entries must be numbers; booleans and numeric strings are invalid") matrix = np.asarray(raw_matrix, dtype=np.float64) except (ValueError, TypeError, OverflowError) as exc: raise ValueError(f"Invalid AlphaFold PAE numeric matrix: {label}") from exc if matrix.shape != (expected_length, expected_length) or not np.all(np.isfinite(matrix)) or np.any(matrix < 0): raise ValueError(f"AlphaFold PAE must be a finite nonnegative {expected_length}-by-{expected_length} matrix: {label}") if "max_predicted_aligned_error" in payload: maximum = payload["max_predicted_aligned_error"] try: valid_maximum = (not isinstance(maximum, (bool, np.bool_)) and isinstance(maximum, Real) and math.isfinite(maximum) and maximum >= 0 and not np.any(matrix > maximum)) except (TypeError, ValueError, OverflowError): valid_maximum = False if not valid_maximum: raise ValueError(f"AlphaFold PAE exceeds or has an invalid declared maximum: {label}") return matrix def _pae_mean(matrix: np.ndarray) -> float: """A finite nonnegative matrix has a finite mean no greater than its maximum.""" if not matrix.size or not np.all(np.isfinite(matrix)) or np.any(matrix < 0): raise ValueError("PAE mean requires a nonempty finite nonnegative matrix") maximum = float(np.max(matrix)) return float(np.mean(matrix / maximum)) * maximum if maximum else 0.0 def _finite_population_moments(values: List[float]) -> Tuple[float, float]: """Finite mean and population SD without overflowing sums or squares.""" data = _finite_real_coordinates(values, "B-factor moments") if data.ndim != 1 or not len(data): raise ValueError("B-factor moments require a nonempty numeric vector") anchor = float(data[0]) with np.errstate(over="ignore", invalid="ignore"): local = data - anchor if not np.all(np.isfinite(local)): anchor, local = 0.0, data scale = float(np.max(np.abs(local))) if scale == 0.0: return anchor, 0.0 scaled = local / scale mean_scaled = math.fsum(float(value) for value in scaled) / len(scaled) mean = anchor + mean_scaled * scale # A convex mean belongs to the finite input interval. The normalized # population variance is at most one because every scaled value is in # [-1, 1]; these bounds also remove endpoint roundoff, not invalid inputs. mean = min(float(np.max(data)), max(float(np.min(data)), mean)) variance_scaled = min(1.0, math.fsum((float(value) - mean_scaled) ** 2 for value in scaled) / len(scaled)) return mean, math.sqrt(variance_scaled) * scale def parse_mmcif_atoms(cif_path: Path, keep_insertion_codes: bool = False, allowed_alt_ids: Tuple[str, ...] = (".", "?", "A"), *, source_bytes: Optional[bytes] = None, include_zero_occupancy: bool = False) -> List[Dict[str, Any]]: """ Parse ATOM/HETATM records from an mmCIF coordinate file (model 1, quote-aware tokenizer). When keep_insertion_codes=True, residues with PDB insertion codes (e.g. 184A in 1IAU) are retained with their exact insertion code so chymotrypsinogen-numbered structures align without dropping residues (closing V70-08 & AUDIT-REF). With source_bytes, parse that immutable snapshot and use cif_path only in diagnostic messages. Otherwise retain the generic arbitrary-file API. """ atoms: List[Dict[str, Any]] = [] cols: List[str] = [] in_atom_loop = False pending: List[str] = [] rows_started = False identities = set() if (type(keep_insertion_codes) is not bool or type(include_zero_occupancy) is not bool or not isinstance(allowed_alt_ids, tuple) or not allowed_alt_ids or any(not isinstance(alt, str) or not alt for alt in allowed_alt_ids) or len(set(allowed_alt_ids) - {".", "?"}) > 1): raise ValueError("Select one named atom conformer and boolean insertion-code/occupancy policies") def _append_selected_atom(rec: Dict[str, str]) -> None: if rec.get("pdbx_PDB_model_num", "1") not in ("1", "?", "."): return alt_id = rec.get("label_alt_id", ".") if alt_id not in allowed_alt_ids: return try: x, y, z = (float(rec[name]) for name in ("Cartn_x", "Cartn_y", "Cartn_z")) b_iso = float(rec.get("B_iso_or_equiv", "0.0")) occupancy = float(rec.get("occupancy", "1.0")) except (ValueError, KeyError) as exc: raise ValueError(f"Invalid atom numeric field in {cif_path}") from exc if not all(math.isfinite(v) for v in (x, y, z, b_iso, occupancy)) or not 0.0 <= occupancy <= 1.0: raise ValueError(f"Non-finite coordinate/confidence or invalid occupancy in {cif_path}") if occupancy == 0.0 and not include_zero_occupancy: return auth_seq_str = rec.get("auth_seq_id", rec.get("label_seq_id", "?")) try: auth_seq_id = int(auth_seq_str) except ValueError: return label_seq_str = rec.get("label_seq_id", "?") label_seq_id = None if label_seq_str not in ("?", "."): try: label_seq_id = int(label_seq_str) except ValueError as exc: raise ValueError(f"Invalid polymer sequence identifier in {cif_path}") from exc if label_seq_id <= 0: raise ValueError(f"Polymer sequence identifiers must be positive in {cif_path}") ins_raw = rec.get("pdbx_PDB_ins_code", "?") ins_code = "" if ins_raw in ("?", ".") else ins_raw if not keep_insertion_codes and ins_code: return atom_id = rec.get("label_atom_id", rec.get("auth_atom_id", ""))