OpenIslet

scripts/run_layer3_structural_binder_plane.py

Layer 3: 3D Structural & Protein Interface Verification Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 410 KB · 25 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer3_structural_binder_plane.py · SHA-256: a070de200dfefd3d…

    min_heavy_dist_pro376_only_to_hinge_318_334 = float(np.min(np.linalg.norm(c_pro376[:, None, :] - c_hinge_318_334[None, :, :], axis=-1)))
    min_heavy_dist_pro376_c_to_hinge_318_334 = float(np.min(np.linalg.norm(c_hinge_318_334 - pro376_c_atom[None, :], axis=-1)))

    gzmb_1iau = filter_polymer_atoms(atoms_1iau, ["A"])
    iepd_1iau = [a for a in atoms_1iau if a["chain"] == "B" and a["comp_id"] != "HOH"]
    iepd_interface = compute_interface_metrics(gzmb_1iau, iepd_1iau)

    gzmb_1iau_altb = filter_polymer_atoms(atoms_1iau_altb, ["A"])
    iepd_1iau_altb = [a for a in atoms_1iau_altb if a["chain"] == "B" and a["comp_id"] != "HOH"]
    iepd_interface_altb = compute_interface_metrics(gzmb_1iau_altb, iepd_1iau_altb)

    def _active_site_dists(atom_rows: List[Dict[str, Any]]) -> Dict[str, float]:
        s195_og = get_atom_coord(atom_rows, "A", 195, "OG")
        r226_nh2 = get_atom_coord(atom_rows, "A", 226, "NH2")
        asj405_c = get_atom_coord(atom_rows, "B", 405, "C")
        asj405_od2 = get_atom_coord(atom_rows, "B", 405, "OD2")
        return {
            "Ser195_OG_to_ASJ405_C_angstrom": round(euclidean_distance(s195_og, asj405_c), 6),
            "Arg226_NH2_to_ASJ405_OD2_angstrom": round(euclidean_distance(r226_nh2, asj405_od2), 6),
        }

    altloc_1iau_audit = {
        "conformer_selection_policy": "Altloc A (occupancy 0.38) retained as historical baseline interface with dominant Altloc B (occupancy 0.62) reported alongside without atom-wise conformer mixing",
        "altloc_A_minor_occupancy_0p38": {
            "alternate_occupancies": sorted({a["occupancy"] for a in atoms_1iau if a["alt_id"] == "A"}),
            "heavy_atom_contact_pairs": iepd_interface["heavy_atom_contact_pairs"],
            "unique_residue_contact_pairs": iepd_interface["unique_residue_contact_pairs"],
            "polar_contact_atom_pairs": iepd_interface["polar_contact_atom_pairs"],
            **_active_site_dists(atoms_1iau),
        },
        "altloc_B_major_occupancy_0p62": {
            "alternate_occupancies": sorted({a["occupancy"] for a in atoms_1iau_altb if a["alt_id"] == "B"}),
            "heavy_atom_contact_pairs": iepd_interface_altb["heavy_atom_contact_pairs"],
            "unique_residue_contact_pairs": iepd_interface_altb["unique_residue_contact_pairs"],
            "polar_contact_atom_pairs": iepd_interface_altb["polar_contact_atom_pairs"],
            **_active_site_dists(atoms_1iau_altb),
            "interface_metrics": iepd_interface_altb,
        },
    }

    # Insertion-code-safe alignment between mature AF-P10144 (residues 21..246 = 226 aa) and PDB:1IAU Chain A (226 aa)
    ca_gzmb_af_list = [a for a in get_ca_ordered_list_with_ins_codes(atoms_gzmb_af, "A") if a["seq_id"] >= 21]
    ca_1iau_list = get_ca_ordered_list_with_ins_codes(atoms_1iau, "A")
    if not (len(ca_1iau_list) == 226):
        raise ValueError(f"Expected 226 CA atoms in 1IAU Chain A with insertion codes, got {len(ca_1iau_list)}")
    matched_af_coords = []
    matched_iau_coords = []
    identical_pairs = 0
    for a_af, a_iau in zip(ca_gzmb_af_list[:226], ca_1iau_list):
        if a_af["comp_id"] == a_iau["comp_id"]:
            identical_pairs += 1
        matched_af_coords.append([a_af["x"], a_af["y"], a_af["z"]])
        matched_iau_coords.append([a_iau["x"], a_iau["y"], a_iau["z"]])
    if not (identical_pairs == 226):
        raise ValueError('Molecular source invariant failed: identical_pairs == 226')
    rmsd_gzmb_af_vs_1iau, _, _ = kabsch_rmsd(np.array(matched_af_coords, dtype=np.float64), np.array(matched_iau_coords, dtype=np.float64))

    # Derive SERPINB9 P4..P1' sequence directly from coordinates and pinned Layer 2 polypeptide ledger (closes AUDIT-REF)
    sb9_ledger = layer2_ledger["SERPINB9_cytosolic_with_21aa_GSG_P2A_stub"]
    aa3_to_title = {
        "ALA": "Ala", "ARG": "Arg", "ASN": "Asn", "ASP": "Asp", "CYS": "Cys",
        "GLN": "Gln", "GLU": "Glu", "GLY": "Gly", "HIS": "His", "ILE": "Ile",
        "LEU": "Leu", "LYS": "Lys", "MET": "Met", "PHE": "Phe", "PRO": "Pro",
        "SER": "Ser", "THR": "Thr", "TRP": "Trp", "TYR": "Tyr", "VAL": "Val",
    }
    rcl_coord_res_337_341 = [ca_sb9[r]["comp_id"] for r in range(337, 342)]
    rcl_encoded_337_341 = sb9_ledger["sequence"][336:341]
    if not (rcl_encoded_337_341 == "VVAEC" and rcl_coord_res_337_341 == ["VAL", "VAL", "ALA", "GLU", "CYS"]):
        raise ValueError('Molecular source invariant failed: rcl_encoded_337_341 == "VVAEC" and rcl_coord_res_337_341 == ["VAL", "VAL", "ALA", "GLU", "CYS"]')
    rcl_p4_to_p1p_str = (
        f"{aa3_to_title[rcl_coord_res_337_341[0]]}337-{aa3_to_title[rcl_coord_res_337_341[1]]}338-"
        f"{aa3_to_title[rcl_coord_res_337_341[2]]}339-{aa3_to_title[rcl_coord_res_337_341[3]]}340-"
        f"{aa3_to_title[rcl_coord_res_337_341[4]]}341 "
        f"(P4-{rcl_encoded_337_341[0]}337, P3-{rcl_encoded_337_341[1]}338, P2-{rcl_encoded_337_341[2]}339, "
        f"P1-{rcl_encoded_337_341[3]}340, P1'-{rcl_encoded_337_341[4]}341; sequence {rcl_encoded_337_341})"
    )

    # Evaluate polymer contour upper bounds vs WLC RMS reach of the possible 2A C-terminal extensions on SERPINB9 (21 aa, 26 aa, 50 aa; closes 089)
    tail_ensemble_models = []
    for stub_len in [21, 26, 50]:
        contour_a = stub_len * 3.50
        wlc_rms_a = math.sqrt(2.0 * 4.0 * contour_a * (1.0 - (4.0 / contour_a) * (1.0 - math.exp(-contour_a / 4.0))))
        contour_exceeds = bool(contour_a >= min_heavy_dist_cterm_to_rcl)
        rms_exceeds = bool(wlc_rms_a >= min_heavy_dist_cterm_to_rcl)
        tail_ensemble_models.append(
            {
                "stub_length_aa": stub_len,
                "contour_length_angstrom": round(contour_a, 2),
                "wlc_rms_extension_angstrom": round(wlc_rms_a, 2),
                "serpin_intrinsic_cterm_to_rcl_reference_distance_angstrom": round(min_heavy_dist_cterm_to_rcl, 3),
                "pro376_c_peptide_bond_anchor_to_rcl_335_345_distance_angstrom": round(min_heavy_dist_pro376_c_to_rcl_335_345, 3),
                "pro376_c_peptide_bond_anchor_to_rcl_335_350_distance_angstrom": round(min_heavy_dist_pro376_c_to_rcl_335_350, 3),
                "pro376_c_peptide_bond_anchor_to_hinge_318_334_distance_angstrom": round(min_heavy_dist_pro376_c_to_hinge_318_334, 3),
                "contour_upper_bound_exceeds_serpin_intrinsic_cterm_to_rcl_distance": contour_exceeds,
                "wlc_rms_reach_exceeds_serpin_intrinsic_cterm_to_rcl_distance": rms_exceeds,
                "wlc_rms_reach_exceeds_pro376_c_anchor_to_rcl_335_345_distance": bool(wlc_rms_a >= min_heavy_dist_pro376_c_to_rcl_335_345),
                "exceeds_24p05A_unmodified_cterm_to_rcl_clearance": contour_exceeds,
                "steric_conclusion": (
                    "contour_upper_bound_exceeds_but_wlc_rms_below_unmodified_serpin_intrinsic_distance_requires_GzmB_kinetics_assay"
                    if (contour_exceeds and not rms_exceeds)
                    else "both_contour_and_wlc_rms_exceed_unmodified_serpin_intrinsic_distance_requires_GzmB_kinetics_assay"
                ),
            }
        )

    # Parse cached Foldseek table to verify both 4GA7 (top E-value homolog) and 8H4X -> 8ZCR (same-protein cleaved PI-9 structure; closes 092)
    fs_md_path = STRUCT_DIR / "serpinb9_foldseek_results.md"
    fs_md_bytes = fs_md_path.read_bytes()
    fs_md_text = fs_md_bytes.decode("utf-8")
    if ("/" + "Users/") in fs_md_text:
        raise ValueError("Redistributed Foldseek log must not contain local absolute user paths")

    def _parse_foldseek_md_hit(md_text: str, target_prefix: str) -> Dict[str, Any]:
        for line in md_text.splitlines():
            s = line.strip()
            if not s.startswith("|"):
                continue
            cols = [c.strip() for c in s.strip("|").split("|")]
            if len(cols) >= 6 and cols[0].lower().startswith(target_prefix.lower()):
                return {
                    "target_col": cols[0],
                    "q_cov_pct": round(float(cols[1].rstrip("%")), 1),
                    "prob": round(float(cols[2]), 3),
                    "e_value": float(cols[3]),
                    "seq_identity_pct": round(float(cols[4].rstrip("%")), 1),
                    "aligned_length_aa": int(cols[5]),
                }
        raise ValueError(f"Required Foldseek hit '{target_prefix}' not found in {fs_md_path}")

    hit_4ga7 = _parse_foldseek_md_hit(fs_md_text, "4ga7-assembly1.cif.gz_A")
    hit_8h4x = _parse_foldseek_md_hit(fs_md_text, "8h4x-assembly1.cif.gz_A")

    return {
        "complex_id": "LAYER3_COMPLEX_3_SERPINB9_GRANZYME_B",
        "locus": "Locus 3 (CXCL10 Exon-1 KI: CXCL10::SERPINB9-GSG-P2A-PD-L1)",
        "engineered_protein": "Cytosolic SERPINB9 (PI-9, 376 aa + 21-aa C-terminal GSG-P2A stub, Furin-free per R01)",
        "layer2_processed_polypeptide_hashes": {
            "SERPINB9_397aa_with_21aa_P2A_stub_sha256": sb9_ledger["sha256"],
            "SERPINB9_376aa_scar_free_L3_BFB_and_DXL3_sequence": sb9_ledger["sequence"][:376],
            "SERPINB9_376aa_scar_free_L3_BFB_and_DXL3_sha256": hashlib.sha256(sb9_ledger["sequence"][:376].encode("utf-8")).hexdigest(),
            "alternative_26aa_tpt2a_stub_sha256": sb9_ledger["alternative_26aa_stub_sha256"],
            "alternative_50aa_tpt2a_stub_sha256": sb9_ledger["alternative_50aa_stub_sha256"],
        },
        "structures_analyzed": [
            {
                "id": "AF-P50453-F1-model_v6",
                "source": "AlphaFold DB v6 (UniProt P50453 unmodified 376-aa reference model)",
                "global_plddt": meta_sb9["coordinate_global_plddt"],
                "global_plddt_source_audit": meta_sb9["global_plddt_audit"],
                "core_beta_sheet_domain_1_322_mean_plddt": round(float(np.mean(core_plddts)), 2),
                "rcl_loop_322_348_mean_plddt": round(float(np.mean(rcl_hinge_to_p3p_plddts)), 2),
                "rcl_mobile_loop_335_350_mean_plddt": round(float(np.mean(rcl_mobile_loop_335_350_plddts)), 2),
                "p1_glu340_plddt": round(plddt_glu340, 2),
                "p1_prime_cys341_plddt": round(plddt_cys341, 2),
                "c_terminal_sheet_b_349_376_mean_plddt": round(float(np.mean(cterm_plddts)), 2),
                "sha256": hashlib.sha256(snapshots["AF-P50453-F1-model_v6.cif"]).hexdigest(),
                "pae_sha256": hashlib.sha256(snapshots["AF-P50453-F1-predicted_aligned_error_v6.json"]).hexdigest(),
            },
            {
                "id": "AF-P10144-F1-model_v6",
                "source": "AlphaFold DB v6 (UniProt P10144 Granzyme B)",
                "global_plddt": meta_gzmb["coordinate_global_plddt"],
                "global_plddt_source_audit": meta_gzmb["global_plddt_audit"],
                "sha256": hashlib.sha256(snapshots["AF-P10144-F1-model_v6.cif"]).hexdigest(),
                "pae_sha256": hashlib.sha256(snapshots["AF-P10144-F1-predicted_aligned_error_v6.json"]).hexdigest(),
            },
            {
                "pdb_id": "1IAU",
                "resolution_angstrom": 2.00,
                "pmid": "11325591",
                "citation": "Rotonda et al. 2001 Chem Biol",
                "description": "Human Granzyme B in complex with Ac-IEPD-CHO tetrapeptide inhibitor (not full-length SERPINB9)",
                "sha256": hashlib.sha256(snapshots["pdb_00001iau.cif"]).hexdigest(),
            },
        ],
        "foldseek_structural_homolog_verification": {
            "evidence_class": "cached_foldseek_homolog_search_summary",
            "search_provenance": {
                "query_structure_sha256": hashlib.sha256(snapshots["AF-P50453-F1-model_v6.cif"]).hexdigest(),
                "ticket_id": (re.search(r"Ticket ID generated:\s*(\S+)", fs_md_text).group(1) if re.search(r"Ticket ID generated:\s*(\S+)", fs_md_text) else None),
                "source_artifact_sha256": hashlib.sha256(fs_md_bytes).hexdigest(),
                "tool_or_api_version": None, "query_date": None,
                "database_snapshot_versions": {"pdb100": None, "afdb-swissprot": None},
                "missing_historical_fields_status": "NOT_RECORDED",
                "qualification_status": "HISTORICAL_CACHED_HITS_DATABASE_SNAPSHOT_NOT_REPRODUCIBLE",
                "scope": "Replays retained hit values only; no independently reproducible historical search is claimed."},
            "query_structure": "AF-P50453-F1-model_v6.cif",
            "query_structure_sha256": hashlib.sha256(snapshots["AF-P50453-F1-model_v6.cif"]).hexdigest(),
            "foldseek_log_sha256": hashlib.sha256(fs_md_bytes).hexdigest(),
            "databases_searched": ["pdb100", "afdb-swissprot"],
            "top_experimental_pdb100_crystal_homolog": {
                "pdb_id": "4GA7",
                "description": "Crystal structure of human SerpinB1 (clade B ovalbumin-serpin scaffold; top overall E-value crystal hit)",
                "q_cov_pct": hit_4ga7["q_cov_pct"],
                "prob": hit_4ga7["prob"],
                "e_value": hit_4ga7["e_value"],
                "seq_identity_pct": hit_4ga7["seq_identity_pct"],
                "aligned_length_aa": hit_4ga7["aligned_length_aa"],
            },
            "same_protein_human_serpinb9_pdb_hit_and_supersession": {
                "cached_foldseek_pdb_id": "8H4X",
                "cached_description": "Structure of cleaved Serpin B9 (8h4x-assembly1.cif.gz_A)",
                "q_cov_pct": hit_8h4x["q_cov_pct"],
                "prob": hit_8h4x["prob"],
                "e_value": hit_8h4x["e_value"],
                "seq_identity_pct": hit_8h4x["seq_identity_pct"],
                "aligned_length_aa": hit_8h4x["aligned_length_aa"],
                "rcsb_obsoleted_date": "2024-12-25",
                "superseded_by_pdb_id": "8ZCR",
                "superseding_structure_citation": "Yan, Zhou et al. 2024 Acta Crystallogr Sect F Struct Biol Commun 80:286-293 (DOI:10.1107/S2053230X24009439, PMID:39382088; 1.93 A X-ray structure of human PI-9 / SERPINB9)",
                "scope_qualification_note": (
                    f"Foldseek pdb100 hit 8H4X (obsoleted 2024-12-25 and replaced by 8ZCR, Yan, Zhou et al. 2024 Acta Crystallogr Sect F Struct Biol Commun 80:286-293, PMID:39382088) is a cleaved/RCL-divergent "
                    f"human SERPINB9 crystal structure ({hit_8h4x['aligned_length_aa']} aa aligned, {hit_8h4x['q_cov_pct']}% query coverage) and does not resolve the intact mobile RCL "
                    "or C-terminal 21-aa GSG-P2A stub kinetics."
                ),
            },
        },
        "granzyme_b_active_site_and_s1_pocket_1IAU": {
            "alignment_method": "Insertion-code-preserving global sequence alignment (retaining all 6 PDB chymotrypsinogen insertion codes: 36A, 36B, 145A, 172A, 184A, 188A)",
            "chymotrypsinogen_insertion_code_mappings": [
                "1IAU:ASP36A -> AF:ASP42",
                "1IAU:GLN36B -> AF:GLN43",
                "1IAU:PRO145A -> AF:PRO152",
                "1IAU:ARG172A -> AF:ARG178 (S2/S4 pocket contact)",
                "1IAU:GLY184A -> AF:GLY190",
                "1IAU:LYS188A -> AF:LYS195",
            ],
            "aligned_ca_residues_AF_vs_1IAU": len(matched_af_coords),
            "identical_residue_pairs": identical_pairs,
            "rmsd_AF_P10144_vs_1IAU_angstrom": round(rmsd_gzmb_af_vs_1iau, 4),
            "af_p10144_mature_226aa_global_mean_plddt": round(float(np.mean([a["b_iso"] for a in ca_gzmb_af_list[:226]])), 2),
            "covalent_adduct_and_tyr247_alignment_scope_note_kimi_r3_005": (
                "In PDB:1IAU (Granzyme B complexed with Ac-IEPD-CHO aldehyde inhibitor), the 1.4711 A distance (< 2.0 A) between catalytic "
                "Ser195.OG and inhibitor ASJ405.C is the expected covalent tetrahedral hemiacetal adduct bond rather than a non-covalent steric clash. "
                "AF-P10144-F1 predicts 227 mature residues (Ile21..Tyr247), whereas 1IAU resolves 226 mature residues (21..246, omitting C-terminal Tyr247)."
            ),
            "iepd_inhibitor_interface": iepd_interface,
            "altloc_conformer_sensitivity_1IAU_claude_v80_091": altloc_1iau_audit,
        },
        "r01_c_terminal_tpt2a_tail_and_rcl_suicide_trap_geometry": {
            "evidence_class": "unmodified_reference_geometry_plus_polymer_contour_analysis_requires_wetlab_kinetics",
            "functional_status": "experimentally_unresolved_requires_GzmB_kinetics_assay",
            "rcl_p4_to_p1_prime_sequence": rcl_p4_to_p1p_str,
            "rcl_p4_to_p1_prime_5mer_code": rcl_encoded_337_341,
            "rcl_322_348_loop_mean_plddt": round(float(np.mean(rcl_hinge_to_p3p_plddts)), 2),
            "rcl_335_345_hinge_to_p1p1prime_mean_plddt": round(float(np.mean(rcl_recognition_335_345_plddts)), 2),
            "rcl_335_345_recognition_loop_mean_plddt": round(float(np.mean(rcl_recognition_335_345_plddts)), 2),
            "rcl_335_350_mean_plddt": round(float(np.mean(rcl_mobile_loop_335_350_plddts)), 2),
            "alphafold_pae_uncertainty_summary_claude_v80_065": {
                "serpinb9_core_1_322_mean_pae_angstrom": sb9_core_pae_mean,