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…

                f"mismatches at {g01_1c_trap_l['mismatch_positions_1based']}, {g01_1c_trap_l['seed_region_mismatches']}/18 seed mismatches, WT Cas12a positional heuristic={g01_1c_trap_l['uncalibrated_positional_mismatch_score']:.6f}, "
                f"Ultra attenuated={g01_1c_trap_l['nuclease_attenuated_positional_heuristic']:.6f}) and {g01_astar_term_l['total_mismatches_vs_wt_spacer']}/23 ({g01_astar_term_l['candidate_pam_5to3']}+{g01_astar_term_l['candidate_protospacer_5to3']}, "
                f"mismatches at {g01_astar_term_l['mismatch_positions_1based']}, {g01_astar_term_l['seed_region_mismatches']}/18 seed mismatches, WT Cas12a positional heuristic={g01_astar_term_l['uncalibrated_positional_mismatch_score']:.6f}, "
                f"Ultra attenuated={g01_astar_term_l['nuclease_attenuated_positional_heuristic']:.6f}; or 0.0 with S3 TCTC PAM+seed shield) mismatches respectively, and 100% identical 3' right junctions (TAGC PAM abolished, heuristic=0.0)."
            ),
        },
    }

    return {
        "multiplex_editing_schedule": (
            "Two-Pass Orthogonal RNP Schedule (Zero Simultaneous 4-Locus DSBs): "
            "Pass 1 uses AsCas12a Ultra (B2M Exon 1 + CIITA Exon 5 Pan-Isoform) followed by single-cell cloning, "
            ">=63,000x TP53 duplex-seq (>=62,958 independent duplex molecules), 20q11.21 BCL2L1 ddPCR, and CAST-seq; "
            "Pass 2 uses HiFi-SpCas9 R691A (CXCL10 Exon 1 + AAVS1 Intron 1) followed by final MCB release QC."
        ),
        "guides": grna_specs,
        "post_hdr_junction_cfd_and_split_protospacer_audit_claude_v80_004": post_hdr_junction_cfd_audit,
        "off_target_scoring_methodology_reconciliation_claude_v80_006": off_target_reconciliation_table,
        "gnomad_v4_1_and_dbsnp_guide_overlap_audit_claude_v80_045": gnomad_v4_1_and_dbsnp_guide_overlap_audit,
        "live_ncbi_dbsnp_polymorphism_audit": dbsnp_summary,
        "live_ncbi_clinvar_tyk2_rs34536443_record": clinvar_summary,
    }


def _validate_finite_float(val: Any, name: str, low: float, high: float) -> float:
    if isinstance(val, (bool, np.bool_)) or not isinstance(val, (int, float, np.integer, np.floating)):
        raise ValueError(f"{name} must be a finite numeric value in [{low}, {high}], got {val!r}")
    fval = float(val)
    if not math.isfinite(fval) or fval < low or fval > high:
        raise ValueError(f"{name} must be finite and within [{low}, {high}], got {fval}")
    return fval


def _validate_strict_bool(val: Any, name: str) -> bool:
    if not isinstance(val, bool):
        raise ValueError(f"{name} must be a strict boolean (True or False), got {val!r}")
    return val


def _normalize_hla_e_genotype(raw_val: str) -> str:
    s = raw_val.strip().upper().replace("HLA-E*", "*").replace("HLA-E", "")
    parts = [p.strip() for p in s.split("/")]
    if len(parts) == 2:
        norm_parts = [(p if p.startswith("*") else f"*{p}") for p in parts]
        return f"{norm_parts[0]}/{norm_parts[1]}"
    return raw_val.strip()


def _normalize_sirpa_genotype(raw_val: str) -> str:
    s = raw_val.strip().lower()
    parts = sorted(p.strip() for p in s.split("/"))
    if len(parts) == 2:
        return f"{parts[0]}/{parts[1]}"
    return s


def _get_opt(patient: Dict[str, Any], key: str, default: Any) -> Any:
    val = patient.get(key, default)
    return default if val is None else val


def compile_personalized_patient_blueprint(
    patient: Dict[str, Any],
    *,
    engineering_parameters: Dict[str, Any] | None = None,
    track2_subbank_mode: str | None = None,
) -> Dict[str, Any]:
    """
    Deterministic Personalized Patient-DNA & Autoantigen Compiler (closes AUDIT-REF, AUDIT-REF,
    AUDIT-REF, and AUDIT-REF):
    Validates all patient genotype/biomarker inputs (strictly rejecting non-string patient_id and non-boolean flags),
    treats present-None optional keys consistently as missing/defaulted (`DEFAULT_IMPUTED_NOT_MEASURED`),
    separates recipient vs donor TYK2 rs34536443 genotypes (`0/1/2` alleles requiring prime edit vs natural `C/C`
    protective state), emits explicit warnings when forced tracks override Plan B indications, and tracks
    `(K, B)` chromosomal edit counts alongside an assigned utility discount and unmeasured physical yield.
    """
    if not isinstance(patient, dict):
        raise ValueError("patient input must be a dictionary")

    required_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",
    )
    allowed_patient_keys = {
        *required_keys,
        "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_pt_keys = sorted(set(patient) - allowed_patient_keys)
    if unknown_pt_keys:
        raise ValueError(f"Unrecognized patient input keys: {unknown_pt_keys} (AUDIT-REF; DEC-071)")
    for k in required_keys:
        if k not in patient or patient[k] is None:
            raise ValueError(f"Missing required patient field: {k}")

    if not isinstance(patient["patient_id"], str):
        raise ValueError(f"patient_id must be a string, got {patient['patient_id']!r}")
    patient_id = patient["patient_id"].strip()
    if not patient_id:
        raise ValueError("patient_id must be a non-empty string")

    if not isinstance(patient["ancestry"], str):
        raise ValueError(f"ancestry must be a string, got {patient['ancestry']!r}")
    ancestry = patient["ancestry"].strip().upper()
    if ancestry not in VALID_ANCESTRIES:
        raise ValueError(f"Invalid ancestry {ancestry!r}; must be one of {sorted(VALID_ANCESTRIES)}")

    if not isinstance(patient["sirpa_genotype"], str):
        raise ValueError(f"sirpa_genotype must be a string, got {patient['sirpa_genotype']!r}")
    sirpa_genotype = patient["sirpa_genotype"].strip().lower()
    if sirpa_genotype not in VALID_SIRPA_GENOTYPES:
        raise ValueError(f"Invalid sirpa_genotype {sirpa_genotype!r}; must be one of {sorted(VALID_SIRPA_GENOTYPES)}")

    kir_licensed_nkg2a_neg_fraction = _validate_finite_float(
        patient["nkg2a_neg_kir_educated_nk_fraction"], "nkg2a_neg_kir_educated_nk_fraction", 0.0, 1.0
    )
    autoantigen_t_cell_titer = _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_genetic_risk_score = _validate_finite_float(
        patient["ifn1_ish_genetic_risk_percentile"], "ifn1_ish_genetic_risk_percentile", 0.0, 100.0
    )

    # Track explicit missingness vs measured status for optional host modifier fields (closing AUDIT-REF, AUDIT-REF, & AUDIT-REF):
    optional_field_provenance = {
        k: ("MEASURED_PATIENT_INPUT" if k in patient and patient[k] is not None else "DEFAULT_IMPUTED_NOT_MEASURED")
        for k in (
            "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",
        )
    }
    recipient_immunological_screen_complete = all(
        k in patient and patient[k] is not None
        for k in (
            "recipient_anti_hla_c_dsa",
            "recipient_anti_hla_e_dsa",
            "recipient_cpra_pct",
            "cmv_nkg2c_adaptive_nk_fraction",
        )
    )
    recipient_immunological_screen_completeness_status = (
        "COMPLETE_EXPLICIT_RECIPIENT_IMMUNOLOGICAL_SCREEN"
        if recipient_immunological_screen_complete
        else "INCOMPLETE_UNMEASURED_IMMUNOLOGICAL_HAZARD_INPUTS_DEFAULTED_FOR_SCENARIO_SCORING_ONLY"
    )

    # Validate optional host modifier genotypes & BMI (handling present-None consistently as default; AUDIT-REF):
    raw_ifih1 = _get_opt(patient, "ifih1_rs1990760_genotype", "C/T")
    if not isinstance(raw_ifih1, str):
        raise ValueError(f"Invalid ifih1_rs1990760_genotype {raw_ifih1!r}")
    ifih1_genotype = raw_ifih1.strip().upper()
    if ifih1_genotype not in VALID_IFIH1_GENOTYPES:
        raise ValueError(f"Invalid ifih1_rs1990760_genotype {ifih1_genotype!r}; must be one of {sorted(VALID_IFIH1_GENOTYPES)}")

    raw_donor_ifih1 = _get_opt(patient, "donor_ifih1_rs1990760_genotype", "UNMEASURED")
    if not isinstance(raw_donor_ifih1, str):
        raise ValueError(f"Invalid donor_ifih1_rs1990760_genotype {raw_donor_ifih1!r}")
    donor_ifih1_genotype = raw_donor_ifih1.strip().upper()
    if donor_ifih1_genotype not in VALID_DONOR_IFIH1_GENOTYPES:
        raise ValueError(
            f"Invalid donor_ifih1_rs1990760_genotype {donor_ifih1_genotype!r}; must be one of {sorted(VALID_DONOR_IFIH1_GENOTYPES)}"
        )
    if donor_ifih1_genotype == "T/C":
        donor_ifih1_genotype = "C/T"

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

    raw_hla_e = _get_opt(patient, "recipient_hla_e_genotype", "*01:03/*01:03")
    if not isinstance(raw_hla_e, str) or raw_hla_e.strip() not in VALID_HLA_E_GENOTYPES:
        raise ValueError(f"Invalid recipient_hla_e_genotype {raw_hla_e!r}; must be one of {sorted(VALID_HLA_E_GENOTYPES)}")
    recipient_hla_e = _normalize_hla_e_genotype(raw_hla_e)

    # Validate recipient and donor TYK2 rs34536443 genotypes separately (closing AUDIT-REF & AUDIT-REF):
    raw_recip_tyk2 = _get_opt(
        patient,
        "recipient_tyk2_rs34536443_genotype",
        _get_opt(patient, "tyk2_rs34536443_genotype", "G/G"),
    )