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…

    if not isinstance(raw_recip_tyk2, str):
        raise ValueError(f"Invalid tyk2_rs34536443_genotype {raw_recip_tyk2!r}")
    recipient_tyk2_genotype = raw_recip_tyk2.strip().upper()
    if recipient_tyk2_genotype not in VALID_TYK2_RS34536443_GENOTYPES:
        raise ValueError(
            f"Invalid tyk2_rs34536443_genotype {recipient_tyk2_genotype!r}; must be one of {sorted(VALID_TYK2_RS34536443_GENOTYPES)}"
        )

    raw_donor_tyk2 = _get_opt(patient, "donor_tyk2_rs34536443_genotype", "G/G")
    if not isinstance(raw_donor_tyk2, str):
        raise ValueError(f"Invalid donor_tyk2_rs34536443_genotype {raw_donor_tyk2!r}")
    donor_tyk2_genotype = raw_donor_tyk2.strip().upper()
    if donor_tyk2_genotype not in VALID_TYK2_RS34536443_GENOTYPES:
        raise ValueError(
            f"Invalid donor_tyk2_rs34536443_genotype {donor_tyk2_genotype!r}; must be one of {sorted(VALID_TYK2_RS34536443_GENOTYPES)}"
        )

    kir_ligand_group_explicitly_supplied = (
        "recipient_kir_ligand_group" in patient
        and patient.get("recipient_kir_ligand_group") is not None
    )
    raw_kir = _get_opt(patient, "recipient_kir_ligand_group", "C1/C2")
    if not isinstance(raw_kir, str):
        raise ValueError(f"Invalid recipient_kir_ligand_group {raw_kir!r}")
    kir_ligand_group = raw_kir.strip().upper().replace("_", "/")
    if kir_ligand_group not in VALID_KIR_LIGAND_GROUPS:
        raise ValueError(f"Invalid recipient_kir_ligand_group {kir_ligand_group!r}; must be one of {sorted(VALID_KIR_LIGAND_GROUPS)}")
    if kir_ligand_group == "C2/C1":
        kir_ligand_group = "C1/C2"

    recipient_bmi = _validate_finite_float(_get_opt(patient, "recipient_bmi_kg_m2", 24.0), "recipient_bmi_kg_m2", 10.0, 70.0)
    raw_dose_override = _get_opt(patient, "prescribed_dose_ieq", None)
    if raw_dose_override is not None:
        prescribed_dose_ieq = int(round(_validate_finite_float(raw_dose_override, "prescribed_dose_ieq", 50000.0, 2000000.0)))
        dose_source_mode = "EXPLICIT_PATIENT_PRESCRIBED_DOSE_IEQ_OVERRIDE"
    else:
        prescribed_dose_ieq = int(round(500000.0 * (recipient_bmi / 24.0)))
        dose_source_mode = "BMI_PROPORTIONAL_DEFAULT_500K_AT_24KG_M2"
    areal_loading_at_fixed_200cm2 = round(prescribed_dose_ieq / 200.0, 1)
    required_pouch_area_cm2_at_2500_ieq_cm2 = round(prescribed_dose_ieq / 2500.0, 2)
    required_pouch_area_cm2_at_1500_ieq_cm2 = round(prescribed_dose_ieq / 1500.0, 2)
    modular_100cm2_omental_cassette_count_at_1500_ieq_cm2 = max(1, int(math.ceil(required_pouch_area_cm2_at_1500_ieq_cm2 / 100.0)))
    actual_areal_loading_ieq_per_cm2_across_modular_cassettes = round(
        prescribed_dose_ieq / (100.0 * modular_100cm2_omental_cassette_count_at_1500_ieq_cm2), 1
    )

    raw_req_track = _get_opt(patient, "requested_track", "AUTO_RECOMMEND")
    if not isinstance(raw_req_track, str):
        raise ValueError("requested_track must be a string")
    deployment_mode = raw_req_track.strip().upper()
    if deployment_mode not in VALID_TRACK_REQUESTS:
        raise ValueError(f"Invalid requested_track {deployment_mode!r}; must be one of {sorted(VALID_TRACK_REQUESTS)}")

    # Strictly validate boolean SNP and CD47-SIRPA flags (rejecting string "false" coercion; AUDIT-REF, AUDIT-REF & AUDIT-REF):
    recipient_has_protospacer_snp = _validate_strict_bool(
        _get_opt(patient, "carries_rare_snp_in_standard_grna", False), "carries_rare_snp_in_standard_grna"
    )
    donor_mcb_has_protospacer_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_input = _validate_strict_bool(
        _get_opt(patient, "rare_snp_pam_disrupted", False), "rare_snp_pam_disrupted"
    )
    cd47_sirpa_binding_compromised_input = _validate_strict_bool(
        _get_opt(patient, "cd47_sirpa_binding_compromised", False), "cd47_sirpa_binding_compromised"
    )

    # Select Track 1 (Off-the-Shelf), Track 2 (Stratified Allogeneic HLA-C/TYK2 Sub-Line), or Track 3 (Personalized Autologous iPSC)
    # Note: Track-2 stratification threshold for IFN-I risk is 80.0 (aligned with TYK2 P1104A indication threshold; AUDIT-REF)
    if deployment_mode == "TRACK_3_AUTOLOGOUS_IPSC":
        selected_track = "TRACK_3_PERSONALIZED_AUTOLOGOUS_PATIENT_IPSC"
    elif deployment_mode == "TRACK_2_STRATIFIED_SUBLINE":
        selected_track = "TRACK_2_PATIENT_DNA_STRATIFIED_ALLOGENEIC_SUBLINE"
    elif deployment_mode == "TRACK_1_OFF_THE_SHELF":
        selected_track = "TRACK_1_UNIVERSAL_OFF_THE_SHELF_ALLOGENEIC"
    elif (
        kir_licensed_nkg2a_neg_fraction >= 0.42
        or autoantigen_t_cell_titer >= 2.0
        or ifn1_genetic_risk_score >= 80.0
        or ifih1_genotype == "T/T"
        or ptpn22_genotype in {"A/G", "G/A", "A/A"}
    ):
        selected_track = "TRACK_2_PATIENT_DNA_STRATIFIED_ALLOGENEIC_SUBLINE"
    else:
        selected_track = "TRACK_1_UNIVERSAL_OFF_THE_SHELF_ALLOGENEIC"

    # Plan B (Design B) is unified with the canonical Blueprint's Selective HLA-A/HLA-B KO + Retained HLA-C*07:02 (C1) / HLA-C*04:01 (C2)
    # sub-bank architecture for recipients with extreme KIR-educated NKG2A- NK fractions (>= 0.48), avoiding unbudgeted 5th-locus FGL1 (AUDIT-REF & AUDIT-REF):
    plan_b_biologically_indicated = bool(kir_licensed_nkg2a_neg_fraction >= 0.48)
    use_plan_b_hla_c_retained = bool(
        selected_track == "TRACK_2_PATIENT_DNA_STRATIFIED_ALLOGENEIC_SUBLINE"
        and plan_b_biologically_indicated
    )
    clinical_override_warnings: List[str] = []
    track1_sorted_kir_nk_cleared = _validate_strict_bool(
        _get_opt(patient, "track1_sorted_kir_nkg2a_neg_nk_lysis_cleared", False),
        "track1_sorted_kir_nkg2a_neg_nk_lysis_cleared",
    )
    arm1b_cd47_sirpa_nk_cliff_unverified = _validate_strict_bool(
        _get_opt(patient, "arm1b_cd47_sirpa_nk_cliff_unverified", False),
        "arm1b_cd47_sirpa_nk_cliff_unverified",
    )
    single_200cm2_pouch_forced_without_modular_scaling = _validate_strict_bool(
        _get_opt(patient, "single_200cm2_pouch_forced_without_modular_scaling", False),
        "single_200cm2_pouch_forced_without_modular_scaling",
    )
    tyk2_independent_ifng_tnfa_or_indirect_dr3_dq8_hazard = _validate_strict_bool(
        _get_opt(patient, "tyk2_independent_ifng_tnfa_or_indirect_dr3_dq8_hazard", False),
        "tyk2_independent_ifng_tnfa_or_indirect_dr3_dq8_hazard",
    )
    gate0_indirect_dr3_dq8_and_ifng_tnfa_stress_cleared = _validate_strict_bool(
        _get_opt(patient, "gate0_indirect_dr3_dq8_and_ifng_tnfa_stress_cleared", False),
        "gate0_indirect_dr3_dq8_and_ifng_tnfa_stress_cleared",
    )
    recipient_bw4_kir3dl1_educated = _validate_strict_bool(
        _get_opt(patient, "recipient_bw4_kir3dl1_educated", False),
        "recipient_bw4_kir3dl1_educated",
    )
    bw4_kir3dl1_nk_lysis_cleared = _validate_strict_bool(
        _get_opt(patient, "bw4_kir3dl1_sorted_nk_lysis_cleared", False),
        "bw4_kir3dl1_sorted_nk_lysis_cleared",
    )
    c1c2_phasing_explicitly_supplied = (
        "c1c2_heteroallelic_phased_longread_ddpcr_verified" in patient
        and patient.get("c1c2_heteroallelic_phased_longread_ddpcr_verified") is not None
    )
    c1c2_heteroallelic_phased_verified = _validate_strict_bool(
        _get_opt(patient, "c1c2_heteroallelic_phased_longread_ddpcr_verified", False),
        "c1c2_heteroallelic_phased_longread_ddpcr_verified",
    )
    if plan_b_biologically_indicated and not use_plan_b_hla_c_retained:
        clinical_override_warnings.append(
            f"WARNING_FORCED_TRACK_OVERRIDES_HIGH_KIR_NK_PLAN_B_INDICATION: nkg2a_neg_kir_educated_nk_fraction={kir_licensed_nkg2a_neg_fraction:.3f} >= 0.48 "
            f"indicates Plan B (HLA-C-retained sub-bank), but requested_track={deployment_mode} forced {selected_track} Plan A."
        )

    # Resolve starting TYK2 rs34536443 genotype on the actual genome being edited (autologous recipient iPSC in Track 3 vs allogeneic donor MCB in Track 1/2):
    starting_graft_tyk2_genotype = (
        recipient_tyk2_genotype
        if selected_track == "TRACK_3_PERSONALIZED_AUTOLOGOUS_PATIENT_IPSC"
        else donor_tyk2_genotype
    )
    if starting_graft_tyk2_genotype == "C/C":
        tyk2_alleles_to_edit = 0
    elif starting_graft_tyk2_genotype in {"G/C", "C/G"}:
        tyk2_alleles_to_edit = 1
    else:
        tyk2_alleles_to_edit = 2
    already_homozygous_tyk2_p1104a = (starting_graft_tyk2_genotype == "C/C")

    tyk2_biologically_indicated = bool(
        ifn1_genetic_risk_score >= 80.0
        or autoantigen_t_cell_titer >= 2.0
        or ifih1_genotype == "T/T"
        or ptpn22_genotype == "A/A"
    )
    # Prime editing guide OI-GRNA-05 is prescribed when TYK2 protection is indicated AND the starting graft genome is not already C/C:
    include_tyk2_p1104a_edit = bool(tyk2_biologically_indicated and not already_homozygous_tyk2_p1104a)
    if deployment_mode == "TRACK_1_OFF_THE_SHELF" and include_tyk2_p1104a_edit:
        clinical_override_warnings.append(
            "WARNING_FORCED_TRACK1_WITH_TYK2_INDICATION: Track 1 off-the-shelf MCB requires selecting the pre-banked TYK2-P1104A sub-stock or routing to Track 2."
        )
    final_graft_tyk2_p1104a_protective_state = bool(already_homozygous_tyk2_p1104a or include_tyk2_p1104a_edit)

    has_anti_hlac_dsa_input = _validate_strict_bool(
        _get_opt(patient, "recipient_anti_hla_c_dsa", False), "recipient_anti_hla_c_dsa"
    )
    raw_hlac_rel = _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",
    )
    if not isinstance(raw_hlac_rel, str) or not raw_hlac_rel.strip():
        raise ValueError(f"Invalid hlac_4digit_relation {raw_hlac_rel!r}: must be a non-empty string (AUDIT-REF)")
    hlac_4digit_rel_input = raw_hlac_rel.strip().upper()
    if hlac_4digit_rel_input not in _VALID_HLAC_4DIGIT_RELATIONS:
        raise ValueError(
            f"Invalid hlac_4digit_relation {hlac_4digit_rel_input!r}; must be one of {sorted(_VALID_HLAC_4DIGIT_RELATIONS)} (AUDIT-REF)"
        )
    track2_subbank_mode_eff = str(
        track2_subbank_mode if track2_subbank_mode is not None else _get_opt(patient, "track2_subbank_mode", "AUTO")
    ).strip().upper()
    if track2_subbank_mode_eff == "B_ENDORETAINED_HLAC":
        track2_subbank_mode_eff = "ENDOGENOUS_HLAC_EXPLORATORY"
    if track2_subbank_mode_eff not in {"AUTO", "B_PRIME_SCT", "ENDOGENOUS_HLAC_EXPLORATORY"}:
        raise ValueError(
            f"Invalid track2_subbank_mode {track2_subbank_mode_eff!r}; must be one of "
            "['AUTO', 'B_PRIME_SCT', 'ENDOGENOUS_HLAC_EXPLORATORY', 'B_ENDORETAINED_HLAC'] (AUDIT-REF)"
        )
    sct_crossmatch_cleared_input = _validate_strict_bool(
        _get_opt(patient, "b_prime_sct_recipient_crossmatch_and_mlc_cleared", False),
        "b_prime_sct_recipient_crossmatch_and_mlc_cleared",
    )
    sct_serum_crossmatch_neg_input = _validate_strict_bool(
        _get_opt(patient, "b_prime_sct_exact_product_serum_cdc_adcc_crossmatch_negative", False),
        "b_prime_sct_exact_product_serum_cdc_adcc_crossmatch_negative",
    )
    sct_cd8_mlc_neg_input = _validate_strict_bool(
        _get_opt(patient, "b_prime_sct_recipient_cd8_mlc_negative", False),
        "b_prime_sct_recipient_cd8_mlc_negative",
    )
    has_activating_kir2ds1_hazard_input = _validate_strict_bool(
        _get_opt(patient, "recipient_activating_kir2ds1_unlicensed_hazard", False),
        "recipient_activating_kir2ds1_unlicensed_hazard",
    )
    kir2ds1_cleared_input = _validate_strict_bool(
        _get_opt(patient, "b_prime_sct_kir2ds1_non_activation_cleared", False),
        "b_prime_sct_kir2ds1_non_activation_cleared",
    )
    has_anti_hlae_dsa_input = _validate_strict_bool(
        _get_opt(patient, "recipient_anti_hla_e_dsa", False),
        "recipient_anti_hla_e_dsa",
    )
    exact_hlae_sct_serum_crossmatch_neg_input = _validate_strict_bool(
        _get_opt(patient, "exact_hlae_sct_serum_crossmatch_negative", False),
        "exact_hlae_sct_serum_crossmatch_negative",
    )
    exact_product_non_hla_and_sct_flow_crossmatch_neg_input = _validate_strict_bool(
        _get_opt(patient, "exact_product_non_hla_and_sct_flow_crossmatch_negative", False),
        "exact_product_non_hla_and_sct_flow_crossmatch_negative",
    )
    gate0a_nkg2c_adaptive_nk_cleared_input = _validate_strict_bool(
        _get_opt(patient, "gate0a_nkg2c_adaptive_nk_cleared", False),
        "gate0a_nkg2c_adaptive_nk_cleared",
    )
    recipient_cpra_pct_input = _validate_finite_float(
        _get_opt(patient, "recipient_cpra_pct", 0.0), "recipient_cpra_pct", 0.0, 100.0
    )
    cmv_nkg2c_adaptive_nk_fraction_input = _validate_finite_float(
        _get_opt(patient, "cmv_nkg2c_adaptive_nk_fraction", 0.0), "cmv_nkg2c_adaptive_nk_fraction", 0.0, 1.0
    )
    use_b_prime_sct_k4 = bool(
        use_plan_b_hla_c_retained and track2_subbank_mode_eff == "B_PRIME_SCT"
    )
    sct_cd8_mlc_explicit_false_input = (
        "b_prime_sct_recipient_cd8_mlc_negative" in patient
        and patient.get("b_prime_sct_recipient_cd8_mlc_negative") is False
    )
    sct_serum_xm_explicit_false_input = (
        "b_prime_sct_exact_product_serum_cdc_adcc_crossmatch_negative" in patient
        and patient.get("b_prime_sct_exact_product_serum_cdc_adcc_crossmatch_negative") is False
    )
    anti_hlac_dsa_cleared_input = bool(
        use_b_prime_sct_k4 and sct_serum_crossmatch_neg_input and not sct_serum_xm_explicit_false_input
    )
    cd8_mlc_cleared_input = bool(
        use_b_prime_sct_k4
        and not sct_cd8_mlc_explicit_false_input
        and not sct_serum_xm_explicit_false_input
        and (sct_cd8_mlc_neg_input or sct_crossmatch_cleared_input)