OpenIslet

scripts/verify_iip0059_five_transgene_joint_coverage_gate.py

Standalone Zero-LIMS-Touch Executable Verifier for IIP-0059 / DEC-140 / GATE-38:

script Release v0.8.0 gen-eb955f8266035aba 20 KB · 2 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0059_five_transgene_joint_coverage_gate.py · SHA-256: 0b9054f5e6c0a4ac…

    sigma_map = record.get("obs_hypoxic_72h_sigma_ln_by_axis") or {}
    for ax in ("CD47_IgV_GPI", "HLAE_SCT"):
        if ax in active_axes:
            s_val = sigma_map.get(ax)
            if not isinstance(s_val, (int, float)) or float(s_val) <= 0.0:
                reasons.append(f"HOLD_MISSING_OBSERVED_SIGMA_LN: observed sigma_ln required for active axis {ax}.")
            elif float(s_val) > OPERATIONAL_SIGMA_LN_MAX:
                warnings.append(
                    f"SIGMA_LN_ABOVE_OPERATIONAL_TARGET: {ax} sigma_ln={float(s_val):.3f} > {OPERATIONAL_SIGMA_LN_MAX:.2f}."
                )

    # 6. f_ISR floor & scrap-risk warning
    f_isr = record.get("obs_hypoxic_15mmhg_f_isr_translation_ratio")
    if not isinstance(f_isr, (int, float)) or float(f_isr) < 0.50:
        reasons.append("HOLD_F_ISR_BELOW_0P50_FLOOR: obs_hypoxic_15mmhg_f_isr_translation_ratio < 0.50.")
    elif float(f_isr) < 0.75:
        warnings.append(
            f"F_ISR_IN_SCRAP_RISK_BAND: observed f_ISR={float(f_isr):.3f} in [0.50, 0.75); below atlas clearing trajectory band [0.75, 0.85]."
        )

    diagnostics: dict[str, Any] = {"arm_scope": arm_spec["scope"], "active_axes": active_axes}
    if not missing_axes and isinstance(p_joint, (int, float)) and isinstance(se_joint, (int, float)):
        marg_vals = [float(marginals_map[ax]) for ax in active_axes]
        if any(not (0.0 <= v <= 1.0) for v in marg_vals):
            reasons.append("HOLD_INVALID_MARGINAL_RANGE: marginal fraction outside [0, 1].")
        else:
            bounds = frechet_bounds(marg_vals)
            pj = float(p_joint)
            lower95 = pj - CRIT_95_MULT * float(se_joint)
            diagnostics.update(bounds)
            diagnostics["observed_joint"] = round(pj, 6)
            diagnostics["observed_lower95"] = round(lower95, 6)

            # Same-event mathematical impossibility check
            if pj > bounds["frechet_upper"] + 1e-9 or pj < bounds["frechet_lower"] - 1e-9:
                reasons.append(
                    f"FAIL_IMPOSSIBLE_FRECHET_VIOLATION: joint={pj:.6f} outside [{bounds['frechet_lower']:.6f}, {bounds['frechet_upper']:.6f}]."
                )
            else:
                denom = bounds["frechet_upper"] - bounds["independent_product"]
                if denom > 1e-9:
                    diagnostics["empirical_dependence_index"] = round(
                        (pj - bounds["independent_product"]) / denom, 6
                    )
                else:
                    diagnostics["empirical_dependence_index"] = None

            if pj < JOINT_MIN_FRAC or lower95 < JOINT_MIN_FRAC:
                reasons.append(
                    f"FAIL_JOINT_GATE_BELOW_0P90: joint={pj:.6f}, lower95={lower95:.6f} < 0.90."
                )

    passed = len(reasons) == 0
    return {
        "verdict": "PASS_GATE38_JOINT_COVERAGE_AND_DEPENDENCE" if passed else reasons[0].split(":")[0],
        "pass": passed,
        "reasons": reasons,
        "warnings": warnings,
        "diagnostics": diagnostics,
    }


def run_self_tests(side_contract: dict[str, Any]) -> list[dict[str, Any]]:
    """Run 11 deterministic adversarial self-tests covering math, scoping, and fail-closed guards."""
    results: list[dict[str, Any]] = []
    audit = build_trajectory_and_copula_audit()
    cop = audit["copula_and_frechet_stress_table"]

    def _rec(name: str, ok: bool, detail: str) -> None:
        results.append({"test": name, "passed": bool(ok), "detail": detail})

    # T1: Exact p10 / p02 Fréchet & independence arithmetic
    t1 = (
        math.isclose(cop["five_equal_p10_0p90"]["independent_product"], 0.59049, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p10_0p90"]["frechet_lower"], 0.50, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p02_0p98"]["frechet_lower"], 0.90, abs_tol=1e-7)
        and math.isclose(cop["five_equal_p02_0p98"]["independent_product"], 0.9039208, abs_tol=1e-6)
    )
    _rec("T01_exact_frechet_and_independence_identities", t1, "0.9^5=0.59049, p10_lo=0.50, p02_lo=0.90")

    # T2: Minimum qualifying lot (320k / 26,144) cannot clear lower95 >= 0.90 even at rho=1.0
    m_min = cop["atlas_min_qualifying_lot_320k_26144_f0p85_s0p28"]
    t2 = (
        math.isclose(m_min["frechet_upper"], 0.90000, abs_tol=1e-4)
        and not m_min["clears_lower95_at_default_se_under_rho_1p00"]
    )
    _rec("T02_min_qualifying_lot_fails_lower95_in_expectation", t2, f"upper={m_min['frechet_upper']}")

    # T3: Upper remediated lot (366k / 32k, f=0.85, s=0.28) clears lower95 even at rho=0.0
    m_up = cop["upper_remediated_lot_366k_32k_f0p85_s0p28"]
    t3 = m_up["clears_lower95_at_default_se_under_rho_0p00"] and m_up["gaussian_copula_joint"]["rho_0.00"] > 0.93
    _rec("T03_upper_remediated_lot_clears_even_under_independence", t3, f"rho0={m_up['gaussian_copula_joint']['rho_0.00']}")

    # T4: Same upper remediated lot collapses at f_ISR=0.50 floor
    m_f50 = cop["remediated_lot_at_f_isr_0p50_floor_366k_32k_s0p28"]
    t4 = m_f50["frechet_upper"] < 0.60 and m_f50["gaussian_copula_joint"]["rho_0.00"] < 0.35
    _rec("T04_f_isr_0p50_floor_collapse_verified", t4, f"rho0={m_f50['gaussian_copula_joint']['rho_0.00']}, hi={m_f50['frechet_upper']}")

    base_pass_lot = {
        "product_id": "ISLET1_DESIGN_A_V080_REF",
        "obs_hypoxic_72h_joint_above_threshold_fraction": 0.945,
        "obs_hypoxic_72h_joint_above_threshold_se": 0.008,
        "obs_hypoxic_72h_per_axis_marginals_above_threshold": {
            "CD47_IgV_GPI": 0.968,
            "HLAE_SCT": 0.977,
            "PDL1": 0.999,
            "SERPINB9": 0.998,
            "iCasp9": 0.990,
        },
        "obs_hypoxic_72h_sigma_ln_by_axis": {"CD47_IgV_GPI": 0.26, "HLAE_SCT": 0.25},
        "obs_hypoxic_72h_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_marginal_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_calibration_chains_verified": {
            "CD47_IgV_GPI": True,
            "HLAE_SCT": True,
            "PDL1": True,
            "SERPINB9": True,
            "iCasp9": True,
        },
        "obs_hypoxic_15mmhg_f_isr_translation_ratio": 0.85,
    }

    # T5: Valid Arm A lot passes with empirical dependence index computed
    r5 = evaluate_gate38_lot(base_pass_lot, side_contract)
    _rec("T05_valid_arm_a_lot_passes", r5["pass"] and r5["diagnostics"]["empirical_dependence_index"] is not None, r5["verdict"])

    # T6: Impossible joint > min(marginals) rejected fail-closed
    bad_frechet = dict(base_pass_lot, obs_hypoxic_72h_joint_above_threshold_fraction=0.985)
    r6 = evaluate_gate38_lot(bad_frechet, side_contract)
    _rec("T06_impossible_frechet_violation_rejected", not r6["pass"] and "FRECHET" in r6["verdict"], r6["verdict"])

    # T7: Cross-regime mismatch (2% marginals vs 1% joint) rejected
    bad_regime = dict(
        base_pass_lot, obs_hypoxic_72h_stress_o2_regime="72h_1pct_O2_16p7mM_glc_cytokines_DEC053"
    )
    r7 = evaluate_gate38_lot(bad_regime, side_contract)
    _rec("T07_cross_regime_o2_mismatch_rejected", not r7["pass"] and "CROSS_REGIME" in r7["verdict"], r7["verdict"])

    # T8: Missing iCasp9 calibration chain rejected
    bad_cal = dict(
        base_pass_lot,
        obs_hypoxic_72h_calibration_chains_verified={
            **base_pass_lot["obs_hypoxic_72h_calibration_chains_verified"],
            "iCasp9": False,
        },
    )
    r8 = evaluate_gate38_lot(bad_cal, side_contract)
    _rec("T08_missing_icasp9_calibration_chain_rejected", not r8["pass"] and "CALIBRATION" in r8["verdict"], r8["verdict"])

    # T9: Missing sigma_ln rejected
    bad_sig = dict(base_pass_lot, obs_hypoxic_72h_sigma_ln_by_axis={"CD47_IgV_GPI": 0.26})
    r9 = evaluate_gate38_lot(bad_sig, side_contract)
    _rec("T09_missing_observed_sigma_ln_rejected", not r9["pass"] and "SIGMA_LN" in r9["verdict"], r9["verdict"])

    # T10: Blind p02 CD47 escalation blocked (GY-018 / IIP-0047)
    bad_p02 = dict(base_pass_lot, blind_p02_cd47_escalation_requested=True)
    r10 = evaluate_gate38_lot(bad_p02, side_contract)
    _rec("T10_blind_p02_cd47_escalation_blocked", not r10["pass"] and "GY018" in r10["verdict"], r10["verdict"])

    # T11: Arm D autologous 3-axis subset (PDL1, SERPINB9, iCasp8) passes WITHOUT requiring CD47/HLA-E/iCasp9
    arm_d_lot = {
        "product_id": "ISLET1_DESIGN_D1B_LEAN_K2",
        "obs_hypoxic_72h_joint_above_threshold_fraction": 0.968,
        "obs_hypoxic_72h_joint_above_threshold_se": 0.008,
        "obs_hypoxic_72h_per_axis_marginals_above_threshold": {
            "PDL1": 0.995,
            "SERPINB9": 0.992,
            "iCasp8": 0.975,
        },
        "obs_hypoxic_72h_sigma_ln_by_axis": {},
        "obs_hypoxic_72h_stress_o2_regime": "72h_2pct_O2_15mmHg_16p7mM_glc_cytokines_DEC050_052",
        "obs_hypoxic_72h_calibration_chains_verified": {
            "PDL1": True,
            "SERPINB9": True,
            "iCasp8": True,
        },
        "obs_hypoxic_15mmhg_f_isr_translation_ratio": 0.85,
    }
    r11 = evaluate_gate38_lot(arm_d_lot, side_contract)
    _rec("T11_arm_d_autologous_3axis_subset_scoped_cleanly", r11["pass"] and r11["diagnostics"]["arm_scope"] == "SUBSET_3_TRANSGENE_AUTOLOGOUS_ICASP8", r11["verdict"])

    return results


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify GATE-38 (IIP-0059 / DEC-140) five-transgene joint coverage & dependence gate.")
    parser.add_argument("--write-receipt", type=Path, default=None, help="Write deterministic verification receipt JSON.")
    args = parser.parse_args()

    side_contract = json.loads(SIDE_CONTRACT_PATH.read_text(encoding="utf-8"))
    audit = build_trajectory_and_copula_audit()
    self_tests = run_self_tests(side_contract)
    passed = sum(1 for t in self_tests if t["passed"])
    all_ok = passed == len(self_tests)

    receipt = {
        "schema_version": "iip0059_five_transgene_joint_coverage_verification_v0.9.0",
        "gate_id": "GATE-38",
        "contribution_id": "IIP-0059",
        "decision_id": "DEC-140",
        "generated_date": "2026-12-03",
        "overall_status": "PASSED" if all_ok else "FAILED",
        "live_odds_delta_pp": 0.0,
        "side_contract_sha256": sha256_file(SIDE_CONTRACT_PATH),
        "self_tests_passed": passed,
        "self_tests_total": len(self_tests),
        "self_tests": self_tests,
        "quantitative_audit": audit,
    }

    if args.write_receipt is not None:
        args.write_receipt.parent.mkdir(parents=True, exist_ok=True)
        args.write_receipt.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")

    print(
        f"{'PASS' if all_ok else 'FAIL'}: GATE-38 (IIP-0059 / DEC-140) self_tests={passed}/{len(self_tests)} "
        f"odds_delta=+0.00pp side_contract_sha256={receipt['side_contract_sha256'][:16]}..."
    )
    return 0 if all_ok else 1


if __name__ == "__main__":
    sys.exit(main())