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…

        raise ValueError(f"{label} must be finite (not NaN/Inf), got {val!r} (IIP-0024; DEC-103)")
    return fv


def compute_common_shock_2pow12_portfolio_tree(
    pa_vec: list[float] | tuple[float, ...],
    pb_vec: list[float] | tuple[float, ...],
    px_vec: list[float] | tuple[float, ...],
    c_vec: list[float] | tuple[float, ...],
) -> dict:
    """
    Exact 4,096-state (2^12; 1,024 positive-mass states) common-shock portfolio probability generator
    (IIP-0022 & IIP-0024; DEC-101/103). Strictly validates finite non-bool 0 <= p_{h,d} <= c_h <= 1
    with zero slack above c_h, shared Hurdle-1 equality, 12-marginal recovery within 1e-12, and positive
    surviving-portfolio denominators, returning both legacy 3-slot and shared-A/X 2-route pouch unions.
    """
    if not all(isinstance(v, (list, tuple)) and len(v) == 4 for v in (pa_vec, pb_vec, px_vec, c_vec)):
        raise ValueError("All hurdle and common-shock vectors must be 4-element lists or tuples (IIP-0024; DEC-103)")
    pa_clean = [_strict_prob_float_iip0024(pa_vec[i], f"pa[{i}]") for i in range(4)]
    pb_clean = [_strict_prob_float_iip0024(pb_vec[i], f"pb[{i}]") for i in range(4)]
    px_clean = [_strict_prob_float_iip0024(px_vec[i], f"px[{i}]") for i in range(4)]
    c_clean = [_strict_prob_float_iip0024(c_vec[i], f"c[{i}]") for i in range(4)]
    for h_idx in range(4):
        ch = c_clean[h_idx]
        if not (0.0 < ch <= 1.0):
            raise ValueError(f"Common-shock ceiling c[{h_idx}]={ch} must lie in (0, 1] (IIP-0024; DEC-103)")
        for d_lbl, pvf in (("A", pa_clean[h_idx]), ("B", pb_clean[h_idx]), ("X", px_clean[h_idx])):
            if pvf < 0.0 or pvf > ch:
                raise ValueError(f"Hurdle {h_idx+1} design {d_lbl} probability {pvf} outside [0, c_h={ch}] (IIP-0024; DEC-103)")
    if not (abs(pa_clean[0] - c_clean[0]) < 1e-12 and abs(pb_clean[0] - c_clean[0]) < 1e-12 and abs(px_clean[0] - c_clean[0]) < 1e-12):
        raise ValueError("Hurdle 1 is a 100% shared class step: pa[0], pb[0], px[0] must equal c[0]")

    # Build 8-outcome single-hurdle distributions under:
    # (1) 3 conditionally independent design slots on H2..H4 (legacy 3-slot pouch on H4), and
    # (2) shared A/X CaO2+catalase pouch route on H4 (where A and X share common pouch shock or paired outcome).
    def _hurdle_dist_independent(h_idx: int) -> list[float]:
        ch = c_clean[h_idx]
        if h_idx == 0:
            # 8 states indexed by 3-bit mask (bit0=A, bit1=B, bit2=X): only 000 (1-c1) and 111 (c1) have positive mass
            d = [0.0] * 8
            d[0] = 1.0 - ch
            d[7] = ch
            return d
        ua = pa_clean[h_idx] / ch
        ub = pb_clean[h_idx] / ch
        ux = px_clean[h_idx] / ch
        d = [0.0] * 8
        d[0] += 1.0 - ch
        for mask in range(8):
            pa_m = ua if (mask & 1) else (1.0 - ua)
            pb_m = ub if (mask & 2) else (1.0 - ub)
            px_m = ux if (mask & 4) else (1.0 - ux)
            d[mask] += ch * pa_m * pb_m * px_m
        return d

    def _hurdle4_dist_shared_ax() -> list[float]:
        c4 = c_clean[3]
        ua = pa_clean[3] / c4
        ub = pb_clean[3] / c4
        ux = px_clean[3] / c4
        # Comonotonic shared A/X CaO2+catalase pouch route coupled independently with orthogonal Design B (140 um Zero-CaO2):
        # P(A=1, X=1 | c4) = min(ua, ux), P(A=1, X=0 | c4) = max(0, ua - ux), P(A=0, X=1 | c4) = max(0, ux - ua), P(A=0, X=0 | c4) = 1 - max(ua, ux)
        p11 = min(ua, ux)
        p10 = max(0.0, ua - ux)
        p01 = max(0.0, ux - ua)
        p00 = 1.0 - max(ua, ux)
        d = [0.0] * 8
        d[0] += 1.0 - c4
        for ax_bits, p_ax in (((0, 0), p00), ((1, 0), p10), ((0, 1), p01), ((1, 1), p11)):
            for b_bit, p_b in ((0, 1.0 - ub), (1, ub)):
                mask = ax_bits[0] | (b_bit << 1) | (ax_bits[1] << 2)
                d[mask] += c4 * p_ax * p_b
        return d

    dists_3slot = [_hurdle_dist_independent(h) for h in range(4)]
    total_states = 0
    pos_states = 0
    total_mass = 0.0
    surv_prefix = [0.0, 0.0, 0.0, 0.0]
    any_cell_h123 = 0.0
    marg_counts = [[0.0, 0.0, 0.0] for _ in range(4)]

    for m0 in range(8):
        p0 = dists_3slot[0][m0]
        for m1 in range(8):
            p01 = p0 * dists_3slot[1][m1]
            s1 = m0 & m1
            for m2 in range(8):
                p012 = p01 * dists_3slot[2][m2]
                s2 = s1 & m2
                for m3 in range(8):
                    total_states += 1
                    pm = p012 * dists_3slot[3][m3]
                    total_mass += pm
                    if pm > 0.0:
                        pos_states += 1
                    s3 = s2 & m3
                    if m0 != 0:
                        surv_prefix[0] += pm
                    if s1 != 0:
                        surv_prefix[1] += pm
                    if s2 != 0:
                        surv_prefix[2] += pm
                        any_cell_h123 += pm
                    if s3 != 0:
                        surv_prefix[3] += pm
                    for h_i, mh in enumerate((m0, m1, m2, m3)):
                        if mh & 1:
                            marg_counts[h_i][0] += pm
                        if mh & 2:
                            marg_counts[h_i][1] += pm
                        if mh & 4:
                            marg_counts[h_i][2] += pm

    if total_states != 4096 or abs(total_mass - 1.0) > 1e-12:
        raise ValueError(f"2^12 tree mass/state check failed: states={total_states}, mass={total_mass}")
    if any(sp <= 0.0 for sp in surv_prefix[:3]):
        raise ValueError("Zero surviving-portfolio denominator encountered in 2^12 tree")
    for h_i in range(4):
        for d_i, (d_lbl, orig_p) in enumerate((("A", pa_clean[h_i]), ("B", pb_clean[h_i]), ("X", px_clean[h_i]))):
            if abs(marg_counts[h_i][d_i] - orig_p) > 1e-12:
                raise ValueError(f"2^12 marginal recovery error on H{h_i+1} {d_lbl}: {marg_counts[h_i][d_i]} vs {orig_p}")

    cond_h1 = surv_prefix[0]
    cond_h2 = surv_prefix[1] / surv_prefix[0]
    cond_h3 = surv_prefix[2] / surv_prefix[1]
    cond_h4 = surv_prefix[3] / surv_prefix[2]
    locked_3slot = surv_prefix[3]

    # Locked shared-A/X pouch tree (comonotonic A/X pouch on H4):
    d4_shared = _hurdle4_dist_shared_ax()
    if abs(sum(d4_shared) - 1.0) > 1e-12:
        raise ValueError("Shared-A/X Hurdle-4 distribution failed unit-mass check")
    h4_sh_margs = [
        sum(d4_shared[m] for m in range(8) if m & 1),
        sum(d4_shared[m] for m in range(8) if m & 2),
        sum(d4_shared[m] for m in range(8) if m & 4),
    ]
    for d_i, orig_p4 in enumerate((pa_clean[3], pb_clean[3], px_clean[3])):
        if abs(h4_sh_margs[d_i] - orig_p4) > 1e-12:
            raise ValueError("Shared-A/X Hurdle-4 marginal recovery drift")
    locked_shared_ax = 0.0
    for m0 in range(8):
        for m1 in range(8):
            for m2 in range(8):
                s2 = m0 & m1 & m2
                if s2 == 0:
                    continue
                p012 = dists_3slot[0][m0] * dists_3slot[1][m1] * dists_3slot[2][m2]
                for m3 in range(8):
                    if (s2 & m3) != 0:
                        locked_shared_ax += p012 * d4_shared[m3]

    # Modular Stage-0 cell x pouch unions:
    # Legacy 3-slot pouch union vs true 2-route shared-A/X pouch union (where A/X share CaO2+catalase route max(pa4, px4) vs B's Design Z pb4):
    c4 = c_clean[3]
    ua4, ub4, ux4 = pa_clean[3] / c4, pb_clean[3] / c4, px_clean[3] / c4
    pouch_union_legacy_3slot = c4 * (1.0 - (1.0 - ua4) * (1.0 - ub4) * (1.0 - ux4))
    u_ax_shared = max(ua4, ux4)
    pouch_union_2route_shared_ax = c4 * (1.0 - (1.0 - u_ax_shared) * (1.0 - ub4))

    return {
        "total_enumerated_states": total_states,
        "positive_mass_states": pos_states,
        "total_probability_mass": round(total_mass, 12),
        "common_shock_ceiling_vector": [round(x, 6) for x in c_clean],
        "recovered_marginals_check": {
            "design_a": [round(marg_counts[h][0], 8) for h in range(4)],
            "design_b": [round(marg_counts[h][1], 8) for h in range(4)],
            "design_x": [round(marg_counts[h][2], 8) for h in range(4)],
        },
        "surviving_portfolio_conditionals_exact": [
            round(cond_h1, 9),
            round(cond_h2, 9),
            round(cond_h3, 9),
            round(cond_h4, 9),
        ],
        "locked_3slot_2pow12_exact": round(locked_3slot, 9),
        "legacy_modular_3slot_cell_x_pouch_exact": round(any_cell_h123 * pouch_union_legacy_3slot, 9),
        "modular_2route_shared_ax_pouch_exact": round(any_cell_h123 * pouch_union_2route_shared_ax, 9),
        "locked_2route_shared_ax_pouch_exact": round(locked_shared_ax, 9),
        "pouch_union_legacy_3slot_exact": round(pouch_union_legacy_3slot, 9),
        "pouch_union_2route_shared_ax_exact": round(pouch_union_2route_shared_ax, 9),
    }


def compute_donor_bank_h1_sensitivity_iip_0024(phi_donor: float = 0.25) -> dict:
    """
    Evaluate conditional Hurdle-1 donor-bank failure-share sensitivity (phi_donor = 0.25; IIP-0024; DEC-103)
    across 2-bank pairings ({A,X}+B, {B,X}+A, {A,B}+X), keeping marginal p_{1,d} = 0.88 and all headline
    single-design / portfolio numbers invariant.
    """
    phi_d = _strict_prob_float_iip0024(phi_donor, "phi_donor")
    if not (0.0 <= phi_d <= 1.0):
        raise ValueError("phi_donor must lie in [0, 1] (IIP-0024; DEC-103)")
    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]
    cv = [0.88, 0.87, 0.89, 0.85]
    base_tree = compute_common_shock_2pow12_portfolio_tree(pa, pb, px, cv)
    c1_class = 1.0 - (1.0 - cv[0]) * (1.0 - phi_d)
    u1_bank = cv[0] / c1_class

    def _eval_pairing(shared_pair: str) -> tuple[float, float]:
        d0 = [0.0] * 8
        d0[0] += 1.0 - c1_class
        for b1, p1 in ((0, 1.0 - u1_bank), (1, u1_bank)):
            for b2, p2 in ((0, 1.0 - u1_bank), (1, u1_bank)):
                if shared_pair == "AX_plus_B":
                    mask = b1 | (b2 << 1) | (b1 << 2)
                elif shared_pair == "BX_plus_A":
                    mask = b2 | (b1 << 1) | (b1 << 2)
                else:
                    mask = b1 | (b1 << 1) | (b2 << 2)
                d0[mask] += c1_class * p1 * p2
        dists = [d0]
        for h in (1, 2, 3):
            ch = cv[h]
            ua, ub, ux = pa[h] / ch, pb[h] / ch, px[h] / ch
            d = [0.0] * 8
            d[0] += 1.0 - ch
            for mask in range(8):
                d[mask] += ch * (ua if (mask & 1) else 1.0 - ua) * (ub if (mask & 2) else 1.0 - ub) * (ux if (mask & 4) else 1.0 - ux)
            dists.append(d)
        c4 = cv[3]
        ua4, ub4, ux4 = pa[3] / c4, pb[3] / c4, px[3] / c4
        d4_sh = [0.0] * 8
        d4_sh[0] += 1.0 - c4
        for axb, pax in (((0, 0), 1.0 - max(ua4, ux4)), ((1, 0), max(0.0, ua4 - ux4)), ((0, 1), max(0.0, ux4 - ua4)), ((1, 1), min(ua4, ux4))):
            for bb, pbp in ((0, 1.0 - ub4), (1, ub4)):
                d4_sh[axb[0] | (bb << 1) | (axb[1] << 2)] += c4 * pax * pbp
        l3, lsh = 0.0, 0.0
        for m0 in range(8):
            for m1 in range(8):
                for m2 in range(8):
                    s2 = m0 & m1 & m2
                    if s2 == 0:
                        continue
                    p012 = dists[0][m0] * dists[1][m1] * dists[2][m2]
                    for m3 in range(8):
                        if s2 & m3:
                            l3 += p012 * dists[3][m3]
                            lsh += p012 * d4_sh[m3]
        return lsh, l3

    pair_results = {
        k: _eval_pairing(k)
        for k in ("AX_plus_B", "BX_plus_A", "AB_plus_X")
    }
    sh_vals = [v[0] for v in pair_results.values()]