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…
"LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01", "LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17",
})
CANONICAL_FASTA_CONSTRUCT_IDS = {
"ISLET1_LOCUS1_ARM1A_B2M_HLAE_SCT_GSGP2A_CD47_IGV_GPI_4880bp": "LOCUS1_ARM1A_TPT2A_BICISTRONIC",
"ISLET1_LOCUS1_ARM1B_B2M_BIDIR_2AFREE_CD47_IGV_GPI_HLAE_SCT_3974bp": "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01",
"ISLET1_LOCUS3_CXCL10_SERPINB9_GSGP2A_PDL1_NO_FURIN_4090bp": "LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01",
"ISLET1_LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_EEF1A1_ICASP9_3457bp": "LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17",
}
def parse_construct_fasta_text(text: str) -> Dict[str, str]:
"""Read exactly four reference donors without duplicate-ID or preamble loss."""
if not isinstance(text, str):
raise ValueError("Construct FASTA must be UTF-8 text")
records: Dict[str, str] = {}
metadata: Dict[str, Dict[str, str]] = {}
current: Optional[str] = None
for line_number, raw_line in enumerate(text.splitlines(), 1):
line = raw_line.strip()
if not line:
continue
if line.startswith(">"):
tokens = line[1:].split()
if not tokens or tokens[0] in records:
raise ValueError(f"Missing or duplicate FASTA identifier at line {line_number}")
current = tokens[0]
if current not in CANONICAL_FASTA_CONSTRUCT_IDS:
raise ValueError(f"Unknown reference construct FASTA identifier: {current}")
records[current], metadata[current] = "", {}
for token in tokens[1:]:
key, sep, value = token.partition("=")
if not sep or key not in {"length", "sha256"} or key in metadata[current]:
raise ValueError(f"Invalid or duplicate FASTA header metadata for {current}")
metadata[current][key] = value
else:
if current is None or any(base not in "ACGT" for base in line):
raise ValueError(f"FASTA sequence must follow a header and contain uppercase A/C/G/T at line {line_number}")
records[current] += line
if set(records) != set(CANONICAL_FASTA_CONSTRUCT_IDS):
raise ValueError("Construct FASTA requires exactly the four canonical reference donor IDs")
for key, sequence in records.items():
expected_length = int(re.search(r"_(\d+)bp$", key).group(1))
if len(sequence) != expected_length:
raise ValueError(f"FASTA donor length disagrees with canonical identifier: {key}")
declared = metadata[key]
if "length" in declared and declared["length"] != str(len(sequence)):
raise ValueError(f"FASTA header length mismatch: {key}")
if "sha256" in declared and declared["sha256"] != sha256_str(sequence):
raise ValueError(f"FASTA header SHA-256 mismatch: {key}")
return records
def validate_construct_fasta_binding(construct_verification: Dict[str, Any], fasta_path: Path) -> Dict[str, Any]:
"""Bind expected processed products to translations of the current donor bytes.
Self-consistent amino-acid hashes do not establish a connection to DNA.
Processing slices are expected reference products, not measured cleavage.
"""
data = Path(fasta_path).read_bytes()
if hashlib.sha256(data).hexdigest() != construct_verification.get("fasta_sha256"):
raise ValueError("Layer-2 linked FASTA hash differs from current construct bytes")
records = parse_construct_fasta_text(data.decode("utf-8"))
grammar = verify_construct_part_grammar(construct_verification)
if not grammar["all_construct_grammars_verified"]:
raise ValueError("Current donor construct grammar is invalid")
constructs = {c["construct_id"]: c for c in construct_verification["constructs"]}
coding: Dict[str, Dict[str, str]] = {}
for record_id, cid in CANONICAL_FASTA_CONSTRUCT_IDS.items():
sequence, construct = records[record_id], constructs[cid]
if len(sequence) != construct["total_length_bp"] or sha256_str(sequence) != construct.get("donor_sha256"):
raise ValueError(f"FASTA donor identity differs from construct ledger: {cid}")
coding[cid] = {}
for part in construct["part_ledger"]:
sub = sequence[part["start_1based"] - 1:part["end_1based"]]
if len(sub) != part["length_bp"] or sha256_str(sub) != part.get("sha256"):
raise ValueError(f"FASTA component identity differs from part ledger: {cid}/{part['part_name']}")
if part["part_type"] == "CDS":
aa = translate_dna(sub if part["orientation"] == "+" else revcomp(sub))
if aa != part.get("translated_aa_sequence"):
raise ValueError(f"FASTA translation differs from part ledger: {cid}/{part['part_name']}")
coding[cid][part["part_name"]] = aa
a, b, c, d = [coding[cid] for cid in CANONICAL_FASTA_CONSTRUCT_IDS.values()]
for cid, modules in coding.items():
for name, aa in modules.items():
prefixes = [prefix for prefix in REFERENCE_CODING_MODULE_SHA256 if name.startswith(prefix)]
if len(prefixes) != 1 or sha256_str(aa.removesuffix("*")) != REFERENCE_CODING_MODULE_SHA256[prefixes[0]]:
raise ValueError(f"FASTA translation differs from the named reference precursor: {cid}/{name}")
def one(parts: Dict[str, str], prefix: str) -> str:
hits = [aa for name, aa in parts.items() if name.startswith(prefix)]
if len(hits) != 1:
raise ValueError(f"Expected one translated {prefix} module")
return hits[0]
hla_a, hla_b = one(a, "HLAE_"), one(b, "HLAE_")
cd_a, cd_b = one(a, "CD47_"), one(b, "CD47_")
if hla_a != hla_b[:-1] or cd_a != cd_b:
raise ValueError("Arm 1A/1B shared protein modules differ")
p2a_a, p2a_c = one(a, "GSG_P2A_"), one(c, "GSG_P2A_")
if p2a_a != "GSGATNFSLLKQAGDVEENPGP" or p2a_c != p2a_a:
raise ValueError("Reference GSG-P2A sequence differs")
expected = {
"HLAE_0103_VMAPRTLVL_SCT_Arm1B_mature_surface": hla_b[20:-1],
"HLAE_0103_VMAPRTLVL_SCT_Arm1A_mature_with_cytosolic_P2A_stub": hla_a[20:] + p2a_a[:-1],
"CD47_IgV_GPI_mature_cell_surface": cd_a[18:147],
"SERPINB9_cytosolic_with_21aa_GSG_P2A_stub": one(c, "SERPINB9_") + p2a_c[:-1],
"PDL1_mature_cell_surface": one(c, "PDL1_")[18:-1],
"iCasp9_cytosolic_monomer": one(d, "iCasp9_")[:-1],
}
ledger = construct_verification.get("processed_polypeptide_ledger")
if not isinstance(ledger, dict) or set(ledger) != set(expected):
raise ValueError("Exactly six processed product records must bind to FASTA translations")
for key, sequence in expected.items():
entry = ledger[key]
if not isinstance(entry, dict):
raise ValueError(f"Processed product must be an object: {key}")
lengths = [entry[name] for name in ("mature_length_aa", "processed_length_aa") if name in entry]
if (sequence != entry.get("sequence") or sha256_str(sequence) != entry.get("sha256")
or not lengths or any(type(value) is not int or value != len(sequence) for value in lengths)):
raise ValueError(f"Processed polypeptide is not the expected product of current FASTA: {key}")
if not expected["HLAE_0103_VMAPRTLVL_SCT_Arm1B_mature_surface"].startswith("VMAPRTLVL"):
raise ValueError("Current HLA-E peptide differs from the named VMAPRTLVL reference analysis")
return {"status": "FASTA_TRANSLATIONS_AND_SIX_EXPECTED_PROCESSED_PRODUCTS_BOUND",
"fasta_sha256": hashlib.sha256(data).hexdigest(), "construct_count": len(records),
"processed_product_count": len(expected), "processing_status": "EXPECTED_NOT_EMPIRICALLY_MEASURED"}
def validate_homology_arm_sources(ref: Dict[str, Any]) -> Dict[str, Any]:
"""Bind raw GRCh38 intervals and bases to the retained, separately pinned source registry."""
elems = ref["ensembl_verified_homology_arms_and_elements"]
registry = ref.get("validated_homology_arm_source_registry")
required = {"B2M_HA_L_800bp", "B2M_HA_R_800bp", "B2M_HA_L_600bp", "B2M_HA_R_600bp",
"CXCL10_HA_L_600bp_minus", "CXCL10_HA_R_600bp_minus", "AAVS1_HA_L_600bp_minus", "AAVS1_HA_R_600bp_minus"}
if not isinstance(registry, dict) or set(registry) != required:
raise ValueError("Complete pinned eight-arm source registry is required")
if sha256_str(json.dumps(registry, sort_keys=True, separators=(",", ":"), allow_nan=False)) != REFERENCE_HOMOLOGY_REGISTRY_SHA256:
raise ValueError("Homology source registry differs from the frozen GRCh38 reference")
for key in sorted(required):
entry, pin = elems[key], registry[key]
start, end, strand = entry.get("start_1based"), entry.get("end_1based"), entry.get("strand")
seq = entry.get("sequence", "")
if entry.get("assembly") != "GRCh38":
raise ValueError(f"Homology assembly must be explicitly GRCh38: {key}")
if type(start) is not int or type(end) is not int or not 1 <= start <= end:
raise ValueError(f"Invalid ordered homology interval: {key}")
if type(strand) is not int or strand not in (-1, 1) or end - start + 1 != len(seq):
raise ValueError(f"Homology arm length/strand mismatch: {key}")
region = f"GRCh38:{entry.get('chrom')}:{start}-{end}:strand={strand:+d}"
if entry.get("region") != region:
raise ValueError(f"Raw interval string disagrees with typed fields: {key}")
actual = {"assembly": entry["assembly"], "chrom": entry["chrom"], "start_1based": start,
"end_1based": end, "strand": strand, "length_bp": len(seq), "sequence_sha256": sha256_str(seq)}
if actual != pin or entry.get("length_bp") != len(seq) or (entry.get("sha256") and entry["sha256"] != actual["sequence_sha256"]):
raise ValueError(f"Homology arm source identity differs from retained registry: {key}")
for left, right in [("B2M_HA_L_800bp", "B2M_HA_R_800bp"), ("B2M_HA_L_600bp", "B2M_HA_R_600bp"),
("CXCL10_HA_L_600bp_minus", "CXCL10_HA_R_600bp_minus"), ("AAVS1_HA_L_600bp_minus", "AAVS1_HA_R_600bp_minus")]:
a, b = registry[left], registry[right]
if a["assembly"] != b["assembly"] or a["chrom"] != b["chrom"] or a["strand"] != b["strand"]:
raise ValueError(f"Homology pair locus/orientation mismatch: {left}/{right}")
if max(a["start_1based"], b["start_1based"]) <= min(a["end_1based"], b["end_1based"]):
raise ValueError(f"Overlapping homology arms: {left}/{right}")
return copy.deepcopy(registry)
def compute_chs4_alignment(insert: str, ref: Dict[str, Any]) -> Dict[str, Any]:
"""Compute the native/adapted sequence ledger; coordinates are not literal proof flags."""
native = ref["primary_accession_references"]["U78775.2"]
sequence = native["sequence"]
if sha256_str(sequence) != native["sha256"]:
raise ValueError("U78775.2 primary sequence hash mismatch")
matcher = difflib.SequenceMatcher(a=insert, b=sequence, autojunk=False)
block = matcher.find_longest_match(0, len(insert), 0, len(sequence))
# Anchor the flank audit at the maximal exact block. Unconstrained short matches
# elsewhere in the 1,211-bp accession do not establish adjacent native provenance.
tail_start = block.a + block.size
native_tail_start = block.b + block.size
tail = insert[tail_start:]
best_following = (0, 0)
for skipped in range(min(8, len(sequence) - native_tail_start) + 1):
matched = 0
while (matched < len(tail) and native_tail_start + skipped + matched < len(sequence)
and tail[matched] == sequence[native_tail_start + skipped + matched]):
matched += 1
if matched > best_following[0]:
best_following = (matched, skipped)
matched, skipped = best_following
flank_ledger = {
"left_outside_block_sequence": insert[:block.a],
"left_outside_block_classification": "short sequence also present in native accession; synthetic origin not established",
"right_outside_block_sequence": tail,
"native_bases_omitted_before_following_exact_match": sequence[native_tail_start:native_tail_start + skipped],
"native_omission_interval_1based_closed": ([native_tail_start + 1, native_tail_start + skipped] if skipped else None),
"following_exact_native_sequence": tail[:matched],
"following_match_insert_interval_1based_closed": ([tail_start + 1, tail_start + matched] if matched else None),
"following_match_native_interval_1based_closed": ([native_tail_start + skipped + 1, native_tail_start + skipped + matched] if matched else None),
"remaining_engineered_tail_sequence": tail[matched:],
"remaining_tail_contains_sacii_recognition_motif": "CCGCGG" in tail[matched:],
"classification_scope": "computed sequence adaptation ledger, not an acquisition or design-intent receipt",
}
return {
"native_accession": "U78775.2", "native_accession_sequence_sha256": native["sha256"],
"insert_sequence_sha256": sha256_str(insert), "longest_exact_contiguous_match_bp": block.size,
"insert_start_1based": block.a + 1, "insert_end_1based": block.a + block.size,
"reference_start_1based": block.b + 1, "reference_end_1based": block.b + block.size,
"left_flank_outside_match_bp": block.a, "right_flank_outside_match_bp": len(insert) - block.a - block.size,
"anchored_native_adjacent_adaptation_ledger": flank_ledger,
"alignment_method": "maximal exact contiguous match plus anchored adjacent-flank audit; global SequenceMatcher diagnostics are not a phylogenetic alignment",
"alignment_operations": [{"operation": tag, "insert_interval_0based_half_open": [i1, i2],
"reference_interval_0based_half_open": [j1, j2]} for tag, i1, i2, j1, j2 in matcher.get_opcodes()],
"classification": "ENGINEERED_CHS4_DERIVED_VARIANT_NOT_EXACT_NATIVE_FRAGMENT",
"functional_insulation_status": "PREREGISTERED_PENDING",
"scope": "Outside-match bases may include native-adjacent sequence and engineered adaptation; they are not all claimed synthetic adapters.",
}
DONOR_FREQ_SS87: List[Dict[str, float]] = [
{"A": 0.33, "C": 0.36, "G": 0.19, "T": 0.12}, # -3 (C/A)
{"A": 0.60, "C": 0.13, "G": 0.13, "T": 0.14}, # -2 (A)
{"A": 0.09, "C": 0.03, "G": 0.80, "T": 0.08}, # -1 (G)
{"A": 0.00, "C": 0.00, "G": 1.00, "T": 0.00}, # +1 (G invariant in GT)
{"A": 0.00, "C": 0.00, "G": 0.00, "T": 1.00}, # +2 (T invariant in GT)
{"A": 0.59, "C": 0.03, "G": 0.35, "T": 0.03}, # +3 (A/G purine)
{"A": 0.71, "C": 0.07, "G": 0.11, "T": 0.11}, # +4 (A)
{"A": 0.07, "C": 0.05, "G": 0.84, "T": 0.04}, # +5 (G)
{"A": 0.16, "C": 0.15, "G": 0.21, "T": 0.48}, # +6 (T)
]
DONOR_MIN_SS87 = sum(min(pos.values()) for pos in DONOR_FREQ_SS87)
DONOR_MAX_SS87 = sum(max(pos.values()) for pos in DONOR_FREQ_SS87)
U1_CONSENSUS_9MER = "CAGGTAAGT"
ALLOWED_LAYER3_PDB_IDS_IIP0015 = {
"3CDG", "1MHE", "3BZE", # Complex 1: HLA-E SCT / CD94-NKG2A
"2JJS", "4CMM", "4KJY", # Complex 2: CD47 / SIRPA V1-V2
"1IAU", "4GA7", "8ZCR", # Complex 3: SERPINB9 / Granzyme B
"4ZQK", # Complex 4: PD-L1 / PD-1
"1BL4", "1JXQ", "1NW9", # Locus 4 Ref: iCasp9 domain references (FULL_FUSION_UNRESOLVED)
}
def score_5prime_donor_9mer(nine_mer: str) -> Dict[str, Any]:
"""
Open 5' splice donor metrics on a 9-mer spanning exonic [-3..-1] | intronic [+1..+6]:
- Shapiro-Senapathy consensus value (Shapiro & Senapathy 1987 PMID:3658675)
- Log2-odds bits vs uniform 0.25 background (Yeo & Burge 2004 PMID:15285897)
- Antiparallel U1 snRNA Watson-Crick + G:U/G:psi wobble pairing count across [-3..+6]
(Roca et al. 2013 PMID:23348838; heuristic prioritization rule noting
canonical GC-AG, AT-AC, and bulged/shifted U1 registers exist outside this 9-mer model).
"""