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…

                skipped_ambiguous_windows_cnt += 1
                continue
            sint = sum(col_int[j][window[j]] for j in range(w))
            score = sint / float(scale_int)
            relative_numerator = sint - min_possible_int
            rel_score = relative_numerator / support_width_int if support_width_int else 0.0
            # The 0.80 boundary is exactly 4/5 on the declared integer grid.
            # A rounded display value must not disagree with the decision at
            # a mathematically exact boundary because of decimal summation.
            passes_relative_score = support_width_int > 0 and 5 * relative_numerator >= 4 * support_width_int
            z_score = (score - null_mean) / null_sd
            p_analytical = 0.5 * math.erfc(z_score / math.sqrt(2.0))
            p_exact_markov0 = (
                _lookup_exact_tail(tail_plus, origin_plus, sint)
                if strand == "+"
                else _lookup_exact_tail(tail_minus, origin_minus, sint)
            )
            # Empirical Markov-0 2000-window tail with +1 pseudocount continuity correction (resolution floor = 1/2001)
            strand_empirical_null = empirical_null_scores if strand == "+" else empirical_null_scores_reverse
            ge_cnt = sum(1 for ns in strand_empirical_null if ns >= score - 1e-12)
            p_empirical_markov0 = (ge_cnt + 1.0) / (n_null_windows + 1.0)
            p_bonferroni_analytical = min(1.0, p_analytical * n_tests)
            p_bonferroni_exact_markov0 = min(1.0, p_exact_markov0 * n_tests)
            p_bonferroni_region_all_matrices = min(1.0, p_exact_markov0 * n_tests * max(1, n_matrices_in_scan))
            p_bonferroni_empirical = min(1.0, p_empirical_markov0 * n_tests)
            pos_1based = (i + 1) if strand == "+" else (n - i - w + 1)
            hits.append(
                {
                    "matrix_id": pwm_entry["matrix_id"],
                    "tf_name": pwm_entry["tf_name"],
                    "strand": strand,
                    "start_1based_in_window": pos_1based,
                    "end_1based_in_window": pos_1based + w - 1,
                    "matched_kmer": window,
                    "log2_odds_score": round(score, 4),
                    "relative_score_0_to_1": round(rel_score, 4),
                    "null_z_score": round(z_score, 3),
                    "analytical_gaussian_p_value_unadjusted": round(p_analytical, 6),
                    "exact_markov0_p_value_unadjusted": float(f"{p_exact_markov0:.12g}"),
                    "empirical_markov0_2000_window_p_value_unadjusted": round(p_empirical_markov0, 6),
                    "bonferroni_window_p_value": float(f"{p_bonferroni_exact_markov0:.10g}"),
                    "bonferroni_corrected_p_value_6_motifs": float(f"{p_bonferroni_region_all_matrices:.10g}"),
                    "bonferroni_region_across_all_matrices_p_value": float(f"{p_bonferroni_region_all_matrices:.10g}"),
                    "analytical_bonferroni_window_p_value": round(p_bonferroni_analytical, 6),
                    "empirical_markov0_2000_window_bonferroni_p_value": round(p_bonferroni_empirical, 6),
                    "passes_rel_score_0p80_and_p_le_0p05": bool(passes_relative_score and p_bonferroni_exact_markov0 <= 0.05),
                    "passes_region_wide_bonferroni_0p05": bool(passes_relative_score and p_bonferroni_region_all_matrices <= 0.05),
                    "passes_2000_window_mc_bonferroni_0p05": bool(passes_relative_score and p_bonferroni_empirical <= 0.05),
                    "mc_2000_window_min_achievable_bonferroni_p": round(min(1.0, (n_tests / float(n_null_windows + 1))), 6),
                    "mc_2000_window_gate_resolution_limited": bool((n_tests / float(n_null_windows + 1)) > 0.05),
                }
            )
    hits.sort(key=lambda x: (-x["log2_odds_score"], x["start_1based_in_window"]))
    sig_hits = [h for h in hits if h["passes_rel_score_0p80_and_p_le_0p05"]]
    all_significant_hits = [
        h for h in hits if h["passes_rel_score_0p80_and_p_le_0p05"] or h["passes_region_wide_bonferroni_0p05"]
    ]
    significant_count = len(sig_hits)
    significant_region_wide_count = sum(1 for h in hits if h["passes_region_wide_bonferroni_0p05"])
    distinct_loci_intervals: List[Tuple[int, int]] = []
    for sh in sig_hits:
        s_i, e_i = int(sh["start_1based_in_window"]), int(sh["end_1based_in_window"])
        if not any(max(s_i, os_i) <= min(e_i, oe_i) for os_i, oe_i in distinct_loci_intervals):
            distinct_loci_intervals.append((s_i, e_i))
    focal_family_factor = n_tests * max(1, n_matrices_in_scan)
    resolved_family_total = (
        actual_family_total_tests
        if actual_family_total_tests is not None
        else (n_tests if n_matrices_in_scan == 1 else None)
    )
    return {
        "input_sequence_length_bp": n,
        "lowercase_bases_normalized_to_uppercase_count": lowercase_normalized_cnt,
        "non_acgt_ambiguous_bases_count": non_acgt_ambiguous_cnt,
        "skipped_ambiguous_windows_count": skipped_ambiguous_windows_cnt,
        "pfm_counts_sha256": pwm_entry.get("pfm_counts_sha256"),
        "pfm_to_pwm_conversion_verified": pfm_verified,
        "scan_family_size_matrices": n_matrices_in_scan,
        "total_positions_tested_both_strands": n_tests,
        "focal_matrix_bonferroni_family_factor": focal_family_factor,
        "total_tests_across_all_scanned_matrices_in_region": resolved_family_total,
        "multiplicity_correction_scope": (
            f"Reports within-matrix two-strand window scan (2 * (L - w + 1) = {n_tests} tests) and "
            f"equal-alpha family-wise Bonferroni factor across {n_matrices_in_scan} JASPAR matrices "
            f"(focal_matrix_bonferroni_family_factor = {focal_family_factor}"
            + (
                f"; exact total windows across family = {actual_family_total_tests}"
                if actual_family_total_tests is not None
                else ""
            )
            + "; closes AUDIT-REF & 109)"
        ),
        "null_calibration_method": (
            "Exact discrete Markov-0 base-composition dynamic-programming convolution on a 0.0001-bit (10,000 units/bit) "
            "integer lattice with strand-complemented mononucleotide frequencies for reverse-complement windows "
            "(guaranteeing exact reverse-complement invariance and probability mass = 1.0; closing AUDIT-REF & AUDIT-REF)"
        ),
        "null_probability_mass_forward_strand": round(mass_plus, 12),
        "null_probability_mass_reverse_strand": round(mass_minus, 12),
        "null_background_mean_log2_odds": round(null_mean, 3),
        "null_background_sd_log2_odds": round(null_sd, 3),
        "empirical_markov0_p95_score": round(empirical_null_scores[int(0.95 * n_null_windows)], 3),
        "empirical_markov0_reverse_strand_p95_score": round(empirical_null_scores_reverse[int(0.95 * n_null_windows)], 3),
        "empirical_markov0_strand_background": "Forward windows use observed mononucleotide frequencies; reverse windows use complemented frequencies, matching the exact lattice model",
        "mc_2000_window_min_achievable_bonferroni_p": round(min(1.0, (n_tests / float(n_null_windows + 1))), 6),
        "mc_2000_window_gate_resolution_limited": bool((n_tests / float(n_null_windows + 1)) > 0.05),
        "empirical_sequence_gc_fraction": round((seq.count("G") + seq.count("C")) / max(1, len(seq)), 4),
        "null_model_gc_qualification_note": (
            "Exact DP and 2000-window MC p-values are calibrated against the observed strand mononucleotide composition "
            "while raw log2-odds weights use JASPAR's standard uniform {A:0.25,C:0.25,G:0.25,T:0.25} background denominator."
        ),
        "significant_hits_rel0p80_bonferroni_0p05": significant_count,
        "significant_window_hits_rel0p80_bonferroni_0p05": significant_count,
        "distinct_non_overlapping_significant_loci_rel0p80_bonferroni_0p05": len(distinct_loci_intervals),
        "distinct_non_overlapping_merged_sites_rel0p80_bonferroni_0p05": len(distinct_loci_intervals),
        "significant_hits_rel0p80_region_wide_bonferroni_0p05": significant_region_wide_count,
        "all_significant_hits": all_significant_hits,
        "top_hits": hits[:top_k],
    }


def verify_avi_integrity_mirror(archive: Dict[str, Any]) -> Dict[str, Any]:
    """Check two supplied copies of a private archival table; this is not model generation."""
    if not AVI_SEED_PATH.exists():
        raise FileNotFoundError(f"Missing private AVI integrity mirror: {AVI_SEED_PATH}")
    mirror = json.loads(AVI_SEED_PATH.read_text(encoding="utf-8"))
    anchors = mirror.get("seed_anchors_26", [])
    ledger = mirror.get("deterministic_window_reconstruction_ledger", {})
    if len(anchors) != 26 or set(ledger) != set(archive.get("windows", {})):
        raise ValueError("AVI supplied mirror/archival windows or highlighted-row count mismatch")
    verified_rows, digests = 0, {}
    for key, supplied in ledger.items():
        schema, values = supplied["row_schema"], supplied["compact_rows"]
        rows = values if schema == "full_variant_dict" else [dict(zip(schema, row)) for row in values]
        digest = sha256_str(json.dumps(rows, indent=2))
        if rows != archive["windows"][key]["variants"] or digest != supplied["serialized_variants_array_sha256"]:
            raise ValueError(f"AVI integrity mirror mismatch: {key}")
        if digest != archive["windows"][key]["serialized_variants_array_sha256"]:
            raise ValueError(f"AVI archival array hash mismatch: {key}")
        verified_rows += len(rows)
        digests[key] = digest
    if verified_rows != 3118:
        raise ValueError(f"Expected 3118 supplied archival rows, got {verified_rows}")
    for anchor in anchors:
        row = archive["windows"][anchor["window_name"]]["variants"][int(anchor["anchor_rank_in_window"]) - 1]
        if row["variant"] != anchor["variant"] or float(row["avi_phred"]) != float(anchor["avi_phred"]):
            raise ValueError("AVI highlighted-row mirror mismatch")
    return {"source_origin": "UNRESOLVED_ARCHIVAL_TABLE", "highlighted_reference_rows_count": len(anchors),
            "supplied_rows_count": verified_rows, "mirror_array_hashes": digests,
            "integrity_status": "SUPPLIED_COPIES_MATCH_NOT_INDEPENDENT_GENERATION",
            "origin_and_redistribution_rights": "UNVERIFIED", "model_predictions_provided": False}


# Deprecated entry points explicitly perform only an integrity-mirror check.
verify_or_regenerate_avi_3118_surrogate_archive = verify_avi_integrity_mirror
reconstruct_and_verify_avi_archive_from_seed = verify_avi_integrity_mirror


def recompute_avi_summaries_from_full_archive() -> Dict[str, Any]:
    """Public-safe quarantine metadata. No unverified archival score is a prediction input."""
    ref = json.loads(REF_PATH.read_text(encoding="utf-8"))
    window_coords = {
        "B2M_exon1_cut_window": "chr15:44711480-44711620",
        "CIITA_exon1_cut_window": "chr16:10877250-10877390",
        "CXCL10_exon1_cut_window": "chr4:76023380-76023560",
        "AAVS1_PPP1R12C_intron1_cut_window": "chr19:55115700-55115820",
        "CBX3_A2UCOE_455bp_window": "chr7:26200580-26201034",
    }
    return {
        "source": "Private archival table (non-commercial AlphaGenome output terms conflict with CC-BY-4.0 public redistribution; 9 scoped edits + 50-row random sample verified by private API receipt)",
        "source_origin": "UNRESOLVED_ARCHIVAL_TABLE",
        "origin_and_redistribution_rights": "UNVERIFIED",
        "redistribution_exclusion_reason": "ALPHAGENOME_OUTPUT_TERMS_NON_COMMERCIAL_CONFLICT_WITH_CC_BY_4_0",
        "private_live_receipt_verification": {
            "status": "LIVE_VERIFIED_BY_PRIVATE_API_RECEIPT_9_EDITS_PLUS_50_ROW_SAMPLE",
            "alphagenome_python_package_version": "0.10.0",
            "scoped_9_edits_verified": "9/9",
            "random_50_archive_rows_verified": "50/50",
            "total_exact_6decimal_matches_on_phred_raw_quantile": "59/59",
        },
        "scope_reconciliation_by_component": {
            "full_3118_row_saturation_archive": "UNRESOLVED_ARCHIVAL_TABLE / UNAVAILABLE_NO_AUTHENTICATED_MODEL_OUTPUT: full 3,118-row window-scan batch provenance was not independently re-executed across all 3,118 positions, and numeric window summaries remain null in the CC-BY-4.0 public bundle.",
            "scoped_59_variant_live_api_audit_2026_10_28": "LIVE_VERIFIED_BY_PRIVATE_API_RECEIPT_9_EDITS_PLUS_50_ROW_SAMPLE: all 9 scoped Blueprint A/B/X single-nucleotide edits plus a 50-row random archive sample (59/59 total) were independently re-queried against the live AlphaGenome Atlas API (alphagenome v0.10.0) on 2026-10-28T08:54:44Z and matched to 6 decimal places.",
            "licensing_and_evaluator_boundary": "AlphaGenome API output terms restrict outputs to non-commercial research use only, conflicting with OpenIslet's CC-BY-4.0 public data license; therefore raw numeric AVI scores are excluded from public artifacts and are never used as active evaluator ranking weights or as certification of multi-kilobase HDR insertion safety.",
        },
        "distribution_status": "PRIVATE_QUARANTINE_EXCLUDED_FROM_PUBLIC_EXPORT",
        "prediction_status": "UNAVAILABLE_NO_AUTHENTICATED_MODEL_OUTPUT",
        "supplied_rows_count": 3118, "highlighted_reference_rows_count": 26,
        "total_snvs_scored_and_archived": None,
        "seed_anchor_verification": {"seed_anchors_verified_count": None,
            "scope": "26 highlighted rows plus a full 3118-row duplicate ledger; not seed-based inference"},
        "license_and_provenance": ref["alphagenome_avi_saturation_mutagenesis_and_variants"],
        "window_saturation_mutagenesis_summaries": {
            key: {"genomic_interval_grch38": coord, "coordinate_scope": "retained archival-window label, not model validation",
                  "snvs_evaluated": None, "mean_avi_phred": None, "median_avi_phred": None,
                  "p90_avi_phred": None, "max_avi_phred": None, "snvs_ge_phred_20_high_impact": None,
                  "snvs_ge_phred_15_moderate_impact": None, "top_5_hotspot_snvs": [],
                  "prediction_status": "UNAVAILABLE_NO_AUTHENTICATED_MODEL_OUTPUT"}
            for key, coord in window_coords.items()},
        "single_variant_queries": {"TYK2_rs34536443_P1104A": {"variant_id": "chr19:10352442:G>C",
            "rsid": "rs34536443", "avi_raw": None, "avi_phred": None, "avi_percentile": None,
            "prediction_status": "UNAVAILABLE_NO_AUTHENTICATED_MODEL_OUTPUT"}},
        "gencode_v46_transcript_models_pinned": ref["gencode_v46_transcript_models_pinned"],
        "interpretation_scope": "Reconciles three distinct scopes: (1) the full 3,118-row window-scan archive has incomplete batch provenance (source_origin = UNRESOLVED_ARCHIVAL_TABLE) and its window-level prediction_status is UNAVAILABLE_NO_AUTHENTICATED_MODEL_OUTPUT; (2) a limited 28 Oct 2026 live API re-run (alphagenome v0.10.0) independently verified all 9 scoped Blueprint A/B/X single-letter edits and a 50-row random archive sample (59/59 exact 6-decimal matches on avi_phred, avi_raw, and avi_quantile); and (3) numeric AVI outputs are omitted from the CC-BY-4.0 public bundle because AlphaGenome output terms permit non-commercial research use only, and no AVI score is used as an active ranking weight or as certification of HDR insertion safety.",
    }


def build_constructs(ref: Dict[str, Any], avi_summary: Dict[str, Any]) -> Dict[str, Any]:
    """
    Assemble and audit authentic HDR donor sequences from verified GRCh38 non-overlapping
    homology arms, NCBI GenBank regulatory elements, and UniProt canonical proteins.
    Closes V70-01, V70-02, V70-03, V70-05, R01, AUDIT-REF, 007, 022, 066, 067, 068, 069.
    """
    uniprot = ref["uniprot_protein_sequences"]
    validated_reference_coding_modules(ref)
    elems = ref["ensembl_verified_homology_arms_and_elements"]
    ha_registry = validate_homology_arm_sources(ref)
    def ha_source(key: str) -> str:
        e = ha_registry[key]
        return f"GRCh38:{e['chrom']}:{e['start_1based']}-{e['end_1based']}:{e['strand']:+d}"

    # Verified UniProt sequences (exact residue identities: CD47[138]=Ser138, CD55[345]=Pro345, closing 067)
    b2m_full = uniprot["P61769"]["sequence"]       # M1..M119 (signal M1..A20 = 20 aa, mature I21..M119 = 99 aa)
    hlae_full = uniprot["P13747"]["sequence"]      # M1..L358 (signal M1..A21 = 21 aa, full mature G22..L358 = 337 aa)
    cd47_full = uniprot["Q08722"]["sequence"]      # M1..E323 (signal M1..A18 = 18 aa, IgV+stalk Q19..S138 = 120 aa, S138='S')
    cd55_full = uniprot["P08174"]["sequence"]      # M1..T381 (C-term GPI signal P345..T381 = 37 aa, P345='P', omega-Ser353='S')
    serpinb9_full = uniprot["P50453"]["sequence"]  # M1..P376 (376 aa leaderless cytosolic)
    pdl1_full = uniprot["Q9NZQ7"]["sequence"]      # M1..T290 (signal M1..A18 = 18 aa, mature F19..T290 = 272 aa)
    casp9_full = uniprot["P55211"]["sequence"]     # M1..S416 (dCARD catalytic domain G135..S416 = 282 aa)
    if not (cd47_full[137] == "S" and cd55_full[344] == "P" and cd55_full[352] == "S"):
        raise ValueError('Molecular source invariant failed: cd47_full[137] == "S" and cd55_full[344] == "P" and cd55_full[352] == "S"')

    # 1. Full-length mature HLA-E*01:03(VMAPRTLVL) Single-Chain Trimer (SCT, 500 aa = 1,500 bp without stop, 1,503 bp with TGA):
    #    Retains full-length mature HLA-E residues 22..358 (including 344..358 AEWSDSAQGSESHSL cytoplasmic tail and Lys/Trp motif, closing V70-02!)
    hlae_sct_aa = (
        b2m_full[:20]           # 20 aa B2M signal peptide (M1..A20)
        + "VMAPRTLVL"           # 9 aa HLA-A2 leader peptide
        + ("GGGGS" * 3)         # 15 aa L1 linker
        + b2m_full[20:119]      # 99 aa mature B2M (I21..M119)
        + ("GGGGS" * 4)         # 20 aa L2 linker
        + hlae_full[21:358]     # 337 aa FULL-LENGTH mature HLA-E*01:03 (G22..L358, native cytoplasmic tail preserved)
    )
    if not (len(hlae_sct_aa) == 500):
        raise ValueError('Molecular source invariant failed: len(hlae_sct_aa) == 500')
    if not (hlae_sct_aa.endswith("AEWSDSAQGSESHSL")):
        raise ValueError('Molecular source invariant failed: hlae_sct_aa.endswith("AEWSDSAQGSESHSL")')

    # 2. CD47-IgV-GPI (175 aa = 528 bp with TGA stop):