OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 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_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

        ph_inc = [sum(ph[h] for h in nz_h if (h & 7) == h3) for h3 in range(8)]
        for si, s in enumerate(nz_s):
            for h3 in range(8):
                if ph_inc[h3] <= 1e-15:
                    continue
                r = np.zeros(nv, dtype=np.float64)
                for hi, h in enumerate(nz_h):
                    if (h & 7) == h3:
                        r[si * nh + hi] = 1.0
                rows.append(r)
                rhs.append(ps[s] * ph_inc[h3])

    # 4. Fixed individual arm full-path success probabilities
    arm_full_targets = [math.prod(vec) for vec in arms]
    arm_cond_rows: list[np.ndarray] = []
    for arm_i in range(n_arms):
        bit = 1 << arm_i
        r = np.zeros(nv, dtype=np.float64)
        for si, s in enumerate(nz_s):
            if not (s & bit):
                continue
            for hi, h in enumerate(nz_h):
                if h & bit:
                    r[si * nh + hi] = 1.0
        rows.append(r)
        rhs.append(arm_full_targets[arm_i] / scale)
        arm_cond_rows.append(r)

    c_lck = np.array([1.0 if (s & h) != 0 else 0.0 for s in nz_s for h in nz_h], dtype=np.float64)
    c_mod = np.array([1.0 if _is_mod_ok(s, h) else 0.0 for s in nz_s for h in nz_h], dtype=np.float64)
    c_gain = c_mod - c_lck

    # Published independent cross-stage baseline on this exact support
    x_indep = np.array([ps[s] * ph[h] for s in nz_s for h in nz_h], dtype=np.float64)
    pub_lck = scale * float(np.dot(c_lck, x_indep))
    pub_mod = scale * float(np.dot(c_mod, x_indep))

    lck_min_raw, x_lck_min = _solve_lp_min_bpr05(c_lck, rows, rhs)
    lck_max_neg, x_lck_max = _solve_lp_min_bpr05(-c_lck, rows, rhs)
    mod_min_raw, x_mod_min = _solve_lp_min_bpr05(c_mod, rows, rhs)
    mod_max_neg, x_mod_max = _solve_lp_min_bpr05(-c_mod, rows, rhs)
    gain_min_raw, x_gain_min = _solve_lp_min_bpr05(c_gain, rows, rhs)
    gain_max_neg, x_gain_max = _solve_lp_min_bpr05(-c_gain, rows, rhs)

    # Verify every individual arm marginal stays fixed across all 6 extreme-point witnesses
    max_arm_err = 0.0
    for x_sol in (x_lck_min, x_lck_max, x_mod_min, x_mod_max, x_gain_min, x_gain_max):
        for arm_i in range(n_arms):
            rec_p = scale * float(np.dot(arm_cond_rows[arm_i], x_sol))
            err = abs(rec_p - arm_full_targets[arm_i])
            if err > max_arm_err:
                max_arm_err = err
    if max_arm_err > 1e-8:
        raise RuntimeError(f"BPR-05 arm marginal invariance violated on {scenario_id}: {max_arm_err:.3e}")

    lck_min = scale * lck_min_raw
    lck_max = scale * (-lck_max_neg)
    mod_min = scale * mod_min_raw
    mod_max = scale * (-mod_max_neg)
    gain_min = scale * gain_min_raw
    gain_max = scale * (-gain_max_neg)

    return {
        "scenario_id": scenario_id,
        "n_arms": n_arms,
        "constraints_preserved": {
            "stage_distributions_v_h123_and_dh4_fixed": True,
            "stage_shared_ceilings_fixed": True,
            "individual_arm_full_path_successes_fixed_pct": [round(100.0 * p, 4) for p in arm_full_targets],
            "incumbent_3arm_4stage_joint_history_preserved": preserve_incumbent_3arm_joint_history,
            "max_abs_arm_marginal_err_across_all_extremes": max_arm_err,
        },
        "published_independent_cross_stage": {
            "locked_pct": round(100.0 * pub_lck, 4),
            "modular_k100_pct": round(100.0 * pub_mod, 4),
            "paired_modular_gain_pp": round(100.0 * (pub_mod - pub_lck), 4),
        },
        "feasible_locked_range_pct": [round(100.0 * lck_min, 4), round(100.0 * lck_max, 4)],
        "feasible_modular_range_pct": [round(100.0 * mod_min, 4), round(100.0 * mod_max, 4)],
        "paired_same_branch_modular_gain_range_pp": [round(100.0 * gain_min, 4), round(100.0 * gain_max, 4)],
        "paired_modular_strictly_positive_across_feasible_set": gain_min > 0.0,
        "locked_crosses_50pct_under_permissible_cross_stage_coupling": (lck_min < 0.50 < lck_max),
        "interpretation_notice": (
            "Feasible cross-stage dependence sensitivity bounds (NOT sampling confidence intervals and NOT cure "
            "probabilities). Published cross-stage-independent points are retained; do NOT replace them with "
            "pessimistic endpoints as new point estimates. Policy comparisons between modular and locked use "
            "paired outcomes under the same joint distribution."
        ),
    }


def run_all(
    openislet_root: Path,
    *,
    standalone: bool = False,
    cross_track_dir: Path | None = None,
    expected_shipped_sha256: str | None = None,
    expected_exp028_sha256: str | None = None,
    expected_exp029_sha256: str | None = None,
    allow_unpinned_diagnostic: bool = False,
) -> dict[str, Any]:
    if standalone and cross_track_dir is not None:
        raise ValueError("Mutually exclusive modes: cannot pass both standalone=True and cross_track_dir")
    if standalone and (expected_exp028_sha256 is not None or expected_exp029_sha256 is not None):
        raise ValueError("Cannot pass expected EXP-028/029 SHA-256 pins when standalone=True")
    if allow_unpinned_diagnostic and expected_shipped_sha256 is not None:
        raise ValueError("Mutually exclusive options: cannot pass both allow_unpinned_diagnostic=True and expected_shipped_sha256")
    if str(openislet_root / "scripts") not in sys.path:
        sys.path.insert(0, str(openislet_root / "scripts"))

    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
    _live_2pow12 = ris.compute_common_shock_2pow12_portfolio_tree
    _live_canon_inc = ris._live_canonical_incumbent_dists_iip0034

    # Strict live-registered route compatibility map (IIP-0035 live registry: NO unregistered R3B!)
    compat_strict_live = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3P"}),
    }
    # Parked counterfactual post-registration maps (ONLY if GY-027 BLOCK lifted + Mode-B R3B registered)
    compat_d1_r3b_counterfactual = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3B"}),
    }
    compat_d1_r3b_hypo_transfer = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P", "R3B"}),
        "D1B_AUTO_C_V2": frozenset({"R3P", "R3B"}),
    }
    std_classes = (
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "DESIGN_Y_FULLSTACK_V2",
        "D1B_AUTO_C_V2",
    )

    def eval_3arm_baseline() -> dict[str, Any]:
        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 = _live_2pow12(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"])
        p0_m90 = 0.90 * p0_m + 0.10 * p0_l
        c0 = math.prod(c_base)

        dists = _live_canon_inc()
        v = [0.0] * 8
        v[7] = 1.0
        v_h123: list[float] = []
        for h in range(4):
            dh = dists[h]
            if abs(sum(dh) - 1.0) > 1e-12:
                raise RuntimeError("Hurdle normalization error")
            vn = [0.0] * 8
            for s, vs in enumerate(v):
                if vs:
                    for m, w in enumerate(dh):
                        if w:
                            vn[s & m] += vs * w
            v = vn
            if h == 2:
                v_h123 = list(v)
        dp_locked = 1.0 - v[0]
        dp_mod100 = (1.0 - v_h123[0]) * (1.0 - dists[3][0])
        if abs(dp_locked - p0_l) > 5e-9 or abs(dp_mod100 - p0_m) > 5e-9:
            raise RuntimeError("3-arm baseline DP parity failed")

        arms_dict = {
            nm: {"route": rt, "hurdles": [round(x, 6) for x in vec], "standalone_pct": round(100.0 * math.prod(vec), 4)}
            for nm, vec, rt in (("A", pa, "R1"), ("B", pb, "R2"), ("X", px, "R1"))
        }
        return {
            "layer_id": "L0_CORE_3ARM",
            "label": "Layer 0: Core 3 Blueprints (A, B, X; 2-Route R1/R2)",
            "epistemic_tier": "Tier-0_Live_OQ016_Baseline",
            "drug_status": "ZERO_DRUG_100PCT_LIVE",
            "n_arms": 3,
            "state_space": 2 ** 12,
            "single_arms": arms_dict,
            "eff_ceilings_pct": [round(100.0 * c, 2) for c in c_base],
            "composite_ceiling_pct": round(100.0 * c0, 4),
            "locked_pct": round(100.0 * p0_l, 4),
            "modular_k90_pct": round(100.0 * p0_m90, 4),
            "modular_k100_pct": round(100.0 * p0_m, 4),
            "locked_exact": p0_l,
            "modular_k100_exact": p0_m,
            "ceiling_exact": c0,
            "delta_locked_vs_l0_pp": 0.0,
            "delta_mod100_vs_l0_pp": 0.0,
            "parity_err_vs_rank_islet1_stacks": max(abs(dp_locked - p0_l), abs(dp_mod100 - p0_m)),
            "_internal_l0_bpr05": {
                "arms": [pa, pb, px],
                "dists": dists,
                "v_h123": v_h123,
                "routes": ("R1", "R2", "R1"),
                "cell_classes": ("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X"),
            },
        }

    def build_h1_dist_5arm(c1_allo: float, p_d1: float) -> tuple[list[float], float]:
        if p_d1 > c1_allo + 1e-12:
            raise ValueError(f"p_d1={p_d1} exceeds c1_allo={c1_allo}")
        u_d1 = min(1.0, max(0.0, p_d1 / 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
        return d1, c1_allo

    def build_h2_dist_5arm(
        pa2: float, pb2: float, px2: float, py2: float, pd2: float,
        *, c2_inc: float, c2_y: float, c2_univ: float, c2_auto: float,
        phi_yx: float, phi_c: float,
    ) -> tuple[list[float], float]:
        if c2_inc > c2_y + 1e-12 or c2_y > c2_univ + 1e-12 or c2_auto > c2_univ + 1e-12:
            raise ValueError("Invalid H2 ceiling ordering")
        d2_inc = _frechet_joint([pa2 / c2_inc, pb2 / c2_inc, px2 / c2_inc], 0.0)
        r2 = c2_inc / c2_y
        u_y2 = py2 / c2_y
        d2_both = _frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
        d2_allo4 = [0.0] * 16
        for k in range(16):
            d2_allo4[k] += r2 * d2_both[k]
        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)
        if pd2 > c2_auto + 1e-12:
            raise ValueError(f"pd2={pd2} exceeds c2_auto={c2_auto}")
        u_d2 = pd2 / 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)