scripts/rank_islet1_stacks.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/rank_islet1_stacks.py · SHA-256: c05d5fe606219e88…
"evaluator_disposition_rule": str(gy010.get("evaluator_disposition_rule", "Applies -0.25 logit discount in Gate 2B + requires Decision Experiment #2 indirect APC / SA-FasL gate")),
"reason": "Donor MHC loss does not block host APC presentation of shed autoantigens and alloantigens. An INS leader/DRiP edit does not remove other epitopes or establish indirect immune protection; the warning remains until exact-product assays qualify the residual hazard (PMID:28263308, PMID:36055241, PMID:35559682).",
})
return triggered
def signed_gene_signal(
target_profiles: dict,
genes: list[str] | tuple[str, ...],
scale: float = 0.25,
is_knockout: bool = False,
branch_key: str | None = None,
mode: str | None = None,
) -> float:
"""
Computes a strictly sign-sensitive, perturbation-direction-aware evidence signal from target_profiles.
- Dynamically reads `signed_gene_signal_slope`, `signed_gene_signal_clip_bounds`, and (when `branch_key` is
provided) `gene_signal_scales_by_gate_and_branch` from `COMPLETE_GATE_COEFFICIENT_REGISTRY['auxiliary_evaluator_hyperparameters']` (Audit R10).
- When `is_knockout=True` (or `mode='ko'`), uses the loss-of-function constraint score (`net_evidence_ko_score`,
which applies the gnomAD pLI loss-of-function intolerance penalty).
- When `mode='gof'` (or for gain-of-function transgenes), uses `net_evidence_gof_score` / `net_evidence_and_constraint_score`.
- When `mode in ('preserve', 'base_edit')`, uses `net_evidence_preserve_score` (or `net_evidence_and_constraint_score`)
so gnomAD pLI loss-of-function intolerance is never applied to preserved or base-edited genes (Finding 086).
"""
if not isinstance(target_profiles, dict) or not isinstance(genes, (list, tuple)) or any(not isinstance(g, str) for g in genes):
raise TypeError("Gene signal requires a target mapping and gene identifiers")
if type(is_knockout) is not bool or mode not in (None, "ko", "gof", "preserve", "base_edit"):
raise ValueError("Unknown gene-signal perturbation mode")
_finite_real(scale, "Gene-signal scale")
if not target_profiles or not genes:
return 0.0
eff_scale = _finite_real(_branch_scale(branch_key, scale) if branch_key is not None else scale, "Branch gene-signal scale")
slope = _finite_real(_aux_param("signed_gene_signal_slope", 0.42), "Gene-signal slope")
clip_bounds = _aux_param("signed_gene_signal_clip_bounds", [-4.5, 4.5])
if not isinstance(clip_bounds, (list, tuple)) or len(clip_bounds) != 2:
raise ValueError("Gene-signal clipping requires exactly two finite bounds")
lo_b = _finite_real(clip_bounds[0], "Lower gene-signal bound")
hi_b = _finite_real(clip_bounds[1], "Upper gene-signal bound")
if not lo_b <= 0 <= hi_b or lo_b >= hi_b:
raise ValueError("Gene-signal clipping bounds must be ordered and bracket zero")
total = 0.0
for g in genes:
st = target_profiles.get(g)
if st is None:
continue
if not isinstance(st, dict):
raise ValueError("Target profiles must contain explicit gene mappings")
if not st:
continue
if (is_knockout or mode == "ko") and "net_evidence_ko_score" in st:
net_s = _finite_real(st["net_evidence_ko_score"], f"{g} KO evidence score")
elif mode == "gof" and "net_evidence_gof_score" in st:
net_s = _finite_real(st["net_evidence_gof_score"], f"{g} GOF evidence score")
elif mode in ("preserve", "base_edit") and "net_evidence_preserve_score" in st:
net_s = _finite_real(st["net_evidence_preserve_score"], f"{g} preserve evidence score")
else:
net_s = _finite_real(st.get("net_evidence_and_constraint_score", 0.0), f"{g} evidence score")
term = _finite_real(eff_scale * (slope * net_s), f"{g} scaled gene signal")
total = _finite_real(total + term, "Accumulated gene signal")
bound_scale = (hi_b / 4.5) if total >= 0 else (abs(lo_b) / 4.5)
# Compare before multiplying; overflow must never become a positive score.
if bound_scale == 0:
return 0.0
if total >= 0 and total >= hi_b / bound_scale:
return hi_b
if total < 0 and total <= lo_b / bound_scale:
return lo_b
return max(lo_b, min(hi_b, total * bound_scale))
# Immutable per-evaluation snapshot. Hot-loop lookups never touch the filesystem.
_WETLAB_PARAMETER_DELTAS = MappingProxyType({})
_WETLAB_CALIBRATION_STATUS = {"artifact_present": False, "applied_to_production_priors": False,
"status_reason": "No evaluation context prepared"}
def prepare_wetlab_evaluation_context(report: dict | None = None, path: Path | None = None) -> dict:
"""Validate and freeze one posterior at the evaluation boundary.
The endpoint-to-logit scales are declared engineering mappings, not learned
causal calibrations. Unmapped observations remain visible and unapplied.
"""
global _WETLAB_PARAMETER_DELTAS, _WETLAB_CALIBRATION_STATUS
_WETLAB_PARAMETER_DELTAS = MappingProxyType({})
status = {"calibration_artifact_path": "data/extracted/wetlab_bayesian_posterior_calibration.json",
"artifact_present": False, "applied_to_production_priors": False,
"raw_endpoint_posterior_deltas": {}, "mapped_nonzero_parameter_deltas": {},
"unmapped_endpoint_deltas": {}, "retained_unobserved_endpoints": [], "consumed_parameter_deltas": {}, "mapping_estimand": "uncalibrated engineering logit shift"}
try:
if report is None:
source = path or PROJECT_ROOT / status["calibration_artifact_path"]
if not source.exists():
status["status_reason"] = "Not_Found"
_WETLAB_CALIBRATION_STATUS = status
return dict(status)
report = json.loads(source.read_text(encoding="utf-8"))
if not isinstance(report, dict):
raise ValueError("Posterior report must be a dictionary")
validator_spec = importlib.util.spec_from_file_location("openislet_wetlab_validator", PROJECT_ROOT / "scripts/ingest_wetlab_results.py")
validator = importlib.util.module_from_spec(validator_spec)
validator_spec.loader.exec_module(validator)
status.update(artifact_present=True, calibration_mode=report.get("calibration_mode"),
epistemic_lineage_status=report.get("epistemic_lineage_status"))
if (report.get("calibration_mode") != "EMPIRICAL_WETLAB_INGESTION"
or report.get("epistemic_lineage_status") not in validator.SUPPORTED_EMPIRICAL_LINEAGES
or report.get("contains_synthetic_records", False) is not False):
status["status_reason"] = "Rejected synthetic, mixed or unsupported lineage"
_WETLAB_CALIBRATION_STATUS = status
return dict(status)
raw_updates = report.get("conjugate_posterior_updates")
digest = hashlib.sha256(json.dumps(raw_updates, sort_keys=True, allow_nan=False).encode()).hexdigest()
if report.get("conjugate_posterior_updates_sha256") != digest:
raise ValueError("Missing or mismatched conjugate posterior SHA-256")
# Use fresh identifiers because the validator also guards batch replay.
validator._validate_prior_posterior_report(report, False, "RANKER-EVALUATION-" + digest, "evaluation:" + digest)
updates = dict(raw_updates)
updates.update(report.get("optional_pouch_and_36run_screen_updates_v80_070") or {})
endpoint_map = {
"stage7_sc_beta_yield_fraction_arm1b": ("stage7_trihormonal_120um_mvf_cao2_niche_prior", 1.0),
"cd47_igv_hour0_fold_over_baseline_arm1b": ("resting_b2m_promoter_hour0_density_discount", 0.05),
"serpinb9_p2a_gzmb_log10_kass_M_inv_s_inv": ("Gate4_Intrinsic_Cytokine_ER_Granzyme_and_Amyloid_Resilience::CYTO_CXCL10_SWAP_PDL1_SERPINB9", 0.25),
"aa_vs1_ucoe_icasp9_ap1903_24h_log10_kill": ("Gate5_72h_Vascular_Oxygen_and_80yr_Safety::SAF_AAVS1_CAG_ICASP9_BIALLELIC", 0.25),
"pouch_min_slab_po2_14d_mmhg": ("stage7_trihormonal_120um_mvf_cao2_niche_prior", 0.01),
"ifng_48h_hla_dr_dq_negative_pct_arm1b": ("Gate2A_Allo_Adaptive_T_and_DSA_Stealth::ALLO_B2M_HLAE_CD47_SWAP_CIITA_KO", 0.01),
}
genesis_prior_means = {
row[0]: float(row[1])
for row in (*validator.ENDPOINT_SPECS, *validator.EXTENDED_STAGE0_STAGE1_SPECS)
}
genesis_prior_sds = {
row[0]: float(row[2])
for row in (*validator.ENDPOINT_SPECS, *validator.EXTENDED_STAGE0_STAGE1_SPECS)
}
is_multibatch = len(report.get("ingested_batch_ids", [])) > 1
mapped = {}
for endpoint, update in updates.items():
if endpoint not in genesis_prior_means or endpoint not in genesis_prior_sds:
raise ValueError(f"Unrecognized calibration endpoint {endpoint!r}")
genesis_m = genesis_prior_means[endpoint]
genesis_sd = genesis_prior_sds[endpoint]
if "genesis_prior_mean_exact" in update:
gm_raw = validator._require_finite_float(update["genesis_prior_mean_exact"], f"{endpoint}.genesis_prior_mean_exact")
if not math.isclose(gm_raw, genesis_m, rel_tol=1e-12, abs_tol=0.0):
raise ValueError(f"Endpoint {endpoint!r} genesis_prior_mean_exact={gm_raw} does not match canonical prior {genesis_m}")
if "genesis_prior_sd_exact" in update:
gsd_raw = validator._require_finite_float(update["genesis_prior_sd_exact"], f"{endpoint}.genesis_prior_sd_exact")
if not math.isclose(gsd_raw, genesis_sd, rel_tol=1e-12, abs_tol=0.0):
raise ValueError(f"Endpoint {endpoint!r} genesis_prior_sd_exact={gsd_raw} does not match canonical prior sd {genesis_sd}")
delta = float(update.get("posterior_mean_exact", update["posterior_mean"])) - genesis_m
status["raw_endpoint_posterior_deltas"][endpoint] = delta
if endpoint in endpoint_map:
prior_sd_cur = float(update.get("prior_sd_exact", update.get("prior_sd", genesis_sd)))
has_historical_update = is_multibatch and (
prior_sd_cur < genesis_sd * (1.0 - 1e-12)
)
if update.get("status") == "UPDATED_FROM_OBSERVED_READOUT" or has_historical_update:
key, scale = endpoint_map[endpoint]
mapped[key] = mapped.get(key, 0.0) + scale * delta
else:
status["retained_unobserved_endpoints"].append(endpoint)
else:
status["unmapped_endpoint_deltas"][endpoint] = delta
mapped = {key: value for key, value in mapped.items() if value != 0.0}
_WETLAB_PARAMETER_DELTAS = MappingProxyType(mapped)
status["mapped_nonzero_parameter_deltas"] = dict(mapped)
status["consumed_parameter_deltas"] = dict(mapped)
status["active_posterior_logit_deltas"] = dict(mapped)
status["arm1b_scoped_gate1_only_parameter_deltas"] = {
k: v for k, v in mapped.items() if k != "stage7_trihormonal_120um_mvf_cao2_niche_prior"
}
status["endpoint_scope_qualification_note_astra_r1"] = (
"stage7_sc_beta_yield_fraction_arm1b (scale 1.0) and pouch_min_slab_po2_14d_mmhg (scale 0.01) both accumulate "
"into stage7_trihormonal_120um_mvf_cao2_niche_prior in the shared engineering calibration map; arm1b_scoped_gate1_only_parameter_deltas "
"isolates construct-specific Gate 2A/3/4/5 updates from shared niche priors (AUDIT-REF)."
)
status["applied_to_production_priors"] = bool(mapped)
status["validated_report_sha256"] = hashlib.sha256(json.dumps(report, sort_keys=True, allow_nan=False).encode()).hexdigest()
status["status_reason"] = "Validated empirical mapped shifts frozen for evaluation" if mapped else "Validated observations; no nonzero consumed parameter shift"
except (ValueError, TypeError, KeyError, OSError) as exc:
status["status_reason"] = f"Rejected invalid posterior: {exc}"
_WETLAB_CALIBRATION_STATUS = status
return dict(status)
def _load_active_wetlab_posterior_deltas():
"""Compatibility accessor; returns the frozen snapshot, with zero I/O."""
return _WETLAB_PARAMETER_DELTAS
def _cd47_gate1_gsis_penalty_signal(allo_k: str, target_profiles: dict) -> float:
"""
Routes CD47's deleterious GSIS counter-evidence (Ghimire et al. 2023 PMID:37820008: full-length CD47
receptor signaling inhibits beta-cell GSIS via Cdc42; mitigated by signaling-incompetent CD47-IgV in
Xu et al. 2024 PMID:38508139) into Gate1_Maturation_GSIS_and_Paracrine for CD47-expressing allo-cloak
modules (Grok P1-3; live-wired to cd47_gsis_penalty_scale per Audit R10).
"""
if allo_k not in ("ALLO_B2M_HLAE_CD47_SWAP_CIITA_KO", "ALLO_B2M_CIITA_KO_CD47_LENTI"):
return 0.0
st = (target_profiles or {}).get("CD47") or {}
del_pen = _finite_real(st.get("weighted_deleterious_penalty_score", 0.0), "CD47 deleterious evidence penalty")
if del_pen < 0:
raise ValueError("CD47 deleterious evidence penalty must be nonnegative")
mult = 1.0 if allo_k == "ALLO_B2M_CIITA_KO_CD47_LENTI" else 0.5
pen_scale = _finite_real(_aux_param("cd47_gsis_penalty_scale", -0.25), "CD47 GSIS penalty scale")
return pen_scale * mult * del_pen
def sigmoid(x: float) -> float:
x = _finite_real(x, "Gate logit")
return 1.0 / (1.0 + math.exp(-max(-15.0, min(15.0, x))))
_DEFAULT_CLAMPED_SIGMOID = sigmoid
def sigmoid_unclipped(x: float) -> float:
"""Overflow-safe logistic evaluation without [-15, 15] saturation clamping or [-745, -700) truncation (AUDIT-REF L1-01)."""
x = _finite_real(x, "Gate logit")
if x >= 0.0:
if x > 700.0:
return 1.0
return 1.0 / (1.0 + math.exp(-x))
if x >= -700.0:
return 1.0 / (1.0 + math.exp(-x))
e = math.exp(x)
return e / (1.0 + e)
def compute_series_system_utility(
allo_k: str,
auto_k: str,
cyto_k: str,
er_k: str,
niche_k: str,
saf_k: str,
target_profiles: dict,
recipient_context: str = "Pediatric_Early_Onset_T1D",
) -> dict:
"""
Computes a Prior-Anchored Multi-Gate Scenario Index in [0, 1].
- Returns 0.0 when target_profiles is empty or contains zero extracted empirical studies (AT-20).
- Dynamically wires `ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE` and `COMPLETE_GATE_COEFFICIENT_REGISTRY`
(including all 8 `auxiliary_evaluator_hyperparameters`) into gate logits and manufacturing
penalties (`locus_dsb_penalty_rate_lambda_K`, `base_edit_nickase_penalty_factor_gamma_B`,
`indirect_apc_presentation_residual_hazard_cap`, `resting_b2m_promoter_hour0_density_discount`,
`stage7_trihormonal_120um_mvf_cao2_niche_prior`, `tyk2_stage0_differentiation_yield_penalty`).
- Propagates gene-level posterior standard errors (`posterior_se`) into `lower_10pct_cred_bound` (AT-18).
"""
if recipient_context not in ("Pediatric_Early_Onset_T1D", "Adult_Onset_LADA"):
raise ValueError("Unknown recipient context; select an explicit modeled cohort")