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…

                "Exon-1->Exon-2 splicing, Exon-1->cassette capture, and premature 3' cleavage at SV40pA across all arms."
            ),
            "locus4_cpg_accounting": {
                "window_a_455bp_internal_cpgs": {"wt": wina_wt.count("CG"), "codir_5nt": wina_codir_hard.count("CG"), "twostrand_7nt": wina_2strand_hard.count("CG")},
                "eef1a1_230bp_internal_cpgs": {"wt": eef_wt.count("CG"), "s3_230c": eef_230c.count("CG"), "historical_230a": eef_230a_historical.count("CG")},
                "eef1a1_230c_kozak_seam_delta_cpg": 1,
                "whole_3457bp_donor_cpgs": {"parental_l4_can": l4_can.count("CG"), "s3_l4_splice_230c": l4_splice_230c.count("CG")},
            },
            "locus4_downstream_icasp9_cds13_acceptor": icasp9_cds13_acceptor,
        },
        "aberrant_locus1_sct_to_b2m_exon2_cryptic_splice_audit": {
            "embodiment_a_star_505aa_sct1514_audit": astar_tail_audit,
            "arm1b_and_arm1c_500aa_sct1499_audit": arm1b_tail_audit,
            "candidate_window_interpretation": "Deterministic positional 8..11-mer and 15-mer candidate peptide windows; empirical MHC presentation requires wet-lab immunopeptidomics or T-cell assays.",
        },
        "portfolio_chimeric_boundary_reconciliation": {
            "nine_boundaries_8_11mer": portfolio_sum_8_11,
            "nine_boundaries_15mer_full_polypeptide": portfolio_sum_15,
            "ten_boundaries_with_hlac_l2_alpha1_15mer_full_polypeptide": portfolio_sum_15 + 14,
            "legacy_snippet_scoped_15mer_constant_retained": 136,
        },
        "validator_fail_closed_adversarial_selftests": selftests,
        "parental_open_grammar_scans": parental_open_scans,
        "qualified_mode_b_reference_derivations": qualified_constructs,
        "pam_seed_shielded_synthesis_ready_manifest": pam_shielded_manifest,
        "rtpcr_amplicon_and_ivt_umi_assay_contract": {
            "endoc_bh1_ppp1r12c_minigene_first_screen": (
                "Blinded host-context human beta-cell minigene screen in EndoC-betaH1 spanning PPP1R12C Exon 1 - Intron 1 "
                "(chr19:55115767|55115768) - Exon 2 comparing parental co-directional Window A, co-directional 5-nt + 230C, "
                "co-directional 7-nt + 230C, convergent WT-cargo, convergent 5-nt + 230C, convergent 7-nt + 230C, Window B, "
                "and No-UCOE prior to clonal hPSC scaling."
            ),
            "locus4_internal_splice_rtpcr_tm_matched_primary": {
                "forward_primer_WindowA_380_405_sense": fwd_seq,
                "forward_primer_scope": "Interrogates transcripts initiating upstream of EEF1A1 TSS (inside Window A); never used as the denominator for canonical EEF1A1-initiated iCasp9 mRNA.",
                "forward_tm_sl98_c": nearest_neighbor_tm_sl98(fwd_seq),
                "reverse_primer_iCasp9_105_125_antisense": rev_matched_seq,
                "reverse_tm_sl98_c": nearest_neighbor_tm_sl98(rev_matched_seq),
                "delta_tm_c": round(abs(nearest_neighbor_tm_sl98(fwd_seq) - nearest_neighbor_tm_sl98(rev_matched_seq)), 2),
                "unspliced_amplicon_bp": unspl_matched,
                "spliced_233nt_intron_WinA445_to_EEF222_223AG_bp": unspl_matched - 233,
                "spliced_240nt_intron_WinA445_to_EEF229_230AG_bp": unspl_matched - 240,
                "spliced_241nt_intron_historical_230A_seam_AG_bp": unspl_matched - 241,
            },
            "locus4_internal_splice_rtpcr_iCasp9_40_65_antisense_reference": {
                "forward_primer_WindowA_380_405_sense": fwd_seq,
                "reverse_primer_iCasp9_40_65_antisense": rev_legacy_seq,
                "unspliced_amplicon_bp": unspl_legacy,
                "spliced_233nt_intron_bp": unspl_legacy - 233,
                "spliced_240nt_intron_bp": unspl_legacy - 240,
                "spliced_241nt_intron_historical_230A_bp": unspl_legacy - 241,
            },
            "ivt_rna_recovery_adjusted_umi_and_tost_rules": {
                "recovery_standard_requirement": (
                    "Synthetic chimeric in vitro transcribed (IVT) RNA recovery standards spiked into total cellular RNA "
                    "prior to extraction and reverse transcription (a post-RT cDNA spike-in alone cannot qualify extraction/RT/length recovery)."
                ),
                "effective_umi_denominator_formula": "N_UMI_eff = N_UMI * min(1.0, eta_rel), where eta_rel is pre-extraction chimeric IVT RNA recovery relative to canonical reference RNA.",
                "zero_event_min_effective_umi_two_sided_95_lt_0p10pct": math.ceil(math.log(0.025) / math.log(1.0 - 0.001)),
                "nominal_3700_two_sided_95_upper_bound_pct": round(100.0 * (1.0 - 0.025 ** (1.0 / 3700.0)), 8),
                "nominal_3700_one_sided_95_upper_bound_pct": round(100.0 * (1.0 - 0.05 ** (1.0 / 3700.0)), 8),
                "host_exon_retention_equivalence_test": "Two one-sided 95% tests (90% CI TOST) strictly within [0.80, 1.25] relative to matched parental control across >= 3 independent clones per arm; any host isoform below LOQ routes to HOLD rather than passing by division noise.",
                "convergent_dsrna_and_isg_hold_ceiling": "Upper 95% confidence bound on anti-dsRNA J2 / strand-specific antisense readthrough / IFIT1-OAS1-ISG15 panel <= 1.5x unedited parental control.",
                "non_pooling_rule": "Clone-, arm-, locus-, strand-, and orientation-level measurements are evaluated without pooling across clones or conditions.",
                "tier_6b_safety_precedence": "RNA splice bounds never substitute for Tier 6A 10 nM AP1903 killing or Tier 6B N_eff >= 10^7 clonogenic escape testing.",
            },
        },
        "primary_literature_pmids": [
            "PMID:10458613", "PMID:9012826", "PMID:25580597", "PMID:25497547", "PMID:19262615",
            "PMID:10074136", "PMID:2570734", "PMID:26455413", "PMID:25605798", "PMID:28860464",
            "PMID:19904234", "PMID:28723575", "PMID:36055241", "PMID:37156915", "PMID:35795779",
            "PMID:38508139", "PMID:28504668", "PMID:1644817", "PMID:9573279", "PMID:28801671",
            "PMID:22696657", "PMID:21964334", "PMID:28462820", "PMID:32053646", "PMID:3658675",
            "PMID:15285897", "PMID:23348838", "PMID:26602187", "PMID:39382088",
        ],
    }


def _is_finite_real(value: Any) -> bool:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return False
    try:
        return math.isfinite(float(value))
    except OverflowError:
        return False


def scan_jaspar_pwm(
    seq: str,
    pwm_entry: Dict[str, Any],
    top_k: int = 3,
    n_matrices_in_scan: int = 6,
    pseudocount: float = 0.8,
    actual_family_total_tests: Optional[int] = None,
) -> Dict[str, Any]:
    """
    Scan DNA sequence on both strands with a JASPAR log2-odds PWM and calibrate
    scores against BOTH an analytical uniform background and a 2,000-window empirical
    Markov-0 mononucleotide-composition background null distribution (closes AUDIT-REF,
    AUDIT-REF, AUDIT-REF, and AUDIT-REF).
    Supports both production pseudocount alpha = 0.8 and sensitivity comparator alpha = 0.5.
    """
    if not isinstance(seq, str):
        raise TypeError("PWM scan sequence must be a string")
    if type(top_k) is not int or top_k < 0 or type(n_matrices_in_scan) is not int or n_matrices_in_scan <= 0:
        raise ValueError("PWM result limit and matrix-family size must be nonnegative/positive integers")
    if actual_family_total_tests is not None and (type(actual_family_total_tests) is not int or actual_family_total_tests < 0):
        raise ValueError("actual_family_total_tests must be a nonnegative integer when provided")
    if not _is_finite_real(pseudocount) or float(pseudocount) <= 0.0:
        raise ValueError("PWM pseudocount must be finite and positive")
    pseudocount_f = float(pseudocount)
    raw_seq = str(seq)
    lowercase_normalized_cnt = sum(1 for ch in raw_seq if ch in "acgt")
    seq = raw_seq.upper()
    non_acgt_ambiguous_cnt = sum(1 for ch in seq if ch not in "ACGT")

    if not isinstance(pwm_entry, dict):
        raise ValueError("PWM entry must be a dictionary")
    w = pwm_entry.get("length")
    if type(w) is not int or w <= 0:
        raise ValueError("PWM width must be a positive integer")
    pfm_counts = pwm_entry.get("pfm_counts")
    for label, matrix in (("log2_odds_pwm", pwm_entry.get("log2_odds_pwm")), ("pfm_counts", pfm_counts)):
        if label == "pfm_counts" and matrix is None:
            continue
        if not isinstance(matrix, dict) or set(matrix) != set("ACGT") or any(not isinstance(matrix[b], list) or len(matrix[b]) != w for b in "ACGT"):
            raise ValueError(f"{label} must have four complete A/C/G/T rows")
        if any(not _is_finite_real(v) or (label == "pfm_counts" and float(v) < 0.0) for b in "ACGT" for v in matrix[b]):
            raise ValueError(f"Invalid finite numeric values in {label}")
    if pwm_entry.get("pfm_counts_sha256") is not None:
        if not isinstance(pfm_counts, dict) or sha256_str(json.dumps(pfm_counts, sort_keys=True)) != pwm_entry["pfm_counts_sha256"]:
            raise ValueError(f"JASPAR pfm_counts_sha256 mismatch in {pwm_entry.get('matrix_id')}")
    if pwm_entry.get("pwm_matrix_sha256") is not None:
        if sha256_str(json.dumps(pwm_entry["log2_odds_pwm"], sort_keys=True, separators=(",", ":"))) != pwm_entry["pwm_matrix_sha256"]:
            raise ValueError(f"JASPAR pwm_matrix_sha256 mismatch in {pwm_entry.get('matrix_id')}")
    pfm_verified = False
    if abs(pseudocount_f - 0.8) <= 1e-9:
        pwm = pwm_entry["log2_odds_pwm"]
        if isinstance(pfm_counts, dict):
            for j in range(w):
                col_sum = sum(float(pfm_counts[b][j]) for b in "ACGT")
                for b in "ACGT":
                    expected_w = round(math.log2(((float(pfm_counts[b][j]) + 0.8) / (col_sum + 3.2)) / 0.25), 4)
                    if abs(expected_w - float(pwm[b][j])) > 5e-5:
                        raise ValueError(f"JASPAR PFM-to-PWM mismatch in {pwm_entry['matrix_id']} col {j} base {b}")
            pfm_verified = True
    else:
        if not isinstance(pfm_counts, dict):
            raise ValueError(f"Cannot recompute PWM at pseudocount={pseudocount_f} without pfm_counts in {pwm_entry.get('matrix_id')}")
        pwm = {b: [] for b in "ACGT"}
        for j in range(w):
            col_sum = sum(float(pfm_counts[b][j]) for b in "ACGT")
            for b in "ACGT":
                w_val = round(
                    math.log2(((float(pfm_counts[b][j]) + pseudocount_f) / (col_sum + 4.0 * pseudocount_f)) / 0.25),
                    4,
                )
                pwm[b].append(w_val)
        pfm_verified = True

    # Every score and null calculation must consume the same declared lattice.
    # Otherwise a rounded observed score can exceed its unrounded maximum and
    # can lie above every unrounded Monte Carlo draw of the very same word.
    if any(abs(float(value) - round(float(value), 4)) > 1e-10 for b in "ACGT" for value in pwm[b]):
        raise ValueError("PWM weights must lie on the declared 0.0001-bit lattice")
    pwm = {b: [round(float(value), 4) for value in pwm[b]] for b in "ACGT"}
    scale_int = 10000
    try:
        col_int = [{b: int(round(pwm[b][j] * scale_int)) for b in "ACGT"} for j in range(w)]
    except (ValueError, OverflowError) as exc:
        raise ValueError("PWM integer lattice exceeds the finite numeric domain") from exc
    # The six retained reference matrices use fewer than 1.4 million states.
    # Reject a wider dense lattice before allocating an input-controlled array.
    lattice_states = 1 + sum(max(column.values()) - min(column.values()) for column in col_int)
    if lattice_states > 2_000_000:
        raise ValueError("PWM exact null exceeds the supported 2,000,000-state lattice")

    max_possible_int = sum(max(column.values()) for column in col_int)
    min_possible_int = sum(min(column.values()) for column in col_int)
    support_width_int = max_possible_int - min_possible_int

    # 1. Analytical mean and SD under uniform 0.25 background
    null_mean = sum(0.25 * (pwm["A"][i] + pwm["C"][i] + pwm["G"][i] + pwm["T"][i]) for i in range(w))
    null_var = sum(
        0.25 * sum((pwm[b][i] - 0.25 * (pwm["A"][i] + pwm["C"][i] + pwm["G"][i] + pwm["T"][i])) ** 2 for b in "ACGT")
        for i in range(w)
    )
    null_sd = math.sqrt(max(null_var, 1e-9))

    # 2. Exact discrete Markov-0 base-composition convolution on an exact 0.0001-bit (10,000 units/bit)
    #    integer lattice with strand-specific mononucleotide background probabilities (base_probs_plus for '+'
    #    windows and complemented base_probs_minus for '-' windows on revcomp(seq)), closing AUDIT-REF & AUDIT-REF.
    clean_bases = [b for b in seq if b in "ACGT"] or list("ACGT")
    total_clean = float(len(clean_bases))
    base_probs_plus = {b: clean_bases.count(b) / total_clean for b in "ACGT"}
    rc_base_map = {"A": "T", "C": "G", "G": "C", "T": "A"}
    base_probs_minus = {b: base_probs_plus[rc_base_map[b]] for b in "ACGT"}

    def _build_exact_lattice_tail(b_probs: Dict[str, float]) -> Tuple[Any, int, float]:
        import numpy as np
        dist = np.array([1.0], dtype=np.float64)
        origin = 0
        for j in range(w):
            vals = col_int[j]
            lo = min(vals.values())
            hi = max(vals.values())
            out = np.zeros(len(dist) + (hi - lo), dtype=np.float64)
            for b in "ACGT":
                pb = b_probs[b]
                if pb > 0.0:
                    offset = vals[b] - lo
                    out[offset : offset + len(dist)] += pb * dist
            dist = out
            origin += lo
        total_mass = float(dist.sum())
        tail = np.minimum(1.0, np.cumsum(dist[::-1])[::-1])
        return tail, origin, total_mass

    tail_plus, origin_plus, mass_plus = _build_exact_lattice_tail(base_probs_plus)
    tail_minus, origin_minus, mass_minus = _build_exact_lattice_tail(base_probs_minus)

    def _lookup_exact_tail(tail_arr: Any, orig: int, sint: int) -> float:
        idx = sint - orig
        if idx < 0:
            return 1.0
        if idx >= len(tail_arr):
            return 0.0
        return float(tail_arr[idx])

    rng_null = random.Random(int(hashlib.sha256((pwm_entry["matrix_id"] + seq[:32]).encode("utf-8")).hexdigest()[:8], 16))
    n_null_windows = 2000
    empirical_null_scores: List[float] = []
    empirical_null_scores_reverse: List[float] = []
    for _ in range(n_null_windows):
        rw = [rng_null.choice(clean_bases) for _ in range(w)]
        empirical_null_scores.append(sum(pwm[rw[j]][j] for j in range(w)))
        empirical_null_scores_reverse.append(sum(pwm[rc_base_map[rw[j]]][j] for j in range(w)))
    empirical_null_scores.sort()
    empirical_null_scores_reverse.sort()

    hits: List[Dict[str, Any]] = []
    rc_seq = revcomp(seq)
    n = len(seq)
    n_tests = max(0, 2 * (n - w + 1))
    skipped_ambiguous_windows_cnt = 0

    for strand, s in [("+", seq), ("-", rc_seq)]:
        for i in range(n - w + 1):
            window = s[i : i + w]
            if any(b not in "ACGT" for b in window):