scripts/verify_iip0059_five_transgene_joint_coverage_gate.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0059_five_transgene_joint_coverage_gate.py · SHA-256: 0b9054f5e6c0a4ac…
#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Executable Verifier for IIP-0059 / DEC-140 / GATE-38:
Five-Transgene 72-h Hypoxic ISR Joint Coverage, Fréchet/Copula Reconciliation,
f_ISR Floor Trajectory Grid, Empirical Marginal/Dependence/sigma_ln Audit, and
Wave-6 Arm Scoping.
Zero wetlab_contract.py imports; zero mutations to frozen LIMS contracts, FASTAs,
or live published odds (+0.00 pp). Deterministic under -B and -O -B.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
SIDE_CONTRACT_PATH = (
ROOT / "data" / "protocols" / "iip0059_five_transgene_joint_coverage_side_contract_v0.9.0.json"
)
DEFAULT_RECEIPT_PATH = (
ROOT / "data" / "extracted" / "iip0059_five_transgene_joint_coverage_verification_v0.9.0.json"
)
CRIT_95_MULT = 1.644854
DEFAULT_JOINT_SE = 0.01
JOINT_MIN_FRAC = 0.90
OPERATIONAL_SIGMA_LN_MAX = 0.28
Z_P10 = -1.2815515655446004
Z_P02 = -2.0537489106318230
DECAY_HALF_LIVES_H = {
"CD47_IgV_GPI": 20.0,
"HLAE_SCT": 14.0,
"PDL1": 16.0,
"SERPINB9": 6.0,
"iCasp9": 24.0,
}
THRESHOLDS = {
"CD47_IgV_GPI": 180000.0,
"HLAE_SCT": 15000.0,
"PDL1": 5000.0,
"SERPINB9": 0.30,
"iCasp9": 0.05,
}
def norm_cdf(x: float) -> float:
return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))
def norm_ppf(p: float) -> float:
p_clamped = min(max(p, 1e-12), 1.0 - 1e-12)
lo, hi = -8.0, 8.0
for _ in range(80):
mid = 0.5 * (lo + hi)
if norm_cdf(mid) < p_clamped:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def decay_72h(hour0_mean: float, f_isr: float, t_half_h: float) -> float:
return hour0_mean * (f_isr + (1.0 - f_isr) * (2.0 ** (-72.0 / t_half_h)))
def lognormal_p10(mean_val: float, sigma_ln: float) -> float:
mu = math.log(mean_val) - 0.5 * sigma_ln * sigma_ln
return math.exp(mu + Z_P10 * sigma_ln)
def lognormal_prob_ge(mean_val: float, sigma_ln: float, threshold: float) -> float:
mu = math.log(mean_val) - 0.5 * sigma_ln * sigma_ln
return 1.0 - norm_cdf((math.log(threshold) - mu) / sigma_ln)
def required_hour0_mean(
threshold: float, f_isr: float, t_half_h: float, sigma_ln: float, z_quantile: float
) -> float:
req_72h_mean = threshold * math.exp(0.5 * sigma_ln * sigma_ln - z_quantile * sigma_ln)
retention = f_isr + (1.0 - f_isr) * (2.0 ** (-72.0 / t_half_h))
return req_72h_mean / retention
def frechet_bounds(marginals: list[float]) -> dict[str, float]:
k = len(marginals)
lo = max(0.0, sum(marginals) - (k - 1))
indep = 1.0
for p in marginals:
indep *= p
hi = min(marginals) if marginals else 0.0
return {
"frechet_lower": round(lo, 8),
"independent_product": round(indep, 8),
"frechet_upper": round(hi, 8),
}
def equicorrelated_gaussian_copula_joint(marginals: list[float], rho: float, steps: int = 800) -> float:
if not marginals:
return 0.0
if rho >= 1.0:
return min(marginals)
if rho <= 0.0:
prod = 1.0
for p in marginals:
prod *= p
return prod
zs = [norm_ppf(p) for p in marginals]
sr = math.sqrt(rho)
s1 = math.sqrt(1.0 - rho)
a, b = -8.0, 8.0
h = (b - a) / steps
total = 0.0
inv_sqrt_2pi = 1.0 / math.sqrt(2.0 * math.pi)
for idx in range(steps):
g = a + (idx + 0.5) * h
w = math.exp(-0.5 * g * g) * inv_sqrt_2pi * h
p_cond = 1.0
for z in zs:
p_cond *= norm_cdf((z + sr * g) / s1)
total += w * p_cond
return total
def build_trajectory_and_copula_audit() -> dict[str, Any]:
"""Compute complete f_ISR x sigma_ln Hour-0 requirements and Gaussian-copula stress table."""
hour0_grid = []
for f_isr in (0.50, 0.75, 0.85):
for sigma_ln in (0.28, 0.32, 0.45):
hour0_grid.append(
{
"f_isr": f_isr,
"sigma_ln": sigma_ln,
"cd47_hour0_min_for_72h_p10": round(
required_hour0_mean(THRESHOLDS["CD47_IgV_GPI"], f_isr, 20.0, sigma_ln, Z_P10), 1
),
"cd47_hour0_min_for_72h_p02": round(
required_hour0_mean(THRESHOLDS["CD47_IgV_GPI"], f_isr, 20.0, sigma_ln, Z_P02), 1
),
"hlae_hour0_min_for_72h_p10": round(
required_hour0_mean(THRESHOLDS["HLAE_SCT"], f_isr, 14.0, sigma_ln, Z_P10), 1
),
"hlae_hour0_min_for_72h_p02": round(
required_hour0_mean(THRESHOLDS["HLAE_SCT"], f_isr, 14.0, sigma_ln, Z_P02), 1
),
}
)
def _lot_marginals(cd47_h0: float, hlae_h0: float, f_isr: float, sigma_ln: float) -> list[float]:
return [
lognormal_prob_ge(decay_72h(cd47_h0, f_isr, 20.0), sigma_ln, THRESHOLDS["CD47_IgV_GPI"]),
lognormal_prob_ge(decay_72h(hlae_h0, f_isr, 14.0), sigma_ln, THRESHOLDS["HLAE_SCT"]),
lognormal_prob_ge(decay_72h(45000.0, f_isr, 16.0), sigma_ln, THRESHOLDS["PDL1"]),
lognormal_prob_ge(decay_72h(0.89, f_isr, 6.0), sigma_ln, THRESHOLDS["SERPINB9"]),
0.99, # Prospective iCasp9 assumption pending Hour-0 uM calibration
]
copula_cases = {
"five_equal_p10_0p90": [0.90] * 5,
"five_equal_p02_0p98": [0.98] * 5,
"atlas_min_qualifying_lot_320k_26144_f0p85_s0p28": _lot_marginals(320000.0, 26144.0, 0.85, 0.28),
"upper_remediated_lot_366k_32k_f0p85_s0p28": _lot_marginals(366000.0, 32000.0, 0.85, 0.28),
"remediated_lot_at_f_isr_0p50_floor_366k_32k_s0p28": _lot_marginals(366000.0, 32000.0, 0.50, 0.28),
}
copula_summary: dict[str, Any] = {}
min_pt = JOINT_MIN_FRAC + CRIT_95_MULT * DEFAULT_JOINT_SE
for name, margs in copula_cases.items():
bounds = frechet_bounds(margs)
by_rho = {
f"rho_{rho:.2f}": round(equicorrelated_gaussian_copula_joint(margs, rho), 6)
for rho in (0.0, 0.25, 0.50, 0.75, 0.90, 1.0)
}
copula_summary[name] = {
"marginals": [round(x, 6) for x in margs],
**bounds,
"gaussian_copula_joint": by_rho,
"clears_lower95_at_default_se_under_rho_0p00": by_rho["rho_0.00"] >= min_pt,
"clears_lower95_at_default_se_under_rho_1p00": by_rho["rho_1.00"] >= min_pt,
}
return {
"min_point_estimate_for_lower95_at_default_se": round(min_pt, 8),
"hour0_requirement_grid_f_isr_x_sigma_ln": hour0_grid,
"copula_and_frechet_stress_table": copula_summary,
}
def evaluate_gate38_lot(record: dict[str, Any], side_contract: dict[str, Any]) -> dict[str, Any]:
"""Fail-closed evaluation of a Stage-0 72-h hypoxic joint-coverage lot record."""
reasons: list[str] = []
warnings: list[str] = []
product_id = record.get("product_id")
arm_table = side_contract["arm_scoping_table"]
if product_id not in arm_table:
return {
"verdict": "HOLD_UNDECLARED_PRODUCT_SCOPE",
"pass": False,
"reasons": [f"Undeclared product_id {product_id!r}; must match Gate 38 arm_scoping_table."],
"warnings": [],
}
arm_spec = arm_table[product_id]
active_axes: list[str] = arm_spec["active_axes"]
# 1. Anti-escalation guard (GY-018 / IIP-0047): forbid blind p02 CD47 floor escalation
if record.get("blind_p02_cd47_escalation_requested") is True:
reasons.append(
"BLOCK_GY018_BLIND_P02_CD47_ESCALATION: Raising CD47 floor to p02 without hypoxic TSP-1/UPR ceiling qualification is prohibited (IIP-0047 / OQ-008)."
)
# 2. Stress-regime matching
allowed_regimes = set(side_contract["stress_regime_matching_rule"]["allowed_matched_regimes"])
joint_regime = record.get("obs_hypoxic_72h_stress_o2_regime")
marginal_regime = record.get("obs_hypoxic_72h_marginal_stress_o2_regime", joint_regime)
if joint_regime not in allowed_regimes:
reasons.append(f"HOLD_UNDECLARED_STRESS_REGIME: {joint_regime!r} not in allowed matched O2 regimes.")
elif marginal_regime != joint_regime:
reasons.append(
f"HOLD_CROSS_REGIME_MISMATCH: marginal regime {marginal_regime!r} != joint regime {joint_regime!r}."
)
# 3. Calibration chain provenance for every active axis (especially SERPINB9 uM & iCasp9 Hour-0 uM)
cal_chains = record.get("obs_hypoxic_72h_calibration_chains_verified") or {}
for axis in active_axes:
if cal_chains.get(axis) is not True:
reasons.append(f"HOLD_UNVERIFIED_CALIBRATION_CHAIN: axis {axis} lacks verified calibration chain.")
# 4. Empirical marginals & Fréchet consistency
marginals_map = record.get("obs_hypoxic_72h_per_axis_marginals_above_threshold") or {}
missing_axes = [ax for ax in active_axes if ax not in marginals_map or marginals_map[ax] is None]
if missing_axes:
reasons.append(f"HOLD_MISSING_PER_AXIS_MARGINALS: missing {missing_axes}.")
p_joint = record.get("obs_hypoxic_72h_joint_above_threshold_fraction")
se_joint = record.get("obs_hypoxic_72h_joint_above_threshold_se")
if not isinstance(p_joint, (int, float)) or not (0.0 <= float(p_joint) <= 1.0):
reasons.append("HOLD_INVALID_JOINT_FRACTION: obs_hypoxic_72h_joint_above_threshold_fraction missing or out of [0,1].")
if not isinstance(se_joint, (int, float)) or float(se_joint) <= 0.0:
reasons.append("HOLD_MISSING_EXPLICIT_SE: explicit positive SE required for joint fraction.")
# 5. Empirical sigma_ln observation