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…

                        "total_count": an if valid_counts else None,
                        "raw_ac_over_an": round(f_val, 6) if f_val is not None else None,
                        "folded_minor_allele_frequency": round(min(f_val, 1.0 - f_val), 6) if f_val is not None else None,
                        "allele_identity_in_raw_cache": "UNTYPED_AC_OVER_AN_REQUIRES_SPDI_RESOLUTION" if valid_counts else "INVALID_AC_AN_OBSERVATION_REJECTED",
                    })
        dbsnp_summary[key] = {
            "rsid": rec.get("refsnp_id", rec.get("rsid", key.split("_")[0])),
            "variant_type": rec.get("variant_type", "snv"),
            "genes": rec.get("genes", []),
            "clinical_significance": rec.get("clinical_significances", rec.get("clinical_significance", [])),
            "grch38_placements": rec.get("placements", [])[:2],
            "minor_allele_frequencies": raw_obs,
            "minor_allele_frequencies_schema_note": (
                "Raw cached study rows record untyped allele_count/total_count (where AC/AN > 0.5 reflects the major/reference allele in that study); "
                "see untyped_study_allele_count_observations and derived_folded_minor_allele_frequency_summary (AUDIT-REF)."
            ),
            "untyped_study_allele_count_observations": raw_obs,
            "derived_folded_minor_allele_frequency_summary": folded_summary,
        }

    clinvar_summary = raw_l5.get("clinvar_records", {}).get("rs34536443_TYK2_P1104A", {})

    # Source-verified 5-guide UCSC dbSnp155 identities plus explicitly assumed AF screening priors
    # derived directly from cached primary UCSC dbSnp155 API responses (closing AUDIT-REF & AUDIT-REF):
    ucsc_primary = raw_l5.get("ucsc_dbsnp155_primary_interval_responses", {})
    _check(len(ucsc_primary) == 5, f"Expected 5 primary UCSC dbSnp155 interval records in raw reference, got {len(ucsc_primary)}")
    af_provenance_str = "ASSUMED_NOT_DATABASE_MEASUREMENT_NO_GNOMAD_AC_AN_RECEIPTS"

    def _build_guide_dbsnp_entry(
        guide_id: str,
        grch38_interval: str,
        selected_variant_examples: List[str],
        extra_fields: Dict[str, Any],
    ) -> Dict[str, Any]:
        u_rec = ucsc_primary[guide_id]
        items = u_rec["items"]
        rsids = [it["rsid"] for it in items]
        _check(len(rsids) == u_rec["count"] and rsids == u_rec["rsids"], f"UCSC dbSnp155 count/rsid mismatch for {guide_id}")
        entry: Dict[str, Any] = {
            "grch38_interval": grch38_interval,
            "ucsc_dbsnp155_0based_half_open_query": u_rec["query_url"],
            "ucsc_dbsnp155_data_time_stamp": u_rec["data_time_stamp"],
            "dbsnp_b155_overlapping_variants": len(rsids),
            "enumerated_ucsc_dbsnp155_rsids": rsids,
            "ucsc_dbsnp155_variant_rows": [
                {
                    "rsid": it["rsid"],
                    "chrom": it["chrom"],
                    "chromStart": it["chromStart"],
                    "chromEnd": it["chromEnd"],
                    "ref": it["ref"],
                    "alts": it["alts"],
                    "func": it["func"],
                    "varType": it["varType"],
                }
                for it in items
            ],
            "selected_variant_examples_not_frequency_ranked": selected_variant_examples,
            "variant_example_selection_scope": "Selected illustrative sentinel examples; no frequency ranking is claimed.",
            "gnomad_af_provenance": af_provenance_str,
        }
        assumed = {k.removeprefix("gnomad_v4_1_"): v for k, v in extra_fields.items() if k.startswith("gnomad_v4_1_")}
        entry["assumed_screening_frequency_priors"] = {
            "source_class": "ASSUMED_NOT_DATABASE_MEASUREMENT", "values": assumed,
            "qualification": "Screening assumptions, not an observed database maximum or validated upper bound.",
        }
        entry.update({k: None for k in extra_fields})
        entry["measurement_alias_status"] = "NULL_UNTIL_VARIANT_POPULATION_AC_AN_RECEIPTS"
        return entry

    per_guide_dbsnp_summary = {
        "OI-GRNA-01_B2M_EXON1_ASCAS12A": _build_guide_dbsnp_entry(
            "OI-GRNA-01_B2M_EXON1_ASCAS12A",
            "chr15:44711590-44711616 (+)",
            ["rs572886094", "rs1435611656", "rs757230673"],
            {
                "gnomad_v4_1_global_af_max": 0.00004,
                "gnomad_v4_1_max_subpopulation_af": 0.00018,
                "common_polymorphism_af_gt_0_001_present": False,
            },
        ),
        "OI-GRNA-02_CIITA_EXON1_ASCAS12A": {
            "canonical_exon5_guide_id": "OI-GRNA-02_CIITA_EXON5_ASCAS12A",
            **_build_guide_dbsnp_entry(
                "OI-GRNA-02_CIITA_EXON1_ASCAS12A",
                "chr16:10898963-10898989 (-)",
                ["rs142469968", "rs1398227497", "rs757017931"],
                {
                    "gnomad_v4_1_global_af_max": 0.00003,
                    "gnomad_v4_1_max_subpopulation_af": 0.00024,
                    "common_polymorphism_af_gt_0_001_present": False,
                },
            ),
        },
        "OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9": _build_guide_dbsnp_entry(
            "OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9",
            "chr4:76023451-76023473 (-)",
            ["rs554892214", "rs377480085", "rs767339215"],
            {
                "gnomad_v4_1_global_af_max": 0.00005,
                "gnomad_v4_1_max_subpopulation_af": 0.00031,
                "common_polymorphism_af_gt_0_001_present": False,
            },
        ),
        "OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9": _build_guide_dbsnp_entry(
            "OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9",
            "chr19:55115754-55115776 (-)",
            ["rs946359931", "rs1037294362", "rs920266081"],
            {
                "gnomad_v4_1_global_af_max": 0.00006,
                "gnomad_v4_1_max_subpopulation_af": 0.00042,
                "common_polymorphism_af_gt_0_001_present": False,
            },
        ),
        "OI-GRNA-05_TYK2_P1104A_PEMAX_EPEGRNA_OPTIONAL": _build_guide_dbsnp_entry(
            "OI-GRNA-05_TYK2_P1104A_PEMAX_EPEGRNA_OPTIONAL",
            "chr19:10352421-10352443 (+)",
            ["rs34536443 (intended edit site chr19:10352442G>C)", "rs751482411", "rs373614901"],
            {
                "gnomad_v4_1_rs34536443_global_af": 0.0270,
                "gnomad_v4_1_rs34536443_nfe_eur_af": 0.0422,
                "gnomad_v4_1_rs34536443_fin_af": 0.0528,
                "gnomad_v4_1_max_non_rs34536443_variant_af": 0.00005,
                "common_polymorphism_other_than_intended_rs34536443_present": False,
            },
        ),
    }
    total_dbsnp_b155_variants = sum(v["dbsnp_b155_overlapping_variants"] for v in per_guide_dbsnp_summary.values())
    _check(total_dbsnp_b155_variants == 56, f"Expected 8+13+9+9+17=56 UCSC dbSnp155 variants, got {total_dbsnp_b155_variants}")
    gnomad_v4_1_and_dbsnp_guide_overlap_audit = {
        "audit_methodology_and_reconciliation_note": (
            "Each guide's exact 0-based half-open genomic target interval (protospacer + PAM) was queried against the primary "
            "UCSC hg38 dbSnp155 REST API track (yielding 8, 13, 9, 9, and 17 overlapping variants respectively; sum = 56) and "
            "stored verbatim in data/raw/layer5_dbsnp_clinvar_reference.json under ucsc_dbsnp155_primary_interval_responses. "
            "Whereas live_ncbi_dbsnp_polymorphism_audit tracks the 4 sentinel T1D/HLA functional polymorphisms, "
            "this interval-wide audit enumerates all 56 primary UCSC dbSnp155 short variants (exact rsIDs, 0-based coordinates, "
            "and ref/alt alleles). Frequency screening assumptions are separated from source-verified identities. "
            "No gnomAD measurement or observed frequency maximum is claimed without a variant/population AC/AN receipt."
        ),
        "gnomad_af_provenance": af_provenance_str,
        "total_overlapping_dbsnp_b155_variants_across_5_guides": total_dbsnp_b155_variants,
        "per_guide_ucsc_dbsnp155_counts_vector": [v["dbsnp_b155_overlapping_variants"] for v in per_guide_dbsnp_summary.values()],
        "guides_with_any_non_target_variant_global_af_gt_0_0001": None,
        "frequency_measurement_status": "NOT_ENUMERATED_FROM_GNOMAD_AC_AN_ROWS",
        "per_guide_interval_polymorphism_summary": per_guide_dbsnp_summary,
    }

    g03_r = post_hdr_junction_cfd_audit["OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9"][
        "ISLET1_LOCUS3_CXCL10_SERPINB9_GSGP2A_PDL1_NO_FURIN_4090bp"
    ]["three_prime_insert_ha_right_junction"]
    g03_l = post_hdr_junction_cfd_audit["OI-GRNA-03_CXCL10_EXON1_HIFI_SPCAS9"][
        "ISLET1_LOCUS3_CXCL10_SERPINB9_GSGP2A_PDL1_NO_FURIN_4090bp"
    ]["five_prime_ha_left_insert_junction"]
    g04_r = post_hdr_junction_cfd_audit["OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9"][
        "ISLET1_LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_EEF1A1_ICASP9_3457bp"
    ]["three_prime_insert_ha_right_junction"]
    g04_l = post_hdr_junction_cfd_audit["OI-GRNA-04_AAVS1_PPP1R12C_HIFI_SPCAS9"][
        "ISLET1_LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_EEF1A1_ICASP9_3457bp"
    ]["five_prime_ha_left_insert_junction"]
    g01_1a_l = post_hdr_junction_cfd_audit["OI-GRNA-01_B2M_EXON1_ASCAS12A"][
        "ISLET1_LOCUS1_ARM1A_B2M_HLAE_SCT_GSGP2A_CD47_IGV_GPI_4880bp"
    ]["five_prime_ha_left_insert_junction"]
    g01_1b_l = post_hdr_junction_cfd_audit["OI-GRNA-01_B2M_EXON1_ASCAS12A"][
        "ISLET1_LOCUS1_ARM1B_B2M_BIDIR_2AFREE_CD47_IGV_GPI_HLAE_SCT_3974bp"
    ]["five_prime_ha_left_insert_junction"]
    _g01_proto = "TGGCCTGGAGGCTATCCAGCGTG"
    _g01_pam = "TTTC"
    _g01_nuc = "AsCas12a Ultra (Acidaminococcus sp. BV3L6 M537R/F870L)"
    _g01_r_seq = "TAGCAGGCATGCTGGGGATCCAGCGTG"
    g01_s3_l = compute_split_junction_residual_cleavage_metrics(
        _g01_proto, _g01_pam, _g01_nuc, "TCTCTGGACTCGAAGCTATGCTCCGGT", _g01_r_seq
    )["five_prime_ha_left_insert_junction"]
    g01_1c_trap_l = compute_split_junction_residual_cleavage_metrics(
        _g01_proto, _g01_pam, _g01_nuc, "TTTCTGGCCTGGAGGCTATGTAAGTAT", _g01_r_seq
    )["five_prime_ha_left_insert_junction"]
    g01_astar_term_l = compute_split_junction_residual_cleavage_metrics(
        _g01_proto, _g01_pam, _g01_nuc, "TTTCTGGCCTGGAGGCTATAATAAAAG", _g01_r_seq
    )["five_prime_ha_left_insert_junction"]
    _check(
        g03_r["uncalibrated_positional_mismatch_score"] == 0.247822
        and g03_r["total_mismatches_vs_wt_spacer"] == 6
        and g03_r["seed_region_mismatches"] == 0
        and g03_r["mismatch_positions_1based"] == [1, 2, 3, 4, 5, 6]
        and g04_r["uncalibrated_positional_mismatch_score"] == 0.143472
        and g04_r["total_mismatches_vs_wt_spacer"] == 6
        and g04_r["seed_region_mismatches"] == 0
        and g04_r["mismatch_positions_1based"] == [2, 3, 4, 6, 7, 8]
        and g01_1a_l["total_mismatches_vs_wt_spacer"] == 5
        and g01_1a_l["seed_region_mismatches"] == 2
        and g01_1a_l["uncalibrated_positional_mismatch_score"] == 0.173249
        and g01_1b_l["total_mismatches_vs_wt_spacer"] == 7
        and g01_1b_l["seed_region_mismatches"] == 2
        and g01_1b_l["uncalibrated_positional_mismatch_score"] == 0.157781,
        f"Unexpected junction metrics: g03_r={g03_r}, g04_r={g04_r}, g01_1a_l={g01_1a_l}, g01_1b_l={g01_1b_l}",
    )

    post_hdr_junction_cfd_audit["gate_zero_donor_wgs_and_precloning_junction_recleavage_gate_muse_r1"] = {
        "gate_zero_donor_hpsc_30x_wgs_screening_rule": (
            "Gate 0 mandatory 30x short-read WGS + long-read HLA/KIR haplotyping across all 5 target intervals "
            "(B2M, CIITA, CXCL10, AAVS1, TYK2) plus +/-1,000 bp HDR homology arms on the specific clinical hPSC MCB "
            "prior to GMP guide synthesis; allele-matched spacer or homology-arm substitution if any donor MCB variant "
            "overlaps the 20-23 nt spacer, PAM, or inner 100 bp junction window (closing AUDIT-REF)."
        ),
        "pre_cloning_cxcl10_right_junction_recleavage_gate": (
            f"Pre-cloning in vitro RNP cleavage + rhAmpSeq/ddPCR junction-stability assay on reconstructed CXCL10 "
            f"Locus 3 right-junction amplicons (candidate_protospacer_5to3 = {g03_r['candidate_protospacer_5to3']} + {g03_r['candidate_pam_5to3']}, where the 14-bp "
            f"PAM-proximal spacer TGAGCCTACAGCAG + AGG PAM are retained intact [{g03_r['seed_region_mismatches']}/12 seed mismatches, "
            f"{g03_r['total_mismatches_vs_wt_spacer']}/20 5'-distal mismatches at positions {g03_r['mismatch_positions_1based']} ATATTC->GGGGAT from bGH_polyA, "
            f"unattenuated WT-SpCas9 positional-retention heuristic = {g03_r['uncalibrated_positional_mismatch_score']:.6f}, HiFi positional "
            f"heuristic = {g03_r['nuclease_attenuated_positional_heuristic']:.8f}; vs Audit hand-estimate 0.0020]) and AAVS1 Locus 4 right-junction amplicons "
            f"({g04_r['candidate_protospacer_5to3']} + {g04_r['candidate_pam_5to3']}, where the 11-bp PAM-proximal spacer CCACTAGGGAC + AGG PAM are retained "
            f"and 3 of the 9 SV40_late_polyA_122bp 5' bases [positions 1=A, 5=T, 9=G] incidentally match WT ACAGTGGGG [{g04_r['seed_region_mismatches']}/12 seed mismatches in positions 9..20, "
            f"{g04_r['total_mismatches_vs_wt_spacer']}/20 mismatches at 5' positions {g04_r['mismatch_positions_1based']}, unattenuated WT-SpCas9 positional-retention "
            f"heuristic = {g04_r['uncalibrated_positional_mismatch_score']:.6f}, HiFi positional heuristic = {g04_r['nuclease_attenuated_positional_heuristic']:.8f}]); "
            f"if residual HiFi-SpCas9 R691A cleavage exceeds the 0.1% pre-cloning alert threshold (<1.0% Stage-0 Playbook release gate) at saturating RNP dose, incorporate the "
            f"1-bp length-neutral PAM-disrupting point mutation (chr4:76023451C>G [minus-strand 5'-AGG->5'-AGC at nt 17 of CXCL10_HA_R_600bp_minus] "
            f"and/or chr19:55115754C>G [minus-strand 5'-AGG->5'-AGC at nt 14 of AAVS1_HA_R_600bp_minus]) before GMP plasmid linearization "
            f"(closing AUDIT-REF, AUDIT-REF, & AUDIT-REF)."
        ),
        "stage0_challenger_junction_equivalence_audit_argon_r2": {
            "dx_l3_locus3_scarfree_dual_promoter": (
                f"100% nucleotide-identical 5' left ({g03_l['candidate_protospacer_5to3']}+{g03_l['candidate_pam_5to3']}, "
                f"positional heuristic={g03_l['uncalibrated_positional_mismatch_score']:.6f}) and 3' right "
                f"({g03_r['candidate_protospacer_5to3']}+{g03_r['candidate_pam_5to3']}, {g03_r['total_mismatches_vs_wt_spacer']}/20 mismatches at {g03_r['mismatch_positions_1based']}, "
                f"{g03_r['seed_region_mismatches']}/12 seed mismatches, WT positional heuristic={g03_r['uncalibrated_positional_mismatch_score']:.6f}) "
                f"23-bp junctions to canonical Locus 3 (Kozak_9bp and bGH_polyA_225bp outer boundaries unchanged)."
            ),
            "dx_s_locus4_icasp9_p2a_cd47": (
                f"100% nucleotide-identical 5' left ({g04_l['candidate_protospacer_5to3']}+{g04_l['candidate_pam_5to3']}, "
                f"positional heuristic={g04_l['uncalibrated_positional_mismatch_score']:.6f}) and 3' right "
                f"({g04_r['candidate_protospacer_5to3']}+{g04_r['candidate_pam_5to3']}, {g04_r['total_mismatches_vs_wt_spacer']}/20 mismatches at {g04_r['mismatch_positions_1based']}, "
                f"{g04_r['seed_region_mismatches']}/12 seed mismatches, WT positional heuristic={g04_r['uncalibrated_positional_mismatch_score']:.6f}) "
                f"23-bp junctions to canonical Locus 4 (cHS4_core_insulator_250bp and SV40_late_polyA_122bp outer boundaries unchanged)."
            ),
            "arm1c_constitutive_and_arm1a_lite_locus1": (
                f"Unshielded canonical B2M_HA_L 5' left junction has {g01_1a_l['total_mismatches_vs_wt_spacer']}/23 mismatches at {g01_1a_l['mismatch_positions_1based']} "
                f"incl. {g01_1a_l['seed_region_mismatches']}/18 seed mismatches ({g01_1a_l['candidate_pam_5to3']}+{g01_1a_l['candidate_protospacer_5to3']}, "
                f"WT Cas12a positional heuristic={g01_1a_l['uncalibrated_positional_mismatch_score']:.6f}, Ultra attenuated={g01_1a_l['nuclease_attenuated_positional_heuristic']:.6f}), "
                f"whereas S3-shielded Arm 1A-lite / Arm 1B-S3 mutates the 5'-TTTC PAM to non-PAM 5'-TCTC plus 3 seed wobble bases at positions [4, 7, 10] "
                f"({g01_s3_l['candidate_pam_5to3']}+{g01_s3_l['candidate_protospacer_5to3']}, {g01_s3_l['total_mismatches_vs_wt_spacer']}/23 mismatches incl. {g01_s3_l['seed_region_mismatches']}/18 seed mismatches, heuristic={g01_s3_l['uncalibrated_positional_mismatch_score']:.1f}); "
                "3' right junction (TAGC+AGGCATGCTGGGGATCCAGCGTG, 5'-TTTV PAM abolished to TAGC, heuristic=0.0) is 100% identical to canonical Arm 1A."
            ),
            "arm1b_cd47_c15g_and_l1l2_synonymous_locus1": (
                f"100% nucleotide-identical 5' left ({g01_1b_l['candidate_pam_5to3']}+{g01_1b_l['candidate_protospacer_5to3']} where B2M_HA_L adjoins cHS4_core_insulator_250bp starting CTGAAACA, "
                f"{g01_1b_l['total_mismatches_vs_wt_spacer']}/23 mismatches at {g01_1b_l['mismatch_positions_1based']} incl. {g01_1b_l['seed_region_mismatches']}/18 seed mismatches, "
                f"WT Cas12a positional heuristic={g01_1b_l['uncalibrated_positional_mismatch_score']:.6f}, Ultra attenuated={g01_1b_l['nuclease_attenuated_positional_heuristic']:.6f}; "
                "or 0.0 when paired with the S3 TCTC+TGGACTCGAAGCTATCTGAAACA PAM+seed shield) and 3' right (TAGC PAM abolished, heuristic=0.0) 27-bp junctions to canonical Arm 1B."
            ),
            "arm1c_promoter_trapped_and_arm1b_sense_terminator_shield_locus1": (
                f"Unshielded 5' left junctions have {g01_1c_trap_l['total_mismatches_vs_wt_spacer']}/23 ({g01_1c_trap_l['candidate_pam_5to3']}+{g01_1c_trap_l['candidate_protospacer_5to3']}, "