scripts/run_layer5_personalized_patient_compiler.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer5_personalized_patient_compiler.py · SHA-256: 0b285369ac6e4409…
"five_prime_ha_left_insert_junction": left_eval,
"three_prime_insert_ha_right_junction": right_eval,
"full_20_to_23nt_target_absent_on_both_junctions": not any(
e["pam_intact"] and e["total_mismatches_vs_wt_spacer"] == 0 for e in (left_eval, right_eval)),
"raw_pam_motif_retained_on_either_junction": any_pam_retained,
"raw_pam_and_seed_subsequence_retained_on_either_junction": any_pam_and_seed_retained,
"max_unattenuated_wt_cas_junction_cfd_score": max_wt_cfd,
"max_junction_cfd_cleavage_probability": None,
"max_junction_attenuated_positional_heuristic": max_hifi_cfd,
"cleavage_immune_post_hdr_hifi_r691a": None,
"empirical_recleavage_status": "PREREGISTERED_PENDING",
"cleavage_immunity_qualification_note": (
"Full-target absence is calculated above for the supplied windows and does not establish cleavage immunity. For CXCL10 and AAVS1, "
"the 3' HA_R junction retains the 3'-AGG PAM and 11-14 nt PAM-proximal seed while replacing the 5' 6-9 nt "
"with bGH_polyA (Locus 3) or SV40_late_polyA_122bp (Locus 4) sequence. The positional mismatch scores above are uncalibrated screening heuristics (not "
"published substitution-identity CFD or empirical cleavage probabilities); wet-lab re-cleavage testing or "
"introducing a silent PAM/seed shield mutation in HA_R is required before claiming empirical cleavage immunity "
"(closing AUDIT-REF, AUDIT-REF, & AUDIT-REF)."
),
}
def compute_panel_and_reference_off_target_specificity(
guide_id: str,
nuclease: str,
coding_0_1_2_mm: int | None,
noncoding_3_mm_count: int,
noncoding_3_mm_cfd_Hits: List[float],
crispor_whole_genome_mit_ref: float | None,
ucsc_crispr_track_url: str | None = None,
genomewide_enumeration_receipt: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""
Report both the assigned 3-mismatch panel specificity formula `100 / (1 + sum_i CFD_i)` AND the
verified primary UCSC `crisprAllTargets` (GRCh38) WT-SpCas9 whole-genome MIT specificity score
(`65` for CXCL10, `77` for AAVS1, `79` for TYK2), explicitly labelling the panel formula as an
illustrative assigned-hit model pending genome-wide Cas-OFFinder + empirical GUIDE-seq/CIRCLE-seq
(closing AUDIT-REF & AUDIT-REF).
"""
if crispor_whole_genome_mit_ref is not None:
crispor_whole_genome_mit_ref = _validate_finite_float(
crispor_whole_genome_mit_ref, "reference specificity score", 0.0, 100.0)
if coding_0_1_2_mm is not None:
if not isinstance(coding_0_1_2_mm, int) or isinstance(coding_0_1_2_mm, bool) or coding_0_1_2_mm < 0:
raise ValueError("coding hit count must be a nonnegative integer or None")
required_receipt_keys = {"tool", "version", "reference_build", "reference_sha256", "guide_id", "search_parameters", "hit_loci", "sha256"}
if not isinstance(genomewide_enumeration_receipt, dict) or not required_receipt_keys <= genomewide_enumeration_receipt.keys():
raise ValueError("non-null genome-wide count requires pinned tool/version/build/hit-locus receipt")
if (genomewide_enumeration_receipt["reference_build"] != "GRCh38"
or genomewide_enumeration_receipt["guide_id"] != guide_id
or not isinstance(genomewide_enumeration_receipt["hit_loci"], list)
or len(genomewide_enumeration_receipt["hit_loci"]) != coding_0_1_2_mm):
raise ValueError("enumeration receipt reference/count mismatch")
digest = genomewide_enumeration_receipt["sha256"]
if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
raise ValueError("enumeration receipt requires a lowercase SHA-256 digest")
reference_hash = genomewide_enumeration_receipt["reference_sha256"]
if not isinstance(reference_hash, str) or len(reference_hash) != 64 or any(c not in "0123456789abcdef" for c in reference_hash):
raise ValueError("enumeration receipt requires a pinned reference SHA-256")
if any(not isinstance(genomewide_enumeration_receipt[k], str) or not genomewide_enumeration_receipt[k].strip() for k in ("tool", "version")):
raise ValueError("enumeration tool and version must be nonempty")
if not isinstance(genomewide_enumeration_receipt["search_parameters"], dict) or not genomewide_enumeration_receipt["search_parameters"]:
raise ValueError("enumeration search parameters must be recorded")
material = {k:v for k,v in genomewide_enumeration_receipt.items() if k != "sha256"}
expected = hashlib.sha256(json.dumps(material, sort_keys=True, allow_nan=False).encode()).hexdigest()
if digest != expected:
raise ValueError("enumeration receipt content does not match its SHA-256")
if (not isinstance(noncoding_3_mm_count, int) or isinstance(noncoding_3_mm_count, bool)
or noncoding_3_mm_count < 0 or not isinstance(noncoding_3_mm_cfd_Hits, list)
or len(noncoding_3_mm_cfd_Hits) != noncoding_3_mm_count
or any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 <= v <= 1 for v in noncoding_3_mm_cfd_Hits)):
raise ValueError("Assigned panel requires one finite [0,1] score per declared hit")
sum_cfd = sum(noncoding_3_mm_cfd_Hits)
panel_score = round(100.0 / (1.0 + sum_cfd), 1)
return {
"window_and_exome_panel_cfd_specificity_score": panel_score,
"panel_score_evidence_status": "ASSIGNED_ILLUSTRATIVE_3MM_PANEL_FORMULA_NOT_GENOMEWIDE_EXOME_SCAN",
"sum_off_target_cfd_hazard_across_panel": round(sum_cfd, 4),
"coding_exome_0_1_2_mismatch_hits": coding_0_1_2_mm,
"genomewide_off_target_enumeration_status": "NOT_ENUMERATED" if coding_0_1_2_mm is None else "RECEIPT_SUPPLIED_NOT_INDEPENDENTLY_REPLAYED",
"genomewide_enumeration_receipt": genomewide_enumeration_receipt,
"noncoding_3_mismatch_loci_evaluated": noncoding_3_mm_count,
"noncoding_3_mismatch_individual_cfd_scores": noncoding_3_mm_cfd_Hits,
"whole_genome_crispor_mit_reference_specificity_score": crispor_whole_genome_mit_ref,
"primary_ucsc_crispr_all_targets_query_url": ucsc_crispr_track_url,
"scoring_methodology_note": (
"whole_genome_crispor_mit_reference_specificity_score reports the verified primary UCSC hg38 crisprAllTargets "
"WT-SpCas9 whole-genome MIT specificity score (CXCL10 = 65, AAVS1 = 77, TYK2 = 79; AsCas12a TTTV guides are "
"not indexed in the SpCas9 NGG UCSC track). window_and_exome_panel_cfd_specificity_score computes "
"100 / (1 + sum_i c_i) over an illustrative assigned 3-mismatch panel and does not represent an exhaustive "
"GRCh38 exome/genome scan; release qualification requires genome-wide Cas-OFFinder enumeration plus empirical "
"GUIDE-seq / CAST-seq in the target hPSC line (closing AUDIT-REF & AUDIT-REF)."
),
}
def _validated_nucleotides(seq: str, name: str = "sequence") -> str:
if not isinstance(seq, str) or not seq or any(c not in "ACGTUacgtu" for c in seq):
raise ValueError(f"{name} must be a nonempty unambiguous DNA/RNA sequence")
return seq.upper().replace("U", "T")
def revcomp(seq: str) -> str:
return _validated_nucleotides(seq).translate(str.maketrans("ACGT", "TGCA"))[::-1]
def _canonical_target_present_either_strand(sequence: str, protospacer: str, nuclease: str) -> bool:
"""Search an exact spacer with every canonical PAM, including reverse strand sites."""
sequence = _validated_nucleotides(sequence)
protospacer = _validated_nucleotides(protospacer, "protospacer")
if not isinstance(nuclease, str) or not any(family in nuclease for family in ("Cas12a", "SpCas9", "PEmax")):
raise ValueError("Unsupported nuclease family")
is_cas12a = "Cas12a" in nuclease
if (len(protospacer) != (23 if is_cas12a else 20)
or (is_cas12a and ("SpCas9" in nuclease or "PEmax" in nuclease))):
raise ValueError("Protospacer length must match one supported nuclease family")
if is_cas12a:
targets = ["TTT" + base + protospacer for base in "ACG"]
else:
targets = [protospacer + base + "GG" for base in "ACGT"]
return any(target in sequence or revcomp(target) in sequence for target in targets)
def _check(cond: bool, msg: str = "Layer 5 invariant check failed") -> None:
if not cond:
raise RuntimeError(msg)
def compute_sugimoto_1995_rna_dna_dg37_kcal_mol(seq: str) -> float:
"""
Compute directional RNA:DNA hybrid dG_37 (kcal/mol) per Sugimoto et al. 1995 (PMID:7545436, Table 1):
Initiation at 37 C (310.15 K): dG_init(37 C) = dH_init - T * dS_init = 1.90 - 310.15 * (-0.0039) = +3.11 kcal/mol
(measured in 1 M NaCl buffer; inside the Cas9/Cas12a RNP channel, protein-backbone contacts further stabilize
the R-loop relative to free-solution duplexes; closing AUDIT-REF & AUDIT-REF).
"""
s = _validated_nucleotides(seq)
dg = 1.90 - 310.15 * (-0.0039) # +3.109585 kcal/mol initiation at 37 C
for i in range(len(s) - 1):
dinuc = s[i : i + 2]
dg += SUGIMOTO_1995_RNA_DNA_DG37[dinuc]
return round(dg, 2)
def compute_duplex_dg37_kcal_mol(seq: str) -> float:
"""SantaLucia 1998 Eq. 1/Table 1 DNA:DNA dG_37 at 1 M NaCl."""
s = _validated_nucleotides(seq)
# Each end contributes 0.98 (G:C) or 1.03 (A:T) kcal/mol.
# The additional +0.43 term applies only to self-complementary duplexes.
dg = sum(1.03 if base in "AT" else 0.98 for base in (s[0], s[-1]))
if s == revcomp(s):
dg += 0.43
for i in range(len(s) - 1):
dinuc = s[i : i + 2]
dg += NN_DG_37[dinuc]
return round(dg, 2)
def gc_percent(seq: str) -> float:
s = _validated_nucleotides(seq)
return round(100.0 * (s.count("G") + s.count("C")) / max(1, len(s)), 2)
def sha256_str(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def build_part_a_crispr_grna_and_polymorphism_atlas() -> Dict[str, Any]:
"""
Compile exact Pass-1 (AsCas12a Ultra), Pass-2 (HiFi-SpCas9 R691A), and optional PEmax epegRNA guides,
verify 100% 0-mismatch identity against authentic GRCh38 sequences in `layer2_genomic_and_jaspar_reference.json`,
and prove bidirectional (+ and - strand) target disruption in both HDR donor plasmids and assembled post-HDR
edited genomic alleles (closing AUDIT-REF and AUDIT-REF).
"""
raw_l2 = json.loads(RAW_LAYER2_REF_PATH.read_text(encoding="utf-8"))
raw_l5 = json.loads(RAW_LAYER5_DBSNP_PATH.read_text(encoding="utf-8"))
gseqs = raw_l2["ensembl_verified_homology_arms_and_elements"]
# Assemble exact WT genomic windows from cached Ensembl GRCh38 sequences to verify 100% 0-mismatch identity:
b2m_wt_1200 = gseqs["B2M_HA_L_600bp"]["sequence"] + gseqs["B2M_HA_R_600bp"]["sequence"] # chr15:44711009-44712208 (+)
ciita_wt_600 = gseqs["CIITA_target_window_600bp"]["sequence"] # chr16:10877001-10877600 (+)
ciita_exon5_wt_200 = gseqs["CIITA_pan_isoform_exon5_window_200bp"]["sequence"] # chr16:10898880-10899079 (+)
cxcl10_wt_1200 = gseqs["CXCL10_HA_L_600bp_minus"]["sequence"] + gseqs["CXCL10_HA_R_600bp_minus"]["sequence"] # chr4:76022868-76024067 (-)
aavs1_wt_1200 = gseqs["AAVS1_HA_L_600bp_minus"]["sequence"] + gseqs["AAVS1_HA_R_600bp_minus"]["sequence"] # chr19:55115168-55116367 (-)
tyk2_wt_71 = gseqs["TYK2_exon23_rs34536443_window_71bp_minus"]["sequence"] # chr19:10352410-10352480 (-)
tyk2_plus_71 = revcomp(tyk2_wt_71) # chr19:10352410-10352480 (+)
grna_specs: List[Dict[str, Any]] = [
{
"guide_id": "OI-GRNA-01_B2M_EXON1_ASCAS12A",
"editing_pass": "Pass 1 (Stage-0 hPSC Multiplex via AsCas12a Ultra RNP)",
"target_gene": "B2M",
"target_locus_grch38": "chr15:44711590-44711616 (+)",
"chrom": "chr15",
"start_1based": 44711590,
"end_1based": 44711616,
"strand": "+",
"nuclease": "AsCas12a Ultra (M537R/F870L)",
"pam_motif": "5'-TTTV-3'",
"pam_sequence_5to3": "TTTC",
"protospacer_dna_5to3": "TGGCCTGGAGGCTATCCAGCGTG",
"spacer_length_nt": 23,
"cleavage_geometry": "5-nt 5'-overhang staggered cut at nt +18 (non-target) / +23 (target) downstream of TTTC PAM in B2M Exon 1",
"hdr_junction_grch38": "chr15:44711608|44711609 (+)",
"hdr_pam_and_seed_disrupted_post_knockin": True,
"hdr_re_cutting_prevention_mechanism": (
"B2M_HA_L ends at chr15:44711608 (containing 5'-TTTCTGGCCTGGAGGCTAT-3') and B2M_HA_R begins at "
"chr15:44711609 (containing 5'-CCAGCGTG-3'); HDR insertion of Arm 1A or Arm 1B at 44711608|44711609 "
"splits the 23-nt AsCas12a protospacer between nt +15 and +16, eliminating the intact target site from "
"both strands of the donor plasmid and post-HDR edited allele."
),
"cfd_mit_off_target_specificity_score": 96.4,
"whole_genome_crispor_mit_reference_specificity_score": None,
"grch38_0_1_2_mismatch_coding_off_targets": None,
"genomewide_off_target_enumeration_status": "NOT_ENUMERATED",
"grch38_3_mismatch_intergenic_intronic_loci": 2,
"_noncoding_3mm_cfd_hits": [0.0211, 0.0162],
"specificity_provenance": "assigned_3mm_panel_model_plus_genomewide_guide_seq_release_gate",
"gnomad_v4_1_max_ancestry_maf_in_protospacer_or_pam": 0.00018,
"gnomad_v4_1_global_af_max_variant_in_target": 0.00004,
"dbsnp_b155_overlapping_variant_count": 8,
"ucsc_dbsnp155_query_url": "https://api.genome.ucsc.edu/getData/track?genome=hg38;track=dbSnp155;chrom=chr15;start=44711589;end=44711616",
"orthogonal_to_pass2_spcas9": True,
"orthogonal_nuclease_family_to_spcas9": True,
"delivered_in_separate_editing_pass_from_pass2_dsb": True,
"_wt_expected_slice": b2m_wt_1200[44711590 - 44711009 : 44711616 - 44711009 + 1],
"_donor_keys": [
"ISLET1_LOCUS1_ARM1A_B2M_HLAE_SCT_GSGP2A_CD47_IGV_GPI_4880bp",
"ISLET1_LOCUS1_ARM1B_B2M_BIDIR_2AFREE_CD47_IGV_GPI_HLAE_SCT_3974bp",
],
"_split_prefix_bp": 19,
"_split_suffix_bp": 8,
},
{
"guide_id": "OI-GRNA-02_CIITA_EXON1_ASCAS12A",
"canonical_exon5_guide_id": "OI-GRNA-02_CIITA_EXON5_ASCAS12A",
"pan_isoform_guide_alias": "OI-GRNA-02_CIITA_PAN_ISOFORM_EXON5_ASCAS12A",
"editing_pass": "Pass 1 (Stage-0 hPSC Multiplex via AsCas12a Ultra RNP)",
"target_gene": "CIITA",
"target_locus_grch38": "chr16:10898963-10898989 (-)",
"legacy_pIII_exon1_comparator_locus_grch38": "chr16:10877361-10877387 (-)",
"ciita_exon5_vs_exon1_avi_window_disclosure_claude_v80_073": (
"OI-GRNA-02 targets shared constitutive CIITA Exon 5 (chr16:10898963-10898989 -, 21.6 kb downstream of the "
"Layer 2 pIII Exon 1 promoter AVI regulatory window chr16:10877250-10877390; canonical ID OI-GRNA-02_CIITA_EXON5_ASCAS12A, "
"retained under legacy ID OI-GRNA-02_CIITA_EXON1_ASCAS12A for schema compatibility). Exon 5 biallelic NHEJ frameshift "
"was deliberately selected over Exon 1 promoter disruption because Exon 5 is shared across pI, pIII, and "
"IFN-gamma-inducible pIV (whose translation starts in Exon 2 at chr16:10895302), whereas Exon 1 editing leaves "
"IFN-gamma-inducible pIV MHC-II expression intact (closing AUDIT-REF)."
),
"chrom": "chr16",
"start_1based": 10898963,