#!/usr/bin/env python3 """ Step 5 & 6: Project Islet-1 Sign-Sensitive, Endpoint-Oriented & Locus-Penalized Evaluator (v0.6.9). Upgrades in v0.6.0 (incorporating Red-Team Reviews): 1. Zero-Evidence Baseline = 0.0: - If target_profiles is empty (`{}`), `run_combinatorial_multi_gate_search({})` returns 0.0 across all gates and composite scores. 2. Broadcast Attribution Eliminated (Audit §5.2.1): - Atomic effects are credited ONLY to genes explicitly named in `focal_factor_X` or `verbatim_evidence_quote` (or to the single target gene in single-gene studies). Multi-gene studies never broadcast every effect to all co-mentioned genes. 3. Endpoint-Orientation-Aware Sign & Counter-Evidence Sensitivity (Audit §2.2 + Audit §4.2/§5.2): - Preserves algebraic signs of `log_response_ratio_or_smd` (`sign_flip` changes profiles & rankings). - Orients lower-is-better hazard endpoints (`specific lysis`, `apoptosis`, `cell death`) vs higher-is-better functional endpoints (`GSIS`, `viability`, `survival`, `C-peptide`). - Separates `effect_direction == "Deleterious_or_Impaired"` from independent `secretome_or_differentiation_penalty_observed`. 4. Exact Specification Parity & Base-Edit Penalty (Audit §1.3): - `search_cuts == named_cuts` and `search_base_edits_B == named_base_edits_B` across all architectures. - Implements both chromosomal DSB translocation penalty `exp(-0.15 * max(0, K - 4))` and nickase base/prime-edit penalty `0.965 ** B` (`PMID:39529170`). - Unifies `Chassis B` (`HLA-A/B/CIITA-/- [retaining -21M HLA-C] + TYK2-/- + CXCL10::PD-L1-P2A-SERPINB9 + AAVS1-CAG-iCasp9 + INS base edit`, `K=6, B=1`). - Locks `HLA-E*01:03` single-chain trimer nonamer to `VMAPRTLVL` (HLA-A*02:01 leader, minimizing NKG2C+ adaptive NK activation) and locks suicide switch to biallelic `AAVS1-CAG-iCasp9` (`<10^-8` escape bound). 5. Explicit Engineering Priors, Posterior Uncertainty & Executable Graveyard Rules: - Exposes `engineering_priors_and_sensitivity_table`, `pareto_frontier_by_locus_budget_K`, `global_rank_among_all_combinations`, `lower_10pct_cred_bound`, and `triggered_graveyard_rules`. """ from __future__ import annotations import contextvars import copy import json import hashlib import importlib.util from types import MappingProxyType import math import re from collections import Counter from fractions import Fraction from itertools import product from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parent.parent EXTRACTED_DIR = PROJECT_ROOT / "data" / "extracted" OMICS_DIR = PROJECT_ROOT / "data" / "omics" GRAVEYARD_PATH = PROJECT_ROOT / "data" / "graveyard" / "idea_graveyard_v0.5.json" GRAPH_PATH = EXTRACTED_DIR / "cross_study_discovery_graph.json" OUT_PATH = EXTRACTED_DIR / "islet1_candidate_stack_rankings.json" def _load_local_helper(name): spec = importlib.util.spec_from_file_location("openislet_" + name, PROJECT_ROOT / "scripts" / (name + ".py")) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module engineering_complexity_discount = _load_local_helper("engineering_priors").engineering_complexity_discount validate_public_excerpt_token = _load_local_helper("public_excerpt_policy").validate_token def _finite_real(value, label: str) -> float: """Reject unknown/non-real data before arithmetic, conversion or clipping.""" if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{label} must be a finite real number") try: number = float(value) except (OverflowError, ValueError) as exc: raise ValueError(f"{label} is outside the finite numeric domain") from exc if not math.isfinite(number): raise ValueError(f"{label} must be a finite real number") return number def _profile_has_empirical_studies(profile: dict) -> bool: if not isinstance(profile, dict): raise ValueError("Target profiles must contain explicit gene mappings") count = profile.get("n_empirical_studies", profile.get("n_studies_total", 0)) if type(count) is not int or count < 0: raise ValueError("Empirical study counts must be nonnegative integers") return count > 0 def _profile_standard_error(profile: dict, default: float) -> float: if not isinstance(profile, dict): raise ValueError("Target profiles must contain explicit gene mappings") value = _finite_real(profile.get("posterior_se", default), "Gene evidence dispersion") if value < 0: raise ValueError("Gene evidence dispersion must be nonnegative") return value def _effect_orientation(effect: dict) -> int: """One typed endpoint orientation for private and redacted representations.""" polarity = effect.get("endpoint_polarity_registry") if polarity is None: # Compatibility for deliberately minimal qualitative fixtures. Numeric # contrasts require the explicit measured-endpoint polarity contract. if effect.get("log_response_ratio_or_smd") is not None: raise ValueError("Numeric evidence requires an endpoint_polarity_registry") return int(get_endpoint_orientation_sign((effect.get("outcome_variable_Y") or "") + " " + (effect.get("verbatim_evidence_quote") or ""))) expected = {"Higher_Is_Better_Protective_Endpoint": 1, "Lower_Is_Better_Hazard_Endpoint": -1, "Qualitative_or_Unoriented_Endpoint": 0} if not isinstance(polarity, dict): raise ValueError("endpoint_polarity_registry must be a dictionary") kind = polarity.get("polarity_class"); sign = polarity.get("orientation_sign") if not isinstance(kind, str) or kind not in expected or type(sign) is not int or sign != expected[kind]: raise ValueError("Endpoint polarity class and exact integer orientation must agree") if effect.get("log_response_ratio_or_smd") is not None and sign == 0: raise ValueError("Numeric evidence requires an oriented endpoint") return sign FIDELITY_WEIGHTS = { "Tier_1_Human_InVivo": 1.00, "Tier_2A_Human_Cells_InVivo_NHP_or_HumanizedMouse": 0.85, "Tier_2B_Human_Cells_InVitro_HumanImmune_CoCulture": 0.75, "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture": 0.75, "Tier_2C_NHP_Allogeneic_or_Autologous_NonIslet": 0.45, "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse": 0.60, "Tier_4_Rodent_or_Xenogeneic_Only": 0.25, } # Explicit, auditable table of structural & microenvironmental priors with sensitivity ranges (Audit §5.4/§5.6 + Audit A03/A07) ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE = { "locus_dsb_penalty_rate_lambda_K": { "point_estimate": 0.15, "plausible_range": [0.08, 0.25], "formula": "exp(-lambda_K * max(0, K - 4))", "source_rationale": "Clonal attrition, chromosomal translocation, and p53 selection penalty for multiplex Cas9/Cas12a DSBs above K=4.", }, "base_edit_nickase_penalty_factor_gamma_B": { "point_estimate": 0.965, "plausible_range": [0.920, 0.985], "formula": "gamma_B ** B", "source_rationale": "Conservative engineering prior for multiplex nickase single-strand break conversion to DSBs/deletions and deaminase bystander/structural-variant risk per base-edited locus B (extrapolated from Wu et al. 2024 PMID:39529170, which attributed elevated structural variants under ABE to deaminase activity vs Cas9/PE in single-locus cell-line edits).", }, "indirect_apc_presentation_residual_hazard_cap": { "point_estimate": -0.25, "plausible_range": [-0.60, -0.10], "formula": "Applied to Gate 2B logit for MHC-null designs lacking indirect APC stealth validation", "source_rationale": "Donor B2M-/- + CIITA-/- eliminates direct presentation but not host DC phagocytosis of shed secretome/debris presented on host HLA-DQ2/DQ8 (Audit Review §3.4).", }, "resting_b2m_promoter_hour0_density_discount": { "point_estimate": -0.20, "plausible_range": [-0.55, 0.00], "formula": "Applied to Gate 3 logit for endogenous B2M-promoter bicistronic HLA-E-P2A-CD47 pending QuantiBRITE Hour-0 verification", "source_rationale": "Resting Stage 7 beta-cells have low basal B2M transcription prior to IFN-gamma exposure (Audit Review §3.1).", }, "stage7_trihormonal_120um_mvf_cao2_niche_prior": { "point_estimate": 0.45, "plausible_range": [0.20, 0.70], "formula": "Applied to Gate 1 and Gate 5 when cluster diameter <=120 um + Stage 7 maturation + microvessels are used", "source_rationale": "Balboa 2022 (PMID:35241836), Aghazadeh 2021 (PMID:34480863), and Hill/Krogh R_crit = 74.6 um radial diffusion limit.", }, "tyk2_stage0_differentiation_yield_penalty": { "point_estimate": -0.32, "plausible_range": [-0.55, -0.15], "formula": "Applied to Gate 1 logit when clonal TYK2-/- is carried through Stage 0->7 hPSC endocrine differentiation", "source_rationale": "Chandra et al. 2022 (PMID:36289205) demonstrated ~40-60% compromised endocrine progenitor emergence in TYK2-/- hPSC differentiation.", }, } # Complete registry of all 46 prior gate-logit entries (corresponding to 48 float literals in compute_series_system_utility because 2 composite entries decompose into +positive - discount pairs) across Gates 1..5, plus all 8 live-wired auxiliary_evaluator_hyperparameters (Audit A03, Grok P2-3/P2-8, Audit R10) COMPLETE_GATE_COEFFICIENT_REGISTRY = { "pw_base_scale": { "logit_value": 0.08, "plausible_range": [0.05, 0.12], "expression": "Global multiplicative base scale factor pw applied to all 46 structural gate-logit multipliers", "rationale": "Global structural logit scaling constant (default 0.08) mapping dimensionless module multipliers to log-odds increments (Finding 083)", }, "cross_gate_niche_coupling_note": ( "NICHE_TRIHORMONAL_120UM_MVF_CAO2 contributes to Gate 1 (+0.45), Gate 4 (+0.25 when er_k == ER_NONE), " "and Gate 5 (+0.45) because <=120 um Stage 7 tri-hormonal vascularized clusters physically couple " "paracrine GSIS maturation, lower basal ER/hypoxic stress, and 72h oxygen engraftment across the series system." ), "Gate1_Maturation_GSIS_and_Paracrine": { "base_intercept": {"logit_value": 0.40, "expression": "0.08 * 5.0", "rationale": "Baseline hPSC-islet Stage 6/7 endocrine maturation prior"}, "NICHE_TRIHORMONAL_120UM_MVF_CAO2": {"logit_value": 0.45, "expression": "0.08 * 5.625 + _pdelta('stage7_trihormonal_120um_mvf_cao2_niche_prior', 0.45)", "rationale": "ALK5i-free Stage 7 10 nM T3 + 1 mM NAC + logged ZM447439 (Balboa 0.5 uM endocrine vs S7w0-only covariate, analytical LC-MS/MS <= 0.005 uM pre-iEC washout + vascular function verification) tri-hormonal maturation + <=120 um diameter (Balboa et al. 2022 PMID:35241836; Barsby et al. 2022 PMID:36136756; Velazco-Cruz et al. 2019 PMID:30661993)"}, "NICHE_UNEDITED_MACRODEVICE_ENCAPSULATION": {"logit_value": -0.45, "expression": "-0.08 * 5.625", "rationale": "Diffusional lag and central hypoxia in cell-impermeable macrodevice"}, "ALLO_HLA_C_RETAINED_SUPERDONOR_PLUS_TYK2_KO": {"logit_value": -0.32, "expression": "-0.08 * 4.0 + _pdelta('tyk2_stage0_differentiation_yield_penalty', -0.32)", "rationale": "Clonal TYK2-/- compromises Stage 0->7 endocrine progenitor emergence by ~40-60% (PMID:36289205)"}, "AUTO_FULL_KO_G6PC2_SLC30A8_PLUS_BASE_INS_GAD2_IAPP_CXADR": {"logit_value": -0.55, "expression": "-0.08 * 6.875", "rationale": "G6PC2-/- fasting glucose set-point downshift + high-pLI PTPN2/GAD2 disruption (PMID:32569842, PMID:32432213)"}, "ER_RNLS_KO_or_PRAMLINTIDE": {"logit_value": -0.38, "expression": "-0.08 * 4.75", "rationale": "Human iPSC-beta RNLS-/- elevated basal OCR / metabolic precaution prior (poor dynamic GSIS persisted in both WT and RNLS KO in PMID:39988068 Fig. 6)"}, }, "Gate2A_Allo_Adaptive_T_and_DSA_Stealth": { "base_intercept": {"logit_value": 0.10, "expression": "0.08 * 1.25", "rationale": "Baseline allogeneic T-cell/DSA survival prior"}, "ALLO_B2M_HLAE_CD47_SWAP_CIITA_KO": {"logit_value": 0.55, "expression": "0.08 * 6.875", "rationale": "Complete classical HLA-A/B/C and HLA-II deletion + single-chain HLA-E/CD47 (PMID:37156915, PMID:28504668)"}, "ALLO_HLA_C_RETAINED_SUPERDONOR_PLUS_TYK2_KO": {"logit_value": 0.40, "expression": "0.08 * 5.0", "rationale": "HLA-A/B/CIITA KO retaining 1 recipient-matched HLA-C allele + TYK2-/- (PMID:30853558)"}, "ALLO_B2M_CIITA_KO_CD47_LENTI": {"logit_value": 0.38, "expression": "0.08 * 4.75", "rationale": "B2M-/- + CIITA-/- + lentiviral CD47 OE (UP421 / HIP benchmark, PMID:37156915, PMID:40757665)"}, "ALLO_B2M_KO_PDL1_A20_KI": {"logit_value": -0.10, "expression": "0.08 * -1.25", "rationale": "B2M-/- + PD-L1/A20 KI leaving CIITA (HLA-II) intact (VCTX210 benchmark)"}, "ALLO_NONE_MACRODEVICE": {"logit_value": -0.60, "expression": "0.08 * -7.5", "rationale": "Unedited allogeneic HLA inside cell-impermeable macrodevice (shed alloantigen DSA priming)"}, "ALLO_NONE_NAKED": {"logit_value": -1.80, "expression": "0.08 * -22.5", "rationale": "Unedited allogeneic HLA without encapsulation or immunosuppression"}, }, "Gate2B_Autoimmune_T1D_Memory_and_Indirect_APC_Stealth": { "base_intercept_pediatric": {"logit_value": 0.20, "expression": "0.08 * 2.5", "rationale": "Pediatric early-onset T1D high autoreactive memory baseline"}, "base_intercept_lada": {"logit_value": 0.30, "expression": "0.08 * 3.75", "rationale": "Adult-onset LADA lower autoreactive memory baseline"}, "B2M_NULL_DIRECT_CLOAK_PLUS_INDIRECT_APC_DISCOUNT": {"logit_value": 0.30, "expression": "0.08 * 6.875 - 0.08 * 3.125 + _pdelta('indirect_apc_presentation_residual_hazard_cap', -0.25)", "rationale": "Eliminates direct CD8+ autoantigen presentation (+0.55) minus host HLA-DQ2/DQ8 DC indirect presentation hazard (-0.25)"}, "HLA_C_RETAINED_AUTO_NONE": {"logit_value": -0.55, "expression": "-0.08 * 6.875", "rationale": "Retained HLA-C presents unedited insulin/IGRP/ZnT8 epitopes to T1D memory CD8+ T-cells"}, "HLA_C_RETAINED_AUTO_INS_EDIT": {"logit_value": 0.25, "expression": "0.08 * 3.125", "rationale": "INS leader/DRiP base edit reduces preproinsulin/DRiP presentation on retained HLA-C (PMID:42690930)"}, "HLA_C_RETAINED_AUTO_FULL_KO": {"logit_value": 0.20, "expression": "0.08 * 2.5", "rationale": "Multi-autoantigen KO/base-edit on retained HLA-C"}, "ALLO_NONE": {"logit_value": -1.10, "expression": "-0.08 * 13.75", "rationale": "Unedited HLA-I/II fully exposed to T1D autoreactive memory"}, "CYTO_CXCL10_SWAP_PDL1_SERPINB9": {"logit_value": 0.35, "expression": "0.08 * 4.375", "rationale": "CXCL10 chemokine deletion + inducible PD-L1/SERPINB9 local checkpoint/granzyme shield (PMID:36055241, PMID:19641142, PMID:30269996)"}, "CYTO_CONSTITUTIVE_IL10_VIRAL_OE": {"logit_value": -0.75, "expression": "-0.08 * 9.375", "rationale": "Constitutive viral IL-10 pleiotropic mast-cell/granulocyte hazard (Graveyard 008)"}, "CYTO_STAT1_OR_TYK2_CLONAL_KO_WITH_GAS_IND_PDL1": {"logit_value": -0.85, "expression": "-0.08 * 10.625", "rationale": "Epistatic deadlock: STAT1-/- silences GAS/ISRE-inducible PD-L1 (Graveyard 001)"}, }, "Gate3_Innate_NK_Macrophage_and_IBMIR_Shield": { "base_intercept": {"logit_value": 0.20, "expression": "0.08 * 2.5", "rationale": "Baseline innate NK/macrophage survival prior"}, "ALLO_B2M_HLAE_CD47_SWAP_CIITA_KO": {"logit_value": 0.35, "expression": "0.08 * 6.875 - 0.08 * 2.5 + _pdelta('resting_b2m_promoter_hour0_density_discount', -0.20)", "rationale": "Dual CD94/NKG2A (HLA-E*01:03 VMAPRTLVL; non-covalent soluble 3D SPR CD94/NKG2A K_D = 2.10 uM vs CD94/NKG2C K_D = 6.52 uM -> K_C/K_A = 3.1048x < 4.0 [theta_C = 0.2436 at C_eff = 2.10 uM] per Lin et al. 2023 PMID:37264229, vs HLA-G leader VMAPRTLFL K_D(NKG2A) = 0.80 +/- 0.055 uM, K_D(NKG2C) = 5.20 +/- 0.20 uM -> K_C/K_A = 6.50x per Kaiser et al. 2008 PMID:18448674 Table 1 [Vales-Gomez et al. 1999 PMID:10428963 Table I reports 2.33 uM vs 10.77 uM = 4.62x for VMAPRTLFL, 7.35 uM for VMAPRTLIL, 11.23 uM for VMAPRTVLL]; covalent SCT K_C/K_A >= 4.0 selectivity and non-agonism on NKG2C+ adaptive NK subsets require Stage-0 Gate 0A-NK SPR verification and CMV/NKG2C+ stratification per Switch S10; DEC-078) + SIRPa (CD47) shield (+0.55) minus resting B2M-promoter Hour-0 density discount (-0.20)"}, "ALLO_HLA_C_RETAINED_SUPERDONOR_PLUS_TYK2_KO": {"logit_value": 0.35, "expression": "0.08 * 4.375", "rationale": "Retained single HLA-C allele engages KIR2DL and supplies -21M leader peptide (subject to Graveyard 005 ~10-fold lower HLA-C basal expression check after HLA-A/B deletion; PMID:29302013, PMID:37264229)"}, "ALLO_B2M_CIITA_KO_CD47_LENTI": {"logit_value": 0.30, "expression": "0.08 * 3.75", "rationale": "Constitutive lentiviral CD47 OE (>180k molecules/cell; PMID:37156915)"}, "ALLO_B2M_KO_PDL1_A20_KI": {"logit_value": -0.75, "expression": "-0.08 * 9.375", "rationale": "B2M-/- without CD47 or HLA-E triggers NK missing-self lysis"}, "ALLO_NONE": {"logit_value": -0.25, "expression": "-0.08 * 3.125", "rationale": "Unedited allogeneic graft innate/complement vulnerability"}, }, "Gate4_Intrinsic_Cytokine_ER_Granzyme_and_Amyloid_Resilience": { "base_intercept": {"logit_value": 0.10, "expression": "0.08 * 1.25", "rationale": "Baseline intrinsic stress resilience prior"}, "CYTO_CXCL10_SWAP_PDL1_SERPINB9": {"logit_value": 0.45, "expression": "0.08 * 5.625", "rationale": "CXCL10 KO + SERPINB9 Granzyme-B inhibition + PD-L1 (PMID:19641142, PMID:32814902)"}, "CYTO_CONSTITUTIVE_IL10_VIRAL_OE": {"logit_value": -1.00, "expression": "-0.08 * 12.5", "rationale": "Viral IL-10 overexpression failure mode (Graveyard 008)"}, "CYTO_STAT1_OR_TYK2_CLONAL_KO_WITH_GAS_IND_PDL1": {"logit_value": -1.35, "expression": "-0.08 * 16.875", "rationale": "Epistatic promoter-pathway failure (Graveyard 001)"}, "CYTO_NONE_WITH_VCTX210_A20": {"logit_value": 0.15, "expression": "0.08 * 1.875", "rationale": "TNFAIP3 (A20) NF-kB brake in VCTX210"},