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…

        raise ValueError("compiled_grna_panel must be a list of unique nonempty guide IDs")

    allowed_eval_patient_keys = {
        "patient_id",
        "ancestry",
        "nkg2a_neg_kir_educated_nk_fraction",
        "pre_existing_gad65_ia2_znt8_t_cell_zscore",
        "ifn1_ish_genetic_risk_percentile",
        "sirpa_genotype",
        "ifih1_rs1990760_genotype",
        "ptpn22_rs2476601_genotype",
        "recipient_hla_e_genotype",
        "recipient_bmi_kg_m2",
        "prescribed_dose_ieq",
        "tyk2_rs34536443_genotype",
        "recipient_tyk2_rs34536443_genotype",
        "donor_tyk2_rs34536443_genotype",
        "donor_ifih1_rs1990760_genotype",
        "recipient_kir_ligand_group",
        "recipient_anti_hla_c_dsa",
        "recipient_anti_hla_e_dsa",
        "recipient_cpra_pct",
        "cmv_nkg2c_adaptive_nk_fraction",
        "recipient_activating_kir2ds1_unlicensed_hazard",
        "hlac_4digit_relation",
        "b_prime_sct_exact_product_serum_cdc_adcc_crossmatch_negative",
        "b_prime_sct_recipient_cd8_mlc_negative",
        "b_prime_sct_recipient_crossmatch_and_mlc_cleared",
        "b_prime_sct_kir2ds1_non_activation_cleared",
        "exact_hlae_sct_serum_crossmatch_negative",
        "exact_product_non_hla_and_sct_flow_crossmatch_negative",
        "gate0a_nkg2c_adaptive_nk_cleared",
        "recipient_bw4_kir3dl1_educated",
        "bw4_kir3dl1_sorted_nk_lysis_cleared",
        "tyk2_independent_ifng_tnfa_or_indirect_dr3_dq8_hazard",
        "gate0_indirect_dr3_dq8_and_ifng_tnfa_stress_cleared",
        "requested_track",
        "track2_subbank_mode",
        "carries_rare_snp_in_standard_grna",
        "donor_mcb_carries_rare_snp_in_standard_grna",
        "rare_snp_pam_disrupted",
        "cd47_sirpa_binding_compromised",
        "track1_sorted_kir_nkg2a_neg_nk_lysis_cleared",
        "arm1b_cd47_sirpa_nk_cliff_unverified",
        "single_200cm2_pouch_forced_without_modular_scaling",
        "c1c2_heteroallelic_phased_longread_ddpcr_verified",
        "wetlab_stage0_complete_lot_release_verified",
        "recipient_hla_c_genotype_4digit",
        "recipient_kir_genotype",
    }
    unknown_eval_pt_keys = sorted(set(patient) - allowed_eval_patient_keys)
    if unknown_eval_patient_keys := unknown_eval_pt_keys:
        raise ValueError(f"Unrecognized patient input keys: {unknown_eval_patient_keys} (AUDIT-REF; DEC-071)")

    kir_nk = _validate_finite_float(
        patient["nkg2a_neg_kir_educated_nk_fraction"], "nkg2a_neg_kir_educated_nk_fraction", 0.0, 1.0
    )
    auto_z = _validate_finite_float(
        patient["pre_existing_gad65_ia2_znt8_t_cell_zscore"], "pre_existing_gad65_ia2_znt8_t_cell_zscore", -5.0, 10.0
    )
    ifn1_pct = _validate_finite_float(
        patient["ifn1_ish_genetic_risk_percentile"], "ifn1_ish_genetic_risk_percentile", 0.0, 100.0
    )
    recip_snp = _validate_strict_bool(
        _get_opt(patient, "carries_rare_snp_in_standard_grna", False), "carries_rare_snp_in_standard_grna"
    )
    donor_mcb_snp = _validate_strict_bool(
        _get_opt(patient, "donor_mcb_carries_rare_snp_in_standard_grna", False), "donor_mcb_carries_rare_snp_in_standard_grna"
    )
    rare_snp_pam_disrupted_eval = _validate_strict_bool(
        _get_opt(patient, "rare_snp_pam_disrupted", False), "rare_snp_pam_disrupted"
    )

    if "sirpa_genotype" in patient and not isinstance(patient["sirpa_genotype"], str):
        raise ValueError(f"Invalid sirpa_genotype: explicit value must be a string, got {patient['sirpa_genotype']!r} (AUDIT-REF)")
    for str_field in ("ifih1_rs1990760_genotype", "donor_ifih1_rs1990760_genotype", "ptpn22_rs2476601_genotype", "recipient_hla_e_genotype"):
        if str_field in patient and patient[str_field] is not None and not isinstance(patient[str_field], str):
            raise ValueError(f"Invalid {str_field}: explicit value must be a string, got {patient[str_field]!r} (AUDIT-REF)")
    ifih1_g = str(_get_opt(patient, "ifih1_rs1990760_genotype", "C/T")).strip().upper()
    if ifih1_g not in VALID_IFIH1_GENOTYPES:
        raise ValueError(f"Invalid ifih1_rs1990760_genotype {ifih1_g!r}")
    donor_ifih1_eval = str(_get_opt(patient, "donor_ifih1_rs1990760_genotype", "UNMEASURED")).strip().upper()
    if donor_ifih1_eval not in VALID_DONOR_IFIH1_GENOTYPES:
        raise ValueError(f"Invalid donor_ifih1_rs1990760_genotype {donor_ifih1_eval!r}")
    ptpn22_g = str(_get_opt(patient, "ptpn22_rs2476601_genotype", "G/G")).strip().upper()
    if ptpn22_g not in VALID_PTPN22_GENOTYPES:
        raise ValueError(f"Invalid ptpn22_rs2476601_genotype {ptpn22_g!r}")
    raw_hla_e = str(_get_opt(patient, "recipient_hla_e_genotype", "*01:03/*01:03")).strip()
    if raw_hla_e not in VALID_HLA_E_GENOTYPES:
        raise ValueError(f"Invalid recipient_hla_e_genotype {raw_hla_e!r}")
    hla_e_g = _normalize_hla_e_genotype(raw_hla_e)
    raw_sirpa = str(_get_opt(patient, "sirpa_genotype", "v1/v1")).strip().lower()
    if raw_sirpa not in VALID_SIRPA_GENOTYPES:
        raise ValueError(f"Invalid sirpa_genotype {raw_sirpa!r}")
    sirpa_g = _normalize_sirpa_genotype(raw_sirpa)
    cd47_compromised = _validate_strict_bool(
        _get_opt(patient, "cd47_sirpa_binding_compromised", False), "cd47_sirpa_binding_compromised"
    )
    bmi_val = _validate_finite_float(_get_opt(patient, "recipient_bmi_kg_m2", 24.0), "recipient_bmi_kg_m2", 10.0, 70.0)

    dosing_block = compiled_regimen.get("host_modifier_genotypes_and_dosing", {})
    if not isinstance(dosing_block, dict):
        raise ValueError("host_modifier_genotypes_and_dosing must be a dictionary")
    raw_dose_override = _get_opt(patient, "prescribed_dose_ieq", None)
    default_dose = (_validate_finite_float(raw_dose_override, "prescribed_dose_ieq", 50000.0, 2000000.0)
                    if raw_dose_override is not None else (500000.0 * (bmi_val / 24.0)))
    dose_ieq = _validate_finite_float(dosing_block.get("prescribed_curative_dose_ieq", default_dose),
                                    "prescribed_curative_dose_ieq", 50000.0, 2000000.0)

    p_surv = 0.982

    # Verify core guide panel completeness (CIITA Exon 5 [or legacy Exon 1 ID], CXCL10, AAVS1) and Plan A vs Plan B locus-1 completeness:
    has_ciita_guide = (
        "OI-GRNA-02_CIITA_EXON1_ASCAS12A" in panel
        or "OI-GRNA-02_CIITA_EXON5_ASCAS12A" in panel
        or "OI-GRNA-02_CIITA_PAN_ISOFORM_EXON5_ASCAS12A" in panel
    )
    has_core_3_loci = has_ciita_guide and all(
        g_id in panel
        for g_id in (
            "OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9",
            "OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9",
        )
    )
    if not has_core_3_loci:
        p_surv -= 0.12

    # 1. Check complete classical MHC-I editing prerequisites for Plan B (BOTH HLA-A AND HLA-B KO guides required + retained KIR-matched HLA-C/B2M) vs Plan A (B2M KO guide required):
    raw_recip_kir = str(
        _get_opt(patient, "recipient_kir_ligand_group", dosing_block.get("recipient_kir_ligand_group", "C1/C2"))
    ).strip().upper().replace("_", "/")
    if raw_recip_kir not in VALID_KIR_LIGAND_GROUPS:
        raise ValueError(f"Invalid recipient_kir_ligand_group {raw_recip_kir!r}")
    if raw_recip_kir == "C1/C1":
        raw_recip_kir = "C1/C1"
    elif raw_recip_kir == "C2/C2":
        raw_recip_kir = "C2/C2"
    else:
        raw_recip_kir = "C1/C2"
    kir_subbank_matched = True
    if is_plan_b_arch:
        c1_allele_tags = (
            "C0102", "C*01:02", "C0304", "C*03:04", "CW0302", "CW*0302", "C0702", "C*07:02",
            "C0802", "C*08:02", "C1203", "C*12:03", "C1402", "C*14:02", "C1601", "C*16:01",
        )
        c2_allele_tags = (
            "C0202", "C*02:02", "C0401", "C*04:01", "CW0402", "CW*0402", "C0402", "C*04:02", "C0501", "C*05:01",
            "C0602", "C*06:02", "C1502", "C*15:02", "C1505", "C*15:05", "C1701", "C*17:01",
        )
        explicit_group_tags = ("C1/C1", "C1_C1", "C2/C2", "C2_C2", "C1/C2", "C1_C2", "C2/C1", "C2_C1")
        if prod_def_hlac_str and any(t in prod_def_hlac_str for t in (*c1_allele_tags, *c2_allele_tags, *explicit_group_tags)):
            combined_hlac_donor_str = prod_def_hlac_str.upper()
        else:
            combined_hlac_donor_str = f"{loc1_str} {prod_def_hlac_str}".upper()
        has_c1_allele = any(t in combined_hlac_donor_str for t in c1_allele_tags)
        has_c2_allele = any(t in combined_hlac_donor_str for t in c2_allele_tags)
        has_c1_c2_het = any(tag in combined_hlac_donor_str for tag in ("C1/C2", "C1_C2", "C2/C1", "C2_C1"))
        has_c1_homo = (
            any(tag in combined_hlac_donor_str for tag in ("C1/C1", "C1_C1"))
            or (has_c1_allele and not has_c2_allele and not has_c1_c2_het)
        )
        has_c2_homo = (
            any(tag in combined_hlac_donor_str for tag in ("C2/C2", "C2_C2"))
            or (has_c2_allele and not has_c1_allele and not has_c1_c2_het)
        )
        if raw_recip_kir == "C1/C1" and has_c2_homo:
            kir_subbank_matched = False
        elif raw_recip_kir == "C2/C2" and has_c1_homo:
            kir_subbank_matched = False
        elif raw_recip_kir == "C1/C2" and (has_c1_homo or has_c2_homo):
            kir_subbank_matched = False
    pvid_str = str(compiled_regimen.get("product_variant_id", "")).upper()
    is_b_prime_sct = (
        "B_SCT" in pvid_str
        or "BPRIME_SCT" in pvid_str
        or "B_SCT" in loc1_str
    )
    if is_b_prime_sct and prod_def_hlac_str:
        has_c1_sct = ("C*03:04" in prod_def_hlac_str) and ("C*04:01" not in prod_def_hlac_str)
        has_c2_sct = ("C*04:01" in prod_def_hlac_str) and ("C*03:04" not in prod_def_hlac_str)
        if raw_recip_kir == "C1/C1" and has_c2_sct:
            kir_subbank_matched = False
        elif raw_recip_kir == "C2/C2" and has_c1_sct:
            kir_subbank_matched = False
        elif raw_recip_kir == "C1/C2" and (has_c1_sct or has_c2_sct):
            kir_subbank_matched = False
    mhc_routing_obj = compiled_regimen.get("mhc_locus_routing_contract_iip_0026")
    if mhc_routing_obj is not None:
        if not isinstance(mhc_routing_obj, dict):
            raise ValueError("mhc_locus_routing_contract_iip_0026 must be a dictionary when provided (IIP-0026; DEC-105)")
        expected_mode = (
            "B2M_NULL_CIITA_EXON5_HLA_C_SCT"
            if is_b_prime_sct
            else (
                "ENDOGENOUS_HLA_C_RETAINED_SELECTIVE_HLA_AB_KO_PENDING_PHASED_DONOR_QC"
                if is_plan_b_arch
                else "B2M_NULL_HLA_E_SCT_CD47_IGV_GPI"
            )
        )
        if mhc_routing_obj.get("class_i_routing_mode") != expected_mode:
            raise ValueError(
                f"mhc_locus_routing_contract_iip_0026 class_i_routing_mode={mhc_routing_obj.get('class_i_routing_mode')!r} "
                f"conflicts with prescribed regimen ({expected_mode!r}) (IIP-0026; DEC-105)"
            )
    has_selective_hla_ab_panel_targets = (
        any(
            g == "PLAN_B_HLAA_EXON2_KO_GUIDE_INVESTIGATIONAL" or g.startswith("SCOPED_HLAA_EXON23_CANDIDATE_")
            for g in panel
        )
        and any(
            g == "PLAN_B_HLAB_EXON2_KO_GUIDE_INVESTIGATIONAL" or g.startswith("SCOPED_HLAB_EXON23_CANDIDATE_")
            for g in panel
        )
    )
    has_plan_b_hlac = (
        is_plan_b_arch
        and prod_def_hlac_ok
        and kir_subbank_matched
        and (
            (
                is_b_prime_sct
                and "OI-GRNA-01_B2M_EXON1_ASCAS12A" in panel
                and has_ciita_guide
            )
            or (
                (not is_b_prime_sct)
                and is_plan_b_loc1
                and has_selective_hla_ab_panel_targets
                and has_ciita_guide
                and "OI-GRNA-01_B2M_EXON1_ASCAS12A" not in panel
            )
        )
    )
    if is_plan_b_arch and not has_plan_b_hlac:
        p_surv -= 0.55
    elif (not is_plan_b_arch) and ("OI-GRNA-01_B2M_EXON1_ASCAS12A" not in panel):
        p_surv -= 0.18

    has_arm1b_floor = (
        ("DONOR-1B" in loc1_str and "OI-GRNA-01_B2M_EXON1_ASCAS12A" in panel)
        or has_plan_b_hlac
    )
    arm1b_cd47_sirpa_nk_cliff_unverified_eval = _validate_strict_bool(
        _get_opt(patient, "arm1b_cd47_sirpa_nk_cliff_unverified", False),
        "arm1b_cd47_sirpa_nk_cliff_unverified",
    )
    track1_sorted_kir_nk_cleared_eval = _validate_strict_bool(
        _get_opt(patient, "track1_sorted_kir_nkg2a_neg_nk_lysis_cleared", False),
        "track1_sorted_kir_nkg2a_neg_nk_lysis_cleared",
    )