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…

        "tyk2_independent_autoimmune_memory_and_indirect_dr3_dq8_audit_sonnet55_r5": {
            "finding_ids": ["AUDIT-REF", "AUDIT-REF", "AUDIT-REF"],
            "primary_citations": ["PMID:27807284", "PMID:30578352", "PMID:36289205", "PMID:26239055"],
            "tyk2_p1104a_pathway_scope": (
                "TYK2 P1104A (rs34536443 C/C) selectively dampens Type-I IFN (IFN-alpha/beta via IFNAR1/TYK2-JAK1) and IL-12/IL-23 signaling, "
                "but does NOT block IFN-gamma signaling (which signals exclusively through IFNGR1/IFNGR2 via JAK1 + JAK2, independent of TYK2) "
                "nor TNF-alpha / IL-1beta NF-kB/JNK pro-apoptotic signaling, and does NOT prevent host recipient APCs from phagocytosing shed beta-cell autoantigens (PPI, GAD65, IA-2, ZnT8, HIPs) "
                "for indirect presentation on recipient HLA-DR3-DQ2 / HLA-DQ8 to autoreactive CD4+ helper T cells."
            ),
            "orthogonal_protection_layers_required": (
                "Protection against TYK2-independent IFN-gamma/TNF-alpha + indirect DR3/DQ8 CD4+ autoimmunity relies on: "
                "(1) CXCL10-inducible (or L3-BF-B basal-floor) cytosolic SERPINB9 + surface PD-L1 (harnessing local IFN-gamma/STAT1 to upregulate granzyme-B/PD-1 defense), "
                "(2) peri-implant SA-FasL / SA-THBD microgel + Treg co-delivery to induce apoptosis of infiltrating Fas+ CD4+ Teff and foster FoxP3+ Treg conversion, and "
                "(3) Stage-0 Gate 0C-kinetic verification under combined IFN-gamma + TNF-alpha + IL-1beta + DR3/DQ8 PBMC transwell co-culture."
            ),
        },
        "recipient_carries_rare_protospacer_snp": recipient_has_protospacer_snp,
        "edited_cell_line_requires_custom_allele_grna": editing_genome_has_snp,
        "compiled_grna_panel": grna_set,
        "sirpa_polymorphism_compatibility": (
            f"Reference structures cover SIRPA V1/V2; exact-product affinity/protection for supplied genotype {sirpa_genotype}, "
            "including V8 if present, is unmeasured and requires binding and macrophage assays (AUDIT-REF)"
        ),
        "b_prime_4digit_hlac_and_b_prime_sct_routing_audit_muse_r3": {
            "recipient_hla_c_genotype_4digit": _get_opt(patient, "recipient_hla_c_genotype_4digit", None),
            "recipient_kir_genotype": _get_opt(patient, "recipient_kir_genotype", None),
            "recipient_anti_hla_c_dsa": bool(_get_opt(patient, "recipient_anti_hla_c_dsa", False)),
            "hlac_4digit_relation": _get_opt(
                patient,
                "hlac_4digit_relation",
                "SELF_4DIGIT_MATCH" if not use_plan_b_hla_c_retained else "UNSPECIFIED_ASSUMED_4DIGIT_OR_B_PRIME_SCT",
            ),
            "track2_hlac_4digit_match_status": prod_qual_status,
            "canonical_track2_kir_subbank_product_variant_id": (
                ("ISLET1_B_SCT_C1_CIITA_TYK2_PE" if include_tyk2_p1104a_edit else "ISLET1_B_SCT_C1_CIITA")
                if kir_ligand_group == "C1/C1"
                else (
                    ("ISLET1_B_SCT_C2_CIITA_TYK2_PE" if include_tyk2_p1104a_edit else "ISLET1_B_SCT_C2_CIITA")
                    if kir_ligand_group == "C2/C2"
                    else ("ISLET1_B_SCT_C1C2_CIITA_TYK2_PE" if include_tyk2_p1104a_edit else "ISLET1_B_SCT_C1C2_CIITA")
                )
            ),
            "endogenous_hlac_retention_status": "EXPLORATORY_REQUIRES_4DIGIT_BANK",
            "b_prime_sct_status": (
                "CANONICAL_TRACK2_KIR_ENGAGING_SUBBANK_K4_B1_3PASS_TYK2_PE_SATELLITE"
                if include_tyk2_p1104a_edit
                else "CANONICAL_TRACK2_KIR_ENGAGING_SUBBANK_K4_B0_2PASS"
            ),
            "recipient_bw4_kir3dl1_educated_status": (
                "CLEARED_SORTED_KIR3DL1_NK"
                if (recipient_bw4_kir3dl1_educated and bw4_kir3dl1_nk_lysis_cleared)
                else (
                    "HOLD_REQUIRES_SORTED_KIR3DL1_NKG2A_NEG_NK_CLEARANCE"
                    if recipient_bw4_kir3dl1_educated
                    else "NOT_INDICATED_BW4_KIR3DL1_ABSENT_OR_UNSPECIFIED"
                )
            ),
            "c1c2_heteroallelic_phased_longread_ddpcr_verified": (
                (c1c2_heteroallelic_phased_verified if c1c2_phasing_explicitly_supplied else None)
                if (use_b_prime_sct_k4 and kir_ligand_group in {"C1/C2", "C2/C1"})
                else None
            ),
            "c1c2_heteroallelic_phased_verification_status": (
                (
                    "VERIFIED_EXPLICIT_TRUE"
                    if (c1c2_phasing_explicitly_supplied and c1c2_heteroallelic_phased_verified)
                    else (
                        "HOLD_EXPLICIT_FALSE"
                        if c1c2_phasing_explicitly_supplied
                        else "HOLD_UNMEASURED_MISSING_PHASING_EVIDENCE"
                    )
                )
                if (use_b_prime_sct_k4 and kir_ligand_group in {"C1/C2", "C2/C1"})
                else None
            ),
            "note": (
                "Because KIR C1/C2 dimorphism is a 2-group epitope (Asn80 vs Lys80) while T-cell & DSA alloreactivity is 4-digit allele-specific "
                "(Xu et al. 2019 PMID:30853558; Tran et al. 2011 PMID:21743387), a 3-line endogenous HLA-C sub-bank leaves ~70-85% of recipients "
                "4-digit mismatched at HLA-C unless a ~12-16 line homozygous 4-digit bank is used or a non-allogenic self-peptide HLA-C SCT "
                "(Design B'-SCT: ISLET1_B_SCT_C1_CIITA [GAVDPLLAL, PDB:1EFX] / ISLET1_B_SCT_C2_CIITA [QYDDAVYKL, PDB:1IM9] at CIITA Exon 5, K=4, B=0 [P_passes=2] or B=1 [P_passes=3]) is deployed (AUDIT-REF & AUDIT-REF)."
            ),
        },
    }


VALID_COMPILED_TRACKS = {
    "TRACK_1_UNIVERSAL_OFF_THE_SHELF_ALLOGENEIC",
    "TRACK_2_PATIENT_DNA_STRATIFIED_ALLOGENEIC_SUBLINE",
    "TRACK_3_PERSONALIZED_AUTOLOGOUS_PATIENT_IPSC",
}


def evaluate_regimen_survival_probability(
    patient: Dict[str, Any],
    compiled_regimen: Dict[str, Any],
    *,
    loading_area_mode: str = "selected_physical_route",
    total_burden_penalty_per_extra_100k_ieq: float = 0.0,
) -> float:
    """
    Evaluate conditional 5-year graft survival probability (conditional on transplanting a release-qualified
    MCB clone) from how well `compiled_regimen` addresses `patient`'s sampled immunological and genetic risk
    factors (closing AUDIT-REF, AUDIT-REF, AUDIT-REF, AUDIT-REF, and AUDIT-REF; BPR-09 / DEC-133).
    Recognizes natural homozygous `TYK2 rs34536443 C/C` on the graft genome as conferring the exact same
    biological TYK2 P1104A protection as prime-edited `G/G -> C/C`.

    BPR-09 loading_area_mode:
      - "selected_physical_route" (default): scores local areal loading against the regimen's selected
        modular cassette area (unless `single_200cm2_pouch_forced_without_modular_scaling=True`, which
        preserves the forced 200 cm^2 single-pouch stress test).
      - "legacy_fixed_200cm2": scores against fixed 200 cm^2 to preserve historical provenance.
      - Optional `total_burden_penalty_per_extra_100k_ieq >= 0.0` allows a separately justified
        total-implant-burden sensitivity above 500,000 IEQ without conflating local areal loading.
    """
    if loading_area_mode not in ("selected_physical_route", "legacy_fixed_200cm2"):
        raise ValueError(f"Invalid loading_area_mode {loading_area_mode!r}")
    burden_pen = _validate_finite_float(
        total_burden_penalty_per_extra_100k_ieq, "total_burden_penalty_per_extra_100k_ieq", 0.0, 0.5
    )
    if not isinstance(patient, dict):
        raise ValueError("patient must be a dictionary")
    if not isinstance(compiled_regimen, dict):
        raise ValueError("compiled_regimen must be a dictionary")
    req_reg_keys = (
        "selected_fda_deployment_track",
        "locus1_construct_prescribed",
        "plan_architecture_prescribed",
        "include_tyk2_p1104a_rs34536443_shield",
        "compiled_grna_panel",
    )
    for rk in req_reg_keys:
        if rk not in compiled_regimen:
            raise ValueError(f"compiled_regimen missing required field {rk!r}")

    track_str = compiled_regimen["selected_fda_deployment_track"]
    if not isinstance(track_str, str) or track_str not in VALID_COMPILED_TRACKS:
        raise ValueError(f"Invalid selected_fda_deployment_track {track_str!r}; must be one of {sorted(VALID_COMPILED_TRACKS)}")

    tyk2_flag = _validate_strict_bool(
        compiled_regimen["include_tyk2_p1104a_rs34536443_shield"],
        "include_tyk2_p1104a_rs34536443_shield",
    )

    loc1_str = compiled_regimen["locus1_construct_prescribed"]
    plan_str = compiled_regimen["plan_architecture_prescribed"]
    if not isinstance(loc1_str, str) or not isinstance(plan_str, str):
        raise ValueError("locus1_construct_prescribed and plan_architecture_prescribed must be strings")

    # Enforce strict consistency between Plan A/B architecture and locus1 construct (AUDIT-REF):
    is_plan_b_arch = "Plan B" in plan_str
    is_plan_b_loc1 = ("PLAN_B_SELECTIVE_HLAA_HLAB_KO" in loc1_str) or ("B_SCT" in loc1_str)
    if is_plan_b_arch != is_plan_b_loc1:
        raise ValueError(
            f"Inconsistent regimen: plan_architecture_prescribed={plan_str!r} conflicts with locus1_construct_prescribed={loc1_str!r}"
        )

    # Fail-closed product_definition defaults for Plan B (L5A-02 [DEC-077]):
    # Any Plan B regimen lacking an explicit `product_definition` fails closed on both HLA-C retention and CD47/HLA-E cloak
    # rather than receiving free survival credit, while valid `product_definition` dicts are verified below.
    prod_def_cd47_ok = not is_plan_b_arch
    prod_def_hlac_ok = not is_plan_b_arch
    prod_def_hlac_str = ""
    prod_def_leader_class = "SP-1C"
    ALLOWED_PLAN_B_HLAC_STATES = {
        "RETAINED KIR-MATCHED DONOR ALLELE(S), SEPARATELY PARAMETERIZED",
        "RETAINED_KIR_MATCHED_C1_C2_SUBBANK",
        "RETAINED_KIR_C1_C1_SUBBANK",
        "RETAINED_KIR_C2_C2_SUBBANK",
        "RETAINED_KIR_C1_C2_HETEROZYGOUS_SUBBANK",
        "RETENTION_REQUIRED_KIR_MATCHED_C1_C2",
        "RETENTION_REQUIRED_KIR_MATCHED_C1_C1",
        "RETENTION_REQUIRED_KIR_MATCHED_C2_C2",
        "RETAINED_HLA_C0304_C0401_HETEROZYGOUS_SP1C",
        "RETAINED_HLA_C0304_C0702_HETEROZYGOUS_SP1C_DOMINANT",
        "RETAINED_HLA_C0702_HOMOZYGOUS_SP3C",
    }
    ALLOWED_PLAN_B_B2M_STATES = {
        "RETAINED WT",
        "RETAINED_WT",
        "RETAINED_ENDOGENOUS_WT_FOR_HLAC_SURFACE_PRESENTATION",
        "RETAINED_ENDOGENOUS_WT",
    }
    if "product_definition" in compiled_regimen:
        prod_def_cd47_ok = True
        prod_def_hlac_ok = True
        prod_def = compiled_regimen["product_definition"]
        if not isinstance(prod_def, dict):
            raise ValueError("product_definition must be a dictionary when provided (AUDIT-REF)")
        from scripts.product_contract import validate_product_definition
        validate_product_definition(prod_def)
        expected_family = "B" if is_plan_b_arch else "A"
        if prod_def.get("family") != expected_family:
            raise ValueError("product_definition family conflicts with prescribed architecture")
        if is_plan_b_arch:
            alleles_map = prod_def.get("alleles", {})
            if "HLA-C" not in alleles_map or "B2M" not in alleles_map:
                raise ValueError("Plan B product_definition must declare retained HLA-C and B2M alleles")
            hlac_allele_val = str(alleles_map.get("HLA-C", "")).strip().upper()
            b2m_allele_val = str(alleles_map.get("B2M", "")).strip().upper()
            prod_def_hlac_str = hlac_allele_val
            is_b_sct_prod = "B_SCT" in str(prod_def.get("product_variant_id", "")).upper()
            bad_tokens = (
                "KO", "LOF", "DISRUPT", "ABSENT", "NONE", "DELETED", "NULL", "OMITTED", "FALSE",
                "SILENCED", "ABLATED", "DEFICIENT", "INACTIVATED", "FRAMESHIFT", "STOP", "MUTATED", "TRUNCATED",
                "NONFUNCTIONAL", "UNKNOWN", "UNAVAILABLE",
            )
            if is_b_sct_prod:
                if (
                    ("SINGLE-CHAIN TRIMER" not in hlac_allele_val and "SCT" not in hlac_allele_val)
                    or "EMBODIMENT A*" not in b2m_allele_val
                    or any(tok in hlac_allele_val for tok in ("ABSENT", "NONE", "OMITTED", "FALSE", "DELETED", "NULL", "NONFUNCTIONAL"))
                ):
                    prod_def_hlac_ok = False
            else:
                hlac_allowlist_ok = hlac_allele_val in ALLOWED_PLAN_B_HLAC_STATES
                b2m_allowlist_ok = b2m_allele_val in ALLOWED_PLAN_B_B2M_STATES
                if (
                    not hlac_allowlist_ok
                    or not b2m_allowlist_ok
                    or any(tok in hlac_allele_val for tok in bad_tokens)
                    or any(tok in b2m_allele_val for tok in bad_tokens)
                ):
                    prod_def_hlac_ok = False
            raw_leader_cls = str(prod_def.get("hla_c_leader_class", alleles_map.get("HLA-C_leader_class", ""))).strip().upper()
            if raw_leader_cls in {"SP-3C", "SP3C", "VMAPRALLL"} or (
                "C0702_HOMOZYGOUS" in hlac_allele_val or "C*07:02/C*07:02" in hlac_allele_val or "SP3C" in hlac_allele_val
            ):
                prod_def_leader_class = "SP-3C"
            topo_cd47 = str(prod_def.get("cassette_topology", {}).get("CD47_HLAE", "")).strip().upper()
            # Note: In `islet1_product_definitions_v0.8.0.json`, `ISLET1_B2_5LOCUS_BASE` and
            # `ISLET1_B2_5LOCUS_TYK2_PE` carry `"separate HLA-C-compatible donor design unresolved"`,
            # which represents the conditional-on-release-QC branch (`97.4963%`) whereas explicit
            # `"ABSENT"` / `"NOT_MATERIALIZED"` represents the unmaterialized Plan-B branch (`91.3735%`).
            absent_cloak_tokens = (
                "ABSENT", "NONE", "OMITTED", "FALSE", "DELETED", "NULL",
                "NOT_MATERIALIZED", "UNMATERIALIZED", "NO_SCT", "NOT_PRESENT", "UNAVAILABLE", "UNKNOWN", "KO", "UNCLOAKED",
            )
            if (not topo_cd47) or any(tok in topo_cd47 for tok in absent_cloak_tokens):
                prod_def_cd47_ok = False
    sec_cloak_str = str(compiled_regimen.get("secondary_safe_harbor_cloak", "")).strip().upper()
    if sec_cloak_str and any(
        tok in sec_cloak_str
        for tok in ("ABSENT", "NONE", "OMITTED", "FALSE", "DELETED", "NULL", "NOT_MATERIALIZED", "UNMATERIALIZED", "NO_SCT", "NOT_PRESENT", "UNAVAILABLE", "UNKNOWN", "KO", "UNCLOAKED")
    ):
        prod_def_cd47_ok = False

    panel = compiled_regimen["compiled_grna_panel"]
    if (not isinstance(panel, list)
            or any(not isinstance(guide, str) or not guide.strip() for guide in panel)
            or len(panel) != len(set(panel))):