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…

    p01_a: list[float] = []
    p01_b: list[float] = []
    for x0, y0 in zip(a0, b0):
        if x0 == 0.0 and y0 == 0.0:
            continue
        for x1, y1 in zip(a1, b1):
            va = x0 * x1
            vb = y0 * y1
            if va != 0.0 or vb != 0.0:
                p01_a.append(va)
                p01_b.append(vb)
    p23_a: list[float] = []
    p23_b: list[float] = []
    for x2, y2 in zip(a2, b2):
        if x2 == 0.0 and y2 == 0.0:
            continue
        for x3, y3 in zip(a3, b3):
            va = x2 * x3
            vb = y2 * y3
            if va != 0.0 or vb != 0.0:
                p23_a.append(va)
                p23_b.append(vb)
    max_diff = 0.0
    for u_a, u_b in zip(p01_a, p01_b):
        for w_a, w_b in zip(p23_a, p23_b):
            d = abs(u_a * w_a - u_b * w_b)
            if not math.isfinite(d):
                raise ValueError(f"Non-finite joint-state probability difference encountered: {d!r}")
            if d > max_diff:
                max_diff = d
    return max_diff


def verify_unrounded_alias_and_distinct_laws_iip0035(
    core_laws: dict[str, dict],
    repeated_aliases: dict[str, str],
    *,
    tol: float = 1e-12,
) -> dict:
    """Verify exact <= tol unrounded 2^(4N) full joint-state equality for every alias pair AND exact equivalence partition."""
    if isinstance(tol, bool) or not isinstance(tol, (int, float)) or not math.isfinite(float(tol)) or float(tol) < 0.0:
        raise ValueError(f"Invalid non-finite or negative tolerance tol={tol!r}")
    for sc_id, law in sorted(core_laws.items()):
        dists = law.get("stage_dists")
        c_cls = law.get("cell_architecture_classes")
        r_ids = law.get("h4_route_assignments")
        if not isinstance(dists, (tuple, list)) or len(dists) != 4:
            raise ValueError(f"Scenario law {sc_id!r} must provide exactly 4 stage distributions")
        if not isinstance(c_cls, (tuple, list)) or not isinstance(r_ids, (tuple, list)) or len(c_cls) < 1 or len(c_cls) != len(r_ids):
            raise ValueError(f"Scenario law {sc_id!r} has invalid cell_architecture_classes / h4_route_assignments lengths")
        expected_len = 1 << len(c_cls)
        for st_idx, dist in enumerate(dists):
            if not isinstance(dist, (tuple, list)) or len(dist) != expected_len:
                raise ValueError(
                    f"Scenario law {sc_id!r} stage {st_idx} length {len(dist) if isinstance(dist, (tuple, list)) else type(dist)} != 2^{len(c_cls)} ({expected_len})"
                )
            s_mass = 0.0
            for entry in dist:
                if isinstance(entry, bool) or not isinstance(entry, (int, float)) or not math.isfinite(float(entry)):
                    raise ValueError(
                        f"Non-finite probability encountered in unrounded 2^(4N) scenario law ({sc_id}[{st_idx}]={entry!r})"
                    )
                fv = float(entry)
                if fv < -1e-12:
                    raise ValueError(f"Negative probability mass {fv!r} in unrounded 2^(4N) scenario law ({sc_id}[{st_idx}])")
                s_mass += fv
            if not math.isfinite(s_mass) or abs(s_mass - 1.0) > 1e-9:
                raise ValueError(f"Unnormalized stage distribution in {sc_id}[{st_idx}]: sum={s_mass!r}")

    parent: dict[str, str] = {k: k for k in core_laws}
    def _find(x: str) -> str:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    max_alias_diff = 0.0
    for src_k, dst_k in repeated_aliases.items():
        if src_k == dst_k:
            raise ValueError(f"Self-referential unrounded alias rejected: {src_k!r} -> {dst_k!r}")
        if src_k not in core_laws or dst_k not in core_laws:
            raise ValueError(f"Unresolvable unrounded alias entry: {src_k!r} -> {dst_k!r}")
        la, lb = core_laws[src_k], core_laws[dst_k]
        if la["cell_architecture_classes"] != lb["cell_architecture_classes"] or la["h4_route_assignments"] != lb["h4_route_assignments"]:
            raise ValueError(f"Unrounded alias architecture/route mismatch on {src_k}->{dst_k}")
        diff = _max_abs_full_joint_state_diff_iip0035(la["stage_dists"], lb["stage_dists"])
        if not math.isfinite(diff) or diff > tol:
            raise ValueError(
                f"Unrounded 2^(4N) full joint-state alias divergence on {src_k}->{dst_k}: "
                f"max_abs_diff={diff:.3e} > tol={tol:.1e}"
            )
        if diff > max_alias_diff:
            max_alias_diff = diff
        ra, rb = _find(src_k), _find(dst_k)
        if ra == rb:
            raise ValueError(f"Redundant or cyclic alias edge rejected: {src_k!r} -> {dst_k!r}")
        parent[ra] = rb

    ordered_ids = sorted(core_laws)
    for i, sc_a in enumerate(ordered_ids):
        la = core_laws[sc_a]
        for sc_b in ordered_ids[i + 1 :]:
            lb = core_laws[sc_b]
            same_law = (
                la["cell_architecture_classes"] == lb["cell_architecture_classes"]
                and la["h4_route_assignments"] == lb["h4_route_assignments"]
                and _max_abs_full_joint_state_diff_iip0035(la["stage_dists"], lb["stage_dists"]) <= tol
            )
            in_same_alias_class = _find(sc_a) == _find(sc_b)
            if same_law and not in_same_alias_class:
                raise ValueError(
                    f"Undeclared duplicate unrounded scenario law between {sc_a!r} and {sc_b!r} not captured in repeated_aliases"
                )
            if in_same_alias_class and not same_law:
                raise ValueError(
                    f"Transitive alias equivalence class divergence between {sc_a!r} and {sc_b!r} (> tol={tol:.1e})"
                )

    distinct_classes = {_find(sc_id) for sc_id in ordered_ids}
    expected_distinct = len(core_laws) - len(repeated_aliases)
    if len(distinct_classes) != expected_distinct:
        raise ValueError(
            f"Dynamic unrounded distinct-law count mismatch: got {len(distinct_classes)}, "
            f"expected {expected_distinct} across {len(core_laws)} core laws and {len(repeated_aliases)} aliases"
        )
    return {
        "total_labeled_core_rows": len(core_laws),
        "distinct_core_scenario_laws": len(distinct_classes),
        "alias_full_joint_state_max_abs_diff": max_alias_diff,
        "tolerance": tol,
    }


def compute_5arm_autologous_portfolio_iip0035(repo_root: Path | None = None) -> dict:
    """Emit manifest-pinned data/extracted/islet1_5arm_autologous_portfolio_v0.8.0.json (IIP-0035 / DEC-114).

    Leaves data/extracted/islet1_multiparadigm_portfolio_v0.8.0.json (IIP-0034) and all 2,160 Layer-1
    stacks 100% byte-for-bit untouched while verifying all 5 ISLET1_D1_AUTO_V2_* + 6 ISLET1_Y_FULLSTACK_V2_*
    products & FASTAs via product_contract.load_product_contracts(require_staged_fastas=True).
    """
    active_root = PROJECT_ROOT if repo_root is None else Path(repo_root)
    pc_mod = _load_local_helper("product_contract")
    contracts = pc_mod.load_product_contracts(active_root, require_staged_fastas=True)
    by_id = {p["product_variant_id"]: p for p in contracts["products"]}
    route_map = {"ROUTE_1_MACROENCAPSULATED": "R1", "ROUTE_2_OPEN_PORE_PREVASC": "R2", "ROUTE_3P_MODULAR_PLANAR_ENVELOPE": "R3P"}
    d1_routes = {route_map.get(str(by_id[pid].get("physical_route_id"))) for pid in pc_mod.STAGED_D1B_AUTO_V2_PRODUCT_IDS}
    if d1_routes != {"R3P"}:
        raise ValueError(f"Loaded D1b-Auto-C v2 product routes {sorted(d1_routes)} must bind strictly to ROUTE_3P_MODULAR_PLANAR_ENVELOPE")

    y_routes = {route_map.get(str(by_id[pid].get("physical_route_id"))) for pid in pc_mod.STAGED_DESIGN_Y_V2_PRODUCT_IDS}
    if y_routes != {"R3P"}:
        raise ValueError(f"Loaded Design Y-FullStack v2 product routes {sorted(y_routes)} must bind strictly to ROUTE_3P_MODULAR_PLANAR_ENVELOPE")
    registered_compat: dict[str, frozenset[str]] = {
        **ALLOWED_CELL_ROUTE_PAIRS_IIP0034,
        "DESIGN_Y_FULLSTACK_V2": frozenset(y_routes),
        "D1B_AUTO_C_V2": frozenset(d1_routes),
    }
    r2_only_compat: dict[str, frozenset[str]] = {
        **registered_compat,
        "D1B_AUTO_C_V2": frozenset({"R2", "R3P"}),
    }

    local_laws: dict[str, dict] = {}
    _law_token = _ACTIVE_LAW_COLLECTOR_IIP0035.set(local_laws)
    try:
        # Replay IIP-0034 in memory solely to capture exact unrounded 2^(4N) laws for W_BC1..W_BC5 alias verification
        base_iip0034 = compute_multiparadigm_2pow4n_portfolio_iip0034()

        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)

        def _attach_registry_strict_modular(row: dict) -> dict:
            law = local_laws[row["scenario"]]
            dists = law["stage_dists"]
            c_classes = law["cell_architecture_classes"]
            r_ids = law["h4_route_assignments"]
            n_arms = len(c_classes)
            n_states = 1 << n_arms
            v = [0.0] * n_states
            v[n_states - 1] = 1.0
            for h in range(3):
                dh = dists[h]
                vn = [0.0] * n_states
                for s, vs in enumerate(v):
                    if vs == 0.0:
                        continue
                    for mh, w in enumerate(dh):
                        if w != 0.0:
                            vn[s & mh] += vs * w
                v = vn
            v_h123 = v
            dh4 = dists[3]
            v_all = [0.0] * n_states
            for s, vs in enumerate(v_h123):
                if vs == 0.0:
                    continue
                for mh, w in enumerate(dh4):
                    if w != 0.0:
                        v_all[s & mh] += vs * w
            locked_unc = 1.0 - v_all[0]
            mod100_unc = (1.0 - v_h123[0]) * (1.0 - dh4[0])
            reg_locked_mask = 0
            for i in range(n_arms):
                if r_ids[i] in registered_compat[c_classes[i]]:
                    reg_locked_mask |= (1 << i)
            locked_reg = sum(v_all[s] for s in range(1, n_states) if (s & reg_locked_mask) != 0)
            mod100_reg = 0.0
            mod100_r2_only = 0.0
            mod100_cls = 0.0
            for m_cell in range(1, n_states):
                wc = v_h123[m_cell]
                if wc == 0.0:
                    continue
                allowed_r: set[str] = set()
                allowed_r2: set[str] = set()
                allowed_c: set[str] = set()
                for i in range(n_arms):
                    if m_cell & (1 << i):
                        allowed_r |= registered_compat[c_classes[i]]
                        allowed_r2 |= r2_only_compat[c_classes[i]]
                        allowed_c |= ALLOWED_CELL_ROUTE_PAIRS_IIP0034[c_classes[i]]
                for m_h4 in range(1, n_states):
                    wh = dh4[m_h4]
                    if wh == 0.0:
                        continue
                    if any(r_ids[j] in allowed_r for j in range(n_arms) if (m_h4 & (1 << j))):
                        mod100_reg += wc * wh
                    if any(r_ids[j] in allowed_r2 for j in range(n_arms) if (m_h4 & (1 << j))):
                        mod100_r2_only += wc * wh
                    if any(r_ids[j] in allowed_c for j in range(n_arms) if (m_h4 & (1 << j))):
                        mod100_cls += wc * wh
            mod90_reg = 0.90 * mod100_reg + 0.10 * locked_reg
            mod100_reg_pct = round(100.0 * mod100_reg, 4)
            mod90_reg_pct = round(100.0 * mod90_reg, 4)
            locked_reg_pct = round(100.0 * locked_reg, 4)
            ql_bar_exact = (c0 - p0_l) / (1.0 - p0_l)
            qm_bar_exact = (c0 - p0_m) / (1.0 - p0_m)
            q_l_reg = (locked_reg - p0_l) / (1.0 - p0_l)
            q_m_reg = (mod100_reg - p0_m) / (1.0 - p0_m)
            clears_ql_qm_reg = bool((q_l_reg > ql_bar_exact) and (q_m_reg > qm_bar_exact))
            # Preserve class-level R1+R2 counterfactual expansion values explicitly alongside R2-only expansion
            row["prohibited_locked_mass_excluded_under_class_level_expansion_pp"] = row["prohibited_locked_mass_excluded_pp"]
            row["prohibited_modular_mass_excluded_under_class_level_expansion_pp"] = row["prohibited_modular_mass_excluded_pp"]
            row["locked_under_hypothetical_r2_transfer_pct"] = row["locked_pct"]