STXBP1_Base_Editing_Parameter_Sweep_V2 / run_canonical_parameter_sweep.py
SkyWhal3's picture
Upload 3 files
e63f0a5 verified
Raw
History Blame Contribute Delete
16 kB
#!/usr/bin/env python3
"""
STXBP1 Base-Editing Parameter Sweep - Canonical (603-aa / MANE Plus Clinical)
Re-build of the v1 sweep that was published against NM_001032221.6
(594 aa, MANE Select). This version uses NM_003165.6 (603 aa,
MANE Plus Clinical, NP_003156.1) — the same canonical reference
ARIA's Variant Explorer and Mouse Context Verifier use.
Why the rebuild matters:
* Positions 1-575 are byte-identical between the two transcripts,
so results for common pathogenic variants (K196X, R292H, R406H,
and 168 others in the byte-identical zone) will match v1 exactly.
* Positions 576+ diverge. v1 had 2 variants affected:
- Q576X: mislabeled; canonical[576]=T (Thr), not Q (Gln). This
variant's label is invalid under the canonical frame and has
been removed from the input list. A separate `p.T576*` file
would need to be seeded from ClinVar if that position has a
true pathogenic variant reported on canonical numbering.
- E603D: valid on canonical (pos 603, CDS nt 1807-1809); was
invalid on 594-aa where the CDS ends at nt 1782. v1 would
have errored on this variant; the canonical rebuild resolves it.
* Provenance (S96 canonical rebuild, 2026-04-24): caught a years-old
contamination where the original STXBP1 dataset had been folded
against a 586-aa non-Munc18-1 protein. Documented in
D:/STXBP1_datasets/scripts/stxbp1_canonical.py.
Run:
python run_canonical_parameter_sweep.py \\
--variants stxbp1_snv_variants_170_canonical.txt \\
--output stxbp1_ULTIMATE_v2_canonical_YYYYMMDD.csv
Workers default to cpu_count(). One variant at a time to control memory.
"""
from __future__ import annotations
import argparse
import csv
import os
import re
import sys
import time
from datetime import datetime, timedelta
from multiprocessing import Pool, cpu_count
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import requests
# =============================================================================
# CANONICAL CONFIG — the ONLY frame-dependent values
# =============================================================================
# MANE Plus Clinical frame (603 aa). Matches ARIA's Variant Explorer
# and ClinVar's variant coordinates.
HUMAN_ACCESSION = "NM_003165.6"
# S97 fix: mouse_accession was NM_011502 — that's mouse Syntaxin-3 (Stx3),
# NOT Stxbp1. Same wrong-accession bug that's still in the Mouse Context
# Verifier HF Space's GENE_CONFIGS (which propagated here when ARIA's
# MouseVerifierModal copied it). Correct mouse Stxbp1 accession is
# NM_009295 (NP_033321.2, isoform b, 594 aa, starts MAPIGLKAVV...).
# Verified directly via NCBI eutils efetch on 2026-04-24.
MOUSE_ACCESSION = "NM_009295"
# Banner written into every CSV header for downstream traceability.
REFERENCE_BANNER = (
f"human={HUMAN_ACCESSION} (NP_003156.1, 603 aa, MANE Plus Clinical); "
f"mouse={MOUSE_ACCESSION}"
)
CACHE_DIR = Path(__file__).parent / "sequence_cache_canonical"
# =============================================================================
# PARAMETER SPACE (UNCHANGED from v1 for apples-to-apples comparability)
# =============================================================================
SCAN_RADII = list(range(10, 201)) # 191 values
CONTEXT_RADII = list(range(5, 101)) # 96 values
EDIT_WINDOWS = [(s, e) for s in range(1, 21) for e in range(s, 21)] # 210
TOTAL_PARAM_COMBOS = len(SCAN_RADII) * len(CONTEXT_RADII) * len(EDIT_WINDOWS)
# Worker globals (set by init_worker via fork semantics on Linux; on Windows
# they are passed via initargs and re-initialized per worker).
HUMAN_CDS: Optional[str] = None
MOUSE_CDS: Optional[str] = None
# =============================================================================
# SEQUENCE FETCHING
# =============================================================================
def fetch_cds_from_ncbi(accession: str) -> Optional[str]:
url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"
params = {
"db": "nuccore",
"id": accession,
"rettype": "fasta_cds_na",
"retmode": "text",
}
try:
resp = requests.get(url, params=params, timeout=30)
if resp.status_code == 200:
lines = resp.text.strip().split("\n")
return "".join(
line.strip() for line in lines[1:] if not line.startswith(">")
).upper()
except Exception as e:
print(f"NCBI error: {e}", file=sys.stderr)
return None
def get_sequence(accession: str) -> Optional[str]:
CACHE_DIR.mkdir(exist_ok=True)
# Match with or without version, returning first hit
for f in CACHE_DIR.glob(f"{accession.split('.')[0]}*.fasta"):
return f.read_text().strip()
seq = fetch_cds_from_ncbi(accession)
if seq:
(CACHE_DIR / f"{accession}.fasta").write_text(seq)
return seq
return None
# =============================================================================
# CODON / EDIT-TYPE HELPERS
# =============================================================================
def parse_cdna(cdna: str) -> Tuple[Optional[int], Optional[str], Optional[str]]:
m = re.match(r"c\.(\d+)([ACGT])>([ACGT])", cdna)
return (int(m.group(1)), m.group(2), m.group(3)) if m else (None, None, None)
def classify_edit_type(ref: str, alt: str) -> str:
change = f"{ref}>{alt}"
if change in ("A>G", "T>C"):
return "ABE"
if change in ("C>T", "G>A"):
return "CBE"
return "PRIME"
# =============================================================================
# SINGLE-PARAM ANALYSIS
# =============================================================================
def analyze_one_param(params: Tuple) -> Optional[Dict]:
label, cdna, cdna_pos, edit_type, scan_radius, context_radius, edit_window = params
human_cds = HUMAN_CDS
mouse_cds = MOUSE_CDS
if human_cds is None or mouse_cds is None:
return None
if cdna_pos > len(human_cds) or cdna_pos > len(mouse_cds):
return None
# Context identity
ctx_start = max(0, cdna_pos - 1 - context_radius)
ctx_end = min(len(human_cds), cdna_pos + context_radius)
human_ctx = human_cds[ctx_start:ctx_end]
mouse_ctx = mouse_cds[ctx_start:ctx_end]
min_len = min(len(human_ctx), len(mouse_ctx))
if min_len == 0:
return None
matches = sum(1 for i in range(min_len) if human_ctx[i] == mouse_ctx[i])
context_identity = matches / min_len
# PAM search
scan_start = max(0, cdna_pos - 1 - scan_radius)
scan_end = min(len(human_cds), cdna_pos + scan_radius)
human_scan = human_cds[scan_start:scan_end]
mouse_scan = mouse_cds[scan_start:scan_end]
target_in_scan = cdna_pos - 1 - scan_start
best_mm = 999
best_in_window = False
num_candidates = 0
for i in range(len(human_scan) - 22):
if human_scan[i + 21:i + 23] == "GG":
proto_start = i
if proto_start <= target_in_scan < proto_start + 20:
edit_pos = target_in_scan - proto_start + 1
in_window = edit_window[0] <= edit_pos <= edit_window[1]
if proto_start + 23 <= len(mouse_scan):
mm = sum(
1
for j in range(23)
if human_scan[proto_start + j] != mouse_scan[proto_start + j]
)
num_candidates += 1
if mm < best_mm or (mm == best_mm and in_window and not best_in_window):
best_mm = mm
best_in_window = in_window
score = context_identity * 40
if best_mm < 999:
score += max(0, 30 - best_mm * 2.5)
if best_in_window:
score += 20
compatible = context_identity >= 0.90 and best_mm <= 3 and best_in_window
if compatible:
score += 10
return {
"label": label,
"cdna": cdna,
"edit_type": edit_type,
"scan": scan_radius,
"ctx": context_radius,
"win": f"{edit_window[0]}-{edit_window[1]}",
"identity": round(context_identity, 4),
"candidates": num_candidates,
"best_mm": best_mm if best_mm < 999 else None,
"in_window": best_in_window,
"compat": compatible,
"score": round(min(100, max(0, score)), 1),
}
def init_worker(human_cds: str, mouse_cds: str) -> None:
global HUMAN_CDS, MOUSE_CDS
HUMAN_CDS = human_cds
MOUSE_CDS = mouse_cds
# =============================================================================
# PER-VARIANT DRIVER
# =============================================================================
def process_single_variant(
variant: Dict,
human_cds: str,
mouse_cds: str,
writer: csv.DictWriter,
num_workers: int,
) -> Tuple[int, Optional[Dict]]:
label = variant.get("label", "")
cdna = variant.get("cdna", "")
cdna_pos, ref, alt = parse_cdna(cdna)
if cdna_pos is None:
return 0, None
edit_type = classify_edit_type(ref, alt) if ref and alt else "?"
work_items = [
(label, cdna, cdna_pos, edit_type, scan, ctx, window)
for scan in SCAN_RADII
for ctx in CONTEXT_RADII
for window in EDIT_WINDOWS
]
best_result: Optional[Dict] = None
best_score = -1.0
count = 0
with Pool(num_workers, initializer=init_worker, initargs=(human_cds, mouse_cds)) as pool:
for result in pool.imap_unordered(analyze_one_param, work_items, chunksize=500):
if result is None:
continue
writer.writerow(result)
count += 1
if result["score"] > best_score:
best_score = result["score"]
best_result = result
return count, best_result
# =============================================================================
# VARIANT LOADING
# =============================================================================
def load_variants(filepath: str) -> List[Dict]:
variants = []
# encoding='utf-8-sig' strips an optional BOM; errors='replace' is defense
# against Windows-1252 punctuation (em-dashes, smart quotes) that PowerShell
# tools sometimes inject when piping or saving from Word. Comment lines are
# skipped anyway, so any lossy replacement in the header is harmless.
with open(filepath, "r", encoding="utf-8-sig", errors="replace") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) >= 2:
variants.append(
{"label": parts[0], "cdna": parts[1], "aa": parts[2] if len(parts) > 2 else ""}
)
return variants
# =============================================================================
# MAIN
# =============================================================================
def main() -> None:
parser = argparse.ArgumentParser(
description="STXBP1 Canonical Base-Editing Parameter Sweep (603-aa)"
)
parser.add_argument("--workers", "-w", type=int, default=None)
parser.add_argument(
"--variants", "-v", type=str,
default=str(Path(__file__).parent / "stxbp1_snv_variants_170_canonical.txt"),
)
parser.add_argument("--output", "-o", type=str, default=None)
args = parser.parse_args()
num_workers = args.workers or cpu_count()
print("=" * 70)
print("STXBP1 CANONICAL PARAMETER SWEEP")
print(f"Reference: {REFERENCE_BANNER}")
print("=" * 70)
print(f"Parameter space: {len(SCAN_RADII)} x {len(CONTEXT_RADII)} x {len(EDIT_WINDOWS)} = {TOTAL_PARAM_COMBOS:,}")
print(f"Workers: {num_workers}")
print("=" * 70)
if not os.path.exists(args.variants):
print(f"ERROR: Variant file not found: {args.variants}", file=sys.stderr)
sys.exit(1)
variants = load_variants(args.variants)
print(f"Loaded {len(variants)} variants from {args.variants}")
print("\nFetching canonical CDS sequences...")
human_cds = get_sequence(HUMAN_ACCESSION)
mouse_cds = get_sequence(MOUSE_ACCESSION)
if not human_cds or not mouse_cds:
print("ERROR: Could not get sequences", file=sys.stderr)
sys.exit(1)
# Canonical CDS sanity check — 603 aa + stop = 1812 nt
if len(human_cds) < 1809:
print(
f"WARNING: human CDS length {len(human_cds)} is shorter than expected "
f"1812 nt for NP_003156.1. Did NCBI return a different isoform?",
file=sys.stderr,
)
print(f"Human: {len(human_cds)} nt Mouse: {len(mouse_cds)} nt")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_path = args.output or f"stxbp1_ULTIMATE_v2_canonical_{timestamp}.csv"
json_path = csv_path.replace(".csv", "_best.json")
total_analyses = len(variants) * TOTAL_PARAM_COMBOS
print(f"\nTotal analyses: {total_analyses:,}")
print(f"Output CSV: {csv_path}")
print(f"Best-config JSON: {json_path}\n")
fieldnames = [
"label", "cdna", "edit_type", "scan", "ctx", "win",
"identity", "candidates", "best_mm", "in_window", "compat", "score",
]
start_time = time.time()
total_written = 0
best_configs: Dict[str, Dict] = {}
with open(csv_path, "w", newline="", encoding="utf-8") as f:
# Banner comment rows so a reader grepping the CSV head sees the frame
f.write(f"# reference_frame: {REFERENCE_BANNER}\n")
f.write(f"# build_date: {timestamp}\n")
f.write(f"# variants: {len(variants)} from {os.path.basename(args.variants)}\n")
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for i, variant in enumerate(variants):
var_start = time.time()
count, best = process_single_variant(variant, human_cds, mouse_cds, writer, num_workers)
total_written += count
if best:
best_configs[variant["label"]] = best
f.flush()
var_time = time.time() - var_start
elapsed = time.time() - start_time
rate = total_written / elapsed if elapsed > 0 else 0
eta = (total_analyses - total_written) / rate if rate > 0 else 0
print(
f"[{i+1:3d}/{len(variants)}] {variant['label']:<10} "
f"{count:,} rows {var_time:.1f}s "
f"Total: {total_written:,} "
f"Rate: {rate:,.0f}/s "
f"ETA: {timedelta(seconds=int(eta))}"
)
# Best-config JSON
import json as _json
output_json = {
"_metadata": {
"reference_frame": REFERENCE_BANNER,
"build_date": timestamp,
"total_variants": len(variants),
"total_param_combos_per_variant": TOTAL_PARAM_COMBOS,
"total_rows_written": total_written,
},
"variants": {},
}
for label, row in best_configs.items():
output_json["variants"][label] = {
"cdna": row["cdna"],
"edit_type": row["edit_type"],
"optimal_params": {
"scan_radius": row["scan"],
"context_radius": row["ctx"],
"edit_window": row["win"],
},
"score": row["score"],
"context_identity": row["identity"],
"compatible": row["compat"],
}
with open(json_path, "w", encoding="utf-8") as f:
_json.dump(output_json, f, indent=2)
total_time = time.time() - start_time
print("\n" + "=" * 70)
print("COMPLETE")
print("=" * 70)
print(f"Time: {timedelta(seconds=int(total_time))}")
print(f"Rows: {total_written:,}")
print(f"Rate: {total_written/total_time:,.0f}/s")
print(f"CSV: {csv_path}")
print(f"Best: {json_path}")
if __name__ == "__main__":
main()