OpenIslet

scripts/run_layer2_perturbation_and_regulatory_plane.py

Layer 2: Single-Cell Perturbation & Regulatory Sequence Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 1.13 MB · 71 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_layer2_perturbation_and_regulatory_plane.py · SHA-256: 3220e68f97203dbc…

        ha_coord_overlap = 0
        if len(ha_parts) == 2:
            if ha_parts[0][3] == ha_parts[1][3] or ha_parts[0][3] == revcomp(ha_parts[1][3]):
                ha_seq_overlap = min(len(ha_parts[0][3]), len(ha_parts[1][3]))
            c_l = _parse_grch38_coord(ha_parts[0][1])
            c_r = _parse_grch38_coord(ha_parts[1][1])
            if c_l and c_r and c_l[0] == c_r[0]:
                ha_coord_overlap = max(0, min(c_l[2], c_r[2]) - max(c_l[1], c_r[1]) + 1)
        ha_overlap = max(ha_seq_overlap, ha_coord_overlap)

        whole_donor_pwm_scans: Dict[str, Any] = {}
        for pc_label, pc_val in [("pseudocount_0p8_production", 0.8), ("pseudocount_0p5_comparator", 0.5)]:
            pc_dict: Dict[str, Any] = {}
            total_sig_win = 0
            total_sig_loci = 0
            total_sig_reg6 = 0
            for mid, pwm_entry in ref["jaspar_pwms"].items():
                sc_res = scan_jaspar_pwm(donor_seq, pwm_entry, top_k=2, n_matrices_in_scan=len(ref["jaspar_pwms"]), pseudocount=pc_val)
                top0 = sc_res["top_hits"][0]
                total_sig_win += int(sc_res["significant_window_hits_rel0p80_bonferroni_0p05"])
                total_sig_loci += int(sc_res["distinct_non_overlapping_merged_sites_rel0p80_bonferroni_0p05"])
                total_sig_reg6 += int(sc_res["significant_hits_rel0p80_region_wide_bonferroni_0p05"])
                pc_dict[f"{mid}_{pwm_entry['tf_name']}"] = {
                    "significant_window_hits_rel0p80_bonferroni_0p05": sc_res["significant_window_hits_rel0p80_bonferroni_0p05"],
                    "distinct_non_overlapping_merged_sites_rel0p80_bonferroni_0p05": sc_res["distinct_non_overlapping_merged_sites_rel0p80_bonferroni_0p05"],
                    "significant_hits_rel0p80_region_wide_bonferroni_0p05": sc_res["significant_hits_rel0p80_region_wide_bonferroni_0p05"],
                    "top_hit": {
                        "matched_kmer": top0["matched_kmer"],
                        "strand": top0["strand"],
                        "start_1based_in_donor": top0["start_1based_in_window"],
                        "end_1based_in_donor": top0["end_1based_in_window"],
                        "log2_odds_score": top0["log2_odds_score"],
                        "relative_score_0_to_1": top0["relative_score_0_to_1"],
                        "bonferroni_window_p_value": top0["bonferroni_window_p_value"],
                        "bonferroni_region_across_all_matrices_p_value": top0["bonferroni_region_across_all_matrices_p_value"],
                    },
                }
            whole_donor_pwm_scans[pc_label] = {
                "pseudocount": pc_val,
                "total_significant_window_hits_across_6_pwms": total_sig_win,
                "total_distinct_merged_sites_across_6_pwms": total_sig_loci,
                "total_region_wide_6pwm_significant_hits": total_sig_reg6,
                "per_matrix_summary": pc_dict,
            }

        entry = {
            "construct_id": cid,
            "synthesis_readiness_status": "COMPUTATIONAL_REFERENCE_DESIGN_REQUIRES_WETLAB_JUNCTION_AND_EXPRESSION_QUALIFICATION",
            "target_locus": locus_str,
            "insert_cargo_excluding_ha_bp": insert_bp,
            "total_length_bp": len(donor_seq),
            "payload_excluding_ha_bp": insert_bp,
            "aav2_two_itrs_bp": AAV2_TWO_ITRS_LENGTH_BP,
            "packaged_aav6_genome_with_2x145bp_itrs_bp": packaged_with_itrs_bp,
            "aav6_single_capsid_compatible_le_4700bp": aav6_ok,
            "aav6_packaging_headroom_including_itrs_bp": headroom_with_itrs_bp,
            "aav6_packaging_headroom_bp": headroom_with_itrs_bp,
            "donor_sha256": sha256_str(donor_seq),
            "orf_length_bp": len(orf_seq),
            "total_coding_orfs_bp": len(all_cds_coding_concat),
            "donor_gc_percent": donor_q["gc_percent"],
            "donor_cpg_dinucleotide_count": donor_q["cpg_dinucleotide_count"],
            "donor_cpg_observed_over_expected": donor_q["cpg_observed_over_expected"],
            "cargo_excluding_ha_gc_percent": cargo_q["gc_percent"],
            "cargo_excluding_ha_cpg_dinucleotide_count": cargo_part_sum_cpg,
            "cargo_excluding_ha_part_sum_cpg_dinucleotide_count": cargo_part_sum_cpg,
            "cargo_excluding_ha_contiguous_cpg_dinucleotide_count": cargo_q["cpg_dinucleotide_count"],
            "cargo_excluding_ha_cpg_observed_over_expected": cargo_q["cpg_observed_over_expected"],
            "cds_only_cpg_dinucleotide_count": cds_part_sum_cpg,
            "cds_only_part_sum_cpg_dinucleotide_count": cds_part_sum_cpg,
            "cds_only_contiguous_cpg_dinucleotide_count": cds_q["cpg_dinucleotide_count"],
            "cds_only_cpg_observed_over_expected": cds_q["cpg_observed_over_expected"],
            "cpg_dinucleotide_count_by_scope": {
                "whole_donor_including_homology_arms": donor_q["cpg_dinucleotide_count"],
                "inserted_cargo_excluding_homology_arms_part_sum": cargo_part_sum_cpg,
                "inserted_cargo_excluding_homology_arms_with_part_junctions": cargo_q["cpg_dinucleotide_count"],
                "coding_cds_orfs_only_part_sum": cds_part_sum_cpg,
                "coding_cds_orfs_only_with_2a_junctions": cds_q["cpg_dinucleotide_count"],
            },
            "donor_min_gc_window_50bp_pct": donor_q["min_gc_window_50bp_pct"],
            "donor_max_gc_window_50bp_pct": donor_q["max_gc_window_50bp_pct"],
            "donor_max_homopolymer_run_bp": donor_q["max_homopolymer_run_bp"],
            "donor_longest_exact_repeat_bp": donor_q["longest_exact_repeat_bp"],
            "donor_repeats_ge_20bp_count": donor_q["repeats_ge_20bp_distinct_20mers_count"],
            "cds_only_gc_percent": cds_q["gc_percent"],
            "cds_only_min_gc_window_50bp_pct": cds_q["min_gc_window_50bp_pct"],
            "cds_only_max_gc_window_50bp_pct": cds_q["max_gc_window_50bp_pct"],
            "cds_only_max_homopolymer_run_bp": cds_q["max_homopolymer_run_bp"],
            "cds_only_longest_exact_repeat_bp": cds_q["longest_exact_repeat_bp"],
            "cds_only_repeats_ge_20bp_count": cds_q["repeats_ge_20bp_distinct_20mers_count"],
            "codon_table_and_tandem_linker_synthesis_qualification_claude_v80_005_006": (
                "Reference CDS back-translation uses single-codon-per-AA table (GCC/GGC/CCC/AGC), yielding CDS 50-bp max GC windows "
                f"of {cds_q['max_gc_window_50bp_pct']}% and longest exact repeat {cds_q['longest_exact_repeat_bp']} bp; for commercial dsDNA/ssDNA "
                "synthesis, use synonymous codon balancing (GCA/GCT, GGA/GGT, CCA/CCT, TCC/TCT) and diversified non-overlapping "
                "(GGGGS)3='GGAGGCGGTGGTAGCGGCGGTGGAGGTTCAGGTGGCGGAGGCTCT' / "
                "(GGGGS)4='GGTGGAGGCGGTTCAGGCGGAGGTGGCTCTGGCGGTGGCGGATCAGGAGGTGGAGGCAGC' linkers (longest exact repeat across L1/L2 = 9 bp, full HLA-E CDS repeat = 13 bp < 14 bp, max 50-bp GC <= 68%; AUDIT-REF & AUDIT-REF)."
            ),
            "internal_stop_codons": internal_stops_cnt,
            "internal_cryptic_splice_donors_GTAAGT_GTGAGT": int(("GTAAGT" in all_cds_coding_concat) or ("GTGAGT" in all_cds_coding_concat)),
            "internal_premature_polya_AATAAA_ATTAAA": int(("AATAAA" in all_cds_coding_concat) or ("ATTAAA" in all_cds_coding_concat)),
            "homology_arm_overlap_bp": ha_overlap,
            "whole_donor_jaspar_6pwm_scans_by_pseudocount": whole_donor_pwm_scans,
            "part_ledger": part_ledger,
        }
        entry.update(notes)
        return entry

    ucoe_audit_payload = {
        "canonical_element_id": "HNRNPA2B1_CBX3_UCOE_candidate_455bp_R17",
        "canonical_display_name": "HNRNPA2B1-proximal 455-bp CpG-core candidate (GRCh38 chr7:26200580-26201034)",
        "anti_silencing_functional_status": "PREREGISTERED_PENDING",
        "legacy_construct_alias": "CBX3_A2UCOE_455bp_exact",
        "genomic_coordinates_grch38": ucoe_coord_str,
        "zhang_2017_cbx3_bgli_bsrbi_fragment_grch38": "chr7:26201456-26201908 (outer BglI/BsrBI recognition sites chr7:26201449-26201911)",
        "zhang_2017_cbx3_bgli_bsrbi_overlap_bp": max(0, min(ucoe_end, 26201911) - max(ucoe_start, 26201449) + 1) if ucoe_chrom == "chr7" else 0,
        "avi_scanned_interval_grch38": avi_ucoe_interval,
        "avi_coordinate_overlap_bp": ucoe_overlap_bp,
        "avi_coordinate_overlap_fraction": ucoe_overlap_frac,
        "avi_window_alignment_verified": bool(ucoe_overlap_bp == len(cbx3_a2ucoe_455) and ucoe_coord_str == avi_ucoe_interval and ucoe_seq_sha_ok),
        "length_bp": len(cbx3_a2ucoe_455),
        "cpg_dinucleotide_count": cpg_u455,
        "gc_percent": gc_u455,
        "cpg_observed_over_expected": oe_u455,
        "gardiner_garden_cpg_island_sequence_composition_met": bool(gc_u455 > 50.0 and oe_u455 > 0.60),
        "sequence_sha256": sha256_str(cbx3_a2ucoe_455),
        "published_zhang_2017_455_ucoe_identity_audit_ultracode_v80_01": {
            "inserted_interval_grch38": f"{ucoe_coord_str}:+1 (HNRNPA2B1 exon-1/TSS proximal CpG-island region)",
            "zhang_2017_published_bglI_bsrBI_cbx3_side_interval_grch38": "chr7:26201449-26201911 (CBX3-side BglI/BsrBI restriction subfragment)",
            "zhang_2017_table_s1_chip_forward_primer_5to3": "AGTGACCGGAGTCTCCTCA",
            "zhang_2017_forward_primer_grch38_coord": "chr7:26201482-26201500(-)",
            "primer_present_in_inserted_chr7_26200580_26201034_either_strand": bool("AGTGACCGGAGTCTCCTCA" in cbx3_a2ucoe_455 or revcomp("AGTGACCGGAGTCTCCTCA") in cbx3_a2ucoe_455),
            "qualification_status": "CANDIDATE_HNRNPA2B1_PROXIMAL_CPG_CORE_REQUIRES_HEAD_TO_HEAD_LINEAGE_SILENCING_QUALIFICATION",
            "qualification_requirement": (
                "Because chr7:26200580-26201034 overlaps the HNRNPA2B1 exon-1/TSS side of the HNRNPA2B1-CBX3 CpG island "
                "rather than the Zhang et al. 2017 (PMID:28860464) BglI/BsrBI CBX3-side 455-UCOE restriction "
                "fragment (chr7:26201449-26201911, verified by forward ChIP primer AGTGACCGGAGTCTCCTCA at chr7:26201482-26201500[-]), "
                "this interval is designated as a candidate HNRNPA2B1-proximal CpG core with unproven anti-silencing efficacy transfer. "
                "Stage 0->7 pre-pilot must compare chr7:26200580-26201034 head-to-head against the BglI/BsrBI CBX3-side fragment "
                "chr7:26201449-26201911 for lineage-resolved iCasp9 expression, targeted bisulfite methylation, and AP1903 kill across "
                "beta, alpha, delta, iEC, iPericyte, and residual proliferating/off-target cells (closes AUDIT-REF & 005)."
            ),
        },
        "epigenetic_validation_caveat": (
            "Sequence composition (GC% and CpG O/E), motif scores, and SNV archive alignment do not bound rare-cell "
            "epigenetic silencing during Stage 0->7 differentiation; requires targeted bisulfite sequencing and "
            "clonogenic AP1903 escape testing across all graft lineages."
        ),
        "gencode_v46_enst00000354667_8_exon1_overlap_audit": {
            "transcript_id": "ENST00000354667.8 (HNRNPA2B1 canonical minus-strand transcript)",
            "exon1_grch38_1based_closed": "chr7:26200572-26200746 (-)",
            "exon1_length_bp": 175,
            "inserted_element_grch38_1based_closed": ucoe_coord_str,
            "overlap_interval_grch38_1based_closed": "chr7:26200580-26200746",
            "exact_overlap_length_bp": max(0, min(ucoe_end, 26200746) - max(ucoe_start, 26200572) + 1),
            "orientation_in_locus4_transgene": "antisense to HNRNPA2B1 Exon 1 (inserted as GRCh38 '+' strand in Locus 4)",
            "transcribed_plus_strand_canonical_5prime_splice_donor_hexamers_gtaagt_gtgagt": (
                cbx3_a2ucoe_455.count("GTAAGT") + cbx3_a2ucoe_455.count("GTGAGT")
            ),
            "splicing_qualification_note": (
                "The 455-bp element (chr7:26200580-26201034) overlaps 167 bp of GENCODE v46 HNRNPA2B1 Exon 1 "
                "(chr7:26200572-26200746, minus strand) in the antisense orientation and sits upstream of EEF1A1_core_promoter_230bp "
                "(whose TSS is at position 198 of the 230-bp promoter); zero canonical GTAAGT/GTGAGT 5' splice-donor hexamers occur on the "
                "transcribed '+' strand, which is a consensus motif screen rather than proof of zero non-canonical cryptic splicing (requires Stage-0 RT-PCR/5'-RACE verification)."
            ),
        },
        "primary_citations": ["PMID:23307570", "PMID:25605798", "PMID:28860464"],
    }

    chs4_alignment = compute_chs4_alignment(chs4_core_250, ref)
    chs4_scan_1pwm = scan_jaspar_pwm(chs4_core_250, ref["jaspar_pwms"]["MA0139.1"], top_k=2, n_matrices_in_scan=1)
    chs4_scan_6pwm = scan_jaspar_pwm(chs4_core_250, ref["jaspar_pwms"]["MA0139.1"], top_k=2, n_matrices_in_scan=len(ref["jaspar_pwms"]))
    chs4_top1 = chs4_scan_1pwm["top_hits"][0]
    chs4_top6 = chs4_scan_6pwm["top_hits"][0]

    return {
        "validated_homology_arm_source_registry": ha_registry,
        "fasta_path": str(FASTA_OUT.relative_to(REPO_ROOT)),
        "fasta_sha256": hashlib.sha256(FASTA_OUT.read_bytes()).hexdigest(),
        "regulatory_element_audits": {
            "EEF1A1_core_promoter_230bp": {
                "genomic_coordinates_grch38": "chr6:73521000-73521229:-1",
                "canonical_transcript_tss": "ENST00000309268.11 TSS at chr6:73521032:-1 (window spans -197 bp upstream TATA/Sp1 core promoter through +33 bp Exon 1; 5'-UTR Exon 1 splice donor and intron 1 coordinates invariant across .10 and .11)",
                "length_bp": len(eef1a1_core_230),
                "cpg_dinucleotide_count": cpg_eef1a,
                "gc_percent": gc_eef1a,
                "cpg_observed_over_expected": oe_eef1a,
                "sequence_sha256": sha256_str(eef1a1_core_230),
                "evidence_class": "authentic_grch38_upstream_core_promoter_sequence_functional_strength_requires_stage7_wetlab_qualification",
            },
            "WPREmut6_589bp_J04514_mut6": {
                "genomic_coordinates_or_accession": "GenBank:J04514.1:1093-1681_WHV_WPRE_1503AtoT_WHX_Start_Ablated(PMID:19262615)",
                "organism": "Woodchuck hepatitis virus (WHV, GenBank:J04514.1)",
                "length_bp": len(wpre_mut6_589),
                "mutations_vs_J04514_1093_1681": [
                    "J04514.1:g.1503A>T (WHX c.1A>T, legacy alias c.1503A>T; local_1based_411:A>T, WHX_start_codon_ATG->TTG_ablation_per_PMID_19262615)"
                ],
                "nomenclature_qualification_note": (
                    "Canonical part_name WPREmut6_589bp is retained for SHA-256 registry compatibility; sequence carries the "
                    "single-nucleotide WHX start-codon ablation J04514.1:g.1503A>T (ATG->TTG at local 411..413) rather than a 6-point-mutation WE2/mut6 cluster."
                ),
                "sequence_sha256": sha256_str(wpre_mut6_589),
                "primary_citations": ["PMID:19262615"],
            },
            "cHS4_core_insulator_250bp_ULTRACODE_V80_13": {
                "genomic_coordinates_or_accession": "GenBank:U78775.2:10-244 (current, 235-bp exact match) / GenBank:U78775.1:10-226 (superseded, 217-bp exact match) — Gallus gallus beta-globin 5' HS4 insulator (Chung et al. 1997 PMID:9012826; Bell et al. 1999 PMID:10458613)",
                "length_bp": len(chs4_core_250),
                "exact_u78775_2_contiguous_core_match_bp": chs4_alignment["longest_exact_contiguous_match_bp"],
                "computed_native_accession_alignment": chs4_alignment,
                "u78775_2_bases_outside_longest_exact_block_bp": chs4_alignment["left_flank_outside_match_bp"] + chs4_alignment["right_flank_outside_match_bp"],
                "exact_u78775_1_contiguous_core_match_bp": 217,
                "historical_superseded_u78775_1_bases_outside_match_bp": 33,
                "ctcf_ma0139_1_footprint_fii_scan_claude_v80_007": chs4_scan_1pwm,
                "ctcf_ma0139_1_footprint_fii_scan_6_matrix_family": chs4_scan_6pwm,
                "sequence_adaptation_disclosure": (
                    "Engineered 250-bp core insulator variant containing the 235-bp exact contiguous Gallus U78775.2:10..244 "
                    "CTCF/USF1 FII-footprint core (insert coordinates 3..237, flanked by 2-bp 5' GA and 13-bp 3' AGGCTGCCGCGGG containing a 1-nt T deletion "
                    "immediately 3' of native HindIII plus SacII adapter CCGCGG; 217-bp exact contiguous match to superseded U78775.1:10..226). "
                    f"Direct JASPAR MA0139.1 CTCF scan locates the canonical FII enhancer-blocking footprint at local positions {chs4_top1['start_1based_in_window']}..{chs4_top1['end_1based_in_window']} "
                    f"({chs4_top1['strand']} strand, kmer={chs4_top1['matched_kmer']}, score={chs4_top1['log2_odds_score']} bits, "
                    f"rel_score={chs4_top1['relative_score_0_to_1']}; single-PWM window Bonferroni p={chs4_top1['bonferroni_window_p_value']}, "
                    f"6-PWM family Bonferroni p={chs4_top6['bonferroni_region_across_all_matrices_p_value']}, "
                    f"passes_rel_score_0p80_and_p_le_0p05={chs4_top1['passes_rel_score_0p80_and_p_le_0p05']}; FII identity is verified by exact sequence match to Gallus U78775.2:55..73 per "
                    "Chung et al. 1997 PMID:9012826 & Bell et al. 1999 PMID:10458613; closes AUDIT-REF & 068)."
                ),
                "sequence_sha256": sha256_str(chs4_core_250),
                "primary_citations": ["PMID:9012826", "PMID:10458613"],
            },
            "HNRNPA2B1_CBX3_UCOE_candidate_455bp_R17": dict(ucoe_audit_payload),
            "CBX3_A2UCOE_core_455bp_R17": dict(ucoe_audit_payload),
            "SV40_late_polyA_122bp_J02400": {
                "genomic_coordinates_or_accession": "GenBank:J02400.1:2580-2701 (Simian virus 40 complete genome, late polyadenylation signal)",
                "length_bp": len(sv40_polya_122),
                "sequence_sha256": sha256_str(sv40_polya_122),
                "j02400_alignment_verification": {
                    "accession": "J02400.1",
                    "range_1based_closed": "2580..2701",
                    "donor_extracted_1based_span_in_arm1b": "601..722 (-)",