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…

            or _obs_pfm_sha != _exp_pfm_sha
        ):
            raise ValueError(f"JASPAR PWM/PFM SHA-256 digest mismatch against pinned reference for {_mid_chk}")
    n_pwms = len(pwms_map)
    utr22_3utrs, utr22_cds, utr22_5utrs, utr22_full = _verified_22gene_refseq_panel(ref_bundle)

    verified_preexisting_fastas: Dict[str, str] = {}
    parsed_proxy_fastas: Dict[str, Dict[str, str]] = {}
    for rel_fa, exp_fa_sha in _IIP0031_PREEXISTING_6_FASTA_SHA256.items():
        fa_p = REPO_ROOT / rel_fa
        is_required_proxy = rel_fa in _IIP0031_PROXY_4_FASTAS
        if is_required_proxy and not fa_p.is_file():
            raise ValueError(f"Missing or non-regular required canonical proxy FASTA: {fa_p}")
        if fa_p.exists():
            if not fa_p.is_file():
                raise ValueError(f"Non-regular canonical FASTA path: {fa_p}")
            fa_bytes = fa_p.read_bytes()
            obs_fa_sha = hashlib.sha256(fa_bytes).hexdigest()
            if obs_fa_sha != exp_fa_sha:
                raise ValueError(f"Canonical FASTA SHA-256 mismatch for {rel_fa}: {obs_fa_sha} != {exp_fa_sha}")
            parsed_map = _parse_fa_bytes(fa_bytes, rel_fa)
            verified_preexisting_fastas[rel_fa] = obs_fa_sha
            if is_required_proxy:
                parsed_proxy_fastas[rel_fa] = parsed_map

    canonical_fastas_untouched = len(verified_preexisting_fastas) == len(_IIP0031_PREEXISTING_6_FASTA_SHA256)

    pareto_path = REPO_ROOT / _IIP0031_PARETO_REL
    layer1_pareto_verified = False
    layer1_pareto_sha256: Optional[str] = None
    layer1_score_delta_pp: Optional[float] = None
    if pareto_path.exists():
        if not pareto_path.is_file():
            raise ValueError(f"Non-regular Layer-1 Pareto artifact path: {pareto_path}")
        pareto_bytes = pareto_path.read_bytes()
        obs_pareto_sha = hashlib.sha256(pareto_bytes).hexdigest()
        if obs_pareto_sha != _IIP0031_PARETO_SHA256:
            raise ValueError(
                f"Layer-1 Pareto artifact SHA-256 mismatch for {_IIP0031_PARETO_REL}: "
                f"{obs_pareto_sha} != {_IIP0031_PARETO_SHA256}"
            )
        layer1_pareto_verified = True
        layer1_pareto_sha256 = obs_pareto_sha
        layer1_score_delta_pp = 0.0

    construct_entries: List[Dict[str, Any]] = []
    ciita_isoform_summary_by_acc: Dict[str, Dict[str, Any]] = {}
    extracted_unit2_cds: Dict[str, str] = {}
    extracted_cfh_cds: Optional[str] = None

    for cid in expected_order:
        seq = records[cid]
        dlen = len(seq)
        # Dynamic full 2x375-bp arm alignment & PAM-shield verification against GRCh38 chr16:
        ha_l_obs = seq[:v3_ha_bp]
        ha_r_obs = seq[-v3_ha_bp:]
        ha_l_mm = sum(a != b for a, b in zip(ha_l_obs, ha_l_ref))
        ha_r_diffs = [
            {"offset0_in_ha_r": j, "chr16_pos_1based": 10898968 + j, "ref_base": ha_r_wt_ref[j], "donor_base": ha_r_obs[j]}
            for j in range(v3_ha_bp)
            if ha_r_obs[j] != ha_r_wt_ref[j]
        ]
        if ha_l_mm != 0 or [d["chr16_pos_1based"] for d in ha_r_diffs] != [10898988, 10898989] or [d["donor_base"] for d in ha_r_diffs] != ["C", "C"]:
            raise ValueError(f"Full 375-bp arm GRCh38 alignment failed on {cid}: ha_l_mm={ha_l_mm}, ha_r_diffs={ha_r_diffs}")
        if seq[v3_ha_bp + 12 : v3_ha_bp + 166] != canonical_shield_154:
            raise ValueError(f"Canonical 154-bp shield mismatch on {cid}")
        if revcomp(seq[-v3_ha_bp - 80 : -v3_ha_bp]) != dm1_seq:
            raise ValueError(f"Right-hand 80-bp DM1 CTCF1 mismatch on {cid}")

        has_intron = cid not in ("L2_V3_DESIGN_B_CD200", "L2_V3_DESIGN_B_MANF")
        prom2_len = 250 if cid == "L2_V3_CD274P_ZERO_TATATA" else 148
        mid_ins_len = 250 if cid == "L2_V3_BARRIER_CHS4_250" else 80
        cfh_cds_slice = seq[dlen - 1688 : dlen - 605]
        if extracted_cfh_cds is None:
            extracted_cfh_cds = cfh_cds_slice
        elif extracted_cfh_cds != cfh_cds_slice:
            raise ValueError(f"CFH-STP-GPI CDS mismatch across donors on {cid}")
        eef_start0 = (dlen - 2247) if has_intron else (dlen - 1927)
        u2_cds_start0 = 550 + prom2_len
        u2_cds_end0 = eef_start0 - mid_ins_len - 150
        u2_cds_slice = seq[u2_cds_start0:u2_cds_end0]
        if "CD200" in cid or cid in ("L2_V3_CTRL_NT_SCRAMBLE", "L2_V3_BARRIER_CHS4_250", "L2_V3_CD274P_ZERO_TATATA"):
            extracted_unit2_cds["CD200"] = u2_cds_slice
        elif "MANF" in cid:
            extracted_unit2_cds["MANF"] = u2_cds_slice
        elif "CCL22" in cid:
            extracted_unit2_cds["CCL22"] = u2_cds_slice

        # Dynamic repeat/IR scans (including max overlapping DR outside canonical shield & Syn_5xISRE tandems):
        disj_dr_bp, disj_dr_info = _max_disjoint_dr(seq)
        ov_dr_bp, ov_dr_info = _max_overlapping_dr(seq)
        canonical_tandem_spans = ((387, 541), (541, 541 + prom2_len)) if cid != "L2_V3_CD274P_ZERO_TATATA" else ((387, 541),)
        ov_outside_bp, _ = _max_overlapping_dr(seq, excluded_spans_0based=canonical_tandem_spans)
        disj_ir_bp, disj_ir_info = _max_disjoint_ir(seq)
        ir_ge16_cnt = _count_disjoint_ir_ge_k(seq, min_k=16)
        near_ir_hits = scan_disjoint_inverted_repeats_with_mismatches(seq, min_k=20, max_mismatches=1)
        if disj_dr_bp >= 30 or disj_ir_bp >= 16 or ir_ge16_cnt != 0 or len(near_ir_hits) != 0:
            raise ValueError(
                f"Locus-2 v3 repeat invariant failed on {cid}: disj_dr={disj_dr_bp}, disj_ir={disj_ir_bp}, "
                f"ir_ge16={ir_ge16_cnt}, near_ir_ge20_le1mm={len(near_ir_hits)}"
            )
        t20_cnt = seq.count("T" * 20)
        sv40_cnt = seq.count(sv40_sig)
        bgh_cnt = seq.count(bgh_sig)
        two_a_cnt = seq.count(two_a_sig)
        if t20_cnt or sv40_cnt or bgh_cnt or two_a_cnt:
            raise ValueError(f"Forbidden motif (T20/SV40pA/bGH/2A) found in {cid}")

        # Dynamic isolated vs integrated (chr16 + 2x300-bp flanks) two-strand splice parity:
        sp_iso = scan_donors_and_acceptors_both_strands(seq, cargo_bounds_1based=(v3_ha_bp + 1, dlen - v3_ha_bp))
        sp_int = scan_donors_and_acceptors_both_strands(
            flank_up_300 + seq + flank_dn_300,
            cargo_bounds_1based=(300 + v3_ha_bp + 1, 300 + dlen - v3_ha_bp),
        )
        iso_sp_counts = {
            "plus_donors": int(sp_iso["cargo_donors_plus_strand"]),
            "minus_donors": int(sp_iso["cargo_donors_minus_strand"]),
            "plus_acceptors": sum(1 for a in sp_iso["acceptors"] if a["in_cargo"] and a["strand_relative_to_input"] == "+"),
            "minus_acceptors": sum(1 for a in sp_iso["acceptors"] if a["in_cargo"] and a["strand_relative_to_input"] == "-"),
        }
        int_sp_counts = {
            "plus_donors": int(sp_int["cargo_donors_plus_strand"]),
            "minus_donors": int(sp_int["cargo_donors_minus_strand"]),
            "plus_acceptors": sum(1 for a in sp_int["acceptors"] if a["in_cargo"] and a["strand_relative_to_input"] == "+"),
            "minus_acceptors": sum(1 for a in sp_int["acceptors"] if a["in_cargo"] and a["strand_relative_to_input"] == "-"),
        }
        if iso_sp_counts != int_sp_counts:
            raise ValueError(f"Donor vs integrated chr16 splice parity failed on {cid}: {iso_sp_counts} != {int_sp_counts}")

        # Dynamic 8-isoform CIITA Exon-5 knock-in translation & chimeric k-mer census:
        for acc_c, irec in ciita_iso_verified.items():
            chim_dna = irec["cds_before_ex5_core"] + seq[v3_ha_bp - cut_off_ex5 :]
            aas_c: List[str] = []
            stop_cod = ""
            stop_pos1 = -1
            for i_cod in range(0, len(chim_dna) - 2, 3):
                cod = chim_dna[i_cod : i_cod + 3]
                aa_c = GENETIC_CODE[cod]
                if aa_c == "*":
                    stop_cod = cod
                    stop_pos1 = v3_ha_bp - cut_off_ex5 + (i_cod + 3 - len(irec["cds_before_ex5_core"]))
                    break
                aas_c.append(aa_c)
            trunc_aa_c = "".join(aas_c)
            nat_aa_c = irec["native_aa"]
            ki_nov_8_11 = len(_kmers_aa(trunc_aa_c, (8, 9, 10, 11)) - _kmers_aa(nat_aa_c, (8, 9, 10, 11)))
            ki_nov_15 = len(_kmers_aa(trunc_aa_c, (15,)) - _kmers_aa(nat_aa_c, (15,)))
            if trunc_aa_c != nat_aa_c[: len(trunc_aa_c)] or stop_cod != "TGA" or stop_pos1 != (v3_ha_bp + 4) or ki_nov_8_11 != 0 or ki_nov_15 != 0:
                raise ValueError(f"CIITA isoform {acc_c} junction translation failed on {cid}")
            if cid == "L2_V3_CO_PRIMARY_CD200":
                ciita_isoform_summary_by_acc[acc_c] = {
                    "iso_key": irec["iso_key"],
                    "promoter_first_exon_mapping": irec["promoter_first_exon_mapping"],
                    "exon5_index_in_transcript": irec["exon5_index_in_transcript"],
                    "exon5_length_bp": irec["exon5_length_bp"],
                    "exon5_splice_phase": irec["exon5_splice_phase"],
                    "native_aa_len": len(nat_aa_c),
                    "truncated_aa_len": len(trunc_aa_c),
                    "stop_codon": stop_cod,
                    "stop_donor_pos_1based": stop_pos1,
                    "knockin_created_non_native_8_11mers": ki_nov_8_11,
                    "knockin_created_non_native_15mers": ki_nov_15,
                }

        homos_ge7 = [len(m.group(0)) for m in re.finditer(r"(A{7,}|C{7,}|G{7,}|T{7,})", seq)]
        u2_prom_slice = seq[541 : 541 + prom2_len]
        tatata_cnt = u2_prom_slice.count("TATATAATGG")

        pwm_summary: Dict[str, Any] = {}
        if pwms_map:
            total_win = 0
            total_merged = 0
            total_reg6 = 0
            u2_prom_span = (542, 541 + prom2_len)
            eef_prom_span = (eef_start0 + 1, eef_start0 + 230)
            chs4_span = (eef_start0 - mid_ins_len + 1, eef_start0)
            dm1_span = (dlen - v3_ha_bp - 80 + 1, dlen - v3_ha_bp)
            wholly_non_prom_6pwm = 0
            boundary_irf1_hits: List[Dict[str, Any]] = []
            ctcf_ins_hits: Dict[str, Dict[str, Any]] = {}
            exact_family_tests = sum(max(0, 2 * (dlen - int(m["length"]) + 1)) for m in pwms_map.values())
            for mid, pentry in pwms_map.items():
                sc = scan_jaspar_pwm(
                    seq,
                    pentry,
                    top_k=30,
                    n_matrices_in_scan=n_pwms,
                    actual_family_total_tests=exact_family_tests,
                )
                total_win += int(sc["significant_window_hits_rel0p80_bonferroni_0p05"])
                total_merged += int(sc["distinct_non_overlapping_merged_sites_rel0p80_bonferroni_0p05"])
                total_reg6 += int(sc["significant_hits_rel0p80_region_wide_bonferroni_0p05"])
                for h_p in sc["all_significant_hits"]:
                    s1 = int(h_p["start_1based_in_window"])
                    e1 = int(h_p["end_1based_in_window"])
                    ov_u2 = not (e1 < u2_prom_span[0] or s1 > u2_prom_span[1])
                    in_u2 = (s1 >= u2_prom_span[0] and e1 <= u2_prom_span[1])
                    ov_eef = not (e1 < eef_prom_span[0] or s1 > eef_prom_span[1])
                    if h_p["passes_region_wide_bonferroni_0p05"] and not ov_u2 and not ov_eef:
                        wholly_non_prom_6pwm += 1
                    if mid == "MA0050.2" and ov_u2 and not in_u2 and (h_p["passes_rel_score_0p80_and_p_le_0p05"] or h_p["passes_region_wide_bonferroni_0p05"]):
                        boundary_irf1_hits.append({
                            "matrix_id": mid,
                            "tf_name": str(h_p["tf_name"]),
                            "start_1based": s1,
                            "end_1based": e1,
                            "strand": str(h_p["strand"]),
                            "relative_score_0_to_1": float(h_p["relative_score_0_to_1"]),
                            "p_adj_1pwm": float(h_p["bonferroni_window_p_value"]),
                            "p_adj_6pwm": float(h_p["bonferroni_region_across_all_matrices_p_value"]),
                            "passes_1pwm_0p05": bool(h_p["passes_rel_score_0p80_and_p_le_0p05"]),
                            "passes_6pwm_0p05": bool(h_p["passes_region_wide_bonferroni_0p05"]),
                        })
                    if mid == "MA0139.1" and (h_p["passes_rel_score_0p80_and_p_le_0p05"] or h_p["passes_region_wide_bonferroni_0p05"]):
                        if not (e1 < chs4_span[0] or s1 > chs4_span[1]):
                            ctcf_ins_hits["cHS4"] = {
                                "matrix_id": mid,
                                "start_1based": s1,
                                "end_1based": e1,
                                "strand": str(h_p["strand"]),
                                "relative_score_0_to_1": float(h_p["relative_score_0_to_1"]),
                                "p_adj_1pwm": float(h_p["bonferroni_window_p_value"]),
                                "p_adj_6pwm": float(h_p["bonferroni_region_across_all_matrices_p_value"]),
                            }
                        elif not (e1 < dm1_span[0] or s1 > dm1_span[1]):
                            ctcf_ins_hits["DM1"] = {
                                "matrix_id": mid,
                                "start_1based": s1,
                                "end_1based": e1,
                                "strand": str(h_p["strand"]),
                                "relative_score_0_to_1": float(h_p["relative_score_0_to_1"]),
                                "p_adj_1pwm": float(h_p["bonferroni_window_p_value"]),
                                "p_adj_6pwm": float(h_p["bonferroni_region_across_all_matrices_p_value"]),
                            }
            if wholly_non_prom_6pwm != 0:
                raise ValueError(f"Unexpected wholly non-promoter 6-PWM hit on {cid}: {wholly_non_prom_6pwm}")
            pwm_summary = {
                "counts_window_merged_region6_total": [total_win, total_merged, total_reg6],
                "exact_family_total_tests": exact_family_tests,
                "wholly_non_promoter_6pwm_hits": wholly_non_prom_6pwm,
                "promoter_boundary_irf1_hits": boundary_irf1_hits,
                "ctcf_insulator_hits": ctcf_ins_hits,
                "scope_note": "Descriptive part-resolved 6-PWM JASPAR annotation only (IIP-0027 / DEC-107; never a motif-count stopping rule).",
            }

        entry: Dict[str, Any] = {
            "construct_id": cid,
            "donor_length_bp": dlen,
            "itr_pair_nominal_bp": 290,
            "nominal_aav6_packaged_bp": dlen + 290,