OpenIslet

scripts/verify_wave7_cellgemma_2p24_rebase.py

Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU

script Release v0.8.0 gen-eb955f8266035aba 1.37 MB · 90 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_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…

                    elif is_finite_num(mrna_kd) and abs(min(obs_map[("PMAIP1", "mRNA")][1], obs_map[("BCL2L11", "mRNA")][1]) - float(mrna_kd)) > 1e-6:
                        kd_prov_ok = False
                    elif is_finite_num(prot_kd) and abs(min(obs_map[("PMAIP1", "protein")][1], obs_map[("BCL2L11", "protein")][1]) - float(prot_kd)) > 1e-6:
                        kd_prov_ok = False
                else:
                    if (
                        (is_nonempty_str(mrna_aid) and obs_map[(target, "mRNA")][0] != str(mrna_aid).strip().upper())
                        or (is_nonempty_str(prot_aid) and obs_map[(target, "protein")][0] != str(prot_aid).strip().upper())
                        or (is_finite_num(mrna_kd) and abs(obs_map[(target, "mRNA")][1] - float(mrna_kd)) > 1e-6)
                        or (is_finite_num(prot_kd) and abs(obs_map[(target, "protein")][1] - float(prot_kd)) > 1e-6)
                    ):
                        kd_prov_ok = False
        if not kd_prov_ok:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_MOLECULAR_KD_PROVENANCE_MISMATCH")

    if any(not (-100.0 <= x <= 100.0) for x in c9_f):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_CASP9_OUT_OF_DOMAIN_NEG100_100")
    mean_c9_raw_frac = sum(raw_c9_fracs, Fraction(0, 1)) / expected_n
    mean_c9_raw_diff_frac = sum(
        (_to_exact_fraction(c9_ctrl_raw[i]) - _to_exact_fraction(c9_tr_raw[i]) for i in range(expected_n)),
        Fraction(0, 1),
    ) / expected_n
    if mean_c9_raw_diff_frac <= Fraction(0, 1):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_ADVERSE_OR_ZERO_RAW_CASP9_DIRECTION")
    if mean_c9_raw_frac < Fraction(40, 1):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MEAN_CASP9_REDUCTION_BELOW_40PCT")

    # Derive exact rational Fraction(sv*100, p0) vectors directly from observed integer plated/surviving counts!
    # Caller-submitted percentage arrays are retained strictly as <= 0.05 pp display consistency checks.
    recomp_beta_p: dict[str, float] = {}
    recomp_c9_p: dict[str, float] = {}
    def _derive_exact_beta_fracs(p0_arr: Any, sv_arr: Any, pct_arr: Sequence[float], tag_c: str) -> Optional[list[Fraction]]:
        if not (
            isinstance(p0_arr, list) and isinstance(sv_arr, list)
            and len(p0_arr) == expected_n and len(sv_arr) == expected_n
            and all(is_strict_int(a) and int(a) > 0 and is_strict_int(b) and 0 <= int(b) <= int(a) for a, b in zip(p0_arr, sv_arr))
        ):
            holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_RAW_BETA_PLATED_COUNTS:{tag_c}")
            return None
        fracs_out: list[Fraction] = []
        for a, b, pv in zip(p0_arr, sv_arr, pct_arr):
            fr = Fraction(int(b) * 100, int(a))
            if abs(float(fr) - float(pv)) > 0.05:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_PCT_CONTRADICTS_RAW_PLATED_COUNTS:{tag_c}")
                return None
            fracs_out.append(fr)
        return fracs_out

    ctrl_fracs = _derive_exact_beta_fracs(ctrl_p0, ctrl_sv, ctrl_f, "STRESSED_CTRL")
    tr_fracs = _derive_exact_beta_fracs(tr_p0, tr_sv, tr_f, "ACTIVE_TREATED")
    veh_fracs = _derive_exact_beta_fracs(veh_p0, veh_sv, veh_f, "UNSTRESSED_VEHICLE")
    bcl2l11_comp_fracs: Optional[list[Fraction]] = None

    # Use exact count-derived rational vectors whenever available (display arrays verified above!)
    eff_ctrl_f = [float(x) for x in ctrl_fracs] if ctrl_fracs is not None else ctrl_f
    eff_tr_f = [float(x) for x in tr_fracs] if tr_fracs is not None else tr_f
    eff_veh_f = [float(x) for x in veh_fracs] if veh_fracs is not None else veh_f

    if any(not (0.0 < x <= 100.0) for x in eff_ctrl_f + eff_tr_f + eff_veh_f):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_SURVIVAL_OUT_OF_DOMAIN")
    else:
        if ctrl_fracs is not None and tr_fracs is not None and veh_fracs is not None:
            diff_fracs = [tr_fracs[i] - ctrl_fracs[i] for i in range(expected_n)]
            mean_lift_frac = sum(diff_fracs, Fraction(0, 1)) / expected_n
            mean_pct_veh_frac = Fraction(100, 1) * sum(tr_fracs, Fraction(0, 1)) / sum(veh_fracs, Fraction(0, 1))
            if mean_lift_frac <= 0:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_NONPOSITIVE_NET_BETA_RESCUE")
            elif not (mean_lift_frac >= Fraction(15, 1) or mean_pct_veh_frac >= Fraction(85, 1)):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_EFFECT_THRESHOLD_NOT_MET")
            diffs = [float(d) for d in diff_fracs]
        else:
            diffs = [eff_tr_f[i] - eff_ctrl_f[i] for i in range(expected_n)]
            mean_lift = sum(diffs) / expected_n
            mean_pct_veh = 100.0 * (sum(eff_tr_f) / expected_n) / (sum(eff_veh_f) / expected_n)
            if mean_lift <= 0.0:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_NONPOSITIVE_NET_BETA_RESCUE")
            elif not (mean_lift >= 15.0 or mean_pct_veh >= 85.0):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_EFFECT_THRESHOLD_NOT_MET")

        if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
            nd = blk.get("normality_diagnostic_record")
            nd_keys = frozenset({"beta_qq_r", "casp9_qq_r", "beta_shapiro_wilk_p", "casp9_shapiro_wilk_p", "diagnostic_sha256"})
            if nd is None:
                holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_PAIRED_T_NORMALITY_DIAGNOSTIC")
            elif not isinstance(nd, Mapping) or set(nd.keys()) != nd_keys:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED_NORMALITY_DIAGNOSTIC")
            else:
                dsha = nd.get("diagnostic_sha256")
                b_qq = paired_diff_normality_qq_r(diffs)
                c9_raw_diffs = [c9_ctrl_f[i] - c9_tr_f[i] for i in range(expected_n)]
                c_qq = paired_diff_normality_qq_r(c9_raw_diffs)
                b_sw = shapiro_wilk_test(diffs)
                c_sw = shapiro_wilk_test(c9_raw_diffs)
                if (
                    not is_valid_sha256_hex(dsha)
                    or sha256_bytes(canonical_json_bytes({k: v for k, v in nd.items() if k != "diagnostic_sha256"})) != dsha
                    or not all(is_finite_num(nd.get(k)) for k in ("beta_qq_r", "casp9_qq_r", "beta_shapiro_wilk_p", "casp9_shapiro_wilk_p"))
                ):
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_NORMALITY_DIAGNOSTIC")
                elif b_qq is None or c_qq is None or abs(float(nd["beta_qq_r"]) - b_qq) > 1e-3 or abs(float(nd["casp9_qq_r"]) - c_qq) > 1e-3:
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_NORMALITY_QQ_R_MISMATCH_VS_RAW_DIFFS")
                elif b_sw is None or c_sw is None or abs(float(nd["beta_shapiro_wilk_p"]) - b_sw[1]) > 0.01 or abs(float(nd["casp9_shapiro_wilk_p"]) - c_sw[1]) > 0.01:
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_SHAPIRO_WILK_P_MISMATCH_VS_RAW_DIFFS")
                elif b_qq < 0.88 or c_qq < 0.88 or b_sw[1] < 0.05 or c_sw[1] < 0.05:
                    holds.append(f"HOLD_GATE_C1_{o2_tag}_PAIRED_T_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP")

        if stat_method == "EXACT_TWO_SIDED_SIGN_FLIP" and expected_n > EXACT_SIGN_FLIP_MAX_N:
            holds.append(f"HOLD_GATE_C1_{o2_tag}_EXACT_SIGN_FLIP_N_GT_20_REQUIRES_PAIRED_T")
        elif expected_n >= 6:
            if not isinstance(five_arms, Mapping) or set(five_arms.keys()) != C1_FAMILY_GENES:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_ALL_5_SIBLING_ARM_RAW_VECTORS")
            else:
                arms_ok = True
                for gname in sorted(C1_FAMILY_GENES):
                    adata = five_arms.get(gname)
                    if not isinstance(adata, Mapping) or set(adata.keys()) != {
                        "treated_beta_plated_t0_by_block", "treated_beta_surviving_by_block",
                        "treated_beta_t0_pct_by_block", "casp9_treated_raw_by_block", "casp9_reduction_pct_by_block",
                    }:
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED_SIBLING_ARM_DATA:{gname}"); arms_ok = False; continue
                    ab_p0 = adata.get("treated_beta_plated_t0_by_block")
                    ab_sv = adata.get("treated_beta_surviving_by_block")
                    ab = adata.get("treated_beta_t0_pct_by_block")
                    ac_raw = adata.get("casp9_treated_raw_by_block")
                    ac = adata.get("casp9_reduction_pct_by_block")
                    if not (
                        isinstance(ab, list) and len(ab) == expected_n and all(_is_exact_num_or_str(x) and Fraction(0, 1) < _to_exact_fraction(x) <= Fraction(100, 1) for x in ab)
                        and isinstance(ac_raw, list) and len(ac_raw) == expected_n and all(_is_exact_num_or_str(x) and _to_exact_fraction(x) >= Fraction(0, 1) for x in ac_raw)
                        and isinstance(ac, list) and len(ac) == expected_n and all(_is_exact_num_or_str(x) and Fraction(-100, 1) <= _to_exact_fraction(x) <= Fraction(100, 1) for x in ac)
                    ):
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_SIBLING_ARM_VECTORS:{gname}"); arms_ok = False; continue
                    ab_pct_fracs = [_to_exact_fraction(x) for x in ab]
                    ac_raw_fracs = [_to_exact_fraction(x) for x in ac_raw]
                    ac_pct_fracs = [_to_exact_fraction(x) for x in ac]
                    ab_f = [float(x) for x in ab_pct_fracs]
                    ab_fracs = _derive_exact_beta_fracs(ab_p0, ab_sv, ab_f, f"ARM_{gname}")
                    if ab_fracs is None:
                        arms_ok = False
                    elif gname == "BCL2L11":
                        bcl2l11_comp_fracs = ab_fracs
                    for _ci2 in range(expected_n):
                        recomp_g_c9_fr = Fraction(100, 1) * (c9_ctrl_fracs[_ci2] - ac_raw_fracs[_ci2]) / c9_ctrl_fracs[_ci2]
                        if abs(float(recomp_g_c9_fr - ac_pct_fracs[_ci2])) > 0.05:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_SIBLING_CASP9_RAW_MISMATCH:{gname}"); arms_ok = False; break
                    if gname == target and (ab_pct_fracs != tr_pct_fracs or ac_raw_fracs != c9_tr_fracs or ac_pct_fracs != c9_pct_fracs or ab_p0 != tr_p0 or ab_sv != tr_sv):
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_ACTIVE_ARM_MISMATCH_WITH_5ARM_TABLE"); arms_ok = False
                    if target == "PMAIP1+BCL2L11" and gname == "BCL2L11":
                        comp_v = blk.get("bcl2l11_comparator_beta_t0_pct_by_block")
                        if isinstance(comp_v, list) and [_to_exact_fraction(x) for x in comp_v] != ab_pct_fracs:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_BCL2L11_COMPARATOR_MISMATCH_WITH_5ARM_TABLE"); arms_ok = False
                    if ab_fracs is None or ctrl_fracs is None:
                        arms_ok = False
                        continue
                    # Family-wide paired-t normality & exact count-derived rational sign-flip across ALL 5 sibling arms!
                    ab_diff_fracs = [ab_fracs[i] - ctrl_fracs[i] for i in range(expected_n)]
                    ac_diff_fracs = [c9_ctrl_fracs[i] - ac_raw_fracs[i] for i in range(expected_n)]
                    ab_diffs = [float(d) for d in ab_diff_fracs]
                    ac_diffs = [float(d) for d in ac_diff_fracs]
                    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
                        sb_qq = paired_diff_normality_qq_r(ab_diffs)
                        sc_qq = paired_diff_normality_qq_r(ac_diffs)
                        sb_sw = shapiro_wilk_test(ab_diffs)
                        sc_sw = shapiro_wilk_test(ac_diffs)
                        if (
                            sb_qq is None or sc_qq is None or sb_sw is None or sc_sw is None
                            or sb_qq < 0.88 or sc_qq < 0.88 or sb_sw[1] < 0.05 or sc_sw[1] < 0.05
                        ):
                            holds.append(f"HOLD_GATE_C1_{o2_tag}_PAIRED_T_FAMILY_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP:{gname}")
                    # Directional assignment-symmetric paired contrasts from EXACT rational Fractions!
                    if sum(ab_diff_fracs, Fraction(0, 1)) <= Fraction(0, 1):
                        recomp_beta_p[gname] = 1.0
                    else:
                        pb_val, pb_err = _compute_c1_arm_raw_p(ab_fracs, stat_method, paired_control=ctrl_fracs)
                        if pb_err is not None or pb_val is None:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_ARM_BETA_STAT_ERROR:{gname}:{pb_err}"); arms_ok = False
                        else:
                            recomp_beta_p[gname] = pb_val
                    if sum(ac_diff_fracs, Fraction(0, 1)) <= Fraction(0, 1):
                        recomp_c9_p[gname] = 1.0
                    else:
                        pc_val, pc_err = _compute_c1_arm_raw_p(c9_ctrl_fracs, stat_method, paired_control=ac_raw_fracs)
                        if pc_err is not None or pc_val is None:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_ARM_CASP9_STAT_ERROR:{gname}:{pc_err}"); arms_ok = False
                        else:
                            recomp_c9_p[gname] = pc_val

                if arms_ok:
                    for ep_name, fam_map, recomp_map, sub_holm in (
                        ("BETA", beta_fam, recomp_beta_p, beta_p),
                        ("CASP9", c9_fam, recomp_c9_p, c9_p),
                    ):
                        if not (
                            isinstance(fam_map, Mapping)
                            and set(fam_map.keys()) == C1_FAMILY_GENES
                            and all(is_finite_num(v) and 0.0 < float(v) <= 1.0 for v in fam_map.values())
                        ):
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_5ARM_FAMILY_RAW_PVALUES_{ep_name}")
                        elif target in C1_FAMILY_GENES:
                            for gname in sorted(C1_FAMILY_GENES):
                                if abs(float(fam_map[gname]) - recomp_map[gname]) > max(1e-9, 1e-4 * abs(recomp_map[gname])):
                                    fails.append(f"FAIL_GATE_C1_{o2_tag}_SIBLING_RAW_PVALUE_MISMATCH_{ep_name}:{gname}")
                            holm_map = holm_bonferroni_adjust(recomp_map)
                            holm_calc = holm_map[target]
                            if abs(float(sub_holm) - holm_calc) > max(1e-9, 1e-4 * abs(holm_calc)):
                                fails.append(f"FAIL_GATE_C1_{o2_tag}_HOLM5_ADJUSTED_PVALUE_MISMATCH_{ep_name}")
                            if holm_calc >= 0.01:
                                fails.append(f"FAIL_GATE_C1_{o2_tag}_HOLM_{ep_name}_PVALUE_GE_0P01")

    if target == "PMAIP1+BCL2L11":
        kd_p = blk.get("pmaip1_kd_pct")
        kd_b = blk.get("bcl2l11_kd_pct")
        kd_pm = blk.get("pmaip1_mrna_kd_pct")
        kd_pp = blk.get("pmaip1_protein_kd_pct")
        kd_bm = blk.get("bcl2l11_mrna_kd_pct")
        kd_bp = blk.get("bcl2l11_protein_kd_pct")
        comp_vec = blk.get("bcl2l11_comparator_beta_t0_pct_by_block")
        h2h_l95 = blk.get("head_to_head_vs_bcl2l11_l95_delta_pp")
        if (
            not all(is_finite_num(x) and 70.0 <= float(x) <= 100.0 for x in (kd_p, kd_b, kd_pm, kd_pp, kd_bm, kd_bp))
            or abs(float(kd_p) - min(float(kd_pm), float(kd_pp))) > 1e-6
            or abs(float(kd_b) - min(float(kd_bm), float(kd_bp))) > 1e-6
        ):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_TARGET_COMPONENT_KD_FAILED")
        if not (isinstance(comp_vec, list) and len(comp_vec) == expected_n and all(is_finite_num(x) and 0.0 < float(x) <= 100.0 for x in comp_vec)):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_MISSING_PAIRED_BCL2L11_COMPARATOR")
        else:
            comp_fracs_eff = bcl2l11_comp_fracs if bcl2l11_comp_fracs is not None else [_to_exact_fraction(x) for x in comp_vec]
            tr_fracs_eff = tr_fracs if tr_fracs is not None else [_to_exact_fraction(x) for x in tr_f]
            if all(x is not None for x in comp_fracs_eff) and all(x is not None for x in tr_fracs_eff):
                h2h_diff_fracs = [tr_fracs_eff[i] - comp_fracs_eff[i] for i in range(expected_n)]
                h2h_diffs = [float(d) for d in h2h_diff_fracs]
                if stat_method == "EXACT_TWO_SIDED_SIGN_FLIP" and expected_n >= 6:
                    if expected_n <= EXACT_SIGN_FLIP_MAX_N:
                        # Distribution-free exact rational Fisher sign-flip superiority for dual vs BCL2L11!
                        p_h2h_sf = exact_two_sided_sign_flip_paired_p(tr_fracs_eff, comp_fracs_eff)
                        hl_med = exact_hodges_lehmann_median(h2h_diff_fracs)
                        if sum(h2h_diff_fracs, Fraction(0, 1)) <= 0 or hl_med <= 0 or p_h2h_sf is None or p_h2h_sf >= 0.05:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_SIGN_FLIP_SUPERIORITY_VS_BCL2L11_FAILED")
                else:
                    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
                        h2h_qq = paired_diff_normality_qq_r(h2h_diffs)
                        h2h_sw = shapiro_wilk_test(h2h_diffs)
                        if h2h_qq is None or h2h_sw is None or h2h_qq < 0.88 or h2h_sw[1] < 0.05:
                            holds.append(f"HOLD_GATE_C1_{o2_tag}_DUAL_H2H_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP")
                    h2h_stat = paired_t_summary(h2h_diffs)
                    if h2h_stat is None:
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_H2H_DEGENERATE_VARIANCE")
                    else:
                        _, _, _, l95_calc = h2h_stat
                        if l95_calc <= 0.0 or not is_finite_num(h2h_l95) or float(h2h_l95) <= 0.0 or abs(float(h2h_l95) - l95_calc) > 1e-4: