OpenIslet

scripts/run_layer5_personalized_patient_compiler.py

Layer 5: Personalized Patient-DNA & Multiplex CRISPR Compiler + 10,000-Patient Global Population Simulator (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 494 KB · 31 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_layer5_personalized_patient_compiler.py · SHA-256: 0b285369ac6e4409…

    '3mm":0.472727,"OI_GRNA_04_ZNF710_Ex5_1bp_RNA_bulge_22mer":null,"OI_GRNA_04_chrX":0.370588,"OI_GRNA_05_chr12":0.806723,"O'
    'I_GRNA_05_GRIK5_cis_chr19":0.32,"CBE08_TET1_Ex4_1bp_RNA_bulge_SpG_GGT":null,"DY_TAD01_chr20":0.646154,"DY_TAD03_chr7":0.'
    '785965,"CBE01_chr3":0.568513,"CBE04_chr4":0.262474}}}}'
)


def _is_strict_int_iip_0026(val: Any) -> bool:
    return isinstance(val, int) and not isinstance(val, bool)


def left_normalize_vcf_allele_iip_0026(
    chrom: str,
    chrom_start_0based: int,
    chrom_end_1based: int,
    ucsc_ref: str,
    ucsc_alt: str,
    ref_slice_start_1based: int,
    ref_slice_plus_dna: str,
) -> tuple[str, str, int, str, str]:
    """
    Iterative left-aligned parsimonious VCF normalization on GRCh38 (Tan et al. 2015 PMID:25701572; IIP-0026; DEC-105).
    Enforces strict left-boundary guards (never wrapping negative Python indices and never emitting REF == ALT),
    emitting UNRESOLVED_BOUNDARY when an indel repeat run reaches the left slice boundary or chromosome start.
    """
    ch_num = chrom.replace("chr", "")
    pos1 = chrom_start_0based + 1
    r = ucsc_ref.upper()
    a = ucsc_alt.upper()
    if r == a:
        return "UNRESOLVED_IDENTICAL_ALLELES", "UNRESOLVED_IDENTICAL_ALLELES", pos1, r, a

    s_idx = pos1 - ref_slice_start_1based
    e_idx = chrom_end_1based - ref_slice_start_1based + 1
    if s_idx < 0 or e_idx < s_idx or e_idx > len(ref_slice_plus_dna) or pos1 < 1:
        return "UNRESOLVED_BOUNDARY", "UNRESOLVED_BOUNDARY", pos1, r, a

    expected_ref = ref_slice_plus_dna[s_idx:e_idx]
    if r != expected_ref:
        raise ValueError(f"Reference mismatch at {chrom}:{pos1}: UCSC {r} vs GRCh38 {expected_ref}")

    while (not r or not a) or (r[-1] == a[-1]):
        if r and a and r[-1] == a[-1]:
            r = r[:-1]
            a = a[:-1]
        while not r or not a:
            if pos1 <= ref_slice_start_1based or pos1 <= 1:
                return "UNRESOLVED_BOUNDARY", "UNRESOLVED_BOUNDARY", pos1, ucsc_ref.upper(), ucsc_alt.upper()
            pos1 -= 1
            pad_idx = pos1 - ref_slice_start_1based
            if pad_idx < 0:
                return "UNRESOLVED_BOUNDARY", "UNRESOLVED_BOUNDARY", pos1, ucsc_ref.upper(), ucsc_alt.upper()
            pad_b = ref_slice_plus_dna[pad_idx]
            r = pad_b + r
            a = pad_b + a
    while len(r) > 1 and len(a) > 1 and r[0] == a[0]:
        r = r[1:]
        a = a[1:]
        pos1 += 1

    if not r or not a or r == a:
        return "UNRESOLVED_IDENTICAL_ALLELES", "UNRESOLVED_IDENTICAL_ALLELES", pos1, r, a

    gnomad_id = f"{ch_num}-{pos1}-{r}-{a}"
    colon_id = f"chr{ch_num}:{pos1}:{r}:{a}"
    return gnomad_id, colon_id, pos1, r, a


_IIP_0026_MAJOR_POPS = ("afr", "amr", "asj", "eas", "fin", "mid", "nfe", "sas")


def summarize_gnomad_modality_iip_0026(block: Dict[str, Any] | None) -> Dict[str, Any]:
    """
    Summarize a single gnomAD v4.1 (gnomad_r4) modality block (IIP-0026; DEC-105):
      - Requires observed list `filters` and strict integer `0 <= ac <= an` with `an > 0`;
        never coerces absent/None filters to PASS and never coerces AN=0 to AF=0.0.
      - Preserves exact unrounded `raw_af = ac / an` for threshold comparisons alongside
        6-decimal `global_af`, and preserves missing ancestry blocks as `"UNRESOLVED"`.
    """
    unresolved_pops = {pid: "UNRESOLVED" for pid in _IIP_0026_MAJOR_POPS}
    if (
        block is None
        or "filters" not in block
        or not isinstance(block.get("filters"), list)
        or not _is_strict_int_iip_0026(block.get("ac"))
        or not _is_strict_int_iip_0026(block.get("an"))
        or int(block["ac"]) < 0
        or int(block["an"]) <= 0
        or int(block["ac"]) > int(block["an"])
    ):
        return {
            "resolution_status": "UNRESOLVED",
            "filter_status": "UNRESOLVED",
            "ac": None,
            "an": None,
            "raw_af": "UNRESOLVED",
            "global_af": "UNRESOLVED",
            "max_major_pop": "UNRESOLVED",
            "major_pop_afs": unresolved_pops,
        }
    flts = list(block["filters"])
    ac_int = int(block["ac"])
    an_int = int(block["an"])
    raw_global_af = ac_int / an_int

    pops: Dict[str, Any] = {pid: "UNRESOLVED" for pid in _IIP_0026_MAJOR_POPS}
    valid_pops: Dict[str, Dict[str, Any]] = {}
    for p in block.get("populations") or []:
        pid = p.get("id")
        if (
            pid in _IIP_0026_MAJOR_POPS
            and _is_strict_int_iip_0026(p.get("ac"))
            and _is_strict_int_iip_0026(p.get("an"))
            and 0 <= int(p["ac"]) <= int(p["an"])
            and int(p["an"]) > 0
        ):
            p_ac = int(p["ac"])
            p_an = int(p["an"])
            p_raw = p_ac / p_an
            p_rec = {"ac": p_ac, "an": p_an, "raw_af": p_raw, "af": round(p_raw, 6)}
            pops[pid] = p_rec
            valid_pops[pid] = p_rec
    max_pop: Any = "UNRESOLVED"
    if valid_pops:
        best_pid, best_d = max(valid_pops.items(), key=lambda kv: kv[1]["raw_af"])
        max_pop = {"pop": best_pid, **best_d}
    return {
        "resolution_status": "RESOLVED",
        "filter_status": "PASS" if len(flts) == 0 else f"FLAGGED:{flts}",
        "filters": flts,
        "ac": ac_int,
        "an": an_int,
        "raw_af": raw_global_af,
        "global_af": round(raw_global_af, 6),
        "max_major_pop": max_pop,
        "major_pop_afs": pops,
    }


def classify_gnomad_either_and_wgs_resolution_iip_0026(gv: Dict[str, Any] | None) -> Dict[str, Any]:
    if gv is None:
        return {
            "either_modality_resolved": False,
            "gnomad_r4_status": "UNRESOLVED_ABSENT_FROM_GNOMAD_V4_1",
            "summary": None,
        }
    sm = {
        "variant_id": gv["variant_id"],
        "normalized_grch38": "chr" + gv["variant_id"].replace("-", ":"),
        "rsids": gv.get("rsids") or [],
        "flags": gv.get("flags") or [],
        "genome_wgs": summarize_gnomad_modality_iip_0026(gv.get("genome")),
        "exome": summarize_gnomad_modality_iip_0026(gv.get("exome")),
        "joint_filters": (gv.get("joint") or {}).get("filters"),
    }
    either_ok = (sm["genome_wgs"]["resolution_status"] == "RESOLVED") or (
        sm["exome"]["resolution_status"] == "RESOLVED"
    )
    return {
        "either_modality_resolved": either_ok,
        "gnomad_r4_status": (
            "RESOLVED_BY_NORMALIZED_CHR_POS_REF_ALT"
            if either_ok
            else "UNRESOLVED_ZERO_AN_IN_BOTH_MODALITIES"
        ),
        "summary": sm,
    }


def evaluate_pe4max_piecewise_repeat_indel_cap_iip_0026(
    c_clone: Any,
    c_ctrl: Any,
    coding_or_splice_indels: Any,
) -> tuple[str, int | None]:
    """
    Piecewise repeat-indel qualification cap for held TYK2 PE4max (IIP-0026; DEC-105):
      - Requires coding_or_splice_indels == 0 unconditionally;
      - 0 <= C_ctrl <= 25: C_clone <= C_ctrl + 5 (continuous at C_ctrl = 25 -> cap 30);
      - C_ctrl > 25:       C_clone <= floor(1.2 * C_ctrl) (e.g. C_ctrl = 100 -> cap 120).
    """
    for v in (c_clone, c_ctrl, coding_or_splice_indels):
        if not _is_strict_int_iip_0026(v) or v < 0:
            return ("HOLD_INVALID_OR_MISSING_PE4MAX_INDEL_COUNTS", None)
    if coding_or_splice_indels != 0:
        return ("FAIL_PE4MAX_CODING_OR_SPLICE_DE_NOVO_INDEL_DETECTED", 0)
    cap = (c_ctrl + 5) if c_ctrl <= 25 else int(math.floor(1.2 * c_ctrl))
    if c_clone <= cap:
        return ("PASS_PE4MAX_PIECEWISE_REPEAT_INDEL_CAP", cap)
    return ("FAIL_PE4MAX_REPEAT_INDEL_CAP_EXCEEDED", cap)


def _build_variant_aware_gnomad_hlac_pe4max_and_designy_audit_iip_0026() -> Dict[str, Any]:
    """
    Build deterministic 69-key gnomAD v4.1 normalized join, 17-record coordinate-preserved HLA-C
    audit (recording both 114/115 nominal-cut-in-exon and 106/108 full-23mer-in-exon conventions),
    held TYK2 PE4max piecewise gate, held Design Y 63k/90k-GE ddPCR + TwinPE-79bp specs, and
    2^12 portfolio invariance replay (IIP-0026; DEC-105).
    """
    from itertools import product as _iter_product

    pinned = json.loads(_IIP_0026_RIGHTS_CLEAN_PINNED_JSON)
    raw_bundle_txt = _IIP_0026_RIGHTS_CLEAN_PINNED_JSON
    if ("doench2016_mismatch_scores" in raw_bundle_txt) or ("doench2016_pam_scores" in raw_bundle_txt):
        raise ValueError("Forbidden external CFD weight table detected in pinned bundle")

    comp_tbl = str.maketrans("ACGTNacgtn", "TGCANtgcan")

    def _rc(s: str) -> str:
        return s.upper().translate(comp_tbl)[::-1]

    # 1. Reconcile all 56 UCSC dbSnp155 loci -> 69 normalized GRCh38 chr:pos:ref:alt keys
    raw_l5 = json.loads((REPO_ROOT / "data/raw/layer5_dbsnp_clinvar_reference.json").read_text(encoding="utf-8"))
    ucsc_56 = raw_l5["ucsc_dbsnp155_primary_interval_responses"]
    ref_slices_l5 = pinned["grch38_layer5_target_reference_slices"]
    map_l5_to_reg = {
        "OI-GRNA-01_B2M_EXON1_ASCAS12A": "OI-GRNA-01_B2M",
        "OI-GRNA-02_CIITA_EXON1_ASCAS12A": "OI-GRNA-02_CIITA",
        "OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9": "OI-GRNA-03_CXCL10",
        "OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9": "OI-GRNA-04_AAVS1",
        "OI-GRNA-05_TYK2_P1104A_PEMAX_EPEGRNA_OPTIONAL": "OI-GRNA-05_TYK2",
    }

    per_guide_69: Dict[str, Any] = {}
    total_norm_alleles = 0
    either_resolved = 0
    either_unresolved = 0
    wgs_pass = 0
    wgs_flagged = 0
    wgs_unresolved = 0
    exome_pass = 0
    exome_flagged = 0
    exome_unresolved = 0
    guides_with_pass_wgs_non_target_ge_1e4 = 0

    for gid, rkey in map_l5_to_reg.items():
        reg_vars_by_vid = {gv["variant_id"]: gv for gv in pinned["gnomad_v4_1_layer5_target_regions"][rkey]}
        rslice = ref_slices_l5[gid]
        allele_rows: List[Dict[str, Any]] = []
        pass_wgs_non_target_ge_1e4: List[Dict[str, Any]] = []
        pass_wgs_non_target_pop_ge_1e3: List[Dict[str, Any]] = []

        for item in ucsc_56[gid]["items"]:
            raw_alts = item.get("alts") or []
            alts_to_norm = raw_alts if raw_alts else [""]
            for raw_alt in alts_to_norm:
                total_norm_alleles += 1
                g_vid, c_vid, _np1, _nr, _na = left_normalize_vcf_allele_iip_0026(
                    item["chrom"],
                    int(item["chromStart"]),
                    int(item["chromEnd"]),
                    item["ref"],