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…
holds.append("HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
holds.append(f"HOLD_GATE0V_B_SPIKE_CAL_FRAGILE_UNIT_ID_MISMATCH_{p_tag}_{lin.upper()}")
if not (cal_h_unit_basis_ok and cal_f_unit_basis_ok):
path_5lin_cal_ok = False
all_pathogens_ok = False
if not (
_is_strict_int(rk_i) and _is_strict_int(rn_i) and rn_i >= 1 and 0 <= rk_i <= rn_i
and _is_strict_int(frk_i) and _is_strict_int(frn_i) and frn_i >= 1 and 0 <= frk_i <= frn_i
):
holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_DUAL_SPIKE_CALIBRANT_{p_tag}_{lin.upper()}")
sampling_tracker["all_partitions_reconciled"] = False
path_5lin_cal_ok = False
all_pathogens_ok = False
continue
# By intersection-union principle, min(L_h(alpha), L_f(alpha)) guarantees error <= alpha
# for bounding min(eta_h, eta_f) from below without doubling the calibrant error budget.
eta_healthy_l = exact_clopper_pearson_lower_calibrant(rk_i, rn_i, alpha_obs_tier, prec=80)
eta_fragile_l = exact_clopper_pearson_lower_calibrant(frk_i, frn_i, alpha_obs_tier, prec=80)
eta_eff_l = min(eta_healthy_l, eta_fragile_l)
if eta_eff_l < min_eta_cal:
holds.append(f"HOLD_GATE0V_B_CALIBRANT_SENSITIVITY_BELOW_0P80_{p_tag}_{lin.upper()}")
path_5lin_cal_ok = False
all_pathogens_ok = False
# Apply clustering design effect conservatively (NEVER default deff=1.0 when missing/invalid!)
n_indep: int | None = None
u_lin_str: str | None = None
u_lin_pct_float: float | None = None
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
w_i_float = round(float(Decimal(GRAFT_COMPOSITION_CELLS[lin]) / Decimal(TOTAL_GRAFT_CELLS)), 6)
if deff is None:
lin_pass = False
path_5lin_cal_ok = False
all_pathogens_ok = False
else:
n_indep = _exact_floor_div_by_decimal(n_i, deff)
if n_indep < 1 or eta_eff_l <= Decimal(0):
u_lin = Decimal(1)
elif k2_conf == 0:
cp = sound_zero_event_clopper_pearson_upper(n_indep, alpha_obs_tier, eta_eff_l, prec=80)
u_lin = cp["u_thinned_upper_dec"]
else:
u_raw = exact_clopper_pearson_upper_general(k2_conf, n_indep, alpha_obs_tier, prec=80)
with _clean_dec_ctx(80, ROUND_CEILING):
u_lin = min(Decimal(1), u_raw / eta_eff_l)
with _clean_dec_ctx(80, ROUND_CEILING):
w_i_ceil = Decimal(GRAFT_COMPOSITION_CELLS[lin]) / Decimal(TOTAL_GRAFT_CELLS)
comp_weighted_u95 = comp_weighted_u95 + (w_i_ceil * u_lin)
u_lin_str = format(u_lin, "f")[:24]
u_lin_pct_float = _dec_to_float_pct(u_lin, 6)
lin_pass = bool(
k2_conf == 0
and n2_sorted == k1_i
and screen_frac <= max_stage1_screen_frac
and pre_dissoc is True
and _is_valid_sha256_hex(spike_sha)
and eta_eff_l >= min_eta_cal
and u_lin <= cap_frac_persist
and fpr_u95_pass
and lin_unit_basis_ok
and neg_ctrl_unit_basis_ok
and cal_h_unit_basis_ok
and cal_f_unit_basis_ok
and sampling_spec_valid
and deff == Decimal("1.0")
)
if k2_conf == 0 and eta_eff_l > Decimal(0) and u_lin > cap_frac_persist:
holds.append(f"HOLD_GATE0V_B_INSUFFICIENT_DENOMINATOR_{p_tag}_{lin.upper()}_U95_GT_5E4")
lin_results[lin] = {
"graft_fraction": w_i_float,
"cells_assigned_n": n_assigned if _is_strict_int(n_assigned) else None,
"cells_scored_n": n_i,
"effective_independent_n": n_indep,
"stage1_screen_positive_k": k1_i,
"stage2_sorted_for_confirmation_n": n2_sorted,
"stage2_confirmed_infectious_k": k2_conf,
"uninfected_ctrl_fpr_u95_pct": fpr_u95_disp,
"uninfected_ctrl_fpr_u95_clears_0p15pct": fpr_u95_pass,
"eta_healthy_lower_80d": format(eta_healthy_l, "f")[:24],
"eta_fragile_lower_80d": format(eta_fragile_l, "f")[:24],
"eta_effective_lower_80d": format(eta_eff_l, "f")[:24],
"u_lin_upper_80d": u_lin_str,
"u_lin_upper_pct": u_lin_pct_float,
"uninfected_ctrl_sampling_unit_reconciled": bool(neg_ctrl_unit_basis_ok and sampling_spec_valid),
"spike_calibrant_sampling_units_reconciled": bool(
cal_h_unit_basis_ok and cal_f_unit_basis_ok and sampling_spec_valid
),
"sampling_unit_partition_reconciled": bool(
lin_unit_basis_ok
and neg_ctrl_unit_basis_ok
and cal_h_unit_basis_ok
and cal_f_unit_basis_ok
and sampling_spec_valid
),
"passes_lineage_gate": lin_pass,
}
# R04-B3: Inspect ALL keys in day28_persistence_by_lineage — NEVER silently discard extra
# non-canonical lineage keys! Reject fail-closed and adjudicate any adverse viral counts.
for extra_lin, extra_entry in lin_data.items():
if extra_lin not in GRAFT_LINEAGES:
el_tag = str(extra_lin).upper()
holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_B_{p_tag}_{el_tag}")
path_5lin_cal_ok = False
all_pathogens_ok = False
if not isinstance(extra_entry, dict):
holds.append(f"HOLD_GATE0V_B_INVALID_EXTRA_LINEAGE_ENTRY_{p_tag}_{el_tag}")
continue
ek2 = extra_entry.get("stage2_confirmed_infectious_k")
if _is_strict_int(ek2) and ek2 >= 1:
hard_stops.append(
f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{el_tag}_K_{ek2}"
)
ek1 = extra_entry.get("stage1_screen_positive_k")
en2 = extra_entry.get("stage2_sorted_for_confirmation_n")
if ek1 is not None or en2 is not None:
if not (_is_strict_int(ek1) and _is_strict_int(en2) and en2 == ek1):
holds.append(f"HOLD_GATE0V_B_EXTRA_LINEAGE_UNCONFIRMED_STAGE1_HITS_{p_tag}_{el_tag}")
# B5: Exact arithmetic reconciliation: total_acquired_n == sum(lineage_assigned_n) + unassigned_n!
reconciled_exact = False
if all_assigned_counts_present and _is_strict_int(tot_acq) and _is_strict_int(unassigned_n):
reconciled_exact = (tot_acq == sum_lineage_assigned_n + unassigned_n)
if not reconciled_exact:
holds.append(f"HOLD_GATE0V_B_LINEAGE_ACCOUNTING_RECONCILIATION_MISMATCH_{p_tag}")
path_5lin_cal_ok = False
all_pathogens_ok = False
comp_pct = _dec_to_float_pct(comp_weighted_u95, 6) if path_5lin_cal_ok else None
pathogen_results[path_id] = {
"all_5_lineages_calibrated": path_5lin_cal_ok,
"lineage_unassigned_pct": unassigned_frac_disp,
"lineage_accounting_ledger": {
"total_viable_cells_acquired_n": tot_acq if _is_strict_int(tot_acq) else None,
"sum_lineage_assigned_n": sum_lineage_assigned_n if all_assigned_counts_present else None,
"lineage_unassigned_cells_n": unassigned_n if _is_strict_int(unassigned_n) else None,
"reconciled_exact": reconciled_exact,
},
"unassigned_fraction_viral_readout": unass_ro_summary,
"latent_and_defective_genome_arm": lat_summary,
"composite_weighted_u95_pct": comp_pct,
"lineage_results": lin_results,
}
# B6 / R03-B1: Never silently drop submitted adverse or uncalibrated data in supplemental pathogens!
if isinstance(pathogens_map, dict):
for extra_pid, extra_pblock in pathogens_map.items():
if extra_pid not in required_pathogens:
_adjudicate_supplemental_pathogen_adverse_data(
extra_pid,
extra_pblock,
deff=deff,
alpha_obs_tier=alpha_obs_tier,
hard_stops=hard_stops,
holds=holds,
adjudicated_log=supplemental_adjudicated,
check_unit_basis_fn=_check_estimand_sampling_unit_basis,
)
# B6: Keep edited-genotype non-inferiority ACTIVE for AUTOLOGOUS_D1B_PROCESS_QUAL!
if qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL" and isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES:
ni_map = payload.get("genotype_noninferiority_by_pathogen")
for path_id in GATE0V_PATHOGENS:
p_tag = path_id.upper()
src_blk = None
if isinstance(ni_map, dict) and isinstance(ni_map.get(path_id), dict):
src_blk = ni_map[path_id]
elif isinstance(pathogens_map, dict) and isinstance(pathogens_map.get(path_id), dict):
src_blk = pathogens_map[path_id]
if not isinstance(src_blk, dict):
holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_MISSING_NONINFERIORITY_{p_tag}")
continue
delta_l95 = _to_exact_decimal(src_blk.get("edited_minus_wt_day14_log10_reduction_l95"))
ni_reps = src_blk.get("paired_noninferiority_replicates_n")
if not (_is_strict_int(ni_reps) and ni_reps >= min_noninf_replicates):
holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_UNDERPOWERED_NONINFERIORITY_REPLICATES_{p_tag}")
if delta_l95 is None or delta_l95 < Decimal("-15") or delta_l95 > Decimal("15"):
holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_MISSING_EDITED_VS_WT_NONINFERIORITY_{p_tag}")
elif delta_l95 < Decimal("-0.50"):
hard_stops.append(f"FAIL_GATE0V_GENO_AUTOLOGOUS_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")
# ------------------------------------------------------------------
# 4. Gate 0V-Kill: Raw-Count Recomputed L95s + Exact <= 0.05 Bonferroni Joint Budgets (B4 + B6 + R03-B1)
# ------------------------------------------------------------------
required_kill_regimes: Tuple[str, ...] = (
STRESS_AP1903_REGIMES
if qual_tier == "BANK_QUALIFICATION"
else ("normoxia_baseline", "hypoxia_1pct_plus_cytokines")
)
ap_data = payload.get("gate0v_kill_stress_ap1903")
ap_summary: Dict[str, Any] = {}
supplemental_ap_summary: Dict[str, Any] = {}
if not isinstance(ap_data, dict):
holds.append("HOLD_GATE0V_KILL_MISSING_STRESS_AP1903_PANEL")
else:
for reg in required_kill_regimes:
rblock = ap_data.get(reg)
if not isinstance(rblock, dict):
holds.append(f"HOLD_GATE0V_KILL_MISSING_REGIME_{reg.upper()}")
continue
reg_pass = True
reg_lineage_details: Dict[str, Any] = {}
for lin in GRAFT_LINEAGES:
lblock = rblock.get(lin)
if not isinstance(lblock, dict):
holds.append(f"HOLD_GATE0V_KILL_MISSING_{reg.upper()}_{lin.upper()}")
reg_pass = False
continue
arm_ok, lin_detail = _adjudicate_kill_regime_lineage_arm(
reg,
lin,
lblock,
deff=deff,
hard_stops=hard_stops,
holds=holds,
is_supplemental=False,
sampling_spec_valid=sampling_spec_valid,
sampling_unit_class=sampling_unit_class,
indep_units_n=indep_units,
sampling_tracker=sampling_tracker,
)
if not arm_ok:
reg_pass = False
reg_lineage_details[lin] = lin_detail
# R04-B3: Inspect ALL keys in required stress-regime dict — NEVER silently discard extra
# non-canonical lineage keys! Fail closed on unrecognized keys AND fully adjudicate
# raw counts / caspase / viral survivors so adverse observations ALWAYS emit FAIL_HARD_STOP!
for extra_lin, extra_lblock in rblock.items():
if extra_lin not in GRAFT_LINEAGES:
el_tag = str(extra_lin).upper()
holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_KILL_{reg.upper()}_{el_tag}")
reg_pass = False
if not isinstance(extra_lblock, dict):
holds.append(f"HOLD_GATE0V_KILL_INVALID_EXTRA_LINEAGE_BLOCK_{reg.upper()}_{el_tag}")
continue
_extra_ok, extra_detail = _adjudicate_kill_regime_lineage_arm(
reg,
str(extra_lin),
extra_lblock,
deff=deff,
hard_stops=hard_stops,
holds=holds,
is_supplemental=False,
sampling_spec_valid=sampling_spec_valid,