OpenIslet

scripts/verify_iip0050_islet_shield_coverage_and_debris_gate.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Debris-Recall Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 51 KB · 5 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_iip0050_islet_shield_coverage_and_debris_gate.py · SHA-256: b5a517900e706ea4…

        for _ in range(80):
            mid = 0.5 * (a + b)
            if _binom_sf_ge(n_tot, k_obs, mid) < alpha:
                a = mid
            else:
                b = mid
        lo = 0.5 * (a + b)
    if k_obs == n_tot:
        hi = 1.0
    else:
        a, b = 0.0, 1.0
        for _ in range(80):
            mid = 0.5 * (a + b)
            if _binom_cdf_le(n_tot, k_obs, mid) > alpha:
                a = mid
            else:
                b = mid
        hi = 0.5 * (a + b)
    return lo, hi


def _is_real_number(val: Any) -> bool:
    return isinstance(val, (int, float)) and not isinstance(val, bool) and math.isfinite(float(val))


def _is_strict_int(val: Any) -> bool:
    return isinstance(val, int) and not isinstance(val, bool)


def _mean_se_t95_one_sided(vals: List[float]) -> Dict[str, float]:
    n = len(vals)
    if n < 2:
        raise ValueError("Need at least 2 observations for Student-t CI")
    mean = sum(vals) / n
    var = sum((x - mean) ** 2 for x in vals) / (n - 1)
    sd = math.sqrt(var)
    se = sd / math.sqrt(n)
    tcrit = _student_t_95_one_sided(n - 1)
    return {
        "n": n,
        "mean": mean,
        "sd": sd,
        "se": se,
        "t_crit_one_sided_95": tcrit,
        "l95": mean - tcrit * se,
        "u95": mean + tcrit * se,
    }


def _eval_5arm_exact_2pow20(
    arms: List[Tuple[float, float, float, float]],
    *,
    c1_allo: float,
    c3_uniform: float,
    phi_c: float,
    phi_yx: float = 0.75,
    c2_inc: float = 0.87,
    c2_y: float = 0.87,
    c2_univ: float = 0.95,
    c2_auto: float = 0.93,
    c4_univ: float = 0.92,
    c4_pouch: float = 0.85,
    c4_r3p: float = 0.85,
) -> Dict[str, float]:
    """Exact 2^20 5-arm portfolio kernel synchronized bit-for-bit with verify_iip0042."""
    if str(SCRIPT_DIR) not in sys.path:
        sys.path.insert(0, str(SCRIPT_DIR))
    import rank_islet1_stacks as ris  # noqa: E402

    _bivariate = ris._bivariate_bernoulli_iip0034
    _frechet_joint = ris._frechet_bernoulli_joint_iip0034
    _frechet_couple = ris._frechet_couple_new_arm_iip0034

    compat = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3P"}),
    }
    cell_classes = (
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "DESIGN_Y_FULLSTACK_V2",
        "D1B_AUTO_C_V2",
    )
    pa, pb, px, py, pd = arms

    # H1
    u_d1 = min(1.0, max(0.0, pd[0] / c1_allo))
    d1 = [0.0] * 32
    d1[0] = 1.0 - c1_allo
    d1[15] = c1_allo * (1.0 - u_d1)
    d1[31] = c1_allo * u_d1
    c1_e = c1_allo

    # H2
    d2_inc = _frechet_joint([pa[1] / c2_inc, pb[1] / c2_inc, px[1] / c2_inc], 0.0)
    r2 = c2_inc / c2_y
    u_y2 = py[1] / c2_y
    d2_both = _frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
    d2_allo4 = [r2 * d2_both[k] for k in range(16)]
    d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
    d2_allo4[8] += (1.0 - r2) * u_y2
    biv2 = _bivariate(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    u_d2 = pd[1] / c2_auto
    d2 = [0.0] * 32
    d2[0] += 1.0 - c2_univ
    for (s0, s1), wp in biv2.items():
        w = c2_univ * wp
        if s0 == 0 and s1 == 0:
            d2[0] += w
        elif s0 == 1 and s1 == 0:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4]
        elif s0 == 0 and s1 == 1:
            d2[0] += w * (1.0 - u_d2)
            d2[16] += w * u_d2
        else:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4] * (1.0 - u_d2)
                d2[m4 | 16] += w * d2_allo4[m4] * u_d2
    c2_e = c2_univ * (1.0 - biv2[(0, 0)])

    # H3 (uniform c3 across arms)
    d3_inc = _frechet_joint([pa[2] / c3_uniform, pb[2] / c3_uniform, px[2] / c3_uniform], 0.0)
    d3_both = _frechet_couple(d3_inc, py[2] / c3_uniform, phi_yx, lambda mi: bool(mi & 4))
    d3_5cond = _frechet_couple(d3_both, pd[2] / c3_uniform, phi_c, lambda m4: m4 != 0)
    d3 = [0.0] * 32
    d3[0] += 1.0 - c3_uniform
    for k in range(32):
        d3[k] += c3_uniform * d3_5cond[k]
    c3_e = c3_uniform

    # H4 TWO_PARADIGM_WU3
    d_ax = _frechet_joint([pa[3] / c4_pouch, px[3] / c4_pouch], 1.0)
    u_b = pb[3] / c4_pouch
    d4_inc = [0.0] * 8
    for m_ax in range(4):
        bm = (m_ax & 1) | (((m_ax >> 1) & 1) << 2)
        d4_inc[bm] += d_ax[m_ax] * (1.0 - u_b)
        d4_inc[bm | 2] += d_ax[m_ax] * u_b
    biv4 = _bivariate(c4_pouch / c4_univ, c4_r3p / c4_univ, phi_c)
    d4_r3 = _frechet_joint([py[3] / c4_r3p, pd[3] / c4_r3p], 1.0)
    d4 = [0.0] * 32
    d4[0] += 1.0 - c4_univ
    for (s0, s1), wp in biv4.items():
        w = c4_univ * wp
        if s0 == 0 and s1 == 0:
            d4[0] += w
        elif s0 == 1 and s1 == 0:
            for m3 in range(8):
                d4[m3] += w * d4_inc[m3]
        elif s0 == 0 and s1 == 1:
            for mr in range(4):
                m5 = ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                d4[m5] += w * d4_r3[mr]
        else:
            for m3 in range(8):
                for mr in range(4):
                    m5 = m3 | ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                    d4[m5] += w * d4_inc[m3] * d4_r3[mr]
    c4_e = c4_univ * (1.0 - biv4[(0, 0)])

    routes = ("R1", "R2", "R1", "R3P", "R3P")
    v = [0.0] * 32
    v[31] = 1.0
    v_h123: List[float] = []
    for h, dh in enumerate((d1, d2, d3, d4)):
        if abs(sum(dh) - 1.0) > 1e-12 or min(dh) < -1e-12:
            raise RuntimeError(f"Distribution normalization error in H{h + 1}")
        vn = [0.0] * 32
        for s, vs in enumerate(v):
            if vs != 0.0:
                for m, w in enumerate(dh):
                    if w != 0.0:
                        vn[s & m] += vs * w
        v = vn
        if h == 2:
            v_h123 = list(v)

    locked = sum(v[s] for s in range(1, 32))
    mod100 = 0.0
    for mc in range(1, 32):
        wc = v_h123[mc]
        if wc == 0.0:
            continue
        allowed: set[str] = set()
        for i in range(5):
            if mc & (1 << i):
                allowed |= compat[cell_classes[i]]
        for mh in range(1, 32):
            wh = d4[mh]
            if wh != 0.0 and any(routes[j] in allowed for j in range(5) if (mh & (1 << j))):
                mod100 += wc * wh

    return {
        "locked_exact": locked,
        "modular_k100_exact": mod100,
        "ceiling_exact": math.prod((c1_e, c2_e, c3_e, c4_e)),
        "locked_pct": round(100.0 * locked, 4),
        "modular_k100_pct": round(100.0 * mod100, 4),
        "ceiling_pct": round(100.0 * math.prod((c1_e, c2_e, c3_e, c4_e)), 4),
    }


def _full_stack_arms(m: float) -> List[Tuple[float, float, float, float]]:
    return [
        (0.90, 0.78, 0.625 + m * D_SHIELD_COCKTAIL_ARMS_POST028["A"], 0.745),
        (0.90, 0.79, 0.680 + m * D_SHIELD_COCKTAIL_ARMS_POST028["B"], 0.775),
        (0.90, 0.82, 0.785 + m * D_SHIELD_COCKTAIL_ARMS_POST028["X"], 0.745),
        (0.90, 0.84, 0.800 + m * D_SHIELD_COCKTAIL_ARMS_POST028["Y"], 0.735),
        (0.66, 0.92, 0.700 + m * D_SHIELD_COCKTAIL_ARMS_POST028["D"], 0.715),
    ]


def _cocktail_only_arms(m: float) -> List[Tuple[float, float, float, float]]:
    return [
        (0.88, 0.78, 0.57 + m * D_SHIELD_COCKTAIL_ARMS_BASE["A"], 0.69),
        (0.88, 0.79, 0.64 + m * D_SHIELD_COCKTAIL_ARMS_BASE["B"], 0.70),
        (0.88, 0.82, 0.73 + m * D_SHIELD_COCKTAIL_ARMS_BASE["X"], 0.69),
        (0.88, 0.84, 0.80 + m * D_SHIELD_COCKTAIL_ARMS_BASE["Y"], 0.72),
        (0.62, 0.92, 0.70 + m * D_SHIELD_COCKTAIL_ARMS_BASE["D"], 0.70),
    ]


def compute_exact_2d_coverage_pk_grid(repo_root: Path) -> Dict[str, Any]:
    """Compute exact 2^20 2-D f x PK grid and verify <= 1e-12 parity against iip0042 receipt."""
    rec = load_strict_json_file(repo_root / IIP0042_RECEIPT_REL)
    s25 = {r["layer_id"]: r for r in rec["headline_live_eligible_scenarios_strict_no_r3b"]["phi_0p25_central"]}
    s50 = {r["layer_id"]: r for r in rec["headline_live_eligible_scenarios_strict_no_r3b"]["phi_0p50_harsh_stress"]}

    parity_errors: Dict[str, float] = {}
    out_regimes: Dict[str, Any] = {}

    for phi_c, key_name, sd, l1_id in (
        (0.25, "phi_0p25_central", s25, "L1_LIVE_5ARM_WU3"),
        (0.50, "phi_0p50_harsh_stress", s50, "L1_LIVE_5ARM_WU4"),
    ):
        fs_base = _eval_5arm_exact_2pow20(_full_stack_arms(0.0), c1_allo=0.90, c3_uniform=0.89, phi_c=phi_c)
        fs_full = _eval_5arm_exact_2pow20(_full_stack_arms(1.0), c1_allo=0.90, c3_uniform=0.925, phi_c=phi_c)
        co_base = _eval_5arm_exact_2pow20(_cocktail_only_arms(0.0), c1_allo=0.88, c3_uniform=0.89, phi_c=phi_c)
        co_half = _eval_5arm_exact_2pow20(_cocktail_only_arms(0.5), c1_allo=0.88, c3_uniform=0.89 + 0.5 * DC3_SHIELD_COCKTAIL, phi_c=phi_c)
        co_full = _eval_5arm_exact_2pow20(_cocktail_only_arms(1.0), c1_allo=0.88, c3_uniform=0.925, phi_c=phi_c)

        checks = {
            f"{key_name}_fs_m0_locked": abs(fs_base["locked_exact"] - sd["L3_SHIELD_FAIL_ZERODRUG_BASE"]["locked_exact"]),
            f"{key_name}_fs_m0_mod100": abs(fs_base["modular_k100_exact"] - sd["L3_SHIELD_FAIL_ZERODRUG_BASE"]["modular_k100_exact"]),
            f"{key_name}_fs_m1_locked": abs(fs_full["locked_exact"] - sd["L3B_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            f"{key_name}_fs_m1_mod100": abs(fs_full["modular_k100_exact"] - sd["L3B_STACK_STRICT_100PCT_ZERO_DRUG"]["modular_k100_exact"]),
            f"{key_name}_co_m0_locked": abs(co_base["locked_exact"] - sd[l1_id]["locked_exact"]),