scripts/verify_wave7_cellgemma_2p24_rebase.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…
if not isinstance(raw, list) or len(raw) == 0:
return None, False, True
um: dict[str, tuple[int, int]] = {}
sum_k = 0
sum_n = 0
adverse = False
mismatch = False
for row in raw:
if not isinstance(row, Mapping) or set(row.keys()) != {"unit_id", "k", "n"}:
mismatch = True; continue
uid = str(row.get("unit_id", "")).strip()
uk = row.get("k")
un = row.get("n")
if not uid or uid in um or not (is_strict_int(uk) and is_strict_int(un)):
mismatch = True; continue
ik, in_ = int(uk), int(un)
if in_ <= 0 or ik < 0 or ik > in_:
adverse = True
continue
if is_viral_escape and ik >= 1:
adverse = True
um[uid] = (ik, in_)
sum_k += ik
sum_n += in_
if n_units is not None and len(um) != n_units:
mismatch = True
if sum_k > expected_k:
adverse = True
if sum_k != expected_k or sum_n != expected_n:
mismatch = True
return (um if not mismatch and not adverse else None), adverse, mismatch
def _validate_gate0v_kill_receipt(
g0v_ev: Mapping[str, Any],
*,
prod_id: str,
fails: list[str],
holds: list[str],
) -> None:
"""
Full Canonical GATE-0V-KILL 5-regime x 5-lineage raw-count adjudicator
(docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md:42-48, 76-88):
1. Canonical Product-Family-to-Tier Binding:
- Autologous ISLET1_DESIGN_D1B_LEAN_K2 -> ONLY PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL
- Allogeneic MCB products (A, B, X, Y, Z) -> ONLY PASS_WHOLEGRAFT_BANK_QUALIFICATION or
PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE (never autologous tier! Wrong family -> HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY).
2. Deterministic Hard-Stop Precedence (GATE-0V:78, 82):
- NEVER returns early on missing sampling metadata, n_units < 6, or deff > 1.0!
- ALWAYS scans ALL 25 cells and ALL per-unit rows for deterministic adverse biological hard stops
(k_viral >= 1, caspase < 5.0, k > n, adverse per-unit rows, empirical 24h/72h kill breach)
so FAIL ALWAYS overrides HOLD when an adverse safety observation is recorded!
3. Exact Outward-Rounded 75-Digit Decimal Clopper-Pearson Ratio Bounds:
- 24-h (u_ratio <= 0.001) & 72-h (u_ratio <= 0.0001) at alpha_t=0.025, alpha_v=0.025, s_veh_L975 >= 0.10.
- Infected-Arm Estimand 1 (U_esc,total <= 1.0e-4) & Estimand 2 (DIRECT_INFECTED_VEHICLE_DENOMINATOR, U_esc,cond <= 1.0e-3)
with dual healthy+fragile spike calibrants at alpha_eta = 0.005 (eta_eff_L >= 0.80).
"""
from decimal import localcontext, ROUND_CEILING, ROUND_FLOOR
if not is_valid_sha256_hex(g0v_ev.get("canonical_gate0v_producer_sha256")):
fails.append("FAIL_GATE0V_MISSING_CANONICAL_PRODUCER_SHA256")
tier = g0v_ev.get("canonical_gate0v_tier")
valid_tiers = {
"PASS_WHOLEGRAFT_BANK_QUALIFICATION",
"PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
"PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
}
if tier not in valid_tiers:
fails.append("FAIL_GATE0V_INVALID_CANONICAL_TIER")
else:
is_auto = (prod_id == "ISLET1_DESIGN_D1B_LEAN_K2")
if is_auto and tier != "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL":
holds.append("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY")
elif (not is_auto) and tier == "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL":
holds.append("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY")
elif (not is_auto) and tier == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE":
# Surrogate release requires verified prior MCB bank archive digest (never interchangeable with bank qual!)
if not (is_valid_sha256_hex(g0v_ev.get("prior_bank_qualification_sha256")) and is_strict_bool(g0v_ev.get("archived_bank_payload_verified")) and g0v_ev["archived_bank_payload_verified"]):
holds.append("HOLD_GATE0V_LOT_SURROGATE_REQUIRES_VERIFIED_PRIOR_BANK_ARCHIVE")
if not (is_strict_bool(g0v_ev.get("exposed_product_tested")) and g0v_ev["exposed_product_tested"]):
fails.append("FAIL_GATE0V_EXPOSED_PRODUCT_NOT_TESTED")
# Record sampling/clustering holds WITHOUT returning early so deterministic hard stops ALWAYS run!
uclass = g0v_ev.get("independent_sampling_unit_class")
sampling_ok = True
if uclass not in ("INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT", "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"):
holds.append("HOLD_GATE0V_INVALID_SAMPLING_UNIT_CLASS")
sampling_ok = False
n_units_raw = g0v_ev.get("independent_biological_units_n")
n_units_int: Optional[int] = None
if not is_strict_int(n_units_raw) or int(n_units_raw) < 6:
holds.append("HOLD_GATE0V_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS")
sampling_ok = False
else:
n_units_int = int(n_units_raw)
deff_dec = _to_exact_decimal(g0v_ev.get("clustering_design_effect_deff"))
certify_exact_ci = False
if deff_dec is None:
holds.append("HOLD_GATE0V_MISSING_CLUSTERING_DEFF")
sampling_ok = False
elif deff_dec < Decimal(1):
fails.append("FAIL_GATE0V_INVALID_DEFF_LT_1")
sampling_ok = False
elif deff_dec > Decimal(1):
holds.append("HOLD_GATE0V_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE")
sampling_ok = False
else:
certify_exact_ci = sampling_ok
rmap = g0v_ev.get("regime_by_lineage_raw_counts")
if not isinstance(rmap, Mapping) or set(rmap.keys()) != REQUIRED_5_REGIMES:
fails.append("FAIL_GATE0V_INCOMPLETE_FIVE_REGIME_MATRIX")
return
cell_allowed_base = frozenset({
"treated_24h_survivors_k", "treated_24h_input_n", "veh_24h_alive_k", "veh_24h_input_n",
"treated_72h_survivors_k", "treated_72h_input_n", "veh_72h_alive_k", "veh_72h_input_n",
"per_unit_counts_treated_24h", "per_unit_counts_veh_24h",
"per_unit_counts_treated_72h", "per_unit_counts_veh_72h",
})
cell_allowed_viral = cell_allowed_base | frozenset({
"aliquot_linkage_mode", "aliquot_linkage_id",
"pre_ap1903_lineage_input_cells_n", "post_ap1903_viable_survivors_total_n",
"post_ap1903_viable_viral_pos_k", "caspase9_3_fold_over_veh",
"infected_cell_escape_mode", "pretreat_infected_veh_survivor_k",
"spike_healthy_recovered_k", "spike_healthy_input_n",
"spike_fragile_recovered_k", "spike_fragile_input_n",
"per_unit_counts_direct_infected_veh_72h", "per_unit_counts_viral_pos_72h",
"per_unit_counts_spike_healthy", "per_unit_counts_spike_fragile",
})
is_mw = (uclass == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION")
is_sc = (uclass == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT")
max_denom = 0
cap_24_dec = Decimal("0.001")
cap_72_dec = Decimal("0.0001")
cap_e1_dec = Decimal("0.0001")
cap_e2_dec = Decimal("0.001")
floor_veh_dec = Decimal("0.10")
floor_eta_dec = Decimal("0.80")
for rname in sorted(REQUIRED_5_REGIMES):
lmap = rmap.get(rname)
if not isinstance(lmap, Mapping) or set(lmap.keys()) != REQUIRED_5_LINEAGES:
fails.append(f"FAIL_GATE0V_INCOMPLETE_FIVE_LINEAGE_MAP:{rname}")
continue
is_viral = rname in VIRAL_REGIMES
for lname in sorted(REQUIRED_5_LINEAGES):
cell = lmap.get(lname)
tag = f"{rname}:{lname}"
if not isinstance(cell, Mapping):
fails.append(f"FAIL_GATE0V_MALFORMED_CELL:{tag}")
continue
_check_allowed_keys(cell, cell_allowed_viral if is_viral else cell_allowed_base, fails, f"GATE0V_{rname}_{lname}")
t24_k = cell.get("treated_24h_survivors_k")
t24_n = cell.get("treated_24h_input_n")
v24_k = cell.get("veh_24h_alive_k")
v24_n = cell.get("veh_24h_input_n")
t72_k = cell.get("treated_72h_survivors_k")
t72_n = cell.get("treated_72h_input_n")
v72_k = cell.get("veh_72h_alive_k")
v72_n = cell.get("veh_72h_input_n")
if not all(is_strict_int(x) for x in (t24_k, t24_n, v24_k, v24_n, t72_k, t72_n, v72_k, v72_n)):
fails.append(f"FAIL_GATE0V_NON_INTEGER_RAW_COUNTS:{tag}")
continue
if not (0 <= int(t24_k) <= int(t24_n) and int(t24_n) >= 1 and 0 <= int(v24_k) <= int(v24_n) and int(v24_n) >= 1):
fails.append(f"FAIL_GATE0V_INVALID_24H_COUNTS:{tag}")
continue
if not (0 <= int(t72_k) <= int(t72_n) and int(t72_n) >= 1 and 0 <= int(v72_k) <= int(v72_n) and int(v72_n) >= 1):
fails.append(f"FAIL_GATE0V_INVALID_72H_COUNTS:{tag}")
continue
max_denom = max(max_denom, int(t24_n), int(v24_n), int(t72_n), int(v72_n))
# Deterministic empirical kill-floor hard stop (ALWAYS evaluated even when deff > 1 or sampling metadata missing!)
# At 24h: empirical treated/veh > 0.001 (or treated > 0 with veh == 0) is a direct adverse kill-failure observation
if int(t24_k) > 0 and (int(v24_k) == 0 or Decimal(int(t24_k)) * Decimal(int(v24_n)) > cap_24_dec * Decimal(int(t24_n)) * Decimal(int(v24_k))):
fails.append(f"FAIL_GATE0V_DIRECT_ADVERSE_24H_KILL_FLOOR_BREACH:{tag}")
if int(t72_k) > 0 and (int(v72_k) == 0 or Decimal(int(t72_k)) * Decimal(int(v72_n)) > cap_72_dec * Decimal(int(t72_n)) * Decimal(int(v72_k))):
fails.append(f"FAIL_GATE0V_DIRECT_ADVERSE_72H_KILL_FLOOR_BREACH:{tag}")
# Exact outward-rounded Decimal Clopper-Pearson 24-h & 72-h Bonferroni ratios (only certify when deff == 1 & sampling_ok!)
s_veh_24 = clopper_pearson_lower_decimal(int(v24_k), int(v24_n), "0.025")
u_tr_24 = clopper_pearson_upper_decimal(int(t24_k), int(t24_n), "0.025")
s_veh_72 = clopper_pearson_lower_decimal(int(v72_k), int(v72_n), "0.025")
u_tr_72 = clopper_pearson_upper_decimal(int(t72_k), int(t72_n), "0.025")
if certify_exact_ci:
with localcontext() as ctx:
ctx.prec = 75
ctx.rounding = ROUND_CEILING
if s_veh_24 < floor_veh_dec:
fails.append(f"FAIL_GATE0V_24H_VEHICLE_SURVIVAL_L975_LT_0P10:{tag}")
elif (u_tr_24 / s_veh_24) > cap_24_dec:
fails.append(f"FAIL_GATE0V_24H_RATIO_U95_GT_0P001:{tag}")
if s_veh_72 < floor_veh_dec:
fails.append(f"FAIL_GATE0V_72H_VEHICLE_SURVIVAL_L975_LT_0P10:{tag}")
elif (u_tr_72 / s_veh_72) > cap_72_dec:
fails.append(f"FAIL_GATE0V_72H_RATIO_U95_GT_0P0001:{tag}")
# Pre-schema & reconciled per-estimand sampling-unit partitions (ALWAYS scan for adverse rows even when sampling_ok is False!)
base_part_specs = [
("per_unit_counts_treated_24h", int(t24_k), int(t24_n)),
("per_unit_counts_veh_24h", int(v24_k), int(v24_n)),
("per_unit_counts_treated_72h", int(t72_k), int(t72_n)),
("per_unit_counts_veh_72h", int(v72_k), int(v72_n)),
]
parsed_parts: dict[str, Optional[dict[str, tuple[int, int]]]] = {}
if is_mw or (not is_sc):
for pk, ek, en in base_part_specs:
if cell.get(pk) is not None or is_mw:
pmap, adv, mm = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en)
if adv:
fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
if is_mw and mm:
holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_PARTITION_MISMATCH:{tag}:{pk}")
parsed_parts[pk] = pmap
if is_mw:
ref_uids = set(parsed_parts["per_unit_counts_treated_72h"].keys()) if parsed_parts.get("per_unit_counts_treated_72h") else None
if ref_uids is not None:
for pk in ("per_unit_counts_treated_24h", "per_unit_counts_veh_24h", "per_unit_counts_veh_72h"):
if parsed_parts.get(pk) is not None and set(parsed_parts[pk].keys()) != ref_uids:
holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:{pk}")
else:
for pk, ek, en in base_part_specs:
if cell.get(pk) is not None:
_, adv, _ = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en)
if adv:
fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
holds.append(f"HOLD_GATE0V_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE:{tag}")
if is_viral:
amode = cell.get("aliquot_linkage_mode")
aid = cell.get("aliquot_linkage_id")
pre_n = cell.get("pre_ap1903_lineage_input_cells_n")
post_tot_k = cell.get("post_ap1903_viable_survivors_total_n")
vk = cell.get("post_ap1903_viable_viral_pos_k")
casp = cell.get("caspase9_3_fold_over_veh")
emode = cell.get("infected_cell_escape_mode")
d_inf_k = cell.get("pretreat_infected_veh_survivor_k")
sh_k = cell.get("spike_healthy_recovered_k")
sh_n = cell.get("spike_healthy_input_n")
sf_k = cell.get("spike_fragile_recovered_k")
sf_n = cell.get("spike_fragile_input_n")
# Unconditional deterministic viral & caspase hard stops (ALWAYS run before any HOLD return!)
if not is_strict_int(vk) or int(vk) < 0:
fails.append(f"FAIL_GATE0V_INVALID_VIRAL_ESCAPE_COUNT:{tag}")