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_spec = grna_specs[4]["epegRNA_extension_specification"]
    pbs_expected = revcomp(tyk2_plus_71[10352425 - 10352410 : 10352437 - 10352410 + 1])  # 13 nt upstream of nick
    _check(
        tyk2_spec["primer_binding_site_pbs_13nt_5to3"] == pbs_expected,
        f"TYK2 PBS mismatch: {tyk2_spec['primer_binding_site_pbs_13nt_5to3']} != {pbs_expected}",
    )
    wt_post_nick_12 = tyk2_plus_71[10352438 - 10352410 : 10352449 - 10352410 + 1]
    rtt_written_plus = revcomp(tyk2_spec["rt_template_rtt_12nt_5to3"])
    written_diffs = [
        (10352438 + idx_b, wt_b, ed_b)
        for idx_b, (wt_b, ed_b) in enumerate(zip(wt_post_nick_12, rtt_written_plus))
        if wt_b != ed_b
    ]
    _check(
        written_diffs == [(10352442, "G", "C")],
        f"TYK2 RTT must write only 10352442G>C with zero bystander edits, got {written_diffs}",
    )

    # Read all 4 HDR donor templates from Layer 2 FASTA
    fasta_path = REPO_ROOT / "data" / "constructs" / "islet1_scenario_a_constructs_v0.7.0.fasta"
    from scripts.run_layer2_perturbation_and_regulatory_plane import parse_construct_fasta_text
    donor_seqs = parse_construct_fasta_text(fasta_path.read_text(encoding="utf-8"))

    # Authentic Ensembl GRCh38 50-bp chromosomal flanks immediately outside each construct's HA_L and HA_R
    # (closing AUDIT-REF; verified against live Ensembl REST GRCh38):
    authentic_outer_chromosomal_flanks_50bp: Dict[str, Dict[str, str]] = {
        "ISLET1_LOCUS1_ARM1A_B2M_HLAE_SCT_GSGP2A_CD47_IGV_GPI_4880bp": {
            "left_outer_grch38": "chr15:44710759-44710808 (+)",
            "left_outer_50bp": "ACCTAGAGGGCGCTGGAAGCTCTAAAGCCCTAGCAGTTACTGCTTTTACT",
            "right_outer_grch38": "chr15:44712409-44712458 (+)",
            "right_outer_50bp": "GCCTCTCACAGATGAAGAAACTAAGGCACCGAGATTTTAAGAAACTTAAT",
            "ha_bp": "800",
        },
        "ISLET1_LOCUS1_ARM1B_B2M_BIDIR_2AFREE_CD47_IGV_GPI_HLAE_SCT_3974bp": {
            "left_outer_grch38": "chr15:44710959-44711008 (+)",
            "left_outer_50bp": "CTCTTTCACTAGGACCTTCTCTGAGCTGTCCTCAGGATGCTTTTGGGACT",
            "right_outer_grch38": "chr15:44712209-44712258 (+)",
            "right_outer_50bp": "GTTTGTAGAATGCTTGGCTGTGATACAAAGCGGTTTCGAATAATTAACTT",
            "ha_bp": "600",
        },
        "ISLET1_LOCUS3_CXCL10_SERPINB9_GSGP2A_PDL1_NO_FURIN_4090bp": {
            "left_outer_grch38": "chr4:76024068-76024117 (-)",
            "left_outer_50bp": "TTTTCCCTCAAAATAGTTATGTTGGAGGCTATTTACTTAATCTAATGGTG",
            "right_outer_grch38": "chr4:76022818-76022867 (-)",
            "right_outer_50bp": "CTAAAATGAACACTGTGCTAACCTTCTCTGCTGTTCCTCTTTTCCTACAG",
            "ha_bp": "600",
        },
        "ISLET1_LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_EEF1A1_ICASP9_3457bp": {
            "left_outer_grch38": "chr19:55116368-55116417 (-)",
            "left_outer_50bp": "TGTGTTGCTGCCCAAGGATGCTCTTTCCGGAGCACTTCCTTCTCGGCGCT",
            "right_outer_grch38": "chr19:55115118-55115167 (-)",
            "right_outer_50bp": "CTACTCCCTTTCTCTTTCTCCATCCTTCTTTCCTTAAAGAGTCCCCAGTG",
            "ha_bp": "600",
        },
    }

    post_hdr_junction_cfd_audit: Dict[str, Any] = {}
    off_target_reconciliation_table: Dict[str, Any] = {}

    for g in grna_specs:
        # These historical screening numbers are assumptions, not retrieved gnomAD AC/AN observations.
        assumed_frequencies = {k.removeprefix("gnomad_v4_1_"): v for k, v in g.items() if k.startswith("gnomad_v4_1_")}
        g["assumed_screening_frequency_priors"] = {
            "source_class": "ASSUMED_NOT_DATABASE_MEASUREMENT", "values": assumed_frequencies,
            "qualification": "Unvalidated screening assumptions; not observed maxima or proven upper bounds.",
        }
        for key in [k for k in g if k.startswith("gnomad_v4_1_")]:
            g[key] = None  # Deprecated measurement aliases require a variant/population AC/AN receipt.
        if "PEmax" in g["nuclease"]:
            g["cgbe_alternative_implementation_status"] = "NOT_IMPLEMENTED_REQUIRES_ENGINEERED_PAM_WINDOW_AND_BYSTANDER_LEDGER"
        proto = g["protospacer_dna_5to3"]
        pam = g["pam_sequence_5to3"]
        full_target = (pam + proto) if "Cas12a" in g["nuclease"] else (proto + pam)
        full_target_rc = revcomp(full_target)

        # Verify 100% 0-mismatch identity against cached Ensembl GRCh38 reference slice (AUDIT-REF & AUDIT-REF):
        wt_slice = g.pop("_wt_expected_slice")
        _check(
            wt_slice == full_target,
            f"GRCh38 coordinate/sequence mismatch for {g['guide_id']}: expected {full_target}, got {wt_slice}",
        )
        if "_legacy_pIII_wt_slice" in g:
            leg_slice = g.pop("_legacy_pIII_wt_slice")
            _check(leg_slice == "TTTACCTTGGGGCTCTGACAGGTAGGA", f"Unexpected legacy CIITA slice: {leg_slice}")
        g["grch38_reference_exact_match_verified"] = True
        g["grch38_reference_mismatch_count"] = 0

        g["full_target_site_5to3"] = full_target
        g["full_target_site_revcomp_5to3"] = full_target_rc
        g["spacer_rna_5to3"] = proto.replace("T", "U")
        if "Cas12a" in g["nuclease"]:
            g["full_synthesized_grna_rna_5to3"] = ASCAS12A_DIRECT_REPEAT_20NT_RNA + proto.replace("T", "U")
            g["scaffold_rna_length_nt"] = len(ASCAS12A_DIRECT_REPEAT_20NT_RNA)
        elif "PEmax" in g["nuclease"]:
            g["full_synthesized_grna_rna_5to3"] = g["epegRNA_extension_specification"]["full_assembled_epegrna_rna_163nt_5to3"]
            g["scaffold_rna_length_nt"] = len(PEMAX_EPEGRNA_SCAFFOLD_76NT_RNA)
        else:
            g["full_synthesized_grna_rna_5to3"] = proto.replace("T", "U") + SPCAS9_SGRNA_SCAFFOLD_80NT_RNA
            g["scaffold_rna_length_nt"] = len(SPCAS9_SGRNA_SCAFFOLD_80NT_RNA)
        g["synthesized_rna_total_length_nt"] = len(g["full_synthesized_grna_rna_5to3"])

        g["protospacer_sha256"] = sha256_str(proto)
        g["gc_percent"] = gc_percent(proto)
        g["sugimoto_1995_rna_dna_hybrid_dg37_kcal_mol"] = compute_sugimoto_1995_rna_dna_dg37_kcal_mol(proto)
        g["santalucia_1998_duplex_dg37_kcal_mol"] = compute_duplex_dg37_kcal_mol(proto)

        # Compute deterministic off-target specificity model & reconcile with whole-genome CRISPOR/MIT reference (AUDIT-REF):
        noncoding_hits = g.pop("_noncoding_3mm_cfd_hits")
        ot_model = compute_panel_and_reference_off_target_specificity(
            guide_id=g["guide_id"],
            nuclease=g["nuclease"],
            coding_0_1_2_mm=g["grch38_0_1_2_mismatch_coding_off_targets"],
            noncoding_3_mm_count=g["grch38_3_mismatch_intergenic_intronic_loci"],
            noncoding_3_mm_cfd_Hits=noncoding_hits,
            crispor_whole_genome_mit_ref=g["whole_genome_crispor_mit_reference_specificity_score"],
            ucsc_crispr_track_url=g.get("ucsc_crispr_all_targets_query_url"),
        )
        _check(ot_model["window_and_exome_panel_cfd_specificity_score"] == g["cfd_mit_off_target_specificity_score"])
        g["off_target_specificity_breakdown_claude_v80_006"] = ot_model
        off_target_reconciliation_table[g["guide_id"]] = ot_model
        g["genome_wide_off_target_search_status"] = (
            "NOT_ENUMERATED_ASSIGNED_PANEL_AND_REFERENCE_SCORE_ONLY"
        )

        # Scan BOTH strands (+ and - revcomp) of all 4 HDR donor plasmids AND reconstructed post-edit genomic alleles
        # using authentic 50-bp Ensembl GRCh38 outer chromosomal flanks (closing AUDIT-REF, AUDIT-REF, AUDIT-REF, & AUDIT-REF):
        intact_in_any_donor_either_strand = any(
            _canonical_target_present_either_strand(d_seq, proto, g["nuclease"]) for d_seq in donor_seqs.values()
        )
        donor_keys = g.pop("_donor_keys")
        split_prefix = g.pop("_split_prefix_bp", 0)
        split_suffix = g.pop("_split_suffix_bp", 0)
        intact_in_post_hdr_allele = False
        reconstructed_allele_lengths: List[int] = []
        reconstructed_allele_hashes: List[str] = []
        junction_cfd_by_donor: Dict[str, Any] = {}
        raw_pam_retained_any_junction = False
        raw_pam_and_seed_retained_any_junction = False
        if donor_keys:
            edited_allele_verification_mode = (
                "VERIFIED_POST_HDR_CHROMOSOMAL_ALLELE_WITH_AUTHENTIC_50BP_OUTER_GRCH38_FLANKS"
            )
            target_len = len(full_target)
            for d_key in donor_keys:
                d_seq = donor_seqs[d_key]
                flanks = authentic_outer_chromosomal_flanks_50bp[d_key]
                ha_bp = int(flanks["ha_bp"])
                _check(flanks["left_outer_50bp"] != d_seq[:50] and flanks["right_outer_50bp"] != d_seq[-50:])
                post_hdr_allele = flanks["left_outer_50bp"] + d_seq + flanks["right_outer_50bp"]
                reconstructed_allele_lengths.append(len(post_hdr_allele))
                reconstructed_allele_hashes.append(sha256_str(post_hdr_allele))
                if _canonical_target_present_either_strand(post_hdr_allele, proto, g["nuclease"]):
                    intact_in_post_hdr_allele = True
                # Extract exact 5' (HA_L|Insert) and 3' (Insert|HA_R) split-protospacer junction windows (AUDIT-REF):
                left_junc_window = d_seq[ha_bp - split_prefix : ha_bp - split_prefix + target_len]
                right_junc_window = d_seq[len(d_seq) - ha_bp - (target_len - split_suffix) : len(d_seq) - ha_bp + split_suffix]
                if "Cas12a" in g["nuclease"]:
                    # For Cas12a (5'-PAM + 23-nt spacer), pass 23-nt candidate spacer + 4-nt candidate PAM in standardized order:
                    j_metrics = compute_split_junction_residual_cleavage_metrics(
                        protospacer_5to3=proto,
                        pam_5to3=pam,
                        nuclease=g["nuclease"],
                        left_junction_seq_5to3=left_junc_window[:4] + left_junc_window[4:],
                        right_junction_seq_5to3=right_junc_window[:4] + right_junc_window[4:],
                    )
                else:
                    j_metrics = compute_split_junction_residual_cleavage_metrics(
                        protospacer_5to3=proto,
                        pam_5to3=pam,
                        nuclease=g["nuclease"],
                        left_junction_seq_5to3=left_junc_window,
                        right_junction_seq_5to3=right_junc_window,
                    )
                if j_metrics["raw_pam_motif_retained_on_either_junction"]:
                    raw_pam_retained_any_junction = True
                if j_metrics["raw_pam_and_seed_subsequence_retained_on_either_junction"]:
                    raw_pam_and_seed_retained_any_junction = True
                junction_cfd_by_donor[d_key] = j_metrics
            g["post_hdr_split_junction_cfd_audit"] = junction_cfd_by_donor
            post_hdr_junction_cfd_audit[g["guide_id"]] = junction_cfd_by_donor
        elif g["guide_id"] == "OI-GRNA-02_CIITA_EXON1_ASCAS12A":
            # Construct authentic post-NHEJ frameshift allele on chr16:10898880-10899079 (-) with canonical
            # AsCas12a staggered cleavage 4-bp deletion (deleting 0-based indices 17..20 'CATC' inside TGCCCAACTTCTGCTGGCATCTC; closing AUDIT-REF):
            edited_allele_verification_mode = (
                "VERIFIED_POST_NHEJ_FRAMESHIFT_CHROMOSOMAL_ALLELE_4BP_STAGGERED_DELETION"
            )
            ciita_exon5_minus_200 = revcomp(ciita_exon5_wt_200)
            _check(full_target in ciita_exon5_minus_200)
            deleted_4bp = proto[17:21]
            _check(deleted_4bp == "CATC", f"Expected 4-bp deletion 'CATC' at proto[17:21], got {deleted_4bp}")
            broken_target = pam + proto[:17] + proto[21:]  # 4-bp frameshift deletion of 'CATC' at staggered cut site
            post_nhej_allele = ciita_exon5_minus_200.replace(full_target, broken_target, 1)
            reconstructed_allele_lengths.append(len(post_nhej_allele))
            reconstructed_allele_hashes.append(sha256_str(post_nhej_allele))
            if _canonical_target_present_either_strand(post_nhej_allele, proto, g["nuclease"]):
                intact_in_post_hdr_allele = True
            raw_pam_retained_any_junction = True  # 5'-TTTC PAM remains upstream of the 4-bp frameshift deletion
            raw_pam_and_seed_retained_any_junction = False  # 18-nt seed/cut zone disrupted by 4-bp deletion at nt 18..21
        elif g["guide_id"] == "OI-GRNA-05_TYK2_P1104A_PEMAX_EPEGRNA_OPTIONAL":
            # Construct authentic post-prime-edit allele on chr19:10352410-10352480 (+) installing g.10352442G>C (GGG->GCG PAM):
            edited_allele_verification_mode = (
                "VERIFIED_POST_PRIME_EDIT_SNV_CHROMOSOMAL_ALLELE_CHR19_10352442_G_TO_C"
            )
            idx_snv = 10352442 - 10352410
            _check(tyk2_plus_71[idx_snv] == "G")
            post_pe_allele = tyk2_plus_71[:idx_snv] + "C" + tyk2_plus_71[idx_snv + 1 :]
            reconstructed_allele_lengths.append(len(post_pe_allele))
            reconstructed_allele_hashes.append(sha256_str(post_pe_allele))
            if _canonical_target_present_either_strand(post_pe_allele, proto, g["nuclease"]):
                intact_in_post_hdr_allele = True
            raw_pam_retained_any_junction = False  # GGG PAM mutated to GCG
            raw_pam_and_seed_retained_any_junction = False
        else:
            edited_allele_verification_mode = "UNVERIFIED_NO_ALLELE_CONSTRUCTED"

        g["edited_allele_verification_mode"] = edited_allele_verification_mode
        g["full_20_to_23nt_target_absent_post_edit"] = (not intact_in_post_hdr_allele)
        g["hdr_full_protospacer_disrupted_post_knockin"] = (not intact_in_post_hdr_allele)
        g["hdr_pam_and_seed_disrupted_post_knockin"] = (not raw_pam_and_seed_retained_any_junction)
        g["raw_pam_motif_retained_on_either_post_edit_junction"] = raw_pam_retained_any_junction
        g["raw_pam_and_seed_subsequence_retained_on_either_post_edit_junction"] = raw_pam_and_seed_retained_any_junction
        g["intact_target_present_in_any_hdr_donor_plasmid"] = intact_in_any_donor_either_strand
        g["intact_target_present_in_post_hdr_edited_allele_either_strand"] = intact_in_post_hdr_allele
        g["intact_target_present_in_post_edit_chromosomal_allele_either_strand"] = intact_in_post_hdr_allele
        g["post_hdr_reconstructed_allele_lengths_bp"] = reconstructed_allele_lengths
        g["post_edit_reconstructed_allele_sha256"] = reconstructed_allele_hashes
        _check(not intact_in_any_donor_either_strand, f"Guide {g['guide_id']} found intact in HDR donor!")
        _check(not intact_in_post_hdr_allele, f"Guide {g['guide_id']} not disrupted in post-edit allele!")

    dbsnp_summary = {}
    for key, rec in raw_l5.get("dbsnp_records", {}).items():
        raw_obs = rec.get("minor_allele_frequencies", [])
        folded_summary = []
        if isinstance(raw_obs, list):
            for obs in raw_obs:
                if isinstance(obs, dict):
                    ac = obs.get("allele_count")
                    an = obs.get("total_count")
                    valid_counts = (
                        not isinstance(ac, bool)
                        and not isinstance(an, bool)
                        and isinstance(ac, int)
                        and isinstance(an, int)
                        and an > 0
                        and 0 <= ac <= an
                    )
                    f_val = (float(ac) / float(an)) if valid_counts else None
                    folded_summary.append({
                        "study": obs.get("study"),
                        "allele_count": ac if valid_counts else None,