scripts/verify_iip0041_clinical_h1_cd64t_siglec.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…
fc_glyc_atoms = [(pch, pseq, pcomp, px, py, pz) for (pch, pseq, pcomp, pgrp, px, py, pz) in par_atoms if pgrp == "HETATM"]
fc_glyc_pts = [(gx, gy, gz) for (_c, _s, _m, gx, gy, gz) in fc_glyc_atoms]
resolved_mut_positions = {p for p, _lbl in rec_muts if p in resolved_rec_seqs}
resolved_mut_pts = [(rx, ry, rz) for (_rch, rseq, _rc, rx, ry, rz) in rec_atoms if rseq in resolved_mut_positions]
min_mut_dist_prot: float | None = (
round(min(math.dist(rp, pp) for rp in resolved_mut_pts for pp in par_prot_pts), 3)
if (resolved_mut_pts and par_prot_pts)
else None
)
min_mut_dist_glyc: float | None = (
round(min(math.dist(rp, gp) for rp in resolved_mut_pts for gp in fc_glyc_pts), 3)
if (resolved_mut_pts and fc_glyc_pts)
else None
)
mut_glycan_dists: dict[str, dict[str, float]] = {}
for pos, lbl in rec_muts:
if lbl in muts_in_self_glyc:
rpts = [(rx, ry, rz) for (_rch, rseq, _rc, rx, ry, rz) in rec_atoms if rseq == pos]
d_fc = min(math.dist(rp, (gx, gy, gz)) for rp in rpts for (_c, _s, _m, gx, gy, gz) in fc_glyc_atoms) if (rpts and fc_glyc_atoms) else -1.0
d_self = min(math.dist(rp, (sx, sy, sz)) for rp in rpts for (_c, _s, _m, sx, sy, sz) in self_glyc_atoms) if (rpts and self_glyc_atoms) else -1.0
mut_glycan_dists[lbl] = {
"min_dist_to_fc_linked_glycans_A": round(d_fc, 3),
"min_dist_to_receptor_self_glycans_A": round(d_self, 3),
}
return {
"pdb_file": cif_path.name,
"pdb_sha256_prefix16": sha256_file(cif_path)[:16],
"chain_id_namespace": "label_asym_id_preferred_with_auth_asym_id_fallback",
"cutoff_angstrom": cutoff_angstrom,
"receptor_chains": sorted(receptor_chains),
"partner_chains": sorted(partner_chains),
"fc_linked_glycan_chains_from_struct_conn": conn_info["partner_glycan_chains"],
"receptor_self_glycan_chains_from_struct_conn": sorted(self_g_set),
"struct_conn_covalent_glycan_links": conn_info["covalent_glycan_links"],
"partner_fc_hetatm_glycan_heavy_atoms_by_chain": dict(sorted(partner_hetatm_atoms_by_chain.items())),
"partner_fc_hetatm_glycan_heavy_atoms_total": sum(partner_hetatm_atoms_by_chain.values()),
"receptor_contact_residue_count": len(rec_contact_res),
"receptor_contact_min_max_auth_seq": [min(rec_contact_res), max(rec_contact_res)] if rec_contact_res else [],
"partner_contact_residue_count": len(par_contact_res),
"partner_fc_hetatm_glycan_contact_pairs": fc_glycan_contacts,
"receptor_self_glycan_contact_pairs": self_glycan_contacts,
"declared_engineered_mutation_rows_all_chains": all_eng_mut_rows,
"receptor_chain_engineered_mutations_declared_count": len(rec_muts),
"receptor_chain_engineered_mutations_resolved_count": len(resolved_muts),
"receptor_chain_engineered_mutations_resolved": resolved_muts,
"engineered_mutations_in_protein_contacts_le_4p5A": muts_in_prot,
"engineered_mutations_in_fc_glycan_contacts_le_4p5A": muts_in_fc_glyc,
"engineered_mutations_in_receptor_self_glycan_contacts_le_4p5A": muts_in_self_glyc,
"min_engineered_mutation_dist_to_partner_protein_A": min_mut_dist_prot,
"min_engineered_mutation_dist_to_partner_glycan_A": min_mut_dist_glyc,
"receptor_self_glycan_contact_mutation_distances_A": mut_glycan_dists,
}
def measure_5fo9_stalk_distance(cif_path: pathlib.Path) -> float:
"""Measure exact C3b-TED anchor (hydrolyzed thioester Glu1013, from native C3 Gln1013) to CR1 CCP17 C-terminus distance in PDB 5FO9 (verifying GY-026 49.21 A geometry)."""
cols: list[str] = []
coords: dict[tuple[str, int, str], tuple[float, float, float]] = {}
in_atom = False
for ln in cif_path.read_text(encoding="utf-8", errors="ignore").splitlines():
s = ln.strip()
if s == "loop_":
cols = []
in_atom = False
continue
if s.startswith("_atom_site."):
cols.append(s)
in_atom = True
continue
if in_atom and s.startswith("ATOM "):
toks = s.split()
if len(toks) < len(cols):
continue
cmap = {cols[i]: toks[i] for i in range(len(cols))}
aname = cmap.get("_atom_site.label_atom_id", "")
if aname != "CA":
continue
ch = cmap.get("_atom_site.auth_asym_id", "")
try:
rseq = int(cmap.get("_atom_site.auth_seq_id", "0"))
coords[(ch, rseq, aname)] = (
float(cmap["_atom_site.Cartn_x"]),
float(cmap["_atom_site.Cartn_y"]),
float(cmap["_atom_site.Cartn_z"]),
)
except Exception:
continue
# C3b hydrolyzed thioester Glu1013 (chain B, native C3 Gln1013 per _struct_ref_seq_dif) to CR1 CCP17 C-terminal residue (chain C max auth_seq)
c_res = sorted(r for (ch, r, _) in coords if ch == "C")
b_ca = coords.get(("B", 1013, "CA"))
c_end = coords.get(("C", c_res[-1], "CA")) if c_res else None
if b_ca and c_end:
return round(math.dist(b_ca, c_end), 2)
return -1.0
def verify_gravina_cd64t_cds_comparison(
staged_cds: str,
expected_aa: str | None = None,
*,
check_private_xml_cache: bool = False,
) -> dict[str, Any]:
"""Programmatically compare staged CD64t[1-313] CDS against Gravina et al. 2023 (PMC10188358) published 942-bp CDS.
When check_private_xml_cache=False (default, used by portable --installed-check), verification uses ONLY
the embedded curated PMC10188358 942-bp sequence so output is 100% deterministic across private repos and
public snapshots without depending on local XML caches.
"""
gravina_cds = GRAVINA_2023_PUBLISHED_CD64T_CDS_942BP.upper()
source_origin = "embedded_curated_PMC10188358_942bp_cds"
xml_verified: bool | None = None
if check_private_xml_cache:
xml_verified = False
if GRAVINA_PMC_XML_CACHE.is_file():
xml_txt = GRAVINA_PMC_XML_CACHE.read_text(encoding="utf-8", errors="ignore")
xml_stripped = re.sub(r"\s+", "", re.sub(r"<[^>]+>", " ", xml_txt)).upper()
if gravina_cds in xml_stripped:
xml_verified = True
source_origin = "PMC10188358_xml_cache_verified_and_embedded_942bp_cds"
staged = staged_cds.upper()
if len(staged) != len(gravina_cds) or len(staged) != 942:
raise ValueError(f"Gravina comparison length mismatch: staged={len(staged)}, gravina={len(gravina_cds)}")
if len(staged) % 3 != 0:
raise ValueError(f"CD64t CDS length {len(staged)} not divisible by 3")
nt_diffs = sum(1 for a, b in zip(staged, gravina_cds) if a != b)
aa_staged = l2.translate_dna(staged)
aa_gravina = l2.translate_dna(gravina_cds)
aa_diffs = sum(1 for a, b in zip(aa_staged, aa_gravina) if a != b)
codon_diffs = sum(1 for i in range(0, len(staged) - 3, 3) if staged[i : i + 3] != gravina_cds[i : i + 3])
staged_term_ile = staged[-6:-3]
gravina_term_ile = gravina_cds[-6:-3]
staged_stop = staged[-3:]
gravina_stop = gravina_cds[-3:]
staged_sha = sha256_str(staged)
gravina_sha = sha256_str(gravina_cds)
if expected_aa is not None and aa_staged != expected_aa + "*":
raise ValueError("Staged CD64t translation does not match P12314[1-313]*")
if aa_diffs != 0 or aa_staged != aa_gravina:
raise ValueError(f"Expected 0 amino-acid differences vs Gravina 2023, got {aa_diffs}")
if nt_diffs != 235:
raise ValueError(f"Expected 235 synonymous nucleotide differences vs Gravina 2023, got {nt_diffs}")
if staged_term_ile != "ATT" or gravina_term_ile != "ATA":
raise ValueError(f"Unexpected terminal Ile codons: staged={staged_term_ile}, gravina={gravina_term_ile}")
if staged_stop != "TAG" or gravina_stop != "TAG":
raise ValueError(f"Unexpected stop codons: staged={staged_stop}, gravina={gravina_stop}")
if staged_sha != "0390bb1d298aa7dc4eea19909377bf6e3200091f05f28918e94d6dc148beea86":
raise ValueError(f"Staged CD64t CDS SHA-256 mismatch: {staged_sha}")
if gravina_sha != "76300c42d602eaf14e24d66df1b84e992590f02309127e4a3a0e2dbecc5ad7df":
raise ValueError(f"Gravina published CD64t CDS SHA-256 mismatch: {gravina_sha}")
return {
"source_pmcid": "PMC10188358",
"comparison_method": "programmatic_base_by_base_and_translation_diff",
"gravina_reference_origin": source_origin,
"portable_verification_scope": (
"PRIVATE_CACHE_XML_ATTESTATION_MODE"
if check_private_xml_cache
else "PORTABLE_EMBEDDED_PMC10188358_REFERENCE_NO_PRIVATE_CACHE_DEPENDENCY"
),
"local_private_xml_cache_checked": bool(check_private_xml_cache),
"local_pmc_xml_substring_verified": xml_verified,
"compared_bp": len(staged),
"compared_aa_excl_stop": len(aa_staged) - 1,
"staged_cds_sha256": staged_sha,
"gravina_published_cds_sha256": gravina_sha,
"staged_terminal_ile_codon": staged_term_ile,
"gravina_published_terminal_ile_codon": gravina_term_ile,
"staged_stop_codon": staged_stop,
"gravina_published_stop_codon": gravina_stop,
"synonymous_nucleotide_differences_vs_gravina": nt_diffs,
"synonymous_codon_differences_vs_gravina": codon_diffs,
"amino_acid_differences_vs_gravina": aa_diffs,
"exact_protein_match": aa_diffs == 0,
"exact_nucleotide_match": nt_diffs == 0,
"note": (
f"Embedded-reference comparison against the curated {len(staged)}-bp Gravina 2023 coding sequence "
f"({gravina_sha[:8]}..., encoding UniProt P12314[1-313], published directly in Gravina et al. 2023 "
f"public Methods [PMC10188358]; independent live retrieval of that external article text lies outside "
f"the public snapshot): "
f"exact {len(aa_staged)-1}-aa protein match ({aa_diffs} aa diffs), with {nt_diffs} synonymous nucleotide differences "
f"({codon_diffs} synonymous codon changes; terminal Ile313 {staged_term_ile} vs {gravina_term_ile}) — NOT a 942-bp nucleotide identity match."
),
}
def _is_valid_sha256_hex(val: Any) -> bool:
return (
isinstance(val, str)
and len(val) == 64
and all(ch in "0123456789abcdef" for ch in val)
and len(set(val)) > 1
)
def compute_upstream_record_sha256(record: dict[str, Any]) -> str:
"""Canonical SHA-256 digest of an upstream qualification record excluding its `record_sha256` field."""
body = {k: v for k, v in record.items() if k != "record_sha256"}
canonical = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def build_authenticated_upstream_record(
*,
gate_id: str,
verdict: str,
lot_id: str,
mcb_id: str,
construct_id: str,
chassis_id: str,
evidence_summary: dict[str, Any],
assay_id: str = "ASSAY-QA-VERIFIED-001",
issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
product_track: str = "CORE_ABX",
product_variant_id: str | None = None,
) -> dict[str, Any]:
"""Construct a canonically SHA-256-authenticated, issuer-bound same-lot upstream qualification record."""
if not isinstance(evidence_summary, dict) or len(evidence_summary) == 0:
raise ValueError("evidence_summary is mandatory and must be a non-empty dict")
pvid = product_variant_id if product_variant_id is not None else construct_id
for lbl, val in (
("gate_id", gate_id),
("verdict", verdict),
("lot_id", lot_id),
("mcb_id", mcb_id),
("construct_id", construct_id),
("chassis_id", chassis_id),
("product_track", product_track),
("product_variant_id", pvid),
("assay_id", assay_id),
("issuer_authority_id", issuer_authority_id),
):
if _strict_literal_id(val) is None:
raise ValueError(f"build_authenticated_upstream_record requires strict literal {lbl}, got {val!r}")
assert_strictly_finite_json(evidence_summary, "upstream_evidence_summary")
rec: dict[str, Any] = {
"gate_id": gate_id,
"verdict": verdict,
"lot_id": lot_id,
"mcb_id": mcb_id,
"construct_id": construct_id,
"product_variant_id": pvid,
"chassis_id": chassis_id,
"product_track": product_track,
"assay_id": assay_id,
"issuer_authority_id": issuer_authority_id,
"evidence_summary": copy.deepcopy(evidence_summary),
}
rec["record_sha256"] = compute_upstream_record_sha256(rec)
return rec