scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…
"k_treated_eff_upper": k_treated_eff_upper,
"u_treated_dec": u_treated,
"den_lower_prod_dec": den_lower_prod,
"u_ratio_unclamped_dec": u_ratio,
"u_ratio_dec": u_ratio,
"u_ratio_80d": u_ratio_str,
"estimand_domain": "[0, +infinity)",
"u_ratio_clamped_to_unity": False,
"ratio_upper_limit_exceeds_unity": bool(u_ratio > Decimal(1)),
"exact_directional_confidence_certified": is_exact_independent,
"confidence_scope": (
"EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1"
if is_exact_independent
else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
),
"release_authorizing_eligible": is_exact_independent,
"adjudication_disposition": (
None
if is_exact_independent
else "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
),
"confidence_statement_type": (
"DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
if is_exact_independent
else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
),
}
def exact_paired_vehicle_ratio_bounds(
k_treated: int,
n_treated: int,
k_veh_alive: int,
n_veh: int,
*,
alpha_treated: Decimal = Decimal("0.025"),
alpha_veh: Decimal = Decimal("0.025"),
deff: Decimal = Decimal("1.0"),
prec: int = 80,
) -> Dict[str, Any]:
"""
R06-B2 + R08-M1 + R09-B2 + R10-B3 Exact conservative component-probability ratio limits
(separate directional one-sided upper and lower confidence statements) for the paired
vehicle-normalized survival ratio `R = p_treated / s_veh` over its true mathematical
domain `[0, +infinity)`:
- Effective sample size `n_treated_eff = floor(n_treated / deff)` with outward-consistent
integer event counts:
* Upper bound: `k_treated_eff_upper = ceil(k_treated * n_treated_eff / n_treated)`
(`>= k_treated / n_treated * n_treated_eff`), giving
`u_ratio = ceil(U(k_treated_eff_upper, n_treated_eff; alpha_treated) / L(k_veh_alive, n_veh; alpha_veh))`
(`+Infinity` if `L(k_veh_alive, n_veh; alpha_veh) == 0`; `u_treated = 1` when `n_treated_eff < 1`;
NEVER clamped to `1.0`!).
* Lower bound: `k_treated_eff_lower = floor(k_treated * n_treated_eff / n_treated)`
(`<= k_treated / n_treated * n_treated_eff`), giving
`l_ratio = floor(L(k_treated_eff_lower, n_treated_eff; alpha_treated) / U(k_veh_alive, n_veh; alpha_veh))`
(`0` when `n_treated_eff < 1` or `k_treated_eff_lower == 0`).
By the Kaas-Buhrman (1980) binomial median theorem (`L_CP(k, n, alpha) <= k/n <= U_CP(k, n, alpha)`
for all `0 < alpha <= 0.5`) combined with exact outward integer rounding
`k_eff_lower / n_eff <= k / n <= k_eff_upper / n_eff`, this guarantees
`0 <= l_ratio <= empirical_point <= u_ratio` UNCONDITIONALLY across the ENTIRE admitted
domain (`0 <= k_t <= n_t`, `n_t >= 1`, `0 <= k_v <= n_v`, `n_v >= 1`, `deff >= 1.0`,
`0 < alpha_treated, alpha_veh <= 0.5`, `alpha_treated + alpha_veh < 1`) — eliminating the
`floor(k/deff) / floor(n/deff) > k/n` inward-bias bug (e.g. `200/299` at `deff=100`).
"""
if not (_is_strict_int(k_veh_alive) and _is_strict_int(n_veh) and 0 <= k_veh_alive <= n_veh and n_veh >= 1):
raise ValueError("Require integer 0 <= k_veh_alive <= n_veh and n_veh >= 1")
if not isinstance(alpha_treated, Decimal) or not alpha_treated.is_finite() or not (Decimal(0) < alpha_treated <= Decimal("0.5")):
raise ValueError("alpha_treated must be a finite Decimal in (0, 0.5]")
if not isinstance(alpha_veh, Decimal) or not alpha_veh.is_finite() or not (Decimal(0) < alpha_veh <= Decimal("0.5")):
raise ValueError("alpha_veh must be a finite Decimal in (0, 0.5]")
if alpha_treated + alpha_veh >= Decimal(1):
raise ValueError("Require alpha_treated + alpha_veh < 1 for positive directional confidence")
wprec = max(prec, 80)
cp_prec = min(wprec, 60)
s_veh_lower = exact_clopper_pearson_lower_calibrant(k_veh_alive, n_veh, alpha_veh, prec=cp_prec)
s_veh_upper = exact_clopper_pearson_upper_general(k_veh_alive, n_veh, alpha_veh, prec=cp_prec)
upper_res = exact_component_probability_ratio_upper(
k_treated,
n_treated,
alpha_treated,
(s_veh_lower,),
deff=deff,
prec=wprec,
)
n_treated_eff = upper_res["n_treated_eff"]
# R10-B3 Outward-downward effective numerator count:
# k_eff_lower = floor(k_treated * n_treated_eff / n_treated)
# guarantees k_eff_lower / n_treated_eff <= k_treated / n_treated unconditionally!
k_treated_eff_lower = (k_treated * n_treated_eff) // n_treated if n_treated_eff >= 1 else 0
if n_treated_eff < 1 or k_treated_eff_lower < 1:
l_treated = Decimal(0)
else:
l_treated = exact_clopper_pearson_lower_calibrant(k_treated_eff_lower, n_treated_eff, alpha_treated, prec=cp_prec)
if s_veh_upper <= Decimal(0):
l_ratio = Decimal(0)
else:
with _clean_dec_ctx(wprec, ROUND_FLOOR):
l_ratio = l_treated / s_veh_upper
if k_veh_alive == 0:
emp_ratio_dec: Decimal | None = None if k_treated == 0 else Decimal("Infinity")
else:
with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
emp_ratio_dec = (Decimal(k_treated) * Decimal(n_veh)) / (Decimal(n_treated) * Decimal(k_veh_alive))
with _clean_dec_ctx(wprec, ROUND_FLOOR):
dir_conf_lb = Decimal(1) - (alpha_treated + alpha_veh)
u_ratio = upper_res["u_ratio_dec"]
# R11-M1: Zero-denominator boundary convention:
# - 0/0 (k_treated == 0 and k_veh_alive == 0): empirical point estimate is undefined (None),
# so `bounds_ordered_l_le_point_le_u` is reported as `None` (undefined), NOT `True`!
# - k > 0 / 0 (k_treated > 0 and k_veh_alive == 0): empirical point estimate is `+Infinity`
# and `u_ratio == +Infinity`, so `0 <= l_ratio <= +Infinity <= +Infinity` holds (`True`).
if emp_ratio_dec is None:
bounds_l_le_pt_le_u: bool | None = None
zero_denom_convention = "UNDEFINED_0_OVER_0_POINT_AND_POINT_ORDERING_FLAG_NONE"
elif emp_ratio_dec == Decimal("Infinity"):
bounds_l_le_pt_le_u = bool(Decimal(0) <= l_ratio <= emp_ratio_dec <= u_ratio)
zero_denom_convention = "POSITIVE_NUMERATOR_ZERO_DENOMINATOR_POINT_PLUS_INFINITY"
else:
bounds_l_le_pt_le_u = bool(Decimal(0) <= l_ratio <= emp_ratio_dec <= u_ratio)
zero_denom_convention = "FINITE_POSITIVE_DENOMINATOR"
# R11-B3: Exact Clopper-Pearson directional confidence authorization is STRICTLY narrowed to
# `deff == 1.0` (verified independent binary observations, matching GY-018 and IIP-0044).
# For `deff > 1.0`, variance-adjusted bounds preserve outward point ordering strictly as a
# non-authorizing diagnostic display and NEVER certify exact directional confidence!
is_exact_independent = bool(deff == Decimal("1.0"))
return {
**upper_res,
"k_treated_eff": k_treated_eff_lower,
"k_treated_eff_lower": k_treated_eff_lower,
"s_veh_lower_dec": s_veh_lower,
"s_veh_upper_dec": s_veh_upper,
"l_treated_dec": l_treated,
"l_ratio_dec": l_ratio,
"l_ratio_80d": format(l_ratio, "f"),
"empirical_ratio_point_estimate_dec": emp_ratio_dec,
"zero_denominator_boundary_convention": zero_denom_convention,
"estimand_domain": "[0, +infinity)",
"u_ratio_clamped_to_unity": False,
"treated_survival_exceeds_vehicle_survival": bool(k_treated * n_veh > k_veh_alive * n_treated),
"ratio_lower_limit_exceeds_unity": bool(l_ratio > Decimal(1)),
"ratio_upper_limit_exceeds_unity": bool(u_ratio > Decimal(1)),
"bounds_ordered_l_le_u": bool(l_ratio <= u_ratio),
"bounds_ordered_l_le_point_le_u": bounds_l_le_pt_le_u,
"exact_directional_confidence_certified": is_exact_independent,
"confidence_scope": (
"EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1"
if is_exact_independent
else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
),
"release_authorizing_eligible": is_exact_independent,
"adjudication_disposition": (
None
if is_exact_independent
else "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
),
"confidence_statement_type": (
"DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
if is_exact_independent
else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
),
"directional_one_sided_confidence_lower_bound": (
format(dir_conf_lb, "f") if is_exact_independent else None
),
"simultaneous_two_sided_at_unsplit_alpha_claimed": False,
"confidence_statement_note": (
(
"Estimand R = p_treated / s_veh has mathematical domain [0, +infinity) and may exceed 1.0 "
"when treated survival exceeds matched vehicle survival. At deff == 1.0 (verified independent "
"binary observations, matching GY-018 and IIP-0044), neither u_ratio (ceil(u_treated / s_veh_lower)) "
"nor l_ratio (floor(l_treated / s_veh_upper)) is clamped to 1.0, guaranteeing 0 <= l_ratio <= point <= u_ratio "
"for every defined empirical point (with zero-denominator boundary conventions: 0/0 -> undefined point "
"estimate None and bounds_ordered_l_le_point_le_u = None; k > 0 / 0 -> point estimate +Infinity and "
"u_ratio = +Infinity). u_ratio and l_ratio are separate directional (one-sided) confidence statements "
"at >= 1 - (alpha_treated + alpha_veh) each, using the same per-component one-sided tail budgets in "
"each direction (NOT a simultaneous two-sided confidence interval at that same unsplit alpha)."
)
if is_exact_independent
else (
"NON-AUTHORIZING DIAGNOSTIC ONLY (deff > 1.0): Outward-consistent effective counts "
"k_eff_lower = floor(k * n_eff / n) and k_eff_upper = ceil(k * n_eff / n) with n_eff = floor(n / deff) "
"preserve point ordering (0 <= l_ratio <= point <= u_ratio whenever the empirical point is defined; "
"0/0 yields undefined point estimate None and bounds_ordered_l_le_point_le_u = None; k > 0 / 0 yields "
"+Infinity) strictly for diagnostic display, but variance-adjusted binomial bounds do NOT guarantee "
"exact nominal directional confidence under correlated/clustered observations (exact directional "
"confidence is certified strictly at deff == 1.0). Release adjudication MUST route to "
"HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE."
)
),
}
def _alpha_3pathogen_global_floor(prec: int = 120) -> Decimal:
"""Conservative floor of 0.05 / 30 = 1/600 so 30 * alpha <= 0.05 holds strictly."""
with _clean_dec_ctx(prec, ROUND_FLOOR):
return Decimal(1) / Decimal(600)
# ---------------------------------------------------------------------------
# Part A (NW-18): Canonical Product Registry, Trusted External Qualification Store,
# & Hardened Whole-Graft Gate 0V + Stress-State AP1903 Evaluator
# ---------------------------------------------------------------------------
@lru_cache(maxsize=8)
def _load_canonical_product_registry_cached(openislet_root_str: str) -> Dict[str, Any]:
"""
Load canonical product definitions strictly from:
1. data/protocols/islet1_product_definitions_v0.8.0.json (38 canonical products + aliases)
2. data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json (6 explicit ABX_L2_v2_* donors)
Eliminates ALL fragile substring inference for ectopic viral receptors and genotypes (B2).
"""
root = Path(openislet_root_str)
products_by_id: Dict[str, Dict[str, Any]] = {}
alias_to_canonical: Dict[str, str] = {}
pd_path = root / "data" / "protocols" / "islet1_product_definitions_v0.8.0.json"
if pd_path.is_file():
pd_doc = strict_json_load_file(pd_path, preserve_boundary_decimals=False)
for entry in pd_doc.get("products", []):
cid = str(entry["product_variant_id"])
base_or_prime = list(entry.get("base_or_prime_edit_loci") or [])
dsb_or_indel = list(entry.get("dsb_or_indel_loci") or [])
tyk2_mode = (
"TYK2_PE_P1104A"
if "TYK2" in base_or_prime
else ("TYK2_KO_PROPOSED" if "TYK2" in dsb_or_indel else "TYK2_UNEDITED_DONOR_DECLARED")
)
cell_source_raw = str(((entry.get("donor_lineage") or {}).get("cell_source")) or "").strip().lower()
explicit_bank_origin = str(entry.get("bank_origin") or "").strip().lower()
explicit_tier_family = entry.get("product_tier_family")
if isinstance(explicit_tier_family, str) and explicit_tier_family in PRODUCT_TIER_FAMILY_ALLOWED_TIERS:
tier_family = explicit_tier_family
else:
is_autologous_d1b = bool(
explicit_bank_origin == "autologous_hipsc"
or cell_source_raw == "autologous_hipsc"
or (cid.startswith("ISLET1_D1_AUTO_") and "autologous" in cell_source_raw)
)
tier_family = "AUTOLOGOUS_D1B_AUTO_C" if is_autologous_d1b else "ALLOGENEIC_MCB_BANKED"
rec = {
"product_variant_id": cid,
"registry_source": "islet1_product_definitions_v0.8.0.json",
"family": entry.get("family"),
"product_tier_family": tier_family,