OpenIslet

scripts/rank_islet1_stacks.py

Step 5 & 6: Project Islet-1 Sign-Sensitive, Endpoint-Oriented & Locus-Penalized Evaluator (v0.6.9).

script Release v0.8.0 gen-eb955f8266035aba 638 KB · 42 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/rank_islet1_stacks.py · SHA-256: c05d5fe606219e88…

    dists: list[list[float]],
    eff_ceils: list[float],
    p0_l: float,
    p0_m: float,
    c0: float,
    *,
    stage0_status: str,
    cell_classes: tuple[str, ...] | None = None,
    route_ids: tuple[str, ...] | None = None,
) -> dict:
    n_arms = len(arms)
    n_states = 1 << n_arms
    for nm, sc_val in (("p0_l", p0_l), ("p0_m", p0_m), ("c0", c0)):
        if isinstance(sc_val, bool) or not isinstance(sc_val, (int, float)) or not math.isfinite(float(sc_val)) or not (0.0 <= sc_val <= 1.0):
            raise ValueError(f"Invalid baseline scalar {nm}={sc_val!r} in {label}")
    if len(eff_ceils) != 4 or any(isinstance(c, bool) or not isinstance(c, (int, float)) or not math.isfinite(float(c)) or not (0.0 <= c <= 1.0) for c in eff_ceils):
        raise ValueError(f"Invalid eff_ceils={eff_ceils!r} in {label}")
    for i, arm in enumerate(arms):
        if len(arm) != 4 or any(isinstance(p, bool) or not isinstance(p, (int, float)) or not math.isfinite(float(p)) or not (0.0 <= p <= 1.0) for p in arm):
            raise ValueError(f"Invalid arm probability tuple for arm {i} in {label}: {arm!r}")
    if cell_classes is None:
        if n_arms == 3:
            cell_classes = ('UNHARDENED_A_B_X', 'UNHARDENED_A_B_X', 'UNHARDENED_A_B_X')
        elif n_arms == 4:
            cell_classes = ('UNHARDENED_A_B_X', 'UNHARDENED_A_B_X', 'UNHARDENED_A_B_X', 'DESIGN_Y_FULLSTACK_V2')
        elif n_arms == 5:
            cell_classes = ('UNHARDENED_A_B_X', 'UNHARDENED_A_B_X', 'UNHARDENED_A_B_X', 'DESIGN_Y_FULLSTACK_V2', 'D1B_AUTO_C_V2')
        else:
            cell_classes = tuple('DESIGN_Y_FULLSTACK_V2' for _ in range(n_arms))
    if route_ids is None:
        if n_arms == 3:
            route_ids = ('R1', 'R2', 'R1')
        elif n_arms == 4:
            route_ids = ('R1', 'R2', 'R1', 'R3P')
        elif n_arms == 5:
            route_ids = ('R1', 'R2', 'R1', 'R3P', 'R3P')
        else:
            route_ids = tuple('R2' for _ in range(n_arms))
    if len(cell_classes) != n_arms or len(route_ids) != n_arms:
        raise ValueError(f"cell_classes/route_ids length mismatch for {label}")
    for i in range(n_arms):
        if cell_classes[i] not in ALLOWED_CELL_ROUTE_PAIRS_IIP0034:
            raise ValueError(f"Unknown cell_class {cell_classes[i]!r} in {label}")

    if len(dists) != 4:
        raise ValueError(f"Expected 4 hurdle distributions in {label}, got {len(dists)}")
    d_inc3: list[list[float]] = []
    for h in range(4):
        dh = dists[h]
        if len(dh) != n_states:
            raise ValueError(f"Distribution length mismatch in {label} H{h+1}: {len(dh)} != {n_states}")
        if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)) for v in dh):
            raise ValueError(f"Non-finite probability mass in {label} H{h+1}")
        if min(dh) < -1e-12:
            raise ValueError(f"Negative joint probability mass in {label} H{h+1}: {min(dh)}")
        s_dh = sum(dh)
        if not math.isfinite(s_dh) or abs(s_dh - 1.0) >= 1e-12:
            raise ValueError(f"Normalization check failed for {label} H{h+1}: sum={s_dh}")
        for i in range(n_arms):
            rec = sum(dh[m] for m in range(n_states) if (m & (1 << i)))
            if not math.isfinite(rec) or abs(rec - arms[i][h]) >= 1e-11:
                raise ValueError(f"Marginal drift {label} H{h+1} arm {i}: {rec} vs {arms[i][h]}")
        di = [0.0] * 8
        for m in range(n_states):
            di[m & 7] += dh[m]
        d_inc3.append(di)

    # Full 4,096-state incumbent joint probability distribution parity check (max |delta| <= 1e-12)
    canon_inc = _live_canonical_incumbent_dists_iip0034()
    max_4096_err = 0.0
    if n_arms >= 3:
        for m0 in range(8):
            p0_a, p0_b = d_inc3[0][m0], canon_inc[0][m0]
            for m1 in range(8):
                p1_a, p1_b = p0_a * d_inc3[1][m1], p0_b * canon_inc[1][m1]
                for m2 in range(8):
                    p2_a, p2_b = p1_a * d_inc3[2][m2], p1_b * canon_inc[2][m2]
                    for m3 in range(8):
                        err = abs(p2_a * d_inc3[3][m3] - p2_b * canon_inc[3][m3])
                        if not math.isfinite(err):
                            raise ValueError(f"Non-finite 4,096-state parity error in {label}")
                        if err > max_4096_err:
                            max_4096_err = err
        if max_4096_err > 1e-12:
            raise ValueError(
                f"4,096-state incumbent joint parity violation in {label}: max |delta| = {max_4096_err:.3e} > 1e-12"
            )

    v_inc = [0.0] * 8
    v_inc[7] = 1.0
    for h in range(4):
        vn = [0.0] * 8
        for s in range(8):
            for mh in range(8):
                vn[s & mh] += v_inc[s] * d_inc3[h][mh]
        v_inc = vn
    inc_locked = 1.0 - v_inc[0]
    inc_parity_err = abs(inc_locked - p0_l)
    if not math.isfinite(inc_parity_err) or inc_parity_err >= 1e-8:
        raise ValueError(f"INCUMBENT PARITY VIOLATION in {label}: {inc_locked:.10f} vs {p0_l:.10f}")

    v = [0.0] * n_states
    v[n_states - 1] = 1.0
    surv = []
    v_h123: list[float] = []
    for h in range(4):
        vn = [0.0] * n_states
        dh = dists[h]
        for s in range(n_states):
            vs = v[s]
            if vs == 0.0:
                continue
            for mh in range(n_states):
                w = dh[mh]
                if w == 0.0:
                    continue
                vn[s & mh] += vs * w
        v = vn
        if h == 2:
            v_h123 = list(v)
        surv.append(1.0 - v[0])

    # Apply ALLOWED_CELL_ROUTE_PAIRS_IIP0034 identically to BOTH the locked diagonal and the modular branch
    admissible_locked_mask = 0
    for i in range(n_arms):
        if route_ids[i] in ALLOWED_CELL_ROUTE_PAIRS_IIP0034[cell_classes[i]]:
            admissible_locked_mask |= (1 << i)
    locked_unconstrained = surv[3]
    if admissible_locked_mask == (n_states - 1):
        locked = locked_unconstrained
    else:
        locked = sum(v[s] for s in range(1, n_states) if (s & admissible_locked_mask) != 0)
    prohibited_locked_excl = max(0.0, locked_unconstrained - locked)
    h4_union = 1.0 - dists[3][0]
    unconstrained_mod100 = surv[2] * h4_union

    compat_mod100 = 0.0
    dh4 = dists[3]
    for m_cell in range(1, n_states):
        wc = v_h123[m_cell]
        if wc == 0.0:
            continue
        allowed_routes: set[str] = set()
        for i in range(n_arms):
            if m_cell & (1 << i):
                allowed_routes |= ALLOWED_CELL_ROUTE_PAIRS_IIP0034[cell_classes[i]]
        for m_h4 in range(1, n_states):
            wh = dh4[m_h4]
            if wh == 0.0:
                continue
            if any(route_ids[j] in allowed_routes for j in range(n_arms) if (m_h4 & (1 << j))):
                compat_mod100 += wc * wh

    prohibited_excl = max(0.0, unconstrained_mod100 - compat_mod100)
    mod100 = compat_mod100
    mod90 = 0.90 * mod100 + 0.10 * locked
    ceil = math.prod(eff_ceils)
    q_l = (locked - p0_l) / (1.0 - p0_l)
    q_m = (mod100 - p0_m) / (1.0 - p0_m)
    ql_bar_exact = (c0 - p0_l) / (1.0 - p0_l)
    qm_bar_exact = (c0 - p0_m) / (1.0 - p0_m)
    _law_col = _ACTIVE_LAW_COLLECTOR_IIP0035.get()
    if _law_col is not None:
        _law_col[label] = {
            "cell_architecture_classes": tuple(cell_classes),
            "h4_route_assignments": tuple(route_ids),
            "stage_dists": tuple(tuple(float(x) for x in d) for d in dists),
        }
    return {
        "scenario": label,
        "stage0_qualification_status": stage0_status,
        "n_arms": n_arms,
        "cell_architecture_classes": list(cell_classes),
        "h4_route_assignments": list(route_ids),
        "eff_ceilings_pct": [round(100.0 * c, 2) for c in eff_ceils],
        "composite_ceiling_pct": round(100.0 * ceil, 4),
        "h4_union_pct": round(100.0 * h4_union, 4),
        "locked_pct": round(100.0 * locked, 4),
        "delta_locked_pp": round(100.0 * (locked - p0_l), 4),
        "modular_k100_pct": round(100.0 * mod100, 4),
        "modular_k90_pct": round(100.0 * mod90, 4),
        "modular_unconstrained_reference_pct": round(100.0 * unconstrained_mod100, 4),
        "prohibited_locked_mass_excluded_pp": round(100.0 * prohibited_locked_excl, 4),
        "prohibited_modular_mass_excluded_pp": round(100.0 * prohibited_excl, 4),
        "delta_modular_pp": round(100.0 * (mod100 - p0_m), 4),
        "residual_risk_reduction_locked_pct": round(100.0 * q_l, 2),
        "residual_risk_reduction_mod_pct": round(100.0 * q_m, 2),
        "clears_57p92_locked": bool(locked > c0),
        "clears_qL_14p51_and_qM_8p29": bool((q_l > ql_bar_exact) and (q_m > qm_bar_exact)),
        "incumbent_parity_err": round(inc_parity_err, 12),
        "incumbent_4096_state_max_abs_err": round(max_4096_err, 15),
    }


def compute_multiparadigm_2pow4n_portfolio_iip0034() -> dict:
    """Compute canonical registry-verified compatibility-constrained 2^(4N) multi-paradigm portfolio artifact (IIP-0034; DEC-113)."""
    _pc_mod = _load_local_helper("product_contract")
    _p_defs = _pc_mod.load_product_contracts(PROJECT_ROOT, require_staged_fastas=True)
    _route_map = {"ROUTE_1_MACROENCAPSULATED": "R1", "ROUTE_2_OPEN_PORE_PREVASC": "R2", "ROUTE_3P_MODULAR_PLANAR_ENVELOPE": "R3P"}
    _by_id = {p["product_variant_id"]: p for p in _p_defs["products"]}
    _dy2_routes = {_route_map.get(str(_by_id[pid].get("physical_route_id")), "") for pid in _pc_mod.STAGED_DESIGN_Y_V2_PRODUCT_IDS}
    if _dy2_routes != ALLOWED_CELL_ROUTE_PAIRS_IIP0034["DESIGN_Y_FULLSTACK_V2"]:
        raise ValueError(f"Loaded product registry routes {sorted(_dy2_routes)} disagree with ALLOWED_CELL_ROUTE_PAIRS_IIP0034['DESIGN_Y_FULLSTACK_V2']")
    pa = (0.88, 0.78, 0.57, 0.69)
    pb = (0.88, 0.79, 0.64, 0.70)
    px = (0.88, 0.82, 0.73, 0.69)
    c_base = (0.88, 0.87, 0.89, 0.85)
    live = compute_common_shock_2pow12_portfolio_tree(pa, pb, px, c_base)
    p0_l = float(live["locked_2route_shared_ax_pouch_exact"])
    p0_m = float(live["modular_2route_shared_ax_pouch_exact"])
    c0 = math.prod(c_base)
    ql_bar = 100.0 * (c0 - p0_l) / (1.0 - p0_l)
    qm_bar = 100.0 * (c0 - p0_m) / (1.0 - p0_m)

    def _eval_4arm(
        label: str,
        p_y: tuple[float, float, float, float],
        *,
        c2_y: float,
        c3_y: float,
        phi_yx: float,
        h4_mode: str,
        c4_univ: float,
        c4_r3: float,
        phi_h4: float,
        stage0_status: str,
    ) -> dict:
        d1 = [0.0] * 16
        d1[0] = 0.12
        d1[15] = 0.88

        def _nested_h(inc_probs: list[float], c_inc: float, p_arm_y: float, c_arm_y: float) -> tuple[list[float], float]:
            d_inc = _frechet_bernoulli_joint_iip0034([p / c_inc for p in inc_probs], 0.0)
            r = c_inc / c_arm_y
            u_y = p_arm_y / c_arm_y
            d_both = _frechet_couple_new_arm_iip0034(d_inc, u_y, phi_yx, lambda mi: bool(mi & 4))
            d = [0.0] * 16
            d[0] += 1.0 - c_arm_y
            w_both = c_arm_y * r
            w_yonly = c_arm_y * (1.0 - r)
            for k in range(16):
                d[k] += w_both * d_both[k]
            d[0] += w_yonly * (1.0 - u_y)
            d[8] += w_yonly * u_y
            return d, c_arm_y

        d2, c2_e = _nested_h([pa[1], pb[1], px[1]], 0.87, p_y[1], c2_y)
        d3, c3_e = _nested_h([pa[2], pb[2], px[2]], 0.89, p_y[2], c3_y)
        d4_inc = _live_incumbent_h4_cond_iip0034()
        if h4_mode == "SHARED_R2":