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…

#!/usr/bin/env python3
"""
Layer 2: Single-Cell Perturbation & Regulatory Sequence Plane (v0.8.0)
======================================================================
Performs deterministic regulatory sequence grammar analysis, background-calibrated
JASPAR log-odds PWM motif scanning, quarantined archival-table metadata (no authenticated AVI model predictions),
authentic non-overlapping GRCh38 homology-arm & GenBank regulatory-element construct
assembly, translated/processed polypeptide ledger verification, and data-driven
Stage 0->7 Monte Carlo perturbation modeling across all 6 HIP-Core factors (X1..X6),
Scenario A (Arm 1A vs Arm 1B), Scenario B (HLA-C + TYK2 P1104A vs TYK2-/-), and
cadaveric UP421 benchmarks.

Outputs:
  - data/constructs/islet1_scenario_a_constructs_v0.7.0.fasta
  - data/extracted/layer2_regulatory_and_perturbation_atlas.json
"""

from __future__ import annotations

import hashlib
import json
import math
import random
import re
import copy
import difflib
import sys
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))
from scripts.product_contract import get_product_definition
REF_PATH = REPO_ROOT / "data" / "raw" / "layer2_genomic_and_jaspar_reference.json"
AVI_ARCHIVE_PATH = REPO_ROOT / "data" / "raw" / "alphagenome_avi_3118_snvs_full_archive.json"
AVI_SEED_PATH = REPO_ROOT / "data" / "raw" / "alphagenome_avi_26_seed_anchors.json"
RING1_EFFECTS_PATH = REPO_ROOT / "data" / "extracted" / "ring1_atomic_effects_v0.5.jsonl"
FASTA_OUT = REPO_ROOT / "data" / "constructs" / "islet1_scenario_a_constructs_v0.7.0.fasta"
ATLAS_OUT = REPO_ROOT / "data" / "extracted" / "layer2_regulatory_and_perturbation_atlas.json"

AAV6_PACKAGING_LIMIT_BP = 4700
AAV2_TWO_ITRS_LENGTH_BP = 290  # 2 x 145 bp AAV2 inverted terminal repeats

# Human-optimized codon table avoiding canonical GTAAGT/GTGAGT splice donors and AATAAA/ATTAAA hexamers
CODON_TABLE = {
    "A": "GCC",
    "C": "TGC",
    "D": "GAC",
    "E": "GAG",
    "F": "TTC",
    "G": "GGC",
    "H": "CAC",
    "I": "ATC",
    "K": "AAG",
    "L": "CTG",
    "M": "ATG",
    "N": "AAC",
    "P": "CCC",
    "Q": "CAG",
    "R": "AGA",
    "S": "AGC",
    "T": "ACC",
    "V": "GTG",
    "W": "TGG",
    "Y": "TAC",
    "*": "TGA",
}

GENETIC_CODE = {
    "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
    "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
    "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
    "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
    "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
    "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
    "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
    "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
    "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
    "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
    "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
    "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
    "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
    "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
    "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
    "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
}

COMPLEMENT = str.maketrans("ACGTacgt", "TGCAtgca")

# Frozen native sequence identities for the four v0.7.0 reference donors. These
# match UniProt REST records checked on 2026-10-26; a new biological sequence
# requires a separately reviewed reference contract, not resealed local hashes.
REFERENCE_UNIPROT_SEQUENCE_SHA256 = {
    "P61769": "c319ce623de7d59e9e73c6daf7ec603d5e5ed48358f54b97d1eccdc3c9bf693b",
    "P13747": "c44ad4cd8d5338b0dfd0c9e1bf242e7a650b209b7af90aaf304e9f8a95f43903",
    "Q08722": "caa66c8069880514fd225b7c8673a1f4877dbfc3e15d10e69400cb453a226918",
    "P08174": "989a894cc61bee9971c93b7be051d4d3718d7955ce6e3bb5f2d157377072f96f",
    "P50453": "5941182405e96639c6b0faccdeee7b72d773cd2ab67405bb49143592bebc6567",
    "Q9NZQ7": "b1b17c7fca3cbab15bc66b90bd4c07f73617cb5a03db105b0a38084fe7bca48b",
    "P55211": "4abebcd6fb389b5c4032e147846f854685da6000c7028e0622e8a1612a03006c",
}
FKBP12_F36V_REFERENCE_AA = (
    "MGVQVETISPGDGRTFPKRGQTCVVHYTGMLEDGKKVDSSRDRNKPFKFMLGKQEVIRGWEEGVAQMSVGQRAKLTISPDYAYGATGHPGIIPPHATLVFDVELLKLE"
)
# Precursor pins also let a source-free Layer-3 replay validate the fixed donor
# contract without adding an undeclared dependency on the private raw registry.
REFERENCE_CODING_MODULE_SHA256 = {
    "HLAE_": "a55d6e121d4528648c606fab355bf63a701581116f04898af5249bbdbefe8177",
    "CD47_": "14c634833d8775819193419862c3950d6f54395c0e696d75748a0d06c3f767b3",
    "SERPINB9_": "5941182405e96639c6b0faccdeee7b72d773cd2ab67405bb49143592bebc6567",
    "PDL1_": "b1b17c7fca3cbab15bc66b90bd4c07f73617cb5a03db105b0a38084fe7bca48b",
    "iCasp9_": "9c658142531fb4fbad7b80d7c94d412118e2a878122ab6795bbac88035e836de",
    "GSG_P2A_": "e806ad4825f52e7cb20f76a0d30b20726f1195b96951f4037b298eefb4678fbe",
}
# These pins identify the existing engineered noncoding parts, not native
# authenticity or regulatory function. cHS4/WPRE/UCOE qualifications stay open.
REFERENCE_REGULATORY_PART_SHA256 = {
    "CBX3_A2UCOE_455bp_exact": "6a4a4ad89dc417532b4066c02f8ff660a30706d7e56691e1d376cfb72e79b0d9",
    "Chimeric_Intron_133bp": "a46bca743cba139b9cef7954e012f8ddf4b0609d56c47a5bb91d51d78dff58fb",
    "EEF1A1_core_promoter_230bp": "442aed90cfa20b0191ffeb9037d6016484b960efa959fb571504d02f66fc0745",
    "EEF1A1_core_promoter_230bp_antisense": "6c4b15213b228123bb51d8a26ddb45bd70bcf9f6b3cc67515e530885bd977808",
    "Kozak_9bp": "cf9f348bff321c0460f13f1a1fc4a193a633bd5532ab1676b2c2b77f01c0927f",
    "Kozak_9bp_antisense": "af1f38a376b2eadf7e730edd35940b6f843bd455fd23420d396675f8daec7185",
    "Kozak_9bp_sense": "cf9f348bff321c0460f13f1a1fc4a193a633bd5532ab1676b2c2b77f01c0927f",
    "SV40_late_polyA_122bp": "1e40252e8e5ff79ec2bbb84173ff4ff7e91623f30aef1666051ee98f6c8bc104",
    "SV40_late_polyA_122bp_antisense": "10ebd192b4edc8d91605d14f01d4edc42593a86406870c7d4088bdaa9f6435b9",
    "Syn_5xISRE_minP_148bp_sense": "03ec65848c93e23b8f5e830507c03a955b7e3c2fdce6c5e6c49ad06ad1afa759",
    "WPREmut6_589bp": "48fc761bd6537412375cbc56540b431a5d4206c72253177bd9f0223193703147",
    "bGH_polyA_225bp": "b63940ada3015ada7b956ccad4248b484fdd4a9ab43f6573d9bd6a76a5a492d7",
    "bGH_polyA_225bp_sense": "b63940ada3015ada7b956ccad4248b484fdd4a9ab43f6573d9bd6a76a5a492d7",
    "cHS4_core_insulator_250bp": "e75bdfa12a3b96c7a3611daf366d05bff61905e45f6433667f74feccfe38e357",
}
# All eight intervals and strand-specific sequences matched Ensembl GRCh38
# REST on 2026-10-26. The pin must not be supplied by the input it authenticates.
REFERENCE_HOMOLOGY_REGISTRY_SHA256 = "36c4f0ae286cb2f6421a99ee1126a9f66f175b12f91395f86d3d539079a456f2"


def revcomp(seq: str) -> str:
    return str(seq).upper().translate(COMPLEMENT)[::-1]


def sha256_str(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def validated_reference_coding_modules(ref: Dict[str, Any]) -> Dict[str, str]:
    """Bind named precursor identities before applying expected processing slices.

    Native sequence identity supports the declared reference calculation; it
    does not establish signal cleavage, GPI attachment or 2A skipping in cells.
    """
    proteins = ref.get("uniprot_protein_sequences")
    if not isinstance(proteins, dict):
        raise ValueError("Reference UniProt protein records are required")
    native = {}
    for accession, digest in REFERENCE_UNIPROT_SEQUENCE_SHA256.items():
        entry = proteins.get(accession)
        sequence = entry.get("sequence") if isinstance(entry, dict) else None
        if (not isinstance(sequence, str) or sha256_str(sequence) != digest
                or entry.get("uniprot_id") != accession
                or type(entry.get("length_aa")) is not int or entry["length_aa"] != len(sequence)):
            raise ValueError(f"Native protein differs from the frozen reference identity: {accession}")
        native[accession] = sequence
    return {
        "HLAE_": (native["P61769"][:20] + "VMAPRTLVL" + "GGGGS" * 3
                  + native["P61769"][20:119] + "GGGGS" * 4 + native["P13747"][21:358]),
        "CD47_": native["Q08722"][:138] + native["P08174"][344:381],
        "SERPINB9_": native["P50453"],
        "PDL1_": native["Q9NZQ7"],
        "iCasp9_": FKBP12_F36V_REFERENCE_AA + "SGGGSG" + native["P55211"][134:416],
        "GSG_P2A_": "GSGATNFSLLKQAGDVEENPGP",
    }


def summarize_prior_draws(samples: List[float]) -> Dict[str, float]:
    """Empirical median and type-7 interpolated p10/p90 of finite prior draws."""
    if not isinstance(samples, (list, tuple)) or not samples:
        raise ValueError("Prior interval requires a nonempty sequence of finite numeric draws")
    try:
        if any(isinstance(x, bool) or not isinstance(x, (int, float)) for x in samples):
            raise ValueError("Prior draws must be numeric, not booleans or strings")
        values = sorted(float(x) for x in samples)
    except (TypeError, ValueError, OverflowError) as exc:
        raise ValueError("Prior draws exceed the finite numeric domain") from exc
    if not all(math.isfinite(x) for x in values):
        raise ValueError("Prior draws must be finite")

    def quantile(probability: float) -> float:
        index = (len(values) - 1) * probability
        lower = int(index)
        fraction = index - lower
        upper = min(lower + 1, len(values) - 1)
        return round((1.0 - fraction) * values[lower] + fraction * values[upper], 3)

    return {"median": quantile(0.5), "p10": quantile(0.1), "p90": quantile(0.9)}


def back_translate_clean(aa_seq: str, include_stop: bool = False) -> str:
    """Deterministically back-translate amino acid sequence to human codons."""
    if not isinstance(aa_seq, str) or not aa_seq or any(aa not in CODON_TABLE for aa in aa_seq):
        raise ValueError("A nonempty canonical amino-acid sequence is required")
    if type(include_stop) is not bool:
        raise TypeError("include_stop must be a boolean")
    codons = [CODON_TABLE[aa] for aa in aa_seq]
    if include_stop:
        codons.append("TGA")
    dna = "".join(codons)
    for bad in ("GTAAGT", "GTGAGT", "AATAAA", "ATTAAA"):
        if not (bad not in dna):
            raise ValueError(f"Unexpected motif {bad} in back-translated ORF")
    return dna


def translate_dna(dna: str) -> str:
    if not isinstance(dna, str) or not dna or any(base not in "ACGT" for base in dna):
        raise ValueError("Coding DNA must be a nonempty uppercase A/C/G/T sequence")
    if not (len(dna) % 3 == 0):
        raise ValueError(f"Coding DNA length {len(dna)} is not a multiple of 3")
    out = []
    for i in range(0, len(dna), 3):
        out.append(GENETIC_CODE[dna[i : i + 3]])
    return "".join(out)


def count_cpg(seq: str) -> Tuple[int, float, float]:
    n = len(seq)
    if n < 2:
        return 0, 0.0, 0.0
    c_cnt = seq.count("C")
    g_cnt = seq.count("G")
    gc_pct = 100.0 * (c_cnt + g_cnt) / n
    cpg_cnt = sum(1 for i in range(n - 1) if seq[i : i + 2] == "CG")
    expected = (c_cnt * g_cnt) / float(n) if (c_cnt * g_cnt) > 0 else 0.0
    oe_ratio = cpg_cnt / expected if expected > 0 else 0.0
    return cpg_cnt, round(gc_pct, 2), round(oe_ratio, 4)


def _parse_grch38_coord(source_acc: str) -> Optional[Tuple[str, int, int, str]]:
    """Parse `GRCh38:<chrom>:<start>-<end>:<strand>` from a construct part provenance string."""
    m = re.fullmatch(r"GRCh38:(chr(?:[1-9][0-9]*|X|Y|M)):(\d+)-(\d+):([+-]?1|[+-])", str(source_acc))
    if not m:
        return None
    chrom, s_str, e_str, strand = m.group(1), m.group(2), m.group(3), m.group(4)
    return chrom, int(s_str), int(e_str), "-1" if strand in ("-", "-1") else "+1"


CANONICAL_CONSTRUCT_IDS = frozenset({
    "LOCUS1_ARM1A_TPT2A_BICISTRONIC", "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01",