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…

def _verified_refseq_panel(bundle: dict, key: str) -> Dict[str, str]:
    expected = _IIP0031_TRANSCRIPT_PINS[key]
    records = bundle.get(key)
    if not isinstance(records, dict) or records.keys() != expected.keys():
        raise ValueError(f"{key} requires the exact {len(expected)} pinned accessions")

    verified = {}
    for accession, digest in expected.items():
        row = records[accession]
        sequence = row.get("mrna_sequence") if isinstance(row, dict) else None
        if not isinstance(sequence, str) or not sequence.strip():
            raise ValueError(f"{key} accession {accession} has no transcript sequence")
        sequence = sequence.upper()
        if row.get("mrna_sha256") != digest or sha256_str(sequence) != digest:
            raise ValueError(f"{key} accession {accession} SHA-256 mismatch")
        verified[accession] = sequence
    return verified


def _verified_22gene_refseq_panel(
    bundle: dict,
) -> Tuple[Dict[str, str], Dict[str, str], Dict[str, str], Dict[str, str]]:
    """
    Validate all 22 curated human RefSeq transcripts against pinned gene symbols,
    accessions, CDS start/end coordinates, SHA-256 digests, valid ORF structure
    (ATG..STOP with zero internal stops), and strictly nonempty 3'-UTR & CDS slices.
    Returns (utr3_by_gene, cds_by_gene, utr5_by_gene, full_mrna_by_gene).
    """
    raw_panel = bundle.get("human_22_gene_refseq_panel")
    if not isinstance(raw_panel, dict) or set(raw_panel.keys()) != set(_IIP0031_HUMAN_22_REFSEQ_PINS.keys()):
        raise ValueError("human_22_gene_refseq_panel requires the exact 22 pinned human gene entries")
    utr3_map: Dict[str, str] = {}
    cds_map: Dict[str, str] = {}
    utr5_map: Dict[str, str] = {}
    full_map: Dict[str, str] = {}
    for gsym, (exp_acc, exp_cs, exp_ce, exp_sha) in _IIP0031_HUMAN_22_REFSEQ_PINS.items():
        uobj = raw_panel[gsym]
        if not isinstance(uobj, dict):
            raise ValueError(f"22-gene panel entry {gsym} must be a dict")
        if uobj.get("accession") != exp_acc:
            raise ValueError(f"22-gene panel {gsym} accession mismatch: expected {exp_acc}, got {uobj.get('accession')!r}")
        raw_seq = uobj.get("mrna_sequence")
        if not isinstance(raw_seq, str) or not raw_seq.strip():
            raise ValueError(f"22-gene panel {gsym} missing mrna_sequence")
        m_seq = raw_seq.upper()
        if not set(m_seq).issubset({"A", "C", "G", "T"}):
            raise ValueError(f"22-gene panel {gsym} contains non-ACGT bases")
        if uobj.get("mrna_sha256") != exp_sha or sha256_str(m_seq) != exp_sha:
            raise ValueError(f"22-gene panel RefSeq {gsym} ({exp_acc}) SHA-256 mismatch")
        if "cds_start_1based" not in uobj or "cds_end_1based" not in uobj:
            raise ValueError(f"22-gene panel {gsym} ({exp_acc}) missing explicit cds_start_1based or cds_end_1based")
        cs_raw = uobj["cds_start_1based"]
        ce_raw = uobj["cds_end_1based"]
        if (
            type(cs_raw) is not int
            or type(ce_raw) is not int
            or cs_raw != exp_cs
            or ce_raw != exp_ce
            or not (1 <= cs_raw < ce_raw < len(m_seq))
            or (ce_raw - cs_raw + 1) % 3 != 0
        ):
            raise ValueError(f"22-gene panel {gsym} ({exp_acc}) invalid or out-of-range CDS coordinates ({cs_raw}, {ce_raw}) for length {len(m_seq)}")
        cds_slice = m_seq[cs_raw - 1 : ce_raw]
        utr3_slice = m_seq[ce_raw:]
        utr5_slice = m_seq[: cs_raw - 1]
        if len(cds_slice) < 6 or len(utr3_slice) < 1:
            raise ValueError(f"22-gene panel {gsym} ({exp_acc}) produced an empty CDS or 3'-UTR slice")
        if cds_slice[:3] != "ATG" or cds_slice[-3:] not in ("TAA", "TAG", "TGA"):
            raise ValueError(f"22-gene panel {gsym} ({exp_acc}) CDS does not start with ATG and end with a stop codon")
        if any(cds_slice[i : i + 3] in ("TAA", "TAG", "TGA") for i in range(0, len(cds_slice) - 3, 3)):
            raise ValueError(f"22-gene panel {gsym} ({exp_acc}) CDS contains an internal in-frame stop codon")
        utr3_map[gsym] = utr3_slice
        cds_map[gsym] = cds_slice
        utr5_map[gsym] = utr5_slice
        full_map[gsym] = m_seq
    return utr3_map, cds_map, utr5_map, full_map


def _parse_fa_bytes(raw_bytes: bytes, label: str = "FASTA") -> Dict[str, str]:
    try:
        fasta_text = raw_bytes.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise ValueError(f"{label} is not valid UTF-8") from exc
    out_fa: Dict[str, str] = {}
    cid_cur: Optional[str] = None
    buf_cur: List[str] = []
    for ln in fasta_text.splitlines():
        s = ln.strip()
        if not s:
            continue
        if s.startswith(">"):
            if cid_cur is not None:
                raw_seq = "".join(buf_cur)
                if not raw_seq or not all(ch in "ACGTacgt" for ch in raw_seq):
                    raise ValueError(f"Empty or non-ACGT sequence in {label} record {cid_cur!r}")
                out_fa[cid_cur] = raw_seq.upper()
            tokens = s[1:].split()
            if not tokens:
                raise ValueError(f"Empty FASTA header in {label}")
            cid_cur = tokens[0]
            if cid_cur in out_fa:
                raise ValueError(f"Duplicate FASTA record header {cid_cur!r} in {label}")
            buf_cur = []
        else:
            if cid_cur is None:
                raise ValueError(f"Sequence data before first header in {label}")
            buf_cur.append(s)
    if cid_cur is not None:
        raw_seq = "".join(buf_cur)
        if not raw_seq or not all(ch in "ACGTacgt" for ch in raw_seq):
            raise ValueError(f"Empty or non-ACGT sequence in {label} record {cid_cur!r}")
        out_fa[cid_cur] = raw_seq.upper()
    if not out_fa:
        raise ValueError(f"Empty FASTA file: {label}")
    return out_fa


def _max_disjoint_dr(seq: str, max_k: int = 80) -> Tuple[int, Optional[Dict[str, Any]]]:
    n = len(seq)
    for k in range(min(max_k, n // 2), 0, -1):
        seen: Dict[str, int] = {}
        for i in range(n - k + 1):
            sub = seq[i : i + k]
            if sub in seen and seen[sub] + k <= i:
                return k, {"length_bp": k, "pos1_a": seen[sub] + 1, "pos1_b": i + 1, "sequence": sub}
            if sub not in seen:
                seen[sub] = i
    return 0, None


def _max_overlapping_dr(
    seq: str,
    max_k: int = 80,
    excluded_spans_0based: Tuple[Tuple[int, int], ...] = (),
) -> Tuple[int, Optional[Dict[str, Any]]]:
    n = len(seq)
    for k in range(min(max_k, n - 1), 0, -1):
        seen: Dict[str, List[int]] = {}
        for i in range(n - k + 1):
            sub = seq[i : i + k]
            for j0 in seen.get(sub, ()):
                if not any(
                    j0 >= lo and (j0 + k) <= hi and i >= lo and (i + k) <= hi
                    for (lo, hi) in excluded_spans_0based
                ):
                    return k, {"length_bp": k, "pos1_a": j0 + 1, "pos1_b": i + 1, "sequence": sub}
            seen.setdefault(sub, []).append(i)
    return 0, None


def _max_disjoint_ir(seq: str, max_k: int = 80) -> Tuple[int, Optional[Dict[str, Any]]]:
    n = len(seq)
    for k in range(min(max_k, n // 2), 0, -1):
        seen: Dict[str, int] = {}
        for i in range(n - k + 1):
            sub = seq[i : i + k]
            rc = revcomp(sub)
            if rc in seen and seen[rc] + k <= i:
                return k, {"length_bp": k, "pos1_a": seen[rc] + 1, "pos1_b": i + 1, "seq_a": rc, "seq_b": sub}
            if sub not in seen:
                seen[sub] = i
    return 0, None


def _count_disjoint_ir_ge_k(seq: str, min_k: int = 16) -> int:
    n = len(seq)
    if min_k < 1 or n < 2 * min_k:
        return 0
    pos: Dict[str, List[int]] = {}
    for i in range(n - min_k + 1):
        pos.setdefault(seq[i : i + min_k], []).append(i)
    cnt = 0
    for i in range(n - 2 * min_k + 1):
        rc_sub = revcomp(seq[i : i + min_k])
        if rc_sub in pos:
            cnt += sum(1 for j in pos[rc_sub] if j - i >= min_k)
    return cnt


def _scan_seeds(strand_s: str, targets: Dict[str, str]) -> Dict[str, Dict[str, int]]:
    if not isinstance(strand_s, str) or len(strand_s) < 8 or not all(ch in "ACGTacgt" for ch in strand_s):
        raise ValueError(f"Invalid RNAi strand sequence for seed scan: {strand_s!r}")
    strand_u = strand_s.upper()
    s7m8 = revcomp(strand_u[1:8])
    s8m = s7m8 + "A"
    s7a1 = revcomp(strand_u[1:7]) + "A"
    hits_d: Dict[str, Dict[str, int]] = {}
    for tk, ts in targets.items():
        if not isinstance(ts, str) or not all(ch in "ACGTacgt" for ch in ts):
            raise ValueError(f"Invalid target sequence for seed scan ({tk!r})")
        ts_u = ts.upper()
        nt = len(ts_u)
        c8 = sum(1 for i in range(max(0, nt - 7)) if ts_u[i : i + 8] == s8m)
        c7m8 = sum(1 for i in range(max(0, nt - 6)) if ts_u[i : i + 7] == s7m8)
        c7a1 = sum(1 for i in range(max(0, nt - 6)) if ts_u[i : i + 7] == s7a1)
        if c8 or c7m8 or c7a1:
            hits_d[tk] = {"8mer": c8, "7mer_m8": c7m8, "7mer_A1": c7a1}
    return hits_d


def build_locus2_ciita_modeb_comparators_v3_manifest(
    ref: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Build and verify the Stage-0 Locus-2 CIITA Exon-5 Mode-B v3 research comparator manifest
    100% dynamically from data/constructs/islet1_locus2_ciita_modeb_comparators_v0.8.0.fasta,
    local OpenIslet construct FASTAs, and hash-pinned GRCh38/RefSeq reference sequences in
    data/raw/layer2_genomic_and_jaspar_reference.json (IIP-0031; DEC-110).
    """
    if ref is None:
        ref = json.loads(REF_PATH.read_text(encoding="utf-8"))
    ref_bundle = ref.get("iip0031_locus2_modeb_v3_reference_bundle") if isinstance(ref, dict) else None
    if not isinstance(ref_bundle, dict):
        raise ValueError("Missing iip0031_locus2_modeb_v3_reference_bundle in layer2_genomic_and_jaspar_reference.json")
    pvr_iso_map = _verified_refseq_panel(ref_bundle, "pvr_refseq_isoforms_4")
    cd276_iso_map = _verified_refseq_panel(ref_bundle, "cd276_refseq_isoforms_4")

    fasta_rel = "data/constructs/islet1_locus2_ciita_modeb_comparators_v0.8.0.fasta"
    fasta_path = REPO_ROOT / fasta_rel
    if not fasta_path.is_file():
        raise FileNotFoundError(f"Missing pinned Locus-2 v3 comparator FASTA: {fasta_path}")
    raw_bytes = fasta_path.read_bytes()
    file_sha256 = hashlib.sha256(raw_bytes).hexdigest()
    expected_file_sha256 = "25ffcb10e2bad77a4b34725c7eff0532990ebf7b80864cf7217d33f5ccbe5b6d"
    if file_sha256 != expected_file_sha256:
        raise ValueError(f"Locus-2 v3 FASTA SHA-256 mismatch: {file_sha256} != {expected_file_sha256}")

    records = _parse_fa_bytes(raw_bytes, fasta_rel)
    expected_order = (
        "L2_V3_CO_PRIMARY_CD200",
        "L2_V3_CO_PRIMARY_MANF",
        "L2_V3_DESIGN_B_CD200",
        "L2_V3_DESIGN_B_MANF",
        "L2_V3_ALT2_CCL22",
        "L2_V3_CTRL_NT_SCRAMBLE",
        "L2_V3_BARRIER_CHS4_250",
        "L2_V3_CD274P_ZERO_TATATA",
    )
    if tuple(records.keys()) != expected_order:
        raise ValueError(f"Unexpected Locus-2 v3 FASTA record order: {list(records.keys())}")

    # 1. Authenticate full 2,001-bp GRCh38 chr16 window & cross-verify 200/200 against canonical 200-bp window:
    chr16_obj = ref_bundle.get("grch38_chr16_ciita_exon5_2001bp")
    if not isinstance(chr16_obj, dict) or not isinstance(chr16_obj.get("sequence"), str):
        raise ValueError("Missing grch38_chr16_ciita_exon5_2001bp sequence")
    chr16_seq_raw = chr16_obj["sequence"]
    if not all(ch in "ACGTacgt" for ch in chr16_seq_raw):
        raise ValueError("GRCh38 chr16 2001-bp reference contains non-ACGT bases")
    chr16_seq = chr16_seq_raw.upper()
    if (