scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…
"p_xreact_pass_given_fail": round(p_xreact_pass_given_fail, 6),
"p_xreact_pass_given_s1": round(px_s1, 6),
"p_owner_reauth": round(p_owner_reauth, 6),
"p_owner_reauth_given_fail": round(pr_fail, 6),
"p_owner_reauth_given_s1": round(pr_s1, 6),
"owner_reauth_assumption_note": (
"Conditional on qualifying outcomes (XREACT pass AND SHIELD fail or SHIELD-1-only interim); "
"shared across both branches unless branch-specific overrides p_owner_reauth_given_fail / "
"p_owner_reauth_given_s1 are supplied."
),
"active_ev_pp": round(ev_pp, 4),
"active_ev_exact_pp": ev_pp,
}
def resolve_openislet_root(cli_root: str | None = None) -> Path:
if cli_root:
p = Path(cli_root).expanduser().resolve()
if (p / "scripts" / "rank_islet1_stacks.py").is_file():
return p
raise FileNotFoundError(f"Invalid --repo-root: {p}")
env_root = os.environ.get("OPENISLET_ROOT")
if env_root:
p = Path(env_root).expanduser().resolve()
if (p / "scripts" / "rank_islet1_stacks.py").is_file():
return p
sibling = INV_ROOT.parent / "OpenIslet"
if (sibling / "scripts" / "rank_islet1_stacks.py").is_file():
return sibling
# Also support direct installation under OpenIslet/scripts/
if (ART_DIR.parent / "scripts" / "rank_islet1_stacks.py").is_file():
return ART_DIR.parent
raise FileNotFoundError(
"Could not locate OpenIslet repository. Pass --repo-root or set OPENISLET_ROOT."
)
def subadditive_overlap(base: float, delta_a: float, delta_b: float, omega: float) -> float:
"""
Monotone, bounded, anti-double-counting combination law for two mechanistically
overlapping interventions on Hurdle 3 Channel (a):
delta_joint = max(da, db) + (1 - omega) * min(da, db) * (1 - max(da, db) / (1 - base))
Validates all probability and envelope inputs strictly (finite, in-domain,
base + delta_a < 1, base + delta_b < 1, omega in [0, 1]).
"""
for nm, val in (("base", base), ("delta_a", delta_a), ("delta_b", delta_b), ("omega", omega)):
if not isinstance(val, (int, float)) or not math.isfinite(val):
raise ValueError(f"Non-finite input {nm}={val!r}")
if not (0.0 <= base < 1.0):
raise ValueError(f"Invalid base={base} (must satisfy 0 <= base < 1)")
if delta_a < 0.0 or delta_b < 0.0:
raise ValueError(f"Negative deltas not allowed: delta_a={delta_a}, delta_b={delta_b}")
if base + delta_a >= 1.0 or base + delta_b >= 1.0:
raise ValueError(
f"Single-intervention envelope breach: base={base}, delta_a={delta_a}, delta_b={delta_b}"
)
if not (0.0 <= omega <= 1.0):
raise ValueError(f"Invalid overlap omega={omega} (must satisfy 0 <= omega <= 1)")
hi = max(delta_a, delta_b)
lo = min(delta_a, delta_b)
if lo == 0.0:
return base + hi
rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
val = base + hi + (1.0 - omega) * lo * rem_frac
if not (base <= val < 1.0):
raise ValueError(f"Out-of-envelope combined value={val}")
return val
def _solve_lp_min_bpr05(
c: np.ndarray,
A: list[np.ndarray] | np.ndarray,
b: list[float] | np.ndarray,
*,
tol: float = 1e-11,
max_iter: int = 30000,
) -> tuple[float, np.ndarray]:
"""Pure-NumPy two-phase simplex solver (minimize c^T x s.t. A x = b, x >= 0) with zero SciPy dependency."""
A_mat = np.array(A, dtype=np.float64)
b_vec = np.array(b, dtype=np.float64)
c_vec = np.array(c, dtype=np.float64)
m_raw, n = A_mat.shape
for i in range(m_raw):
if b_vec[i] < 0.0:
A_mat[i] = -A_mat[i]
b_vec[i] = -b_vec[i]
# Remove linearly dependent equality rows via Modified Gram-Schmidt
indep: list[int] = []
q_list: list[np.ndarray] = []
for i in range(m_raw):
v = A_mat[i].copy()
for q in q_list:
v = v - float(np.dot(v, q)) * q
nv = float(np.linalg.norm(v))
if nv > 1e-10:
q_list.append(v / nv)
indep.append(i)
A_mat = A_mat[indep]
b_vec = b_vec[indep]
m, n = A_mat.shape
for i in range(m):
if b_vec[i] < 0.0:
A_mat[i] = -A_mat[i]
b_vec[i] = -b_vec[i]
def _pivot(T: np.ndarray, basis: list[int], r: int, col: int) -> None:
T[r, :] /= T[r, col]
factors = T[:, col].copy()
factors[r] = 0.0
T -= np.outer(factors, T[r, :])
T[r, col] = 1.0
basis[r] = col
def _run_simplex(T: np.ndarray, basis: list[int], nv: int) -> None:
mm = T.shape[0] - 1
for it in range(max_iter):
rc = T[mm, :nv]
if float(np.min(rc)) >= -tol:
return
if it > 2500 and (it % 5 != 0):
col = int(np.where(rc < -tol)[0][0])
else:
col = int(np.argmin(rc))
cv = T[:mm, col]
pos = np.where(cv > tol)[0]
if len(pos) == 0:
raise RuntimeError("BPR-05 LP unbounded")
ratios = T[pos, -1] / cv[pos]
min_r = float(np.min(ratios))
cands = pos[ratios <= min_r + 1e-12]
r = int(cands[int(np.argmin([basis[int(i)] for i in cands]))])
_pivot(T, basis, r, col)
raise RuntimeError("BPR-05 LP simplex did not converge")
# Phase 1: minimize sum of artificial variables
T = np.zeros((m + 1, n + m + 1), dtype=np.float64)
T[:m, :n] = A_mat
T[:m, n : n + m] = np.eye(m, dtype=np.float64)
T[:m, -1] = b_vec
T[m, n : n + m] = 1.0
T[m, :] -= np.sum(T[:m, :], axis=0)
basis = list(range(n, n + m))
_run_simplex(T, basis, n + m)
if abs(float(T[m, -1])) > 1e-6:
raise RuntimeError(f"BPR-05 LP Phase 1 infeasible: residual={abs(float(T[m, -1])):.3e}")
# Drive out zero-valued artificial variables from basis
for r in range(m):
if basis[r] >= n:
nz = np.where(np.abs(T[r, :n]) > 1e-9)[0]
if len(nz) > 0:
_pivot(T, basis, r, int(nz[0]))
keep = [r for r in range(m) if basis[r] < n]
m2 = len(keep)
T2 = np.zeros((m2 + 1, n + 1), dtype=np.float64)
basis2 = [basis[r] for r in keep]
T2[:m2, :n] = T[keep, :n]
T2[:m2, -1] = T[keep, -1]
T2[m2, :n] = c_vec
for r in range(m2):
cb = float(c_vec[basis2[r]])
if cb != 0.0:
T2[m2, :] -= cb * T2[r, :]
_run_simplex(T2, basis2, n)
x = np.zeros(n, dtype=np.float64)
for r in range(m2):
x[basis2[r]] = max(0.0, float(T2[r, -1]))
return float(np.dot(c_vec, x)), x
def compute_bpr05_dependence_sensitivity_bounds(
*,
scenario_id: str,
arms: list[tuple[float, float, float, float]],
dists: list[list[float]],
v_h123: list[float],
routes: tuple[str, ...],
compat_map: dict[str, frozenset[str]],
cell_classes: tuple[str, ...],
preserve_incumbent_3arm_joint_history: bool = False,
stage_ceilings: tuple[float, float, float, float] | None = None,
) -> dict[str, Any]:
"""
BPR-05 cross-stage dependence sensitivity via exact LP over permissible couplings of
earlier survivors (M_cell = H1&H2&H3) and final-route outcomes (M_h4 = H4) conditioned on
the stage-level shared ceilings passing:
- Holds published stage distributions (v_h123, d4), shared ceilings
(explicit `stage_ceilings` when supplied, e.g. (0.88, 0.87, 0.89, 0.85) for Core 3-arm,
or stage-positive survival ceilings (1-d1[0])(1-d2[0])(1-d3[0]) and (1-d4[0])), and EVERY
individual arm's full-path success probability fixed at both extremes.
- For 5-arm scenarios (`preserve_incumbent_3arm_joint_history=True`), ALSO holds fixed the
entire 4-stage joint history of the 3 incumbent designs (A, B, X) alongside M_cell.
- Evaluates both locked and modular feasible ranges AND the paired same-branch
(modular - locked) policy advantage under the SAME joint distribution.
- Note: feasible dependence sensitivity ranges carry NO sampling confidence level, do NOT
measure cure probability, and must NOT replace the independently reproduced point
estimates with pessimistic endpoints.
"""
n_arms = len(arms)
n_states = 1 << n_arms
d1, d2, d3, dh4 = dists
if stage_ceilings is not None:
c1_c, c2_c, c3_c, c4_c = stage_ceilings
f_s = float(c1_c) * float(c2_c) * float(c3_c)
f_h = float(c4_c)
else:
f_s = (1.0 - d1[0]) * (1.0 - d2[0]) * (1.0 - d3[0])
f_h = 1.0 - dh4[0]
scale = f_s * f_h
ps = [v_h123[s] / f_s for s in range(n_states)]
ps[0] = max(0.0, 1.0 - sum(ps[1:]))
ph = [dh4[h] / f_h for h in range(n_states)]
ph[0] = max(0.0, 1.0 - sum(ph[1:]))
nz_s = [s for s in range(n_states) if ps[s] > 1e-15]
nz_h = [h for h in range(n_states) if ph[h] > 1e-15]
ns, nh = len(nz_s), len(nz_h)
nv = ns * nh
def _is_mod_ok(m_cell: int, m_h4: int) -> bool:
if m_cell == 0 or m_h4 == 0:
return False
allowed_r: set[str] = set()
for i in range(n_arms):
if m_cell & (1 << i):
allowed_r |= compat_map[cell_classes[i]]
return any(routes[j] in allowed_r for j in range(n_arms) if (m_h4 & (1 << j)))
rows: list[np.ndarray] = []
rhs: list[float] = []
# 1. Row marginals: conditional M_cell distribution
for si, s in enumerate(nz_s):
r = np.zeros(nv, dtype=np.float64)
r[si * nh : (si + 1) * nh] = 1.0
rows.append(r)
rhs.append(ps[s])
# 2. Column marginals: conditional M_h4 distribution
for hi, h in enumerate(nz_h):
r = np.zeros(nv, dtype=np.float64)
r[hi::nh] = 1.0
rows.append(r)
rhs.append(ph[h])
# 3. Optional 5-arm constraint: preserve entire 4-stage joint history of the 3 incumbent designs
if preserve_incumbent_3arm_joint_history: