OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

                                f"FAIL_HARD_STOP_GATE0V_A_INSUFFICIENT_ISG_INDUCTION_{el_tag}_{ev_ge_2x}_OF_4_LT_3"
                            )

    # ------------------------------------------------------------------
    # 3. Gate 0V-B: Two-Stage True-U95-Calibrated + Dual-Target Latent-Genome + Reconciled Lineage Ledger
    # ------------------------------------------------------------------
    required_pathogens: Tuple[str, ...] = (
        GATE0V_PATHOGENS
        if qual_tier == "BANK_QUALIFICATION"
        else (
            ("cvb4_e2",)
            if qual_tier == "LOT_RELEASE_SURROGATE"
            else (() if (qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL" and tier_allowed_for_product) else GATE0V_PATHOGENS)
        )
    )
    alpha_obs_tier = alpha_3p if len(required_pathogens) == 3 else alpha_1p

    inf = payload.get("gate0v_b_infectious_challenge")
    pathogens_map = inf.get("pathogens") if isinstance(inf, dict) else None
    pathogen_results: Dict[str, Any] = {}
    all_pathogens_ok = True

    if required_pathogens:
        if not isinstance(inf, dict):
            holds.append("HOLD_GATE0V_B_MISSING_LIVE_INFECTIOUS_CHALLENGE_POLY_IC_CANNOT_SUBSTITUTE")
            all_pathogens_ok = False
        elif not isinstance(pathogens_map, dict):
            holds.append("HOLD_GATE0V_B_MISSING_PATHOGEN_SURVEILLANCE_SCHEMA")
            all_pathogens_ok = False
        else:
            for path_id in required_pathogens:
                p_tag = path_id.upper()
                pblock = pathogens_map.get(path_id)
                if not isinstance(pblock, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_PATHOGEN_{p_tag}")
                    all_pathogens_ok = False
                    continue

                # Acute 72-h titers
                for comp_key in (
                    "endocrine_72h_log10_pfu_u95",
                    "vascular_72h_log10_pfu_u95",
                    "coculture_72h_log10_pfu_u95",
                ):
                    v = _to_exact_decimal_nonneg(pblock.get(comp_key))
                    if v is None or v < Decimal(0) or v > Decimal("15"):
                        holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_{p_tag}_{comp_key.upper()}")
                    elif v > Decimal("2.0"):
                        hard_stops.append(f"FAIL_GATE0V_B_ACUTE_TITER_EXCEEDS_2LOG10_{p_tag}_{comp_key.upper()}")

                # Day-14 genome reduction >= 3.0 log10
                for comp_key in ("endocrine_day14_log10_reduction_l95", "vascular_day14_log10_reduction_l95"):
                    v = _to_exact_decimal(pblock.get(comp_key))
                    if v is None or v < Decimal("-10") or v > Decimal("15"):
                        holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_{p_tag}_{comp_key.upper()}")
                    elif v < Decimal("3.0"):
                        hard_stops.append(f"FAIL_GATE0V_B_DAY14_CLEARANCE_BELOW_3LOG10_{p_tag}_{comp_key.upper()}")

                # Day-14 active replication RNA (-RNA for CVB4/CVB3; IE1 RNA for HCMV)
                rna_k = pblock.get("day14_negative_strand_or_ie1_rna_positive_wells_k")
                rna_n = pblock.get("day14_negative_strand_or_ie1_rna_wells_tested_n")
                if not (_is_strict_int(rna_k) and _is_strict_int(rna_n) and rna_k >= 0 and rna_n >= min_neg_rna_wells and rna_k <= rna_n):
                    holds.append(f"HOLD_GATE0V_B_INVALID_OR_UNDERPOWERED_ACTIVE_RNA_WELLS_{p_tag}")
                elif rna_k > 0:
                    hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_ACTIVE_VIRAL_RNA_DETECTED_{p_tag}")

                # Day-28 supernatant infectious shedding == 0 PFU/mL WITH volume >= 1.0 mL & LOD <= 1.0 PFU/mL
                day28_pfu = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_infectious_pfu_ml"))
                day28_vol = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_assay_volume_ml"))
                day28_lod = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_lod_pfu_ml"))
                if day28_pfu is None or day28_pfu < Decimal(0):
                    holds.append(f"HOLD_GATE0V_B_MISSING_DAY28_SUPERNATANT_PLAQUE_{p_tag}")
                elif day28_pfu > Decimal(0):
                    hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_DAY28_INFECTIOUS_SHEDDING_{p_tag}")
                if day28_vol is None or day28_vol < Decimal("1.0"):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_LOW_DAY28_ASSAY_VOLUME_ML_{p_tag}")
                if day28_lod is None or day28_lod <= Decimal(0) or day28_lod > Decimal("1.0"):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_COARSE_DAY28_ASSAY_LOD_{p_tag}")

                # Paired edited-vs-WT non-inferiority across ALL edited antiviral genotypes (with replicate n >= 6)
                if isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES:
                    delta_l95 = _to_exact_decimal(pblock.get("edited_minus_wt_day14_log10_reduction_l95"))
                    ni_reps = pblock.get("paired_noninferiority_replicates_n")
                    if not (_is_strict_int(ni_reps) and ni_reps >= min_noninf_replicates):
                        holds.append(f"HOLD_GATE0V_B_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_B_MISSING_EDITED_VS_WT_NONINFERIORITY_{p_tag}")
                    elif delta_l95 < Decimal("-0.50"):
                        hard_stops.append(f"FAIL_GATE0V_B_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")

                # Dual-Marker Lineage Fidelity + <= 5% Unassigned Cap + Mandatory Unassigned Viral Readout (B5)
                dual_mk_ok = pblock.get("dual_marker_lineage_panel_attested")
                panel_sha = pblock.get("lineage_panel_spec_sha256")
                tot_acq = pblock.get("total_viable_cells_acquired_n")
                unassigned_n = pblock.get("lineage_unassigned_cells_n")
                unassigned_frac_disp: float | None = None
                if dual_mk_ok is not True or not _is_valid_sha256_hex(panel_sha):
                    holds.append(f"HOLD_GATE0V_B_MISSING_DUAL_MARKER_LINEAGE_PANEL_OR_DIGEST_{p_tag}")
                if not (_is_strict_int(tot_acq) and tot_acq >= 1 and _is_strict_int(unassigned_n) and 0 <= unassigned_n <= tot_acq):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_LINEAGE_UNASSIGNED_COUNTS_{p_tag}")
                else:
                    with _clean_dec_ctx(80, ROUND_CEILING):
                        u_frac = Decimal(unassigned_n) / Decimal(tot_acq)
                    unassigned_frac_disp = _dec_to_float_pct(u_frac, 4)
                    if u_frac > max_unassigned_frac:
                        holds.append(f"HOLD_GATE0V_B_LINEAGE_UNASSIGNED_EXCEEDS_5PCT_{p_tag}")

                # B5: Mandatory unassigned-fraction viral readout so infected cells cannot hide in <=5% unassigned bucket!
                unass_ro = pblock.get("unassigned_fraction_viral_readout")
                unass_ro_summary: Dict[str, Any] = {"passed": False}
                if not isinstance(unass_ro, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_UNASSIGNED_FRACTION_VIRAL_READOUT_{p_tag}")
                else:
                    u_scr = unass_ro.get("unassigned_cells_screened_n")
                    u_k1 = unass_ro.get("stage1_screen_positive_k")
                    u_n2 = unass_ro.get("stage2_sorted_for_confirmation_n")
                    u_k2 = unass_ro.get("stage2_confirmed_infectious_k")
                    u_ok = True
                    if not (
                        _is_strict_int(u_scr) and _is_strict_int(unassigned_n) and u_scr == unassigned_n
                        and _is_strict_int(u_k1) and 0 <= u_k1 <= u_scr
                        and _is_strict_int(u_n2) and 0 <= u_n2 <= u_scr
                        and _is_strict_int(u_k2) and 0 <= u_k2 <= u_n2
                    ):
                        holds.append(f"HOLD_GATE0V_B_INVALID_UNASSIGNED_VIRAL_READOUT_COUNTS_{p_tag}")
                        u_ok = False
                    else:
                        if u_k2 >= 1:
                            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_{p_tag}_K_{u_k2}")
                            u_ok = False
                        if u_n2 != u_k1:
                            holds.append(f"HOLD_GATE0V_B_UNCONFIRMED_UNASSIGNED_STAGE1_HITS_{p_tag}")
                            u_ok = False
                        if u_scr >= 1:
                            with _clean_dec_ctx(80, ROUND_CEILING):
                                u_s1_frac = Decimal(u_k1) / Decimal(u_scr)
                            if u_s1_frac > max_stage1_screen_frac:
                                holds.append(f"HOLD_GATE0V_B_UNASSIGNED_STAGE1_SCREEN_EXCEEDS_0P2PCT_{p_tag}")
                                u_ok = False
                    unass_ro_summary = {
                        "unassigned_cells_screened_n": u_scr if _is_strict_int(u_scr) else None,
                        "stage1_screen_positive_k": u_k1 if _is_strict_int(u_k1) else None,
                        "stage2_sorted_for_confirmation_n": u_n2 if _is_strict_int(u_n2) else None,
                        "stage2_confirmed_infectious_k": u_k2 if _is_strict_int(u_k2) else None,
                        "passed": u_ok,
                    }

                # B5: Day-28 Latent-State & Defective-Genome ddPCR Arm with STRICT Dual-Target Panel Validation!
                lat_arm = pblock.get("day28_latent_and_defective_genome_arm")
                lat_summary: Dict[str, Any] = {"passed": False}
                if not isinstance(lat_arm, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_LATENT_OR_DEFECTIVE_GENOME_ARM_{p_tag}")
                else:
                    dd_panel = lat_arm.get("ddpcr_target_panel")
                    dd_targets = lat_arm.get("ddpcr_targets")
                    dd_k = lat_arm.get("ddpcr_positive_events_k")
                    dd_n = lat_arm.get("ddpcr_cell_equivalents_screened_n")
                    dd_sha = lat_arm.get("evidence_sha256")
                    lat_ok = True

                    expected_panel_name = (
                        "HCMV_UL138_UL55_LATENT_LYTIC"
                        if path_id == "hcmv"
                        else "CVB_5PRIME_DELETION_AWARE_POS_NEG_RNA"
                    )
                    required_targets = (
                        HCMV_REQUIRED_DDPCR_TARGETS
                        if path_id == "hcmv"
                        else CVB_REQUIRED_DDPCR_TARGETS
                    )
                    if dd_panel != expected_panel_name:
                        holds.append(f"HOLD_GATE0V_B_INVALID_OR_MISSING_DDPCR_TARGET_PANEL_{p_tag}")
                        lat_ok = False

                    target_details: Dict[str, Any] = {}
                    lat_unit_maps: Dict[str, Dict[str, Tuple[int, int]]] = {}
                    sum_target_k = 0
                    all_targets_valid_ints = True
                    if not isinstance(dd_targets, dict):
                        holds.append(f"HOLD_GATE0V_B_MISSING_DUAL_DDPCR_TARGETS_TABLE_{p_tag}")
                        lat_ok = False
                        all_targets_valid_ints = False
                    else:
                        for tgt in required_targets:
                            t_entry = dd_targets.get(tgt)
                            if not isinstance(t_entry, dict):
                                holds.append(f"HOLD_GATE0V_B_MISSING_REQUIRED_DDPCR_TARGET_{p_tag}_{tgt}")
                                lat_ok = False
                                all_targets_valid_ints = False
                                continue
                            tk = t_entry.get("k")
                            tn = t_entry.get("n")
                            tpv = t_entry.get("primers_verified")
                            if tpv is not True:
                                holds.append(f"HOLD_GATE0V_B_UNVERIFIED_DDPCR_TARGET_PRIMERS_{p_tag}_{tgt}")
                                lat_ok = False
                            if not (_is_strict_int(tk) and _is_strict_int(tn) and tn >= 1 and 0 <= tk <= tn):
                                holds.append(f"HOLD_GATE0V_B_INVALID_DDPCR_TARGET_COUNTS_{p_tag}_{tgt}")
                                lat_ok = False
                                all_targets_valid_ints = False
                                continue
                            sum_target_k += tk
                            if tk >= 1:
                                hard_stops.append(
                                    f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{tgt}_K_{tk}"
                                )
                                lat_ok = False
                            if not _check_estimand_sampling_unit_basis(
                                t_entry.get("per_unit_counts"),
                                k_val=tk,
                                n_val=tn,
                                label=f"LATENT_{p_tag}_{tgt}",
                                zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{tgt}_K_UNIT_POS",
                                out_unit_maps=lat_unit_maps,
                            ):
                                lat_ok = False
                            tn_indep: int | None = None
                            u_tgt_str: str | None = None
                            if deff is None:
                                lat_ok = False
                            else:
                                tn_indep = _exact_floor_div_by_decimal(tn, deff)
                                if tn_indep < 1:
                                    holds.append(f"HOLD_GATE0V_B_LATENT_TARGET_UNDERPOWERED_{p_tag}_{tgt}")
                                    lat_ok = False
                                elif tk == 0:
                                    u_tgt = sound_zero_event_clopper_pearson_upper(
                                        tn_indep, alpha_obs_tier, min_eta_cal, prec=80
                                    )["u_thinned_upper_dec"]
                                    u_tgt_str = format(u_tgt, "f")[:24]
                                    if u_tgt > cap_frac_persist:
                                        holds.append(f"HOLD_GATE0V_B_LATENT_TARGET_UNDERPOWERED_{p_tag}_{tgt}")
                                        lat_ok = False
                            target_details[tgt] = {
                                "k": tk,
                                "n": tn,
                                "effective_independent_n": tn_indep,
                                "primers_verified": bool(tpv is True),
                                "u_target_upper_80d": u_tgt_str,
                            }
                        for extra_tgt, extra_tentry in dd_targets.items():
                            if extra_tgt not in required_targets:
                                et_tag = str(extra_tgt).upper()
                                holds.append(f"HOLD_GATE0V_B_UNRECOGNIZED_DDPCR_TARGET_{p_tag}_{et_tag}")
                                lat_ok = False
                                if isinstance(extra_tentry, dict) and _is_strict_int(extra_tentry.get("k")) and extra_tentry["k"] >= 1:
                                    hard_stops.append(
                                        f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{et_tag}_K_{extra_tentry['k']}"
                                    )