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…
s = nine_mer.upper()
if len(s) != 9:
raise ValueError(f"Expected 9-mer for 5' splice donor scoring, got length {len(s)}")
if s[3:5] != "GT":
return {
"nine_mer": f"{s[:3]}|{s[3:]}",
"is_canonical_gt": False,
"ss87_cv": 0.0,
"pwm_bits": -99.0,
"u1_wc_matches_of_9": 0,
"u1_wc_or_wobble_of_9": 0,
}
raw_sum = sum(DONOR_FREQ_SS87[i][s[i]] for i in range(9))
cv = 100.0 * (raw_sum - DONOR_MIN_SS87) / (DONOR_MAX_SS87 - DONOR_MIN_SS87)
bits = sum(math.log2(max(DONOR_FREQ_SS87[i][s[i]], 0.005) / 0.25) for i in range(9))
wc = sum(1 for i in range(9) if s[i] == U1_CONSENSUS_9MER[i])
wobble_allowed = {
0: {"C", "T"}, # -3 vs U1 G11
1: {"A", "G"}, # -2 vs U1 U10
2: {"G"}, # -1 vs U1 C9
3: {"G"}, # +1 vs U1 C8
4: {"T"}, # +2 vs U1 A7
5: {"A", "G"}, # +3 vs U1 psi6
6: {"A", "G"}, # +4 vs U1 psi5
7: {"G"}, # +5 vs U1 C4
8: {"T"}, # +6 vs U1 A3 (pairs U/T only)
}
wc_gu = sum(1 for i in range(9) if s[i] in wobble_allowed[i])
return {
"nine_mer": f"{s[:3]}|{s[3:]}",
"is_canonical_gt": True,
"ss87_cv": round(cv, 2),
"pwm_bits": round(bits, 3),
"u1_wc_matches_of_9": wc,
"u1_wc_or_wobble_of_9": wc_gu,
}
def score_3prime_acceptor_23mer(twentythree_mer: str) -> Dict[str, Any]:
"""
Explicitly labelled heuristic 3' splice-acceptor index (0..100) on [-20..-1] | [+1..+3]
where [-2..-1] == 'AG':
0.60 * (polypyrimidine count in [-18..-4] / 15)
+ 0.25 * (-3 pyrimidine preference weight / 0.78)
+ 0.15 * (+1 G preference weight / 0.52).
"""
s = twentythree_mer.upper()
if len(s) != 23:
raise ValueError(f"Expected 23-mer for 3' splice acceptor scoring, got length {len(s)}")
if s[18:20] != "AG":
return {
"context": f"{s[10:18]}{s[18:20]}|{s[20:23]}",
"is_canonical_ag": False,
"heuristic_acceptor_index": 0.0,
"ppt_pyr_count_of_15": 0,
}
ppt = s[2:17]
pyr_cnt = sum(1 for b in ppt if b in ("C", "T"))
minus3 = s[17]
plus1 = s[20]
m3_w = {"C": 0.78, "T": 0.72, "A": 0.22, "G": 0.02}[minus3]
p1_w = {"G": 0.52, "A": 0.24, "T": 0.12, "C": 0.12}[plus1]
idx_val = 100.0 * (0.60 * (pyr_cnt / 15.0) + 0.25 * (m3_w / 0.78) + 0.15 * (p1_w / 0.52))
return {
"context": f"{s[10:18]}{s[18:20]}|{s[20:23]}",
"is_canonical_ag": True,
"minus3_base": minus3,
"plus1_base": plus1,
"ppt_pyr_count_of_15": pyr_cnt,
"heuristic_acceptor_index": round(idx_val, 2),
}
def scan_donors_and_acceptors_both_strands(
seq: str,
cargo_bounds_1based: Tuple[int, int] = (601, -600),
min_donor_cv: float = 74.0,
min_acc_idx: float = 68.0,
) -> Dict[str, Any]:
"""Descriptive two-strand open motif census across '+' and '-' strands."""
s_plus = seq.upper()
s_minus = revcomp(s_plus)
seq_len = len(s_plus)
c_lo = cargo_bounds_1based[0]
c_hi = (seq_len + cargo_bounds_1based[1]) if cargo_bounds_1based[1] < 0 else cargo_bounds_1based[1]
donors: List[Dict[str, Any]] = []
acceptors: List[Dict[str, Any]] = []
for strand, cur in [("+", s_plus), ("-", s_minus)]:
for i in range(3, seq_len - 6):
if cur[i : i + 2] == "GT":
sc = score_5prime_donor_9mer(cur[i - 3 : i + 6])
if sc["ss87_cv"] >= min_donor_cv or sc["u1_wc_or_wobble_of_9"] >= 7:
pos1_plus = i if strand == "+" else (seq_len - i + 1)
donors.append(
{
"strand_relative_to_input": strand,
"exon_end_1based_on_input_plus": pos1_plus,
"in_cargo": bool(c_lo <= pos1_plus <= c_hi),
**sc,
}
)
for i in range(20, seq_len - 3):
if cur[i - 2 : i] == "AG":
sc = score_3prime_acceptor_23mer(cur[i - 20 : i + 3])
if sc["heuristic_acceptor_index"] >= min_acc_idx:
pos1_plus = (i + 1) if strand == "+" else (seq_len - i)
acceptors.append(
{
"strand_relative_to_input": strand,
"exon_start_1based_on_input_plus": pos1_plus,
"in_cargo": bool(c_lo <= pos1_plus <= c_hi),
**sc,
}
)
donors.sort(key=lambda r: (r["ss87_cv"], r["u1_wc_or_wobble_of_9"]), reverse=True)
acceptors.sort(key=lambda r: r["heuristic_acceptor_index"], reverse=True)
return {
"total_donors": len(donors),
"donors_cv_ge_74": sum(1 for d in donors if d["ss87_cv"] >= 74.0),
"cargo_donors": sum(1 for d in donors if d["in_cargo"]),
"cargo_donors_plus_strand": sum(1 for d in donors if d["in_cargo"] and d["strand_relative_to_input"] == "+"),
"cargo_donors_minus_strand": sum(1 for d in donors if d["in_cargo"] and d["strand_relative_to_input"] == "-"),
"total_acceptors": len(acceptors),
"cargo_acceptors": sum(1 for a in acceptors if a["in_cargo"]),
"donors": donors,
"acceptors": acceptors,
}
def diff_edit_created_neosites(parent_seq: str, mutant_seq: str) -> Dict[str, List[Dict[str, Any]]]:
"""Identify any donor (CV >= 70 or U1 >= 7) or acceptor (index >= 68) newly created by sequence edits."""
p_scan = scan_donors_and_acceptors_both_strands(parent_seq, min_donor_cv=70.0, min_acc_idx=68.0)
m_scan = scan_donors_and_acceptors_both_strands(mutant_seq, min_donor_cv=70.0, min_acc_idx=68.0)
p_d_keys = {(d["strand_relative_to_input"], d["exon_end_1based_on_input_plus"], d["nine_mer"]) for d in p_scan["donors"]}
p_a_keys = {(a["strand_relative_to_input"], a["exon_start_1based_on_input_plus"], a["context"]) for a in p_scan["acceptors"]}
neo_d = [d for d in m_scan["donors"] if (d["strand_relative_to_input"], d["exon_end_1based_on_input_plus"], d["nine_mer"]) not in p_d_keys]
neo_a = [a for a in m_scan["acceptors"] if (a["strand_relative_to_input"], a["exon_start_1based_on_input_plus"], a["context"]) not in p_a_keys]
return {"created_donors_cv70_or_u1_7": neo_d, "created_acceptors_idx68": neo_a}
def longest_repeats(seq: str, min_k: int = 12) -> Dict[str, Any]:
"""
Deterministic scan for longest overlapping direct repeat, longest disjoint direct repeat,
and longest disjoint inverted repeat >= min_k bp.
"""
s = seq.upper()
rc_s = revcomp(s)
n = len(s)
lo, hi = min_k, n // 2
best_dir_ov = ("", -1, -1)
while lo <= hi:
mid = (lo + hi) // 2
seen: Dict[str, int] = {}
found = None
for i in range(n - mid + 1):
sub = s[i : i + mid]
if sub in seen:
found = (sub, seen[sub] + 1, i + 1)
break
seen[sub] = i
if found:
best_dir_ov = found
lo = mid + 1
else:
hi = mid - 1
lo, hi = min_k, n // 2
best_dir_disj = ("", -1, -1)
while lo <= hi:
mid = (lo + hi) // 2
first_pos: Dict[str, int] = {}
found = None
for i in range(n - mid + 1):
sub = s[i : i + mid]
if sub in first_pos:
if i - first_pos[sub] >= mid:
found = (sub, first_pos[sub] + 1, i + 1)
break
else:
first_pos[sub] = i
if found:
best_dir_disj = found
lo = mid + 1
else:
hi = mid - 1
lo, hi = min_k, n // 2
best_inv = ("", -1, -1)
while lo <= hi:
mid = (lo + hi) // 2
rc_map: Dict[str, List[int]] = {}
for j in range(n - mid + 1):
orig_start0 = n - (j + mid)
rc_map.setdefault(rc_s[j : j + mid], []).append(orig_start0)
found = None
for i in range(n - mid + 1):
sub = s[i : i + mid]
if sub in rc_map:
for o0 in rc_map[sub]:
if abs(o0 - i) >= mid:
a1, b1 = min(i + 1, o0 + 1), max(i + 1, o0 + 1)
found = (sub, a1, b1)
break
if found:
break
if found:
best_inv = found
lo = mid + 1
else:
hi = mid - 1
return {
"longest_direct_repeat_ge_12bp": {
"overlap_mode": "overlapping_allowed_tandem_or_array",
"length_bp": len(best_dir_ov[0]),
"sequence": best_dir_ov[0],
"pos1_a": best_dir_ov[1],
"pos1_b": best_dir_ov[2],
},
"longest_disjoint_direct_repeat_ge_12bp": {
"overlap_mode": "strictly_disjoint",
"length_bp": len(best_dir_disj[0]),
"sequence": best_dir_disj[0],
"pos1_a": best_dir_disj[1],
"pos1_b": best_dir_disj[2],
},
"longest_disjoint_inverted_repeat_ge_12bp": {
"overlap_mode": "strictly_disjoint",
"length_bp": len(best_inv[0]),
"sequence": best_inv[0],
"pos1_a": best_inv[1],
"pos1_b": best_inv[2],
},
}
def nearest_neighbor_tm_sl98(seq: str, na_mm: float = 50.0, oligo_nm: float = 250.0) -> float:
"""SantaLucia 1998 unified nearest-neighbor Tm (50 mM Na+, 250 nM oligo)."""
nn = {
"AA": (-7.9, -22.2), "TT": (-7.9, -22.2), "AT": (-7.2, -20.4), "TA": (-7.2, -21.3),
"CA": (-8.5, -22.7), "TG": (-8.5, -22.7), "GT": (-8.4, -22.4), "AC": (-8.4, -22.4),
"CT": (-7.8, -21.0), "AG": (-7.8, -21.0), "GA": (-8.2, -22.2), "TC": (-8.2, -22.2),
"CG": (-10.6, -27.2), "GC": (-9.8, -24.4), "GG": (-8.0, -19.9), "CC": (-8.0, -19.9),
}
s = seq.upper()
dh = sum(nn[s[i : i + 2]][0] for i in range(len(s) - 1))