OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 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_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

            "out_of_range_phi_gt_1",
            dict(c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=1.05),
        ),
        (
            "non_finite_nan_c1",
            dict(c1=float("nan"), pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0),
        ),
    ]
    results = []
    for cname, kw in bad_cases:
        raised = False
        err_msg = ""
        try:
            eval_5arm_generalized_exact(f"TEST_{cname}", **kw)
        except ValueError as exc:
            raised = True
            err_msg = str(exc)
        if not raised:
            raise RuntimeError(f"Domain guard FAILED to reject {cname}!")
        results.append({"case": cname, "rejected_with_ValueError": True, "error": err_msg})
    return {"total_negative_tests": len(results), "all_rejected_fail_closed": True, "cases": results}


def analyze_part_d_portfolio_odds() -> dict[str, Any]:
    domain_guard_tests = run_portfolio_domain_guard_tests()

    # 1. Live baseline parity check directly via OpenIslet rank_islet1_stacks.py!
    pa0 = (0.88, 0.78, 0.57, 0.69)
    pb0 = (0.88, 0.79, 0.64, 0.70)
    px0 = (0.88, 0.82, 0.73, 0.69)
    py0 = (0.88, 0.84, 0.80, 0.72)
    pd1_0 = (0.62, 0.92, 0.70, 0.70)
    c0_vec = (0.88, 0.87, 0.89, 0.85)

    live_3arm = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa0, pb0, px0, c0_vec)
    live_5arm_bundle = rank_mod.compute_5arm_autologous_portfolio_iip0035(OPENISLET_ROOT)
    wu3_live = next(r for r in live_5arm_bundle["stage0_gated_5arm_unified_waveBC_portfolio"] if r["scenario"].startswith("W_U3_"))
    wu4_live = next(r for r in live_5arm_bundle["stage0_gated_5arm_unified_waveBC_portfolio"] if r["scenario"].startswith("W_U4_"))

    # Verify our generalized 2^20 evaluator reproduces live W_U3 & W_U4 UNROUNDED to < 1e-12!
    def _unrounded_reg_metrics_from_law(law: dict[str, Any], phi_c_val: float) -> tuple[float, float, float]:
        dists = law["stage_dists"]
        c_classes = law["cell_architecture_classes"]
        r_ids = law["h4_route_assignments"]
        reg_compat = {
            "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
            "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
            "D1B_AUTO_C_V2": frozenset({"R3P"}),
        }
        v = [0.0] * 32
        v[31] = 1.0
        for h in range(3):
            dh = dists[h]
            vn = [0.0] * 32
            for s, vs in enumerate(v):
                if vs:
                    for mh, w in enumerate(dh):
                        if w:
                            vn[s & mh] += vs * w
            v = vn
        v_h123 = v
        v_all = [0.0] * 32
        for s, vs in enumerate(v_h123):
            if vs:
                for mh, w in enumerate(dists[3]):
                    if w:
                        v_all[s & mh] += vs * w
        locked_u = 1.0 - v_all[0]
        mod100_u = 0.0
        for mc in range(1, 32):
            wc = v_h123[mc]
            if not wc:
                continue
            al: set[str] = set()
            for i in range(5):
                if mc & (1 << i):
                    al |= reg_compat[c_classes[i]]
            for mh in range(1, 32):
                wh = dists[3][mh]
                if wh and any(r_ids[j] in al for j in range(5) if (mh & (1 << j))):
                    mod100_u += wc * wh
        biv2_l = rank_mod._bivariate_bernoulli_iip0034(0.87 / 0.95, 0.93 / 0.95, phi_c_val)
        biv4_l = rank_mod._bivariate_bernoulli_iip0034(0.85 / 0.92, 0.85 / 0.92, phi_c_val)
        ceil_u = 0.88 * (0.95 * (1.0 - biv2_l[(0, 0)])) * 0.89 * (0.92 * (1.0 - biv4_l[(0, 0)]))
        return locked_u, mod100_u, ceil_u

    live_laws: dict[str, dict[str, Any]] = {}
    _tok = rank_mod._ACTIVE_LAW_COLLECTOR_IIP0035.set(live_laws)
    try:
        p0_l = float(live_3arm["locked_2route_shared_ax_pouch_exact"])
        p0_m = float(live_3arm["modular_2route_shared_ax_pouch_exact"])
        c0_ex = math.prod(c0_vec)
        rank_mod._eval_5arm_unified_iip0035(
            "LIVE_UNROUNDED_W_U3", py0, pd1_0, pa=pa0, pb=pb0, px=px0,
            c2_y=0.87, c3_y=0.89, phi_yx=0.75, phi_c=0.25, d1_on_r3=True,
            c4_univ=0.92, c4_r3=0.85, p0_l=p0_l, p0_m=p0_m, c0=c0_ex, stage0_status="PARITY",
        )
        rank_mod._eval_5arm_unified_iip0035(
            "LIVE_UNROUNDED_W_U4", py0, pd1_0, pa=pa0, pb=pb0, px=px0,
            c2_y=0.87, c3_y=0.89, phi_yx=0.75, phi_c=0.50, d1_on_r3=True,
            c4_univ=0.92, c4_r3=0.85, p0_l=p0_l, p0_m=p0_m, c0=c0_ex, stage0_status="PARITY",
        )
    finally:
        rank_mod._ACTIVE_LAW_COLLECTOR_IIP0035.reset(_tok)

    wu3_live_ex = _unrounded_reg_metrics_from_law(live_laws["LIVE_UNROUNDED_W_U3"], 0.25)
    wu4_live_ex = _unrounded_reg_metrics_from_law(live_laws["LIVE_UNROUNDED_W_U4"], 0.50)
    wu3_check = eval_5arm_generalized_exact("PARITY_W_U3", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=0.25)
    wu4_check = eval_5arm_generalized_exact("PARITY_W_U4", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=0.50)

    parity_errs = [
        abs(wu3_check["locked_exact"] - wu3_live_ex[0]),
        abs(wu3_check["modular_k100_exact"] - wu3_live_ex[1]),
        abs(wu3_check["ceiling_exact"] - wu3_live_ex[2]),
        abs(wu4_check["locked_exact"] - wu4_live_ex[0]),
        abs(wu4_check["modular_k100_exact"] - wu4_live_ex[1]),
        abs(wu4_check["ceiling_exact"] - wu4_live_ex[2]),
    ]
    max_unrounded_parity_err = max(parity_errs)
    if not (max_unrounded_parity_err < 1e-12):
        raise ValueError(f"Unrounded 5-arm parity failed: {max_unrounded_parity_err}")

    s85 = 0.85 / 0.89
    # Compute TRUE unrounded float64 Core 3-arm probabilities directly (NOT 9-dp rounded live_3arm keys!),
    # while asserting exact 9-dp parity against rank_islet1_stacks.compute_common_shock_2pow12_portfolio_tree!
    live_3_l_ex, live_3_m_ex, live_3_c_ex = eval_3arm_2pow12_unrounded(pa0, pb0, px0, c0_vec)
    if round(live_3_l_ex, 9) != float(live_3arm["locked_2route_shared_ax_pouch_exact"]):
        raise ValueError("Unrounded Core 3-arm locked parity mismatch vs live rank_islet1_stacks.py")
    if round(live_3_m_ex, 9) != float(live_3arm["modular_2route_shared_ax_pouch_exact"]):
        raise ValueError("Unrounded Core 3-arm modular parity mismatch vs live rank_islet1_stacks.py")

    def _run_3arm(label: str, c1: float, c3: float, p3_triple: tuple[float, float, float]) -> dict[str, Any]:
        pa = (c1, 0.78, p3_triple[0], 0.69)
        pb = (c1, 0.79, p3_triple[1], 0.70)
        px = (c1, 0.82, p3_triple[2], 0.69)
        c_t = (c1, 0.87, c3, 0.85)
        t_live = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa, pb, px, c_t)
        l_ex, m_ex, c_ex = eval_3arm_2pow12_unrounded(pa, pb, px, c_t)
        if round(l_ex, 9) != float(t_live["locked_2route_shared_ax_pouch_exact"]):
            raise ValueError(f"{label}: 3-arm locked 9-dp mismatch vs live ranker")
        if round(m_ex, 9) != float(t_live["modular_2route_shared_ax_pouch_exact"]):
            raise ValueError(f"{label}: 3-arm modular 9-dp mismatch vs live ranker")
        # Compute ALL deltas from TRUE unrounded float64 probabilities BEFORE 4-dp display rounding!
        dl_ex = 100.0 * (l_ex - live_3_l_ex)
        dm_ex = 100.0 * (m_ex - live_3_m_ex)
        dc_ex = 100.0 * (c_ex - live_3_c_ex)
        return {
            "scenario": label,
            "c1": c1, "c3": c3, "p3_abx": [round(x, 4) for x in p3_triple],
            "locked_pct": round(100.0 * l_ex, 4),
            "delta_locked_vs_live_pp": round(dl_ex, 4),
            "delta_locked_vs_live_exact_pp": round(dl_ex, 12),
            "modular_k100_pct": round(100.0 * m_ex, 4),
            "delta_modular_vs_live_pp": round(dm_ex, 4),
            "delta_modular_vs_live_exact_pp": round(dm_ex, 12),
            "ceiling_pct": round(100.0 * c_ex, 4),
            "delta_ceiling_vs_live_pp": round(dc_ex, 4),
            "locked_exact": l_ex,
            "modular_k100_exact": m_ex,
            "ceiling_exact": c_ex,
        }

    p3_base = (0.57, 0.64, 0.73)
    p3_down = (0.57 * s85, 0.64 * s85, 0.73 * s85)
    p3_cond_stage0 = (0.62, 0.68, 0.78)  # speculative uncalibrated Stage-0 Mode-B sensitivity inside c3=0.89

    core_3arm_scenarios = [
        _run_3arm("S0_Live_Baseline_H1_88_c3_89", 0.88, 0.89, p3_base),
        _run_3arm("S1a_H1_88_Unfixed_CD64t_Downside_c3_85_ProportionalShock", 0.88, 0.85, p3_down),
        _run_3arm("S1b_H1_90_Unfixed_CD64t_Downside_c3_85_ProportionalShock", 0.90, 0.85, p3_down),
        _run_3arm("S1c_H1_90_CeilingCompressionOnly_c3_85_FixedMarginals_Diagnostic", 0.90, 0.85, p3_base),
        _run_3arm("S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_c3_89", 0.90, 0.89, p3_base),
        _run_3arm("S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78_c3_89", 0.90, 0.89, p3_cond_stage0),
    ]

    five_arm_scenarios = []
    for phi_c_val, phi_tag, base_ex in ((0.25, "W_U3_phi0p25", wu3_live_ex), (0.50, "W_U4_phi0p50", wu4_live_ex)):

        def _add5(lbl: str, **kw: Any) -> None:
            res = eval_5arm_generalized_exact(f"{phi_tag}__{lbl}", phi_c=phi_c_val, **kw)
            # Compute ALL deltas from unrounded exact probabilities BEFORE 4-dp display rounding!
            res["delta_locked_vs_live_same_phi_pp"] = round(100.0 * (res["locked_exact"] - base_ex[0]), 4)
            res["delta_modular_vs_live_same_phi_pp"] = round(100.0 * (res["modular_k100_exact"] - base_ex[1]), 4)
            res["delta_ceiling_vs_live_same_phi_pp"] = round(100.0 * (res["ceiling_exact"] - base_ex[2]), 4)
            five_arm_scenarios.append(res)

        pa_90 = (0.90, 0.78, 0.57, 0.69)
        pb_90 = (0.90, 0.79, 0.64, 0.70)
        px_90 = (0.90, 0.82, 0.73, 0.69)
        py_90 = (0.90, 0.84, 0.80, 0.72)

        pa_88_d = (0.88, 0.78, 0.57 * s85, 0.69)
        pb_88_d = (0.88, 0.79, 0.64 * s85, 0.70)
        px_88_d = (0.88, 0.82, 0.73 * s85, 0.69)

        pa_90_d = (0.90, 0.78, 0.57 * s85, 0.69)
        pb_90_d = (0.90, 0.79, 0.64 * s85, 0.70)
        px_90_d = (0.90, 0.82, 0.73 * s85, 0.69)
        py_90_d = (0.90, 0.84, 0.80 * s85, 0.72)
        pd1_d = (0.62, 0.92, 0.70 * s85, 0.70)

        _add5("S0_Live_Baseline_H1_88_c3_89", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S1a_H1_88_Asym_ABX_Unfixed_c3abx85_c3yd89", c1=0.88, pa=pa_88_d, pb=pb_88_d, px=px_88_d, p_y=py0, p_d1=pd1_0, c3_abx=0.85, c3_y=0.89)
        _add5("S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89", c1=0.90, pa=pa_90_d, pb=pb_90_d, px=px_90_d, p_y=py_90, p_d1=pd1_0, c3_abx=0.85, c3_y=0.89)
        _add5("S1c_H1_90_PortfolioWide_c3_85_All5Arms_ProportionalShock", c1=0.90, pa=pa_90_d, pb=pb_90_d, px=px_90_d, p_y=py_90_d, p_d1=pd1_d, c3_abx=0.85, c3_y=0.85)
        _add5("S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S2b_H1_90_ABX_CD64t_IL1RN_Fix_D1bScaled63p41", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=(0.62 * 0.90 / 0.88, 0.92, 0.70, 0.70), c3_abx=0.89, c3_y=0.89)
        _add5("S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78", c1=0.90, pa=(0.90, 0.78, 0.62, 0.69), pb=(0.90, 0.79, 0.68, 0.70), px=(0.90, 0.82, 0.78, 0.69), p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S3_Stress_H1_90_Fix_phiYX1p00_c4u0p90", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89, phi_yx=1.00, c4_univ=0.90)

    by_5 = {r["scenario"]: r for r in five_arm_scenarios}
    wu3_rec_ex = 100.0 * (
        by_5["W_U3_phi0p25__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U3_phi0p25__S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89"]["locked_exact"]
    )
    wu4_rec_ex = 100.0 * (
        by_5["W_U4_phi0p50__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U4_phi0p50__S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89"]["locked_exact"]
    )
    wu3_s1c_ex = 100.0 * (
        by_5["W_U3_phi0p25__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U3_phi0p25__S1c_H1_90_PortfolioWide_c3_85_All5Arms_ProportionalShock"]["locked_exact"]
    )
    by_3 = {r["scenario"]: r for r in core_3arm_scenarios}
    core_h1_only_ex = 100.0 * (
        by_3["S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_c3_89"]["locked_exact"]
        - by_3["S0_Live_Baseline_H1_88_c3_89"]["locked_exact"]
    )
    if round(core_h1_only_ex, 4) != 1.1540:
        raise ValueError(f"Expected +1.1540 pp Core H1-only delta from true unrounded diff, got {core_h1_only_ex}")
    if round(wu3_rec_ex, 4) != 0.6033:
        raise ValueError(f"Expected +0.6033 pp from unrounded diff, got {wu3_rec_ex}")
    if by_5["W_U4_phi0p50__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["delta_locked_vs_live_same_phi_pp"] != 1.2926:
        raise ValueError("Expected +1.2926 pp W_U4 S0->S2a delta from unrounded diff")

    return {
        "live_headline_delta_pp": 0.0,
        "precision_interface_contract": "All Core 3-arm (2^12) and 5-arm (2^20) deltas are computed directly on true unrounded float64 probabilities first (never from 9-dp rounded endpoints) and then rounded to 4 decimal places for display, while asserting exact 9-dp parity against live rank_islet1_stacks.py.",
        "domain_and_ceiling_guard_unit_tests": domain_guard_tests,
        "live_parity_verification": {
            "core_3arm_live_exact_pct": {
                "locked": round(100.0 * live_3_l_ex, 6),
                "modular": round(100.0 * live_3_m_ex, 6),
                "ceiling": round(100.0 * live_3_c_ex, 6),
            },
            "five_arm_W_U3_W_U4_unrounded_max_abs_err": max_unrounded_parity_err,
            "five_arm_unrounded_parity_lt_1e12": max_unrounded_parity_err < 1e-12,
            "five_arm_W_U3_live_pct": {"locked": wu3_live["locked_pct"], "modular": wu3_live["modular_k100_pct"], "ceiling": wu3_live["composite_ceiling_pct"]},
            "five_arm_W_U4_live_pct": {"locked": wu4_live["locked_pct"], "modular": wu4_live["modular_k100_pct"], "ceiling": wu4_live["composite_ceiling_pct"]},
        },