scripts/run_layer2_perturbation_and_regulatory_plane.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer2_perturbation_and_regulatory_plane.py · SHA-256: 3220e68f97203dbc…
"""
Fail-closed DNA-bound construct and transcript-frame validator (IIP-0026; DEC-105):
1. Requires a verified 64-hex expected_donor_sha256 matching sha256(donor_seq) before
emitting COMPUTED_FROM_DNA provenance (rejecting None or mismatched digests).
2. Enforces <= 4,700 bp packaged AAV6 (with 2x145 bp ITRs), 0 encoded 2A motifs, non-empty
orf_specs, non-overlapping same-strand declared ORFs, and non-zero mature protein slices.
3. Evaluates strand-specific transcribed_intervals and declared_cds_frame across all reading
frames on both '+' and '-' strands (inclusive of len - 300):
- Any unterminated [AG]NNATGG run open at the scanned sequence boundary fails closed
(HOLD_OPEN_BOUNDARY_KOZAK_ORF).
- Inside any declared CDS, only in-frame starts matching declared_cds_frame and
terminating at the declared stop are permitted; any internal out-of-frame >= 300-nt
[AG]NNATGG run (e.g. a 357-nt +1 run wholly inside a 600-nt CDS) fails closed
(FAIL_UNDECLARED_KOZAK_ORF).
- Any >= 300-nt [AG]NNATGG start inside a declared upstream regulatory promoter window
upstream of putative TSS (such as c1 2308-3282 or c2 2029-3003, -73 nt upstream of
PD-L1 CDS in frame 2 != 0) emits HOLD_PENDING_5PRIME_RACE_TSS while 5'-RACE is
UNRESOLVED, fails closed (FAIL_TRANSCRIBED_UPSTREAM_KOZAK_ORF_BY_5PRIME_RACE) if
observed 5'-RACE places TSS at or upstream of that ATG, and resolves cleanly only
when observed 5'-RACE places TSS strictly downstream in (tata_atg, cds_start] with
readthrough_umi_k == 0 across readthrough_umi_n_eff >= 3,689.
4. Rejects Boolean or non-positive 5'/3'-RACE coordinates, representing unmeasured empirical
transcript ends explicitly as "UNRESOLVED".
5. Computes exact unique-string peptide-set subtraction alongside positional window counts.
"""
if not isinstance(donor_seq, str) or len(donor_seq) == 0:
raise ValueError(f"[{design_id}] Empty or non-string donor_seq")
seq = donor_seq.upper()
if any(b not in "ACGT" for b in seq):
raise ValueError(f"[{design_id}] Non-ACGT base in donor")
actual_sha256 = sha256_str(seq)
if (
not isinstance(expected_donor_sha256, str)
or not re.fullmatch(r"[0-9a-f]{64}", expected_donor_sha256.lower())
or actual_sha256 != expected_donor_sha256.lower()
):
raise ValueError(
f"[{design_id}] FAIL_CONSTRUCT_SHA256_MISMATCH: expected verified 64-hex {expected_donor_sha256!r}, got {actual_sha256}"
)
aav6_bp = len(seq) + AAV2_TWO_ITRS_LENGTH_BP
if aav6_bp > AAV6_PACKAGING_LIMIT_BP:
raise ValueError(
f"[{design_id}] FAIL_AAV6_PACKAGING_CEILING_EXCEEDED: packaged {aav6_bp} bp > {AAV6_PACKAGING_LIMIT_BP} bp ceiling"
)
p2a_dna = "GGAAGCGGAGCTACTAACTTCAGCCTGCTGAAGCAGGCTGGAGACGTGGAGGAGAACCCTGGACCT"
if p2a_dna in seq or p2a_dna in revcomp(seq):
raise ValueError(f"[{design_id}] FAIL_FORBIDDEN_2A_MOTIF: donor contains GSG-P2A DNA sequence")
if not isinstance(orf_specs, list) or len(orf_specs) == 0:
raise ValueError(f"[{design_id}] HOLD_EMPTY_REQUIRED_ORF_INVENTORY: orf_specs must be non-empty")
c_start, c_end = cargo_bounds_0based
if not (_is_strict_int_iip0026(c_start) and _is_strict_int_iip0026(c_end) and 0 <= c_start < c_end <= len(seq)):
raise ValueError(f"[{design_id}] Invalid cargo_bounds_0based {cargo_bounds_0based} for len={len(seq)}")
def _validate_race_coord(val: Any, label: str) -> Any:
if val is None or val == "UNRESOLVED":
return "UNRESOLVED"
if not _is_strict_int_iip0026(val) or val <= 0 or val > len(seq):
raise ValueError(
f"[{design_id}] FAIL_INVALID_RACE_COORDINATE: {label}={val!r} must be positive int in [1, {len(seq)}] (never bool/<=0)"
)
return val
t5_status = _validate_race_coord(observed_5prime_race_end_bp, "observed_5prime_race_end_bp")
t3_status = _validate_race_coord(observed_3prime_race_end_bp, "observed_3prime_race_end_bp")
if _is_strict_int_iip0026(t5_status) and _is_strict_int_iip0026(t3_status) and t5_status >= t3_status:
raise ValueError(
f"[{design_id}] FAIL_INVALID_RACE_COORDINATE: observed 5'-RACE ({t5_status}) must precede 3'-RACE ({t3_status})"
)
umi_n_status: Any = "UNRESOLVED"
umi_k_status: Any = "UNRESOLVED"
if readthrough_umi_n_eff is not None and readthrough_umi_n_eff != "UNRESOLVED":
if not _is_strict_int_iip0026(readthrough_umi_n_eff) or readthrough_umi_n_eff <= 0:
raise ValueError(f"[{design_id}] FAIL_INVALID_UMI_DENOMINATOR: {readthrough_umi_n_eff!r}")
umi_n_status = readthrough_umi_n_eff
if readthrough_umi_k is not None and readthrough_umi_k != "UNRESOLVED":
if not _is_strict_int_iip0026(readthrough_umi_k) or readthrough_umi_k < 0:
raise ValueError(f"[{design_id}] FAIL_INVALID_UMI_COUNT: {readthrough_umi_k!r}")
umi_k_status = readthrough_umi_k
n_full = len(seq)
declared_by_strand: Dict[str, List[Tuple[int, int]]] = {"+": [], "-": []}
declared_strand_oriented: Dict[str, List[Tuple[int, int, int]]] = {"+": [], "-": []}
mature_proteins: List[str] = []
precursor_proteins: List[str] = []
orf_reports: List[Dict[str, Any]] = []
layer3_identity_map: Dict[str, bool] = {}
for spec in orf_specs:
s0, e0, st = spec.get("start_0based"), spec.get("end_0based"), spec.get("strand")
if st not in ("+", "-") or not _is_strict_int_iip0026(s0) or not _is_strict_int_iip0026(e0):
raise ValueError(f"[{design_id}] Invalid strand/coord types in {spec.get('name')}")
if not (c_start <= s0 < e0 <= c_end):
raise ValueError(
f"[{design_id}] ORF {spec['name']} [{s0}:{e0}] falls outside cargo bounds [{c_start}:{c_end}]"
)
for prev_s0, prev_e0 in declared_by_strand[st]:
if max(s0, prev_s0) < min(e0, prev_e0):
raise ValueError(f"[{design_id}] Overlapping same-strand declared ORFs on {st}: [{s0}:{e0}]")
raw_cds = seq[s0:e0] if st == "+" else revcomp(seq[s0:e0])
aa_full = _translate_strict_cds_iip0026(raw_cds, expect_terminal_stop=spec.get("has_stop", True))
if "GDVEENPGP" in aa_full or "EGRGSLLTCGDVEENPGP" in aa_full:
raise ValueError(f"[{design_id}] FAIL_FORBIDDEN_2A_MOTIF: 2A peptide motif in {spec['name']}")
if aa_full != spec["expected_precursor_aa"]:
raise ValueError(f"[{design_id}] Translation mismatch on {spec['name']}")
mat_slice = spec.get("mature_slice_0based", (0, len(aa_full)))
if (
not isinstance(mat_slice, (tuple, list))
or len(mat_slice) != 2
or not _is_strict_int_iip0026(mat_slice[0])
or not _is_strict_int_iip0026(mat_slice[1])
or not (0 <= mat_slice[0] < mat_slice[1] <= len(aa_full))
):
raise ValueError(
f"[{design_id}] FAIL_ZERO_OR_INVALID_MATURE_PROTEIN_SLICE on {spec['name']}: {mat_slice!r} for len={len(aa_full)}"
)
aa_mature = aa_full[mat_slice[0] : mat_slice[1]]
if len(aa_mature) == 0:
raise ValueError(f"[{design_id}] FAIL_ZERO_OR_INVALID_MATURE_PROTEIN_SLICE on {spec['name']}")
precursor_proteins.append(aa_full)
mature_proteins.append(aa_mature)
declared_by_strand[st].append((s0, e0))
st_s0 = s0 if st == "+" else (n_full - e0)
st_e0 = e0 if st == "+" else (n_full - s0)
decl_frame = st_s0 % 3
declared_strand_oriented[st].append((st_s0, st_e0, decl_frame))
ref_key = spec["reference_key"]
if ref_key not in pinned_layer3_sequences:
raise ValueError(f"[{design_id}] Unknown Layer-3 reference_key {ref_key!r}")
is_ident = bool(aa_full == pinned_layer3_sequences[ref_key])
if require_layer3_identity and not is_ident:
raise ValueError(f"[{design_id}] FAIL_LAYER3_POLYPEPTIDE_MISMATCH on {spec['name']} vs {ref_key}")
layer3_identity_map[spec["name"]] = is_ident
orf_reports.append(
{
"name": spec["name"],
"strand": st,
"coords_1based": [s0 + 1, e0],
"declared_cds_frame": decl_frame,
"precursor_aa_len": len(aa_full),
"mature_aa_len": len(aa_mature),
"precursor_sha256": sha256_str(aa_full),
"identical_to_pinned_reference": is_ident,
}
)
upstream_promoter_windows_plus: List[Dict[str, Any]] = []
normalized_tx_units: List[Dict[str, Any]] = []
if transcribed_intervals is not None:
if not isinstance(transcribed_intervals, list) or len(transcribed_intervals) == 0:
raise ValueError(f"[{design_id}] transcribed_intervals must be non-empty when supplied")
for u in transcribed_intervals:
u_st = u.get("strand")
ptx = u.get("putative_transcribed_1based")
dcds = u.get("declared_cds_1based")
if (
u_st not in ("+", "-")
or not isinstance(ptx, (tuple, list))
or len(ptx) != 2
or not (_is_strict_int_iip0026(ptx[0]) and _is_strict_int_iip0026(ptx[1]) and 1 <= ptx[0] < ptx[1] <= n_full)
or not isinstance(dcds, (tuple, list))
or len(dcds) != 2
or not (_is_strict_int_iip0026(dcds[0]) and _is_strict_int_iip0026(dcds[1]) and ptx[0] <= dcds[0] < dcds[1] <= ptx[1])
):
raise ValueError(f"[{design_id}] Invalid transcribed_intervals entry: {u!r}")
cds_frame = (dcds[0] - 1) % 3 if u_st == "+" else (n_full - dcds[1]) % 3
prom_up = u.get("promoter_upstream_1based")
if prom_up is not None:
if (
u_st != "+"
or not isinstance(prom_up, (tuple, list))
or len(prom_up) != 2
or not (_is_strict_int_iip0026(prom_up[0]) and _is_strict_int_iip0026(prom_up[1]))
or not (c_start + 1 <= prom_up[0] <= prom_up[1] < ptx[0])
):
raise ValueError(f"[{design_id}] Invalid promoter_upstream_1based in {u!r}")
upstream_promoter_windows_plus.append(
{
"unit_id": str(u.get("unit_id", "tx_unit")),
"promoter_start_1based": prom_up[0],
"promoter_end_1based": prom_up[1],
"putative_tss_1based": ptx[0],
"declared_cds_start_1based": dcds[0],
"declared_cds_end_1based": dcds[1],
"declared_cds_frame": cds_frame,
}
)
normalized_tx_units.append(
{
"unit_id": str(u.get("unit_id", "tx_unit")),
"strand": u_st,
"putative_transcribed_1based": [ptx[0], ptx[1]],
"promoter_upstream_1based": list(prom_up) if prom_up is not None else None,
"declared_cds_1based": [dcds[0], dcds[1]],
"declared_cds_frame": cds_frame,
}
)
seq_minus = revcomp(seq)
upstream_regulatory_kozak_records: List[Dict[str, Any]] = []
for st, full_str, scan_s0, scan_e0 in (
("+", seq, c_start, c_end),
("-", seq_minus, n_full - c_end, n_full - c_start),
):
idx_lo = max(3, scan_s0)
idx_hi_excl = min(scan_e0, n_full - 3)
for idx in range(idx_lo, idx_hi_excl):
if (
full_str[idx : idx + 3] == "ATG"
and full_str[idx - 3] in ("A", "G")
and full_str[idx + 3] == "G"
):
end_i = idx
while end_i + 3 <= n_full:
if GENETIC_CODE[full_str[end_i : end_i + 3]] == "*":
break
end_i += 3
terminated = (end_i + 3 <= n_full) and (GENETIC_CODE[full_str[end_i : end_i + 3]] == "*")
if not terminated:
raise ValueError(
f"[{design_id}] HOLD_OPEN_BOUNDARY_KOZAK_ORF: Unterminated strong-Kozak run on {st} at offset {idx}"
)
span = (end_i + 3) - idx
if span >= 300:
if st == "+":
gs0, ge0 = idx, end_i + 3
else:
gs0, ge0 = n_full - (end_i + 3), n_full - idx
run_frame = idx % 3
is_in_frame_declared_cds = any(
st_s0 <= idx < st_e0 and (run_frame == decl_fr) and ((end_i + 3) == st_e0)
for st_s0, st_e0, decl_fr in declared_strand_oriented[st]
)
if is_in_frame_declared_cds:
continue
matched_up_win = None
if st == "+":
atg_1b = gs0 + 1
for uw in upstream_promoter_windows_plus:
if uw["promoter_start_1based"] <= atg_1b <= uw["promoter_end_1based"]:
matched_up_win = uw
break