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…
def simulate_stage0_to_stage7_perturbation_plane(
ref: Dict[str, Any],
construct_verification: Dict[str, Any],
motif_scans: Dict[str, Any],
effects_path: Optional[Path] = None,
) -> Dict[str, Any]:
"""
Literature-anchored stage-specific prior lookup with independent per-stage Monte Carlo
uncertainty bands (N = 1,000 draws per stage/endpoint; not a fitted ODE/GRN dynamical model),
consuming live GTEx TPMs, ENCODE SCREEN cCREs, bounded JASPAR PWM scores, strict construct
promoter-direction & CDS grammar verification, and deduplicated Ring-1 atomic effect studies
across all 6 HIP-Core factors (X1..X6).
Closes V70-04, AUDIT-REF, AUDIT-REF, AUDIT-REF, 019, 043, 053, 069, 074, 111, 112, 113.
"""
eff_file = effects_path if effects_path is not None else RING1_EFFECTS_PATH
# Count biological targets once: PD-L1/PDL1/CD274 are one gene, not
# independent evidence channels. Preserve old display keys explicitly below.
canonical_gene_aliases = {
"B2M": ("B2M",), "HLAE": ("HLAE", "HLA-E"), "CD47": ("CD47",),
"CIITA": ("CIITA",), "CXCL10": ("CXCL10",), "SERPINB9": ("SERPINB9",),
"CD274": ("CD274", "PD-L1", "PDL1"), "TYK2": ("TYK2",),
"TXNIP": ("TXNIP",), "RNLS": ("RNLS",), "CASP9": ("CASP9", "ICASP9"),
}
legacy_gene_keys = {
"B2M": "B2M", "HLA-E": "HLAE", "CD47": "CD47", "CIITA": "CIITA",
"CXCL10": "CXCL10", "SERPINB9": "SERPINB9", "PD-L1": "CD274",
"CD274": "CD274", "TYK2": "TYK2", "TXNIP": "TXNIP", "RNLS": "RNLS", "ICASP9": "CASP9",
}
token_regexes = {
g: re.compile(r"(?<![A-Z0-9])(?:" + "|".join(re.escape(alias) for alias in aliases) + r")(?![A-Z0-9])")
for g, aliases in canonical_gene_aliases.items()
}
gene_study_sets: Dict[str, Dict[str, set]] = {g: {"total": set(), "protective": set(), "penalty": set()} for g in canonical_gene_aliases}
unique_effect_ids: set = set()
seen_effect_records: Dict[str, str] = {}
duplicate_exact_effect_records_skipped = 0
excluded_effect_ids: set = set()
excluded_study_pmids: set = set()
allowed_source_types = {"FullText_XML_or_PDF", "FullText_Plus_Supplement_or_GEO", "Abstract_Only",
"Citation_Only_No_Abstract_Indexed", "Project_Summary",
"Preprint_Superseded_By_Peer_Reviewed", "Review_or_Commentary"}
if not eff_file.exists():
raise FileNotFoundError(f"Required Ring-1 atomic effects file does not exist: {eff_file}")
effects_bytes = eff_file.read_bytes()
effects_sha256 = hashlib.sha256(effects_bytes).hexdigest()
try:
effects_input_path = str(eff_file.resolve().relative_to(REPO_ROOT.resolve()))
except ValueError:
effects_input_path = f"external-input/{eff_file.name}"
for line in effects_bytes.decode("utf-8").splitlines():
sline = line.strip()
if not sline:
continue
eff = json.loads(sline)
if not isinstance(eff, dict):
raise ValueError("Atomic effect rows must be JSON objects")
rec_key, pmid_key = eff.get("effect_id"), eff.get("pmid")
if not isinstance(rec_key, str) or not rec_key.strip():
raise ValueError("Atomic effect rows require a nonempty effect_id")
if not isinstance(pmid_key, str) or re.fullmatch(r"[1-9][0-9]{0,8}", pmid_key) is None:
raise ValueError(f"Atomic effect requires an explicit numeric-string PMID: {rec_key}")
if rec_key.startswith("pmid") and re.match(r"pmid([0-9]+)_", rec_key) and re.match(r"pmid([0-9]+)_", rec_key).group(1) != pmid_key:
raise ValueError(f"Atomic effect ID/PMID identity mismatch: {rec_key}")
try:
canonical_row = json.dumps(eff, sort_keys=True, separators=(",", ":"), allow_nan=False)
except (ValueError, TypeError) as exc:
raise ValueError(f"Atomic effect must contain finite JSON values: {rec_key}") from exc
if rec_key in seen_effect_records:
if seen_effect_records[rec_key] != canonical_row:
raise ValueError(f"Conflicting duplicate atomic effect ID: {rec_key}")
duplicate_exact_effect_records_skipped += 1
continue
seen_effect_records[rec_key] = canonical_row
unique_effect_ids.add(rec_key)
superseded = eff.get("superseded_by_pmid")
if superseded is not None and (not isinstance(superseded, str) or re.fullmatch(r"[1-9][0-9]{0,8}", superseded) is None):
raise ValueError(f"Invalid superseded_by_pmid identity: {rec_key}")
source_type = eff.get("source_text_type")
if source_type not in allowed_source_types:
raise ValueError(f"Atomic effect requires a validated source_text_type: {rec_key}")
if source_type in {"Citation_Only_No_Abstract_Indexed", "Project_Summary", "Preprint_Superseded_By_Peer_Reviewed", "Review_or_Commentary"} or eff.get("superseded_by_pmid"):
excluded_effect_ids.add(rec_key)
excluded_study_pmids.add(pmid_key)
continue
focal_text = eff.get("focal_factor_X")
direction = eff.get("effect_direction")
penalty = eff.get("secretome_or_differentiation_penalty_observed", False)
if not isinstance(focal_text, str):
raise ValueError(f"Atomic effect focal_factor_X must be a string: {rec_key}")
if direction not in {"Protective_or_Improved", "Deleterious_or_Impaired", "Neutral_or_NonInferior", "Descriptive_or_Unoriented"}:
raise ValueError(f"Atomic effect requires a canonical effect_direction: {rec_key}")
if type(penalty) is not bool:
raise ValueError(f"Atomic effect penalty flag must be a boolean: {rec_key}")
focal_text = focal_text.upper()
is_prot = direction == "Protective_or_Improved"
is_pen = penalty or direction == "Deleterious_or_Impaired"
for g in canonical_gene_aliases:
if token_regexes[g].search(focal_text):
gene_study_sets[g]["total"].add(pmid_key)
if is_prot:
gene_study_sets[g]["protective"].add(pmid_key)
if is_pen:
gene_study_sets[g]["penalty"].add(pmid_key)
if len(unique_effect_ids) == 0:
raise ValueError(f"Ring-1 atomic effects file is empty (0 records): {eff_file}")
canonical_gene_effect_counts: Dict[str, Dict[str, int]] = {
g: {k: len(v) for k, v in sdict.items()} for g, sdict in gene_study_sets.items()
}
gene_effect_counts = {legacy: copy.deepcopy(canonical_gene_effect_counts[canonical])
for legacy, canonical in legacy_gene_keys.items()}
# Verify construct ledger architecture and promoter/CDS orientation across Arm 1B, Arm 1A, and Locus 3 (closes 069 & 113)
grammar_audit = verify_construct_part_grammar(construct_verification)
if not grammar_audit["all_construct_grammars_verified"]:
raise ValueError(f"Construct grammar validation failed: {grammar_audit}")
arm1b_constitutive_cd47_verified = grammar_audit["arm1b_constitutive_cd47_verified"]
arm1b_sense_hlae_verified = grammar_audit["arm1b_sense_hlae_verified"]
arm1a_bicistronic_verified = grammar_audit["arm1a_bicistronic_verified"]
locus3_bicistronic_verified = grammar_audit["locus3_bicistronic_verified"]
# Validate consumed calibration inputs before applying bounded prior transforms.
# Invalid values must not be converted into plausible output by min/max clamps.
def calibration_number(value: Any, label: str, is_tpm: bool = False) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{label} must be a finite numeric value, not a boolean or numeric string")
try:
numeric = float(value)
except (ValueError, OverflowError) as exc:
raise ValueError(f"{label} exceeds the finite numeric domain") from exc
if not math.isfinite(numeric):
raise ValueError(f"{label} must be finite")
if is_tpm and not 0.0 <= numeric <= 1_000_000.0:
raise ValueError(f"{label} TPM must be in [0, 1000000]")
return numeric
gtex = ref.get("gtex_v8_v10_human_tissue_expression", {})
screen = ref.get("encode_screen_2456_biosample_expression", {})
try:
b2m_pancreas_tpm = calibration_number(gtex["B2M"]["pancreas_median_tpm"], "GTEx B2M pancreas", True)
cd47_pancreas_tpm = calibration_number(gtex["CD47"]["pancreas_median_tpm"], "GTEx CD47 pancreas", True)
cxcl10_screen = screen["CXCL10"]
cxcl10_screen_key = ("max_tpm_across_encode_biosamples" if "max_tpm_across_encode_biosamples" in cxcl10_screen
else "all_biosamples_max_tpm")
cxcl10_encode_biosample_max_tpm = calibration_number(cxcl10_screen[cxcl10_screen_key], "ENCODE CXCL10 maximum", True)
cxcl10_isre_top_score = calibration_number(
motif_scans["CXCL10_promoter_chr4_76023197_76023797"]["top_jaspar_pwm_hits"]["MA0137.3_STAT1"]["top_hits"][0]["log2_odds_score"],
"CXCL10 STAT1 PWM score")
b2m_isre_top_score = calibration_number(
motif_scans["B2M_promoter_chr15_44711217_44711817"]["top_jaspar_pwm_hits"]["MA0050.2_IRF1"]["top_hits"][0]["log2_odds_score"],
"B2M IRF1 PWM score")
except (KeyError, IndexError, TypeError) as exc:
raise ValueError("Missing or malformed consumed GTEx/ENCODE/PWM calibration input") from exc
# Strictly positive softplus motif activation transforms so negative log2_odds_score never yields <= 0 protein/secretion (closes 074 & 112)
cxcl10_motif_activation = min(1.5, math.log1p(math.exp(max(-20.0, min(25.0, cxcl10_isre_top_score)))) / 20.0)
b2m_motif_activation = min(1.5, math.log1p(math.exp(max(-20.0, min(25.0, b2m_isre_top_score)))) / 20.0)
# Ring-1 empirical evidence weight modifiers indexed continuously by deduplicated directional study PMIDs
# across 11 canonical targets (12 deprecated display keys; aliases count once).
# Note (AUDIT-REF; DEC-071): ring1_evidence_weight = min(1.0, max(0.05, directional_study_total / 148.0))
# is an engineering prior-shrinkage multiplier that couples Layer-2 prior projections to corpus completeness
# (evaluating to 112/148 = 0.756757 on the live 112-count directional corpus vs 1.0 at the 148-study saturation ceiling),
# not a physical biophysical parameter; wet-lab Gate 0A/0B/0C release thresholds (200k resting / 180k post-stress CD47,
# 15k resting / 50k IFN-g HLA-E, >= 0.30 uM Hour-0 SERPINB9) remain fixed absolute physical floors independent of corpus size.
cd47_prot_studies_n = min(gene_effect_counts["CD47"]["protective"], 25)
cd47_pen_studies_n = min(gene_effect_counts["CD47"]["penalty"], 10)
tyk2_pen_studies_n = min(gene_effect_counts["TYK2"]["penalty"], 10)
directional_study_total = sum(c["protective"] + c["penalty"] for c in canonical_gene_effect_counts.values())
ring1_evidence_weight = round(min(1.0, max(0.05, directional_study_total / 148.0)), 6)
effects_corpus_status = (
"PASS_FULL_DIRECTIONAL_EVIDENCE_CORPUS_VERIFIED"
if directional_study_total >= 100
else (
"PARTIAL_EVIDENCE_CORPUS"
if directional_study_total >= 10
else "MINIMAL_SUBSET_EVIDENCE_CORPUS_PRIOR_WEIGHTED"
)
)
# Monte Carlo sampler helper (deterministic seed)
rng = random.Random(20261023)
def mc_interval(mean: float, sd: float, lo_clip: float = 0.0, hi_clip: float = 1e9, n_draws: int = 1000) -> Dict[str, float]:
samples = sorted(min(hi_clip, max(lo_clip, rng.gauss(mean, sd))) for _ in range(n_draws))
return summarize_prior_draws(samples)
# Reference baseline counts (47,919 CD47 and 18,000 HLA-E molecules/cell) are anchored at
# canonical GTEx pancreas median TPMs (CD47=38.4, B2M=243.4, where native surface HLA-E is
# scaled by rate-limiting B2M partner TPM because HLA-E TPM is absent from the 6-gene GTEx table;
# ratio=1.0 on canonical inputs and propagates proportionally under expression perturbation tests):
basal_cd47_wt = max(0.0, 47919.0 * (cd47_pancreas_tpm / 38.4))
basal_hlae_wt = max(0.0, 18000.0 * (b2m_pancreas_tpm / 243.4)) if b2m_pancreas_tpm > 0 else 0.0
raw_eef1a_boost = 1.0 + 5.2418456 * ring1_evidence_weight
eef1a_arm1b_cd47_mult = round(raw_eef1a_boost if arm1b_constitutive_cd47_verified else 1.0, 6)
eta_skip = 0.88 # Assigned downstream-expression prior; not cassette-specific measured skipping (PMID:28526819).
eta_2a_skipping = eta_skip
eef1a_arm1a_cd47_mult = round(raw_eef1a_boost * eta_skip if arm1a_bicistronic_verified else 1.0, 6)
arm1b_hlae_mult = round((4.8 + 0.4 * ring1_evidence_weight) * ring1_evidence_weight if arm1b_sense_hlae_verified else 0.0, 3)
arm1a_hlae_mult = round(4.9 * ring1_evidence_weight if arm1a_bicistronic_verified else 0.0, 3)
cxcl10_inducible_fold = max(1e-4, (cxcl10_encode_biosample_max_tpm / 100.0) * cxcl10_motif_activation * ring1_evidence_weight)
grn_edges = [
{"source_tf": "STAT1_IRF1", "target": "TYK2_KRAS_MAPK", "stage": "Stage_4_to_Stage_6", "effect": "TYK2 loss derepresses KRAS/MAPK and attenuates NEUROG3+ emergence (-46.3%, PMID:36289205)"},
{"source_tf": "PDX1_NKX6-1", "target": "NEUROG3", "stage": "Stage_4_PP2_to_Stage_6_EP", "effect": "Endocrine commitment bottleneck"},
{"source_tf": "NEUROG3_FEV", "target": "MAFA_INS_UCN3", "stage": "Stage_6_EP_to_Stage_7_SC_Beta", "effect": "Beta-cell maturation (-32.0% INS+ under TYK2-/-, PMID:36289205)"},
]
# Stage-specific priors across all 6 HIP-Core factors (X1..X6), Scenario A (Arm 1B & Arm 1A),
# Scenario B (B2 TYK2 P1104A 5-locus & B1 TYK2-/- 6-locus), and UP421 cadaveric benchmark (closes 017, 043, 053, 074, 113):
# Note (AUDIT-REF): Chandra et al. 2022 (PMID:36289205 Source Data Fig 2c, 2i, 2k) observed:
# - Stage 5 NEUROG3+ immunostaining (Fig 2c): 28.81% WT vs 15.45% TYK2-KO (-46.37% relative reduction)
# - Stage 7 INS+ flow cytometry (Fig 2i): 29.78% WT vs 21.90% TYK2-KO (-26.46% relative reduction)
# - Stage 7 INS+ immunostaining (Fig 2k): 23.73% WT vs 16.01% TYK2-KO (-32.54% relative reduction)
# The absolute fractions below (0.678 -> 0.364 [-46.31%] and 0.600 -> 0.408 [-32.00%]) apply those published
# relative reductions to OpenIslet's assigned Stage-0 WT model baselines (0.678 and 0.600).
tyk2_ko_s6_mean = round(0.364 - 0.004 * (tyk2_pen_studies_n - 1), 3)
tyk2_ko_s7_mean = round(0.408 - 0.004 * (tyk2_pen_studies_n - 1), 3)
genotype_specs = [
{
"genotype_id": "WT_UNEDITED_CONTROL",
"hip_core_factor_vector_X1_to_X6": [-1, -1, -1, -1, -1, -1],
"is_hpsc_differentiated": True,
"description": "Unedited WT hPSC line (Stage 0 -> Stage 7 tri-hormonal + isogenic iEC)",
"stage4_mean": 0.840, "stage4_sd": 0.035,
"stage6_mean": 0.678, "stage6_sd": 0.042,
"beta_yield_mean": 0.600, "beta_yield_sd": 0.040,
"gsis_mean": 3.40, "gsis_sd": 0.32,
"iec_branch_mean": 1.00, "iec_branch_sd": 0.08,
"cd47_mult": 1.0, "hlae_mult": 1.0, "hlae_resting_unstim_mult": 1.0,
"cxcl10_ko": False, "locus3_ki": False,
"nkg2a_lysis_mean": 4.2, "kir_lysis_mean": 5.1, "allo_ctl_mean": 88.5, "auto_ctl_mean": 91.2,
"empirical_literature_anchors": [
{
"pmid": "PMID:36289205",
"journal": "Nature Communications (Chandra et al. 2022, reference GEO accession GSE190726)",
"endpoint": "Assigned OpenIslet WT hPSC Stage 4 PP2 (0.840), Stage 5/6 NEUROG3+ endocrine progenitor (0.678), and Stage 7 SC-beta (0.600) model baselines, paired with Chandra et al. 2022 Source Data relative TYK2-/- perturbation ratios (Fig 2c S5 NEUROG3+ immunostaining 28.81% WT vs 15.45% KO [-46.37%]; Fig 2i S7 INS+ flow 29.78% WT vs 21.90% KO [-26.46%]; Fig 2k S7 INS+ immunostaining 23.73% WT vs 16.01% KO [-32.54%]; raw GEO matrix not refitted)",
}
],
},
{
"genotype_id": "SCENARIO_A_ARM_1B_UNIVERSAL_LEAN_4LOCUS",
"hip_core_factor_vector_X1_to_X6": [1, 1, 1, -1, -1, -1],
"construct_arm": "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01",
"is_hpsc_differentiated": True,
"description": "B2M::[Bidir CD47-IgV-GPI <- EEF1A1_core | Syn_5xISRE -> HLA-E*01:03(VMAPRTLVL) full tail] + CIITA-/- + CXCL10::SERPINB9-GSG-P2A-PD-L1 + AAVS1-[455bp-CBX3-A2UCOE]-iCasp9",
"stage4_mean": round(0.812 + 0.014 * ring1_evidence_weight, 3), "stage4_sd": 0.038,
"stage6_mean": round(0.655 + 0.012 * ring1_evidence_weight, 3), "stage6_sd": 0.044,
"beta_yield_mean": round(0.550 + 0.040 * ring1_evidence_weight, 4), "beta_yield_sd": 0.045,
"gsis_mean": round(3.05 + 0.27 * ring1_evidence_weight, 3), "gsis_sd": 0.35,