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…
ds = sum(nn[s[i : i + 2]][1] for i in range(len(s) - 1))
for end in (s[0], s[-1]):
if end in "GC":
dh += 0.1
ds += -2.8
else:
dh += 2.3
ds += 4.1
ds_salt = ds + 0.368 * (len(s) - 1) * math.log(na_mm / 1000.0)
return round((dh * 1000.0) / (ds_salt + 1.987 * math.log(oligo_nm * 1e-9 / 4.0)) - 273.15, 2)
def translate_strict_cds(cds: str, expect_terminal_stop: bool) -> str:
s = cds.upper()
if len(s) == 0 or len(s) % 3 != 0:
raise ValueError(f"Invalid CDS length: {len(s)}")
aa = "".join(GENETIC_CODE[s[i : i + 3]] for i in range(0, len(s), 3))
if expect_terminal_stop:
if not aa.endswith("*") or "*" in aa[:-1]:
raise ValueError("Expected single terminal stop codon")
else:
if "*" in aa:
raise ValueError("Unexpected stop codon in stop-less upstream 2A cistron")
return aa
def enumerate_junction_peptides(left_aa: str, linker_aa: str, right_aa: str) -> Dict[str, Any]:
"""
Deterministically enumerate all unique-position 8..11-mer (Class I) and 15-mer (Class II)
sliding windows that cross a single boundary (when linker_aa == '') or overlap BOTH a
synthetic linker segment AND at least one flanking residue (when linker_aa != '').
"""
full = left_aa + linker_aa + right_aa
len_left = len(left_aa)
len_link = len(linker_aa)
n = len(full)
def _windows_for_k(k: int) -> List[str]:
wins = []
for s in range(0, n - k + 1):
e = s + k
if len_link == 0:
if s <= len_left - 1 and e - 1 >= len_left:
wins.append(full[s:e])
else:
overlaps_linker = (s <= len_left + len_link - 1) and (e - 1 >= len_left)
overlaps_flank = (s < len_left) or (e - 1 >= len_left + len_link)
if overlaps_linker and overlaps_flank:
wins.append(full[s:e])
return wins
w_by_k = {k: _windows_for_k(k) for k in (8, 9, 10, 11, 15)}
return {
"count_8_to_11mer": sum(len(w_by_k[k]) for k in (8, 9, 10, 11)),
"counts_by_length": {str(k): len(w_by_k[k]) for k in (8, 9, 10, 11, 15)},
"count_15mer": len(w_by_k[15]),
"sample_9mers": w_by_k[9][:5],
"sample_15mers": w_by_k[15][:3],
}
def validate_p1_to_p4_fail_closed(
design_id: str,
donor_seq: str,
expected_orfs: List[Dict[str, Any]],
junction_specs: List[Dict[str, Any]],
parent_8_11mer_count: int,
parent_15mer_count: int,
r01_canonical_8_11mer_count: int,
r01_canonical_15mer_count: int,
pdb_refs: List[str],
unresolved_structural_flags: List[str],
) -> Dict[str, Any]:
"""
Fail-closed 4-point protein/packaging/provenance validator (P1-P4) for knock-in donors:
- P1: Rejects empty donor/ORFs, enforces packaged AAV6 <= 4,700 bp, binds every declared
ORF to its exact donor slice & parent protein, and rejects undeclared >=300-nt
Kozak-initiated cargo ORFs on either strand.
- P2: Enforces strict sequence/domain/length signatures on every topology_kind.
- P3: Auto-derives required chimeric/2A/linker junction counts from donor polypeptides.
- P4: Binds each topology_kind to its target-specific Layer-3 PDB subset.
"""
if not donor_seq or not expected_orfs:
raise ValueError(f"[{design_id}] Fail-closed P1: donor_seq and expected_orfs must be non-empty")
aav6_bp = len(donor_seq) + 290
if aav6_bp > 4700:
raise ValueError(f"[{design_id}] Fail-closed P1: packaged AAV6 length {aav6_bp} bp exceeds 4,700 bp engineering cap")
target_pdb_map: Dict[str, Any] = {
"TYPE1_TM_HLAE_SCT": {"3CDG", "1MHE", "3BZE"},
"GPI_ANCHORED_CD47_IGV": {"2JJS", "4CMM", "4KJY"},
"CYTOSOLIC_SERPINB9": {"1IAU", "4GA7", "8ZCR"},
"TYPE1_TM_PDL1": {"4ZQK"},
"CYTOSOLIC_ICASP9": {"1BL4", "1JXQ", "1NW9"},
}
p1_orfs = []
p2_checks = []
declared_intervals_by_strand: Dict[str, List[Tuple[int, int]]] = {"+": [], "-": []}
present_topologies = set()
required_junction_count = 0
for spec in expected_orfs:
name = spec["name"]
s0 = int(spec["start_0based"])
e0 = int(spec["end_0based"])
strand = spec["strand"]
has_stop = bool(spec["has_stop"])
parent_cds = spec["parent_cds"].upper()
if strand not in ("+", "-") or not (0 <= s0 < e0 <= len(donor_seq)):
raise ValueError(f"[{design_id}] Fail-closed P1: ORF {name} span [{s0}:{e0}] ({strand}) invalid")
extracted_cds = donor_seq[s0:e0].upper() if strand == "+" else revcomp(donor_seq[s0:e0])
if len(extracted_cds) != len(parent_cds):
raise ValueError(f"[{design_id}] Fail-closed P1: ORF {name} length mismatch vs parent")
mut_aa = translate_strict_cds(extracted_cds, expect_terminal_stop=has_stop)
wt_aa = translate_strict_cds(parent_cds, expect_terminal_stop=has_stop)
if mut_aa != wt_aa:
raise ValueError(f"[{design_id}] Fail-closed P1/P2: Non-synonymous AA change in {name}")
declared_intervals_by_strand[strand].append((s0, e0))
aa_nostop = mut_aa[:-1] if has_stop else mut_aa
nt_edits = [
{"pos_1based_cds": i + 1, "ref": parent_cds[i], "alt": extracted_cds[i]}
for i in range(len(parent_cds))
if parent_cds[i] != extracted_cds[i]
]
p1_orfs.append(
{
"orf_name": name,
"donor_span_1based": [s0 + 1, e0],
"strand_in_donor": strand,
"cds_length_bp": len(extracted_cds),
"cds_sha256": sha256_str(extracted_cds),
"protein_aa_length": len(aa_nostop),
"protein_sha256": sha256_str(mut_aa),
"aa_substitutions_vs_parent": 0,
"synonymous_nt_edits": nt_edits,
}
)
topo_kind = spec["topology_kind"]
if topo_kind not in target_pdb_map:
raise ValueError(f"[{design_id}] Fail-closed P2: Unknown topology_kind: {topo_kind}")
present_topologies.add(topo_kind)
has_downstream_2a = bool(spec.get("has_downstream_2a", False))
if has_downstream_2a:
if has_stop:
raise ValueError(f"[{design_id}] Fail-closed P2: ORF {name} cannot have both terminal stop and downstream 2A")
tail_2a = (
donor_seq[e0 : e0 + 66].upper()
if strand == "+"
else revcomp(donor_seq[max(0, s0 - 66) : s0])
)
if len(tail_2a) < 54 or "NPGP" not in "".join(
GENETIC_CODE[tail_2a[k : k + 3]] for k in range(0, len(tail_2a) - len(tail_2a) % 3, 3)
):
raise ValueError(f"[{design_id}] Fail-closed P2: Missing canonical NPGP 2A motif downstream of {name}")
required_junction_count += 1
if topo_kind == "GPI_ANCHORED_CD47_IGV":
if has_downstream_2a:
raise ValueError(f"[{design_id}] Fail-closed P2: 2A peptide forbidden downstream of GPI signal")
if (
len(aa_nostop) != 175
or not aa_nostop.startswith("MWPLVAALLLGSACCGSA")
or aa_nostop[138:147] != "PNKGSGTTS"
or aa_nostop[146] != "S"
or aa_nostop[147:] != "GTTRLLSGHTCFTLTGLLGTLVTMGLLT"
):
raise ValueError(f"[{design_id}] Fail-closed P2: CD47-IgV-GPI Ser147 omega-site or Gly148..Thr175 propeptide corrupted")
required_junction_count += 1
p2_checks.append(
{
"orf_name": name,
"signal_peptide_1_18": aa_nostop[:18],
"mature_n_term_res19": aa_nostop[18],
"cd55_stalk_139_147": aa_nostop[138:147],
"gpi_omega_residue_1based": "Ser147 (native CD55 Ser353; cleaved 28-aa propeptide is Gly148..Thr175)",
"cleaved_propeptide_148_175_len": 28,
"sequence_topology_valid": True,
"biological_processing_qualification": "PENDING_WETLAB_SEC11_PIGK_QUANTIBRITE",
}
)
elif topo_kind == "TYPE1_TM_PDL1":
if not aa_nostop.startswith("MRIFAVFIFMTYWHLLNA") or aa_nostop[18] != "F" or len(aa_nostop) != 290:
raise ValueError(f"[{design_id}] Fail-closed P2: PD-L1 SP (1..18) or mature Phe19/290-aa topology corrupted")
p2_checks.append(
{
"orf_name": name,
"signal_peptide_1_18": aa_nostop[:18],
"mature_n_term_res19": "Phe19",
"cytoplasmic_c_tail_intact": aa_nostop[-15:],
"has_downstream_2a": has_downstream_2a,
"sequence_topology_valid": True,
"biological_processing_qualification": "PENDING_WETLAB_SURFACE_PDL1_FLOW_AND_SHEDDING",
}
)
elif topo_kind == "TYPE1_TM_HLAE_SCT":
if (
len(aa_nostop) < 495
or not aa_nostop.startswith("MSRSVALAVLALLSLSGLEA")
or not aa_nostop.endswith("AEWSDSAQGSESHSL")
or aa_nostop.count("GGGGSGGGGSGGGGSGGGGS") < 1
):
raise ValueError(f"[{design_id}] Fail-closed P2: HLA-E SCT B2M-SP, G4S linkers, or cytoplasmic tail corrupted")
required_junction_count += 4
p2_checks.append(
{
"orf_name": name,
"b2m_signal_peptide_1_20": aa_nostop[:20],
"tethered_peptide_21_29": aa_nostop[20:29],
"precursor_length_aa": len(aa_nostop),
"cytoplasmic_tail_intact": "AEWSDSAQGSESHSL",
"has_downstream_2a": has_downstream_2a,
"sequence_topology_valid": True,
"biological_processing_qualification": "PENDING_WETLAB_QUANTIBRITE_HLAE_AND_NK_GATE",
}
)
elif topo_kind == "CYTOSOLIC_SERPINB9":
if len(aa_nostop) != 376 or not aa_nostop.startswith("METLSNASGTFAIRLLKILC"):
raise ValueError(f"[{design_id}] Fail-closed P2: CYTOSOLIC_SERPINB9 requires 376-aa leaderless human PI-9 sequence")
p2_checks.append(
{
"orf_name": name,
"compartment": "cytosolic_leaderless",
"has_c_terminal_2a_stub": has_downstream_2a,
"sequence_topology_valid": True,
"biological_processing_qualification": "PENDING_WETLAB_GZMB_KINETICS",
}
)
elif topo_kind == "CYTOSOLIC_ICASP9":
if len(aa_nostop) != 396 or not aa_nostop.startswith("MGVQVETISPGDGRTFPKRG") or aa_nostop[108:114] != "SGGGSG":
raise ValueError(f"[{design_id}] Fail-closed P2: CYTOSOLIC_ICASP9 requires 396-aa FKBP12(F36V)-SGGGSG-dCasp9 sequence")
required_junction_count += 1
p2_checks.append(
{
"orf_name": name,
"compartment": "cytosolic_leaderless",
"has_c_terminal_2a_stub": has_downstream_2a,
"sequence_topology_valid": True,
"biological_processing_qualification": "PENDING_WETLAB_AP1903_KILL_AND_TIER6B_ESCAPE",
}
)
if len(donor_seq) >= 1800:
c_start, c_end = 580, len(donor_seq) - 580