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…
#!/usr/bin/env python3
"""
Layer 5: Personalized Patient-DNA & Multiplex CRISPR Compiler + 10,000-Patient Global Population Simulator (v0.8.0)
===================================================================================================================
Closes the final in-silico execution layer of the 5-Layer OpenIslet Architecture (folding in AUDIT-REF,
AUDIT-REF, AUDIT-REF, AUDIT-REF, and AUDIT-REF):
- Part A: Exact Multiplex CRISPR Guide RNA (gRNA) Compiler & Polymorphism Audit
* Pass 1 (AsCas12a Ultra, 5'-TTTV-3' PAM, 23-nt spacer):
- OI-GRNA-01: B2M Exon 1 (`chr15:44711590-44711616 (+)`, straddling the Layer 2 `44711608|44711609` HDR junction)
- OI-GRNA-02: CIITA Shared Constitutive Exon 5 (`chr16:10898963-10898989 (-)`, ablating pI, pIII, and IFN-gamma-inducible pIV; legacy pIII Exon 1 comparator at `chr16:10877361-10877387 (-)`)
* Pass 2 (HiFi-SpCas9 R691A, 5'-NGG-3' PAM, 20-nt spacer):
- OI-GRNA-03: CXCL10 Exon 1 (`chr4:76023451-76023473 (-)`, straddling the Layer 2 `76023468|76023467` HDR junction)
- OI-GRNA-04: AAVS1 / PPP1R12C Intron 1 (`chr19:55115754-55115776 (-)`, straddling the Layer 2 `55115768|55115767` HDR junction)
* Optional Non-DSB Prime Edit (PEmax SpCas9-H840A nickase + M-MLV RT + epegRNA; CGBE is an unimplemented contingency, requiring an explicit bystander/window ledger; minus-strand C:G->G:C editing requires an engineered SpG/SpRY PAM variant because no canonical 5'-NGG-3' minus-strand PAM places chr19:10352442C within positions 4-7):
- OI-GRNA-05: TYK2 Exon 23 (`chr19:10352421-10352443 (+)`, installing protective rs34536443 `c.3310C>G` [`p.Pro1104Ala` in the catalytic `JH1` kinase domain; PMID:27807284, PMID:35470158] transversion)
* Computes directional Sugimoto et al. (1995, PMID:7545436) RNA:DNA hybrid nearest-neighbor dG_37C alongside
SantaLucia (1998) DNA:DNA duplex dG_37C, verifies 100% 0-mismatch identity against GRCh38 reference sequences,
and proves bidirectional (+ and - strand) protospacer/PAM disruption in both HDR donor plasmids and assembled
post-HDR edited alleles (`HA_L + insert + HA_R`).
- Part B: Personalized Patient-DNA & Autoantigen Compiler + 10,000-Patient Global Population Scenario Simulator
* Validates all patient input fields (rejecting NaN/Inf, out-of-range scores, and invalid SIRPA alleles),
distinguishes recipient vs donor cell-line protospacer SNPs, unifies Plan B with the canonical HLA-C-retaining
selective HLA-A/HLA-B KO architecture, and executes `compile_personalized_patient_blueprint` across all
10,000 simulated virtual T1D patients so population outcomes are causally coupled to compiler outputs.
Outputs: `data/extracted/layer5_personalized_patient_and_crispr_atlas.json`
"""
from __future__ import annotations
import hashlib
import json
import math
import copy
import sys
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Dict, List
import numpy as np
REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from scripts.engineering_priors import engineering_complexity_discount
from scripts.product_contract import get_product_definition
@lru_cache(maxsize=16)
def _product_contract_snapshot(root_path: str, variant_id: str) -> Dict[str, Any]:
"""One immutable contract snapshot per imported compiler and product variant."""
return get_product_definition(variant_id, root=Path(root_path))
def _engineering_parameters() -> Dict[str, Any]:
"""Read the shared in-memory registry at an evaluation boundary, never a file per patient."""
from scripts.rank_islet1_stacks import ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE
reg = ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE
return {
"lambda_K": float(reg["locus_dsb_penalty_rate_lambda_K"]["point_estimate"]),
"gamma_B": float(reg["base_edit_nickase_penalty_factor_gamma_B"]["point_estimate"]),
"lambda_K_range": tuple(reg["locus_dsb_penalty_rate_lambda_K"]["plausible_range"]),
"gamma_B_range": tuple(reg["base_edit_nickase_penalty_factor_gamma_B"]["plausible_range"]),
}
RAW_LAYER2_REF_PATH = REPO_ROOT / "data" / "raw" / "layer2_genomic_and_jaspar_reference.json"
RAW_LAYER5_DBSNP_PATH = REPO_ROOT / "data" / "raw" / "layer5_dbsnp_clinvar_reference.json"
LAYER2_ATLAS_PATH = REPO_ROOT / "data" / "extracted" / "layer2_regulatory_and_perturbation_atlas.json"
OUT_PATH = REPO_ROOT / "data" / "extracted" / "layer5_personalized_patient_and_crispr_atlas.json"
# Sugimoto et al. (1995) Biochemistry 34:11211-11216 (PMID:7545436, Table 1) directional RNA(5'->3'):DNA(3'->5') hybrid dG_37 (kcal/mol)
# Keys are 5'->3' RNA dinucleotides (written with T for U) base-paired to antiparallel DNA target strand (closing AUDIT-REF):
SUGIMOTO_1995_RNA_DNA_DG37: Dict[str, float] = {
"AA": -1.00, "TT": -0.20, "AT": -0.90, "TA": -0.60,
"CA": -0.90, "TG": -1.60, "GT": -1.10, "AC": -2.10,
"CT": -0.90, "AG": -1.80, "GA": -1.30, "TC": -1.50,
"CG": -1.70, "GC": -2.70, "GG": -2.90, "CC": -2.10,
}
# SantaLucia (1998) Proc Natl Acad Sci USA 95:1460-1465 DNA:DNA nearest-neighbor dG_37 (kcal/mol)
NN_DG_37: Dict[str, float] = {
"AA": -1.00, "TT": -1.00, "AT": -0.88, "TA": -0.58,
"CA": -1.45, "TG": -1.45, "GT": -1.44, "AC": -1.44,
"CT": -1.28, "AG": -1.28, "GA": -1.30, "TC": -1.30,
"CG": -2.17, "GC": -2.24, "GG": -1.84, "CC": -1.84,
}
VALID_SIRPA_GENOTYPES = {
"v1/v1", "v1/v2", "v2/v1", "v2/v2",
"v1/v8", "v8/v1", "v2/v8", "v8/v2", "v8/v8",
}
VALID_ANCESTRIES = {"EUR", "AFR", "EAS", "SAS", "AMR", "OTHER_ADMIXED"}
VALID_TRACK_REQUESTS = {
"AUTO_RECOMMEND",
"TRACK_1_OFF_THE_SHELF",
"TRACK_2_STRATIFIED_SUBLINE",
"TRACK_3_AUTOLOGOUS_IPSC",
}
VALID_IFIH1_GENOTYPES = {"C/C", "C/T", "T/C", "T/T"}
VALID_DONOR_IFIH1_GENOTYPES = {"UNMEASURED", *VALID_IFIH1_GENOTYPES}
VALID_PTPN22_GENOTYPES = {"G/G", "G/A", "A/G", "A/A"}
VALID_HLA_E_GENOTYPES = {
"*01:01/*01:01", "*01:01/*01:03", "*01:03/*01:01", "*01:03/*01:03",
"01:01/01:01", "01:01/01:03", "01:03/01:01", "01:03/01:03",
"HLA-E*01:01/*01:01", "HLA-E*01:01/*01:03", "HLA-E*01:03/*01:01", "HLA-E*01:03/*01:03",
"HLA-E*01:01/HLA-E*01:01", "HLA-E*01:01/HLA-E*01:03", "HLA-E*01:03/HLA-E*01:01", "HLA-E*01:03/HLA-E*01:03",
}
VALID_TYK2_RS34536443_GENOTYPES = {"G/G", "G/C", "C/G", "C/C"}
VALID_KIR_LIGAND_GROUPS = {"C1/C1", "C1/C2", "C2/C1", "C2/C2"}
_VALID_HLAC_4DIGIT_RELATIONS = {
"SELF_4DIGIT_MATCH",
"EXACT_4DIGIT_AUTOLOGOUS_OR_MATCHED",
"KIR_MATCH_FOREIGN_4DIGIT_ALLO",
"KIR_LIGAND_MISMATCH",
"UNSPECIFIED",
"UNSPECIFIED_ASSUMED_4DIGIT_OR_B_PRIME_SCT",
}
# Standard synthesized guide RNA scaffolds (5'->3' RNA) for manufacturing sequence completeness (AUDIT-REF):
ASCAS12A_DIRECT_REPEAT_20NT_RNA = "UAAUUUCUACUCUUGUAGAU"
SPCAS9_SGRNA_SCAFFOLD_80NT_RNA = "GUUUUAGAGCUAGAAAUAGCAAGUUAAAAUAAGGCUAGUCCGUUAUCAACUUGAAAAAGUGGCACCGAGUCGGUGCUUUU"
SPCAS9_SGRNA_SCAFFOLD_76NT_RNA = SPCAS9_SGRNA_SCAFFOLD_80NT_RNA # Backwards-compatible alias; actual string length is 80 nt (76-nt core + 4U tail)
PEMAX_EPEGRNA_SCAFFOLD_76NT_RNA = "GUUUUAGAGCUAGAAAUAGCAAGUUAAAAUAAGGCUAGUCCGUUAUCAACUUGAAAAAGUGGCACCGAGUCGGUGC"
# 42-nt 3' motif = 37-nt tevopreQ1 pseudoknot (whose 5' stem begins with the 8-nt CGCGGUUC sequence; 0-nt separate linker) + 5-nt AUUUU U6 termination tail (AUDIT-REF [DEC-078]):
TEVOPREQ1_PSEUDOKNOT_37NT_CORE_RNA = "CGCGGUUCUAUCUAGUUACGCGUUAAACCAACUAGAA"
TEVOPREQ1_U6_TERMINATION_TAIL_5NT_RNA = "AUUUU"
TEVOPREQ1_PSEUDOKNOT_42NT_RNA = TEVOPREQ1_PSEUDOKNOT_37NT_CORE_RNA + TEVOPREQ1_U6_TERMINATION_TAIL_5NT_RNA
# Uncalibrated positional mismatch retention weights for split-junction screening diagnostics (AUDIT-REF):
SPCAS9_POS_RETENTION_WEIGHTS_20NT = (
0.88, 0.85, 0.82, 0.78, 0.74, 0.70, 0.65, 0.58, 0.50, 0.44,
0.38, 0.32, 0.25, 0.18, 0.12, 0.08, 0.05, 0.03, 0.02, 0.01,
)
ASCAS12A_POS_RETENTION_WEIGHTS_23NT = (
0.01, 0.02, 0.02, 0.03, 0.04, 0.05, 0.07, 0.09, 0.12, 0.15,
0.18, 0.22, 0.26, 0.30, 0.35, 0.42, 0.50, 0.58, 0.78, 0.85,
0.90, 0.94, 0.97,
)
def compute_split_junction_residual_cleavage_metrics(
protospacer_5to3: str,
pam_5to3: str,
nuclease: str,
left_junction_seq_5to3: str,
right_junction_seq_5to3: str,
) -> Dict[str, Any]:
"""
Evaluate raw PAM/seed retention and uncalibrated positional mismatch diagnostics across both the
5' (`HA_L|Insert`) and 3' (`Insert|HA_R`) post-HDR chromosomal junctions when a protospacer is
split across an HDR insertion site (closing AUDIT-REF & AUDIT-REF).
Separates nuclease-specific AsCas12a Ultra vs HiFi-SpCas9 R691A rules and explicitly qualifies
heuristic mismatch scores as uncalibrated screening diagnostics rather than empirical probabilities.
"""
protospacer_5to3 = _validated_nucleotides(protospacer_5to3, "protospacer")
pam_5to3 = _validated_nucleotides(pam_5to3, "PAM")
left_junction_seq_5to3 = _validated_nucleotides(left_junction_seq_5to3, "left junction")
right_junction_seq_5to3 = _validated_nucleotides(right_junction_seq_5to3, "right junction")
if not isinstance(nuclease, str) or not any(x in nuclease for x in ("Cas12a", "SpCas9", "PEmax")):
raise ValueError("Unsupported nuclease family")
n_len = len(protospacer_5to3)
is_cas12a = "Cas12a" in nuclease
if is_cas12a and ("SpCas9" in nuclease or "PEmax" in nuclease):
raise ValueError("Ambiguous nuclease family")
if (n_len != (23 if is_cas12a else 20) or len(pam_5to3) != (4 if is_cas12a else 3)
or any(len(s) != n_len + len(pam_5to3) for s in (left_junction_seq_5to3, right_junction_seq_5to3))):
raise ValueError("Protospacer, PAM and complete junction window lengths must match the nuclease")
if ((is_cas12a and not (pam_5to3[:3] == "TTT" and pam_5to3[3] in "ACG"))
or (not is_cas12a and pam_5to3[1:] != "GG")):
raise ValueError("Reference PAM does not match the declared nuclease family")
weights = ASCAS12A_POS_RETENTION_WEIGHTS_23NT if is_cas12a else SPCAS9_POS_RETENTION_WEIGHTS_20NT
def _score_candidate_window(candidate_proto: str, candidate_pam: str) -> Dict[str, Any]:
mismatches = [
idx + 1 for idx, (a, b) in enumerate(zip(protospacer_5to3, candidate_proto)) if a != b
]
if is_cas12a:
pam_intact = len(candidate_pam) == 4 and candidate_pam[:3] == "TTT" and candidate_pam[3] in {"A", "C", "G"}
seed_mismatches = [m for m in mismatches if m <= 18]
seed_intact = (len(seed_mismatches) == 0)
attenuation_model = "AsCas12a_Ultra_M537R_F870L_5prime_PAM_and_18nt_seed_requirement"
else:
pam_intact = len(candidate_pam) == 3 and candidate_pam[1:] == "GG"
seed_mismatches = [m for m in mismatches if m >= 9]
seed_intact = (len(seed_mismatches) == 0)
attenuation_model = "HiFi_SpCas9_R691A_PAM_distal_R_loop_docking_checkpoint"
if not pam_intact:
raw_pos_prod = 0.0
nuclease_attenuated_heuristic = 0.0
else:
raw_pos_prod = 1.0
for m_pos in mismatches:
raw_pos_prod *= weights[m_pos - 1]
if is_cas12a:
# AsCas12a Ultra (M537R/F870L) requires intact 5'-TTTV-3' PAM + PAM-proximal positions 1..18;
# splitting between nt +15 and +16 introduces mismatches in positions 16..23 (including 3 inside nt 1..18):
cas12a_factor = 0.02 if len(seed_mismatches) >= 2 else (0.15 if len(seed_mismatches) == 1 else 0.50)
nuclease_attenuated_heuristic = raw_pos_prod * cas12a_factor
else:
# HiFi-SpCas9 R691A (Vakulskas et al. 2018, Nat Med 24:1216) requires 20-bp R-loop zipping across
# PAM-distal positions 1..6 to activate HNH domain docking; when the 3'-AGG PAM and 11-14 nt PAM-proximal
# seed remain intact on HA_R, silent PAM/seed shield mutations in HA_R are recommended for complete immunity:
hifi_factor = (0.015 ** max(1, len(mismatches) - 3)) if len(mismatches) >= 4 else 0.10
nuclease_attenuated_heuristic = raw_pos_prod * hifi_factor
heuristic_mit_proxy = 0.0 if (not pam_intact or len(mismatches) >= 5) else round(raw_pos_prod * 0.25, 8)
return {
"candidate_protospacer_5to3": candidate_proto,
"candidate_pam_5to3": candidate_pam,
"pam_intact": pam_intact,
"seed_region_intact": seed_intact,
"total_mismatches_vs_wt_spacer": len(mismatches),
"seed_region_mismatches": len(seed_mismatches),
"mismatch_positions_1based": mismatches,
"nuclease_specific_attenuation_model": attenuation_model,
"score_calibration_status": "UNCALIBRATED_POSITIONAL_HEURISTIC_REQUIRING_WETLAB_T7E1_NGS_VALIDATION",
"positional_retention_product_assigned_weights_uncalibrated": round(raw_pos_prod, 6),
"positional_retention_product_assigned_weights": round(raw_pos_prod, 6),
"hsu_2013_mit_off_target_score": None,
"doench_2016_cfd_off_target_score": None,
"published_cfd_or_hsu_mit_matrix_status": "UNAVAILABLE_UNCALIBRATED_POSITIONAL_HEURISTIC_ONLY",
"unattenuated_wt_cas_cfd_score": round(raw_pos_prod, 6),
"uncalibrated_positional_mismatch_score": round(raw_pos_prod, 6),
"residual_cfd_cleavage_probability": None,
"residual_mit_cleavage_probability": None,
"nuclease_attenuated_positional_heuristic_uncalibrated": round(nuclease_attenuated_heuristic, 8),
"nuclease_attenuated_positional_heuristic": round(nuclease_attenuated_heuristic, 8),
"assigned_panel_heuristic": round(heuristic_mit_proxy, 8),
"silent_ha_r_pam_or_seed_shield_recommended_if_wt_cas": bool(pam_intact and seed_intact),
}
if is_cas12a:
left_eval = _score_candidate_window(left_junction_seq_5to3[4 : 4 + n_len], left_junction_seq_5to3[:4])
right_eval = _score_candidate_window(right_junction_seq_5to3[4 : 4 + n_len], right_junction_seq_5to3[:4])
else:
left_eval = _score_candidate_window(left_junction_seq_5to3[:n_len], left_junction_seq_5to3[n_len : n_len + len(pam_5to3)])
right_eval = _score_candidate_window(right_junction_seq_5to3[:n_len], right_junction_seq_5to3[n_len : n_len + len(pam_5to3)])
max_hifi_cfd = max(
left_eval["nuclease_attenuated_positional_heuristic"],
right_eval["nuclease_attenuated_positional_heuristic"],
)
max_wt_cfd = max(
left_eval["unattenuated_wt_cas_cfd_score"],
right_eval["unattenuated_wt_cas_cfd_score"],
)
any_pam_retained = bool(left_eval["pam_intact"] or right_eval["pam_intact"])
any_pam_and_seed_retained = bool(
(left_eval["pam_intact"] and left_eval["seed_region_intact"])
or (right_eval["pam_intact"] and right_eval["seed_region_intact"])
)
return {