OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 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/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

def scan_swissprot_peptides(aa: str, sp_kmers: dict[int, set[str]]) -> dict[str, Any]:
    out = {}
    tot_8_11 = 0
    f8_11_list = []
    for k in (8, 9, 10, 11, 15):
        n_tot = max(0, len(aa) - k + 1)
        foreign = [aa[i : i + k] for i in range(n_tot) if aa[i : i + k] not in sp_kmers[k]]
        out[f"k{k}_total"] = n_tot
        out[f"k{k}_foreign"] = len(foreign)
        if k in (8, 9, 10, 11):
            tot_8_11 += len(foreign)
            f8_11_list.extend(foreign[:5])
        if k == 15:
            out["k15_foreign_examples"] = foreign[:5]
    out["foreign_8_11mers_total"] = tot_8_11
    out["foreign_8_11mer_examples"] = f8_11_list[:8]
    return out


def _mmcif_chain_id(row: dict[str, str], label_key: str, auth_key: str) -> str:
    """Prefer wwPDB canonical label_asym_id over author-assigned auth_asym_id (preserving deposited glycan subchains)."""
    lbl = row.get(label_key, "")
    if lbl and lbl not in (".", "?"):
        return lbl
    auth = row.get(auth_key, "")
    return "" if auth in (".", "?") else auth


def _parse_mmcif_struct_conn_glycan_links(
    lines: list[str], receptor_chains: set[str], partner_protein_chains: set[str]
) -> dict[str, Any]:
    """Parse _struct_conn covalent links directly (preferring wwPDB label_asym_id over auth_asym_id) to classify
    glycan chains covalently attached to partner (Fc) protein chains vs receptor self-glycan chains."""
    cols: list[str] = []
    in_loop = False
    reading_rows = False
    tok_buf: list[str] = []
    rows: list[dict[str, str]] = []
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            cols = []
            in_loop = False
            reading_rows = False
            tok_buf = []
            continue
        if s.startswith("_struct_conn."):
            cols.append(s)
            in_loop = True
            reading_rows = False
            continue
        if in_loop and cols:
            if not s or s.startswith("#") or s.startswith("_"):
                in_loop = False
                reading_rows = False
                continue
            reading_rows = True
            toks = re.findall(r"'[^']*'|\"[^\"]*\"|\S+", s)
            tok_buf.extend(t.strip("'\"") for t in toks)
            while len(tok_buf) >= len(cols):
                row_toks = tok_buf[: len(cols)]
                tok_buf = tok_buf[len(cols) :]
                rows.append({cols[i]: row_toks[i] for i in range(len(cols))})
    partner_glyc: set[str] = set()
    receptor_glyc: set[str] = set()
    glycan_links: list[dict[str, str]] = []
    for r in rows:
        if r.get("_struct_conn.conn_type_id") != "covale":
            continue
        c1 = _mmcif_chain_id(r, "_struct_conn.ptnr1_label_asym_id", "_struct_conn.ptnr1_auth_asym_id")
        comp1 = r.get("_struct_conn.ptnr1_auth_comp_id") or r.get("_struct_conn.ptnr1_label_comp_id", "")
        seq1 = r.get("_struct_conn.ptnr1_auth_seq_id") or r.get("_struct_conn.ptnr1_label_seq_id", "")
        c2 = _mmcif_chain_id(r, "_struct_conn.ptnr2_label_asym_id", "_struct_conn.ptnr2_auth_asym_id")
        comp2 = r.get("_struct_conn.ptnr2_auth_comp_id") or r.get("_struct_conn.ptnr2_label_comp_id", "")
        seq2 = r.get("_struct_conn.ptnr2_auth_seq_id") or r.get("_struct_conn.ptnr2_label_seq_id", "")
        if c1 != c2:
            if c1 in partner_protein_chains and c2 not in receptor_chains and c2 not in partner_protein_chains:
                partner_glyc.add(c2)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "PARTNER_FC", "from": f"{c1}:{comp1}{seq1}", "to": f"{c2}:{comp2}{seq2}"})
            elif c2 in partner_protein_chains and c1 not in receptor_chains and c1 not in partner_protein_chains:
                partner_glyc.add(c1)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "PARTNER_FC", "from": f"{c2}:{comp2}{seq2}", "to": f"{c1}:{comp1}{seq1}"})
            elif c1 in receptor_chains and c2 not in receptor_chains and c2 not in partner_protein_chains:
                receptor_glyc.add(c2)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "RECEPTOR_SELF", "from": f"{c1}:{comp1}{seq1}", "to": f"{c2}:{comp2}{seq2}"})
            elif c2 in receptor_chains and c1 not in receptor_chains and c1 not in partner_protein_chains:
                receptor_glyc.add(c1)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "RECEPTOR_SELF", "from": f"{c2}:{comp2}{seq2}", "to": f"{c1}:{comp1}{seq1}"})
    return {
        "partner_glycan_chains": sorted(partner_glyc),
        "receptor_self_glycan_chains": sorted(receptor_glyc),
        "covalent_glycan_links": glycan_links,
    }


def parse_mmcif_interface_contacts(
    cif_path: pathlib.Path,
    receptor_chains: set[str],
    partner_chains: set[str],
    cutoff_angstrom: float = 4.5,
    include_partner_hetatm: bool = False,
    partner_protein_chains: set[str] | None = None,
    receptor_self_glycan_chains: set[str] | None = None,
) -> dict[str, Any]:
    """Direct pure-Python mmCIF parser computing heavy-atom interface contacts (ATOM + partner Fc HETATM
    glycans, strictly separated from receptor-linked self-glycans verified via _struct_conn), using
    wwPDB canonical label_asym_id (with auth_asym_id fallback) so glycan label subchains sharing an
    author chain ID (such as 4X4M Assembly 2 chains L and M sharing auth_asym_id='D') are never dropped."""
    cols: list[str] = []
    rec_atoms: list[tuple[str, int, str, float, float, float]] = []
    par_atoms: list[tuple[str, int, str, str, float, float, float]] = []
    self_glyc_atoms: list[tuple[str, int, str, float, float, float]] = []
    partner_hetatm_atoms_by_chain: dict[str, int] = {}
    lines = cif_path.read_text(encoding="utf-8", errors="ignore").splitlines()
    p_prot = partner_protein_chains if partner_protein_chains is not None else set(partner_chains)
    conn_info = _parse_mmcif_struct_conn_glycan_links(lines, receptor_chains, p_prot)
    partner_glyc_set = (set(conn_info["partner_glycan_chains"]) | (partner_chains - p_prot)) & partner_chains
    self_g_set = set(receptor_self_glycan_chains) if receptor_self_glycan_chains is not None else set(conn_info["receptor_self_glycan_chains"])
    in_atom_loop = False
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            cols = []
            in_atom_loop = False
            continue
        if s.startswith("_atom_site."):
            cols.append(s)
            in_atom_loop = True
            continue
        if in_atom_loop and (s.startswith("ATOM ") or s.startswith("HETATM ")):
            toks = s.split()
            if len(toks) < len(cols):
                continue
            cmap = {cols[i]: toks[i] for i in range(len(cols))}
            grp = cmap.get("_atom_site.group_PDB", "")
            elem = cmap.get("_atom_site.type_symbol", "")
            if elem in ("H", "D"):
                continue
            ch = _mmcif_chain_id(cmap, "_atom_site.label_asym_id", "_atom_site.auth_asym_id")
            comp = cmap.get("_atom_site.auth_comp_id") or cmap.get("_atom_site.label_comp_id", "")
            if comp == "HOH":
                continue
            try:
                resn = int(cmap.get("_atom_site.auth_seq_id") or cmap.get("_atom_site.label_seq_id") or "0")
                x = float(cmap["_atom_site.Cartn_x"])
                y = float(cmap["_atom_site.Cartn_y"])
                z = float(cmap["_atom_site.Cartn_z"])
            except Exception:
                continue
            if grp == "ATOM" and ch in receptor_chains:
                rec_atoms.append((ch, resn, comp, x, y, z))
            if grp == "ATOM" and ch in p_prot:
                par_atoms.append((ch, resn, comp, grp, x, y, z))
            elif include_partner_hetatm and grp == "HETATM" and ch in partner_glyc_set:
                par_atoms.append((ch, resn, comp, grp, x, y, z))
                partner_hetatm_atoms_by_chain[ch] = partner_hetatm_atoms_by_chain.get(ch, 0) + 1
            if grp == "HETATM" and ch in self_g_set:
                self_glyc_atoms.append((ch, resn, comp, x, y, z))
        elif in_atom_loop and s and not s.startswith("#") and not s.startswith("_"):
            if s.startswith("loop_"):
                cols = []
                in_atom_loop = False
            else:
                in_atom_loop = False

    c2 = cutoff_angstrom * cutoff_angstrom
    rec_contact_res: set[int] = set()
    rec_protein_contact_res: set[int] = set()
    rec_fc_glycan_contact_res: set[int] = set()
    rec_self_glycan_contact_res: set[int] = set()
    par_contact_res: set[tuple[str, int, str, str]] = set()
    fc_glycan_contacts = 0
    self_glycan_contacts = 0
    for rch, rseq, rcomp, rx, ry, rz in rec_atoms:
        for pch, pseq, pcomp, pgrp, px, py, pz in par_atoms:
            dx = rx - px
            if abs(dx) > cutoff_angstrom:
                continue
            dy = ry - py
            if abs(dy) > cutoff_angstrom:
                continue
            dz = rz - pz
            if dx * dx + dy * dy + dz * dz <= c2:
                rec_contact_res.add(rseq)
                par_contact_res.add((pch, pseq, pcomp, pgrp))
                if pgrp == "HETATM":
                    fc_glycan_contacts += 1
                    rec_fc_glycan_contact_res.add(rseq)
                else:
                    rec_protein_contact_res.add(rseq)
        for sch, sseq, scomp, sx, sy, sz in self_glyc_atoms:
            dx = rx - sx
            if abs(dx) > cutoff_angstrom:
                continue
            dy = ry - sy
            if abs(dy) > cutoff_angstrom:
                continue
            dz = rz - sz
            if dx * dx + dy * dy + dz * dz <= c2:
                self_glycan_contacts += 1
                rec_self_glycan_contact_res.add(rseq)

    # Parse _struct_ref_seq_dif engineered mutations on receptor_chains & check contact overlap directly from mmCIF!
    aa3_to_1 = {
        "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q", "GLU": "E",
        "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L", "LYS": "K", "MET": "M", "PHE": "F",
        "PRO": "P", "SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V",
    }
    resolved_rec_seqs = {rseq for (_rch, rseq, _rcomp, _rx, _ry, _rz) in rec_atoms}
    eng_muts_per_chain: dict[str, list[tuple[int, str]]] = {}
    all_eng_mut_rows = 0
    dif_cols: list[str] = []
    in_dif = False
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            dif_cols = []
            in_dif = False
            continue
        if s.startswith("_struct_ref_seq_dif."):
            dif_cols.append(s)
            in_dif = True
            continue
        if in_dif:
            if not s or s.startswith("#") or s.startswith("_") or s == "loop_":
                in_dif = False
                continue
            if "engineered mutation" in s.lower():
                all_eng_mut_rows += 1
                toks = re.findall(r"'[^']*'|\"[^\"]*\"|\S+", s)
                if len(toks) >= len(dif_cols):
                    dmap = {dif_cols[i]: toks[i].strip("'\"") for i in range(len(dif_cols))}
                    ch_d = dmap.get("_struct_ref_seq_dif.pdbx_pdb_strand_id", "")
                    if ch_d in receptor_chains:
                        db_num = dmap.get("_struct_ref_seq_dif.pdbx_seq_db_seq_num", "")
                        wt3 = dmap.get("_struct_ref_seq_dif.db_mon_id", "")
                        mut3 = dmap.get("_struct_ref_seq_dif.mon_id", "")
                        if db_num.isdigit():
                            pos = int(db_num)
                            lbl = f"{aa3_to_1.get(wt3, wt3)}{pos}{aa3_to_1.get(mut3, mut3)}"
                            eng_muts_per_chain.setdefault(ch_d, []).append((pos, lbl))
    rec_muts = sorted({item for v in eng_muts_per_chain.values() for item in v})
    resolved_muts = [lbl for p, lbl in rec_muts if p in resolved_rec_seqs]
    muts_in_prot = [lbl for p, lbl in rec_muts if p in rec_protein_contact_res]
    muts_in_fc_glyc = [lbl for p, lbl in rec_muts if p in rec_fc_glycan_contact_res]
    muts_in_self_glyc = [lbl for p, lbl in rec_muts if p in rec_self_glycan_contact_res]

    # Exact minimum heavy-atom distances for ALL resolved engineered mutations to partner protein & partner Fc glycans
    par_prot_pts = [(px, py, pz) for (_pch, _pseq, _pcomp, pgrp, px, py, pz) in par_atoms if pgrp == "ATOM"]