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…
len(chr16_seq) != 2001
or chr16_obj.get("chrom") != "chr16"
or type(chr16_obj.get("start_1based")) is not int
or chr16_obj.get("start_1based") != 10898000
or type(chr16_obj.get("end_1based")) is not int
or chr16_obj.get("end_1based") != 10900000
or type(chr16_obj.get("strand")) is not int
or chr16_obj.get("strand") != 1
or type(chr16_obj.get("length_bp")) is not int
or chr16_obj.get("length_bp") != 2001
or chr16_obj.get("region") != "GRCh38.p14:chr16:10898000-10900000:strand=+1"
or chr16_obj.get("sha256") != _IIP0031_CHR16_2001BP_SHA256
or sha256_str(chr16_seq) != _IIP0031_CHR16_2001BP_SHA256
):
raise ValueError("GRCh38 chr16 2001-bp reference SHA-256, length, or coordinate metadata mismatch")
outer_elems = ref.get("ensembl_verified_homology_arms_and_elements") if isinstance(ref, dict) else None
w200_obj = outer_elems.get("CIITA_pan_isoform_exon5_window_200bp") if isinstance(outer_elems, dict) else None
if not isinstance(w200_obj, dict) or not isinstance(w200_obj.get("sequence"), str):
raise ValueError("Missing or malformed CIITA_pan_isoform_exon5_window_200bp in ensembl_verified_homology_arms_and_elements")
w200_raw = w200_obj["sequence"]
if not all(ch in "ACGTacgt" for ch in w200_raw):
raise ValueError("CIITA_pan_isoform_exon5_window_200bp contains non-ACGT bases")
w200_pinned = w200_raw.upper()
if (
len(w200_pinned) != 200
or w200_obj.get("chrom") != "chr16"
or type(w200_obj.get("start_1based")) is not int
or w200_obj.get("start_1based") != 10898880
or type(w200_obj.get("end_1based")) is not int
or w200_obj.get("end_1based") != 10899079
or type(w200_obj.get("strand")) is not int
or w200_obj.get("strand") != 1
or type(w200_obj.get("length_bp")) is not int
or w200_obj.get("length_bp") != 200
or w200_obj.get("sha256") != _IIP0031_CIITA_EXON5_200BP_SHA256
or sha256_str(w200_pinned) != _IIP0031_CIITA_EXON5_200BP_SHA256
):
raise ValueError("CIITA_pan_isoform_exon5_window_200bp SHA-256 or coordinate metadata mismatch")
if chr16_seq[10898880 - 10898000 : 10899079 - 10898000 + 1] != w200_pinned:
raise ValueError("GRCh38 chr16 2001-bp slice disagrees with pinned CIITA_pan_isoform_exon5_window_200bp")
dm1_obj = ref_bundle.get("grch38_chr19_dm1_ctcf1_80bp")
if not isinstance(dm1_obj, dict) or not isinstance(dm1_obj.get("sequence"), str):
raise ValueError("Missing grch38_chr19_dm1_ctcf1_80bp sequence")
dm1_raw = dm1_obj["sequence"]
if not all(ch in "ACGTacgt" for ch in dm1_raw):
raise ValueError("GRCh38 chr19 DM1 CTCF1 80-bp reference contains non-ACGT bases")
dm1_seq = dm1_raw.upper()
if (
len(dm1_seq) != 80
or dm1_obj.get("chrom") != "chr19"
or type(dm1_obj.get("start_1based")) is not int
or dm1_obj.get("start_1based") != 45770299
or type(dm1_obj.get("end_1based")) is not int
or dm1_obj.get("end_1based") != 45770378
or type(dm1_obj.get("strand")) is not int
or dm1_obj.get("strand") != 1
or type(dm1_obj.get("length_bp")) is not int
or dm1_obj.get("length_bp") != 80
or dm1_obj.get("region") != "GRCh38.p14:chr19:45770299-45770378:strand=+1"
or dm1_obj.get("sha256") != _IIP0031_DM1_80BP_SHA256
or sha256_str(dm1_seq) != _IIP0031_DM1_80BP_SHA256
):
raise ValueError("GRCh38 chr19 DM1 CTCF1 80-bp reference SHA-256 or coordinate metadata mismatch")
v3_ha_bp = 375
ha_l_ref = chr16_seq[(10898967 - 10898000 + 1) - v3_ha_bp : 10898967 - 10898000 + 1]
ha_r_wt_ref = chr16_seq[10898968 - 10898000 : (10898968 - 10898000) + v3_ha_bp]
flank_up_300 = chr16_seq[(10898967 - 10898000 + 1) - v3_ha_bp - 300 : (10898967 - 10898000 + 1) - v3_ha_bp]
flank_dn_300 = chr16_seq[(10898968 - 10898000) + v3_ha_bp : (10898968 - 10898000) + v3_ha_bp + 300]
native_ir_18bp_excluded = chr16_seq[10898566 - 10898000 : 10898583 - 10898000 + 1]
if revcomp(native_ir_18bp_excluded) not in ha_l_ref:
raise ValueError("Expected native 18-bp HA_L inverted-repeat partner verification failed")
canonical_shield_154 = (
"AATAAAAGATCTTTATTTTCATTAGATCTGTGTGTTGGTTTTTTGTGTG"
+ "CTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCA"
+ "CTGGAGGGGCTGGAGGGGCTGGAGGGGCTGGAGGGGCACTGGAGGGGCTGGAGGGGCTGGAGGGG"
)
def _kmers_aa(prot: str, sizes: Tuple[int, ...]) -> set[str]:
out_k: set[str] = set()
for sz in sizes:
for idx_k in range(max(0, len(prot) - sz + 1)):
out_k.add(prot[idx_k : idx_k + sz])
return out_k
# 2. Authenticate all 8 curated human CIITA NM_* RefSeq transcripts from reference bundle:
ex5_78bp = chr16_seq[10898925 - 10898000 : 10899002 - 10898000 + 1]
cut_off_ex5 = 10898967 - 10898925 + 1 # 43 nt of constitutive 78-bp Exon-5 core in HA_L
expected_ciita_accs = (
"NM_001286402.1",
"NM_000246.4",
"NM_001286403.2",
"NM_001379330.1",
"NM_001379331.1",
"NM_001379332.1",
"NM_001379333.1",
"NM_001379334.1",
)
ciita_iso_bundle = ref_bundle.get("ciita_refseq_isoforms_8")
if (
not isinstance(ciita_iso_bundle, dict)
or len(ciita_iso_bundle) != 8
or set(ciita_iso_bundle.keys()) != set(expected_ciita_accs)
):
got_n = len(ciita_iso_bundle) if isinstance(ciita_iso_bundle, dict) else 0
raise ValueError(
f"Expected exact 8 curated human CIITA RefSeq isoforms ({list(expected_ciita_accs)}), got {got_n}"
)
ciita_iso_verified: Dict[str, Dict[str, Any]] = {}
for acc_c, rec_c in ciita_iso_bundle.items():
if not isinstance(rec_c, dict) or not isinstance(rec_c.get("mrna_sequence"), str):
raise ValueError(f"CIITA RefSeq {acc_c} missing mrna_sequence")
mrna_raw_c = rec_c["mrna_sequence"]
if not mrna_raw_c or not all(ch in "ACGTacgt" for ch in mrna_raw_c):
raise ValueError(f"CIITA RefSeq {acc_c} empty or non-ACGT mrna_sequence")
mrna_c = mrna_raw_c.upper()
exp_cs_c, exp_ce_c, exp_sha_c, exp_exons_c, exp_iso_key_c, exp_prom_map_c = _IIP0031_CIITA_REFSEQ_PINS[acc_c]
if rec_c.get("mrna_sha256") != exp_sha_c or sha256_str(mrna_c) != exp_sha_c:
raise ValueError(f"CIITA RefSeq {acc_c} SHA-256 mismatch")
cs_c, ce_c = rec_c.get("cds_start_1based"), rec_c.get("cds_end_1based")
if type(cs_c) is not int or type(ce_c) is not int or cs_c != exp_cs_c or ce_c != exp_ce_c:
raise ValueError(f"CIITA RefSeq {acc_c} CDS coordinate mismatch")
iso_key_c = rec_c.get("iso_key")
prom_map_c = rec_c.get("promoter_first_exon_mapping")
if (
not isinstance(iso_key_c, str)
or iso_key_c != exp_iso_key_c
or not isinstance(prom_map_c, str)
or prom_map_c != exp_prom_map_c
):
raise ValueError(f"CIITA RefSeq {acc_c} iso_key or promoter_first_exon_mapping mismatch")
exons_raw_c = rec_c.get("exons_1based")
if not isinstance(exons_raw_c, list) or not exons_raw_c:
raise ValueError(f"CIITA RefSeq {acc_c} missing or empty exons_1based")
parsed_exons_c: List[Tuple[int, int]] = []
expected_next_start = 1
for pair_ex in exons_raw_c:
if (
not isinstance(pair_ex, (list, tuple))
or len(pair_ex) != 2
or type(pair_ex[0]) is not int
or type(pair_ex[1]) is not int
):
raise ValueError(f"CIITA RefSeq {acc_c} malformed exon interval {pair_ex!r}")
es_i, ee_i = pair_ex[0], pair_ex[1]
if es_i != expected_next_start or ee_i < es_i or ee_i > len(mrna_c):
raise ValueError(f"CIITA RefSeq {acc_c} non-contiguous or out-of-range exon interval [{es_i}, {ee_i}]")
parsed_exons_c.append((es_i, ee_i))
expected_next_start = ee_i + 1
if expected_next_start - 1 != len(mrna_c) or tuple(parsed_exons_c) != exp_exons_c:
raise ValueError(f"CIITA RefSeq {acc_c} exons_1based mismatch against pinned RefSeq exon coordinates")
ex5_pos1 = mrna_c.find(ex5_78bp) + 1
if ex5_pos1 <= 0:
raise ValueError(f"Constitutive Exon-5 78-bp core not found in {acc_c}")
ex5_end1 = ex5_pos1 + len(ex5_78bp) - 1
matching_exons = [
(ei, es_i, ee_i, ee_i - es_i + 1)
for ei, (es_i, ee_i) in enumerate(parsed_exons_c, 1)
if es_i <= ex5_pos1 and ex5_end1 <= ee_i
]
if len(matching_exons) != 1:
raise ValueError(f"CIITA RefSeq {acc_c} Exon-5 core [{ex5_pos1}, {ex5_end1}] not wholly contained in a single exon")
ex_hit = matching_exons[0]
sp_start = (ex_hit[1] - cs_c) % 3
sp_end = (ex_hit[2] - cs_c + 1) % 3
if sp_start != 1 or sp_end != 1:
raise ValueError(f"Unexpected Exon-5 splice phase on {acc_c}: {sp_start}->{sp_end}")
cds_seq_c = mrna_c[cs_c - 1 : ce_c]
native_aa_c = translate_dna(cds_seq_c)
if native_aa_c.endswith("*"):
native_aa_c = native_aa_c[:-1]
ciita_iso_verified[acc_c] = {
"iso_key": iso_key_c,
"promoter_first_exon_mapping": prom_map_c,
"exon5_index_in_transcript": ex_hit[0],
"exon5_length_bp": ex_hit[3],
"exon5_splice_phase": f"{sp_start}->{sp_end}",
"cds_before_ex5_core": mrna_c[cs_c - 1 : ex5_pos1 - 1],
"native_aa": native_aa_c,
}
# Verify canonical cHS4-80 vs cHS4-250 combined length-and-sequence diff directly on disk:
chs4_80_slice = records["L2_V3_CO_PRIMARY_CD200"][1685:1765]
chs4_250_slice = records["L2_V3_BARRIER_CHS4_250"][1685:1935]
best_mm, best_off = min(
((sum(a != b for a, b in zip(chs4_80_slice, chs4_250_slice[i : i + 80])), i) for i in range(len(chs4_250_slice) - 79))
)
chs4_diffs = [
{
"chs4_250_pos_1based": best_off + j + 1,
"chs4_80_pos_1based": j + 1,
"u78775_2_pos_1based": best_off + j + 8,
"base_in_80bp": chs4_80_slice[j],
"base_in_250bp": chs4_250_slice[best_off + j],
}
for j in range(80)
if chs4_80_slice[j] != chs4_250_slice[best_off + j]
]
if best_mm != 2 or len(chs4_diffs) != 2:
raise ValueError(f"Expected 2-bp U78775.2 C79T/C80A diff between cHS4-80 and cHS4-250, got {chs4_diffs}")
sv40_sig = "AACTTGTTTATTGCAGCTTATAATGGTTACAAATAAAGCAATAGCATCACAAATTTCACAAATAAAGCATTTTTTTCACTGC"
bgh_sig = "CGACTGTGCCTTCTAGTTGCCAGCCATCTGTTGTTTGCCCCTCCCCCGTGCCTTCCTTGACCCTGGAAGGTGCCACTCCCAC"
two_a_sig = "GGAAGCGGAGCTACTAACTTCAGCCTGCTGAAGCAGGCTGGAGACGTGGAGGAGAACCCTGGACCT"
pwms_map = ref.get("jaspar_pwms") if isinstance(ref, dict) else None
if not isinstance(pwms_map, dict) or set(pwms_map.keys()) != set(_IIP0031_JASPAR_6PWM_PINS.keys()):
raise ValueError(
f"Missing, incomplete, or unpinned 6-PWM JASPAR reference map in layer2_genomic_and_jaspar_reference.json "
f"(expected exact keys {sorted(_IIP0031_JASPAR_6PWM_PINS.keys())}, got {sorted(pwms_map.keys()) if isinstance(pwms_map, dict) else None})"
)
for _mid_chk, (_exp_tf, _exp_len, _exp_pwm_sha, _exp_pfm_sha) in _IIP0031_JASPAR_6PWM_PINS.items():
_ment_chk = pwms_map[_mid_chk]
if not isinstance(_ment_chk, dict):
raise ValueError(f"Malformed JASPAR PWM entry for {_mid_chk}")
_l2p = _ment_chk.get("log2_odds_pwm")
_pfm = _ment_chk.get("pfm_counts")
_mlen = _ment_chk.get("length")
if (
_ment_chk.get("matrix_id") != _mid_chk
or _ment_chk.get("tf_name") != _exp_tf
or type(_mlen) is not int
or _mlen != _exp_len
or not isinstance(_l2p, dict)
or set(_l2p.keys()) != {"A", "C", "G", "T"}
or any(
not isinstance(_l2p[_b], list)
or len(_l2p[_b]) != _exp_len
or any(not _is_finite_real(_v) for _v in _l2p[_b])
for _b in ("A", "C", "G", "T")
)
or not isinstance(_pfm, dict)
or set(_pfm.keys()) != {"A", "C", "G", "T"}
or any(
not isinstance(_pfm[_b], list)
or len(_pfm[_b]) != _exp_len
or any(not _is_finite_real(_v) or float(_v) < 0.0 for _v in _pfm[_b])
for _b in ("A", "C", "G", "T")
)
):
raise ValueError(f"Corrupted, unauthenticated, or non-finite JASPAR PWM/PFM entry for {_mid_chk}")
_obs_pwm_sha = sha256_str(json.dumps(_l2p, sort_keys=True, separators=(",", ":")))
_obs_pfm_sha = sha256_str(json.dumps(_pfm, sort_keys=True))
if (
_ment_chk.get("pwm_matrix_sha256") != _exp_pwm_sha
or _obs_pwm_sha != _exp_pwm_sha
or _ment_chk.get("pfm_counts_sha256") != _exp_pfm_sha