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…

                        a_ord = arow.get("randomized_arm_order")
                        if (
                            not ab_id or not ab_bat or ab_id in abids_seen or ab_bat in abatches_seen
                            or not (
                                isinstance(a_ord, list) and len(a_ord) == len(exp_arms_set)
                                and all(isinstance(x, str) for x in a_ord) and set(a_ord) == exp_arms_set
                            )
                        ):
                            fails.append(f"FAIL_GATE_C1_PREREG_INVALID_BATCH_OR_ARM_ORDER:{ak}"); alloc_ok = False; break
                        a_ord_s = [str(x) for x in a_ord]
                        abids_seen.append(ab_id); abatches_seen.add(ab_bat)
                        abatches_list.append(ab_bat); aorders_list.append(a_ord_s)
                        aclean_rows.append({"block_id": ab_id, "differentiation_batch_id": ab_bat, "randomized_arm_order": a_ord_s})
                    if alloc_ok:
                        if target_slot == "norm":
                            prereg_norm_bids = abids_seen
                            prereg_norm_batches = abatches_list
                            prereg_norm_orders = aorders_list
                            prereg_norm_alloc_clean = aclean_rows
                        else:
                            prereg_hyp_bids = abids_seen
                            prereg_hyp_batches = abatches_list
                            prereg_hyp_orders = aorders_list
                            prereg_hyp_alloc_clean = aclean_rows
        if not is_strict_int(n_blocks) or int(n_blocks) < 3:
            fails.append("FAIL_GATE_C1_UNDERPOWERED_BLOCKS_LT_3")
        else:
            n_b = int(n_blocks)
            if n_b < 6:
                is_pilot_only = True
            elif stat_m == "EXACT_TWO_SIDED_SIGN_FLIP" and n_b < 10:
                fails.append("FAIL_GATE_C1_EXACT_SIGN_FLIP_REQUIRES_AT_LEAST_10_BLOCKS_FOR_HOLM5")
            norm_res = _validate_c1_oxygen_block(
                c1_ev.get("c1_normoxia"), o2_tag="NORMOXIA", target=target,
                stat_method=str(stat_m), expected_n=n_b,
                min_acq_ts=t_c1_start, max_acq_ts=t_c1_acq,
                expected_block_ids_norm=prereg_norm_bids,
                expected_batch_ids_norm=prereg_norm_batches,
                expected_arm_orders=prereg_norm_orders,
                expected_prod_id=prod_s, expected_lot_id=lot_s, expected_cohort_id=c1_cohort_id,
                fails=fails, holds=holds,
            )
            hyp_res = _validate_c1_oxygen_block(
                c1_ev.get("c1_hypoxia_2pct_o2"), o2_tag="HYPOXIA_2PCT", target=target,
                stat_method=str(stat_m), expected_n=n_b,
                min_acq_ts=t_c1_start, max_acq_ts=t_c1_acq,
                expected_block_ids_norm=prereg_hyp_bids,
                expected_batch_ids_norm=prereg_hyp_batches,
                expected_arm_orders=prereg_hyp_orders,
                expected_prod_id=prod_s, expected_lot_id=lot_s, expected_cohort_id=c1_cohort_id,
                fails=fails, holds=holds,
            )
            if norm_res is not None and hyp_res is not None:
                if norm_res[0] == hyp_res[0]:
                    fails.append("FAIL_GATE_C1_DUPLICATE_ASSAY_RECORD_ID_ACROSS_OXYGEN_REGIMES")
                if norm_res[1] == hyp_res[1]:
                    fails.append("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_CASP9_ACROSS_OXYGEN_REGIMES")
                if (norm_res[2], norm_res[3], norm_res[4]) == (hyp_res[2], hyp_res[3], hyp_res[4]):
                    fails.append("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_BETA_ACROSS_OXYGEN_REGIMES")
                # Immutable shared 5-arm x 2-oxygen family matrix SHA-256 incl. study/plan/blocks/common controls!
                if n_b >= 6 and isinstance(c1_ev.get("c1_normoxia"), Mapping) and isinstance(c1_ev.get("c1_hypoxia_2pct_o2"), Mapping):
                    def _fam_o2_slice(ob: Mapping[str, Any]) -> dict[str, Any]:
                        return {
                            "block_ids": ob.get("block_ids"),
                            "stressed_ctrl_beta_plated_t0_by_block": ob.get("stressed_ctrl_beta_plated_t0_by_block"),
                            "stressed_ctrl_beta_surviving_by_block": ob.get("stressed_ctrl_beta_surviving_by_block"),
                            "stressed_ctrl_beta_t0_pct_by_block": ob.get("stressed_ctrl_beta_t0_pct_by_block"),
                            "casp9_stressed_ctrl_raw_by_block": ob.get("casp9_stressed_ctrl_raw_by_block"),
                            "all_five_arms_paired_data": ob.get("all_five_arms_paired_data"),
                        }
                    fam_mat = {
                        "shared_study_id": c1_ev.get("shared_study_id"),
                        "locked_analysis_plan_id": c1_ev.get("locked_analysis_plan_id"),
                        "normoxia": _fam_o2_slice(c1_ev["c1_normoxia"]),
                        "hypoxia_2pct_o2": _fam_o2_slice(c1_ev["c1_hypoxia_2pct_o2"]),
                    }
                    fam_sha_calc = sha256_bytes(canonical_json_bytes(fam_mat))
                    fam_sha_sub = c1_ev.get("five_arm_family_matrix_sha256")
                    if not is_valid_sha256_hex(fam_sha_sub) or str(fam_sha_sub) != fam_sha_calc:
                        fails.append("FAIL_GATE_C1_FIVE_ARM_FAMILY_MATRIX_SHA256_MISMATCH")
                    # Candidate-agnostic producer common family acquisition record binding preregistration + batch/arm assignments + 5-arm x 2-O2 matrix!
                    cacq = c1_ev.get("c1_common_family_acquisition_record")
                    cacq_keys = frozenset({
                        "producer_acquisition_record_id", "shared_study_id", "locked_analysis_plan_id",
                        "preregistration_receipt_sha256", "block_randomization_seed_sha256",
                        "normoxia_block_allocations", "hypoxia_2pct_o2_block_allocations",
                        "normoxia_family_matrix", "hypoxia_2pct_o2_family_matrix",
                        "common_family_acquisition_sha256",
                    })
                    if cacq is None:
                        holds.append("HOLD_GATE_C1_MISSING_COMMON_FAMILY_ACQUISITION_RECORD")
                    elif not isinstance(cacq, Mapping) or set(cacq.keys()) != cacq_keys or not is_nonempty_str(cacq.get("producer_acquisition_record_id")):
                        fails.append("FAIL_GATE_C1_COMMON_FAMILY_ACQUISITION_MISMATCH")
                    else:
                        csha = cacq.get("common_family_acquisition_sha256")
                        def _norm_alloc_rows(rows: Any) -> Optional[list[dict[str, Any]]]:
                            if not isinstance(rows, list):
                                return None
                            out_r: list[dict[str, Any]] = []
                            for r_a in rows:
                                if not isinstance(r_a, Mapping) or set(r_a.keys()) != {"block_id", "differentiation_batch_id", "randomized_arm_order"}:
                                    return None
                                if not (is_nonempty_str(r_a.get("block_id")) and is_nonempty_str(r_a.get("differentiation_batch_id")) and isinstance(r_a.get("randomized_arm_order"), list)):
                                    return None
                                out_r.append({
                                    "block_id": str(r_a["block_id"]).strip().upper(),
                                    "differentiation_batch_id": str(r_a["differentiation_batch_id"]).strip().upper(),
                                    "randomized_arm_order": [str(x) for x in r_a["randomized_arm_order"]],
                                })
                            return out_r
                        ca_na = _norm_alloc_rows(cacq.get("normoxia_block_allocations"))
                        ca_ha = _norm_alloc_rows(cacq.get("hypoxia_2pct_o2_block_allocations"))
                        if (
                            not is_valid_sha256_hex(csha)
                            or sha256_bytes(canonical_json_bytes({k: v for k, v in cacq.items() if k != "common_family_acquisition_sha256"})) != str(csha)
                            or cacq.get("shared_study_id") != c1_ev.get("shared_study_id")
                            or cacq.get("locked_analysis_plan_id") != c1_ev.get("locked_analysis_plan_id")
                            or cacq.get("block_randomization_seed_sha256") != c1_ev.get("block_randomization_seed_sha256")
                            or (c1_prereg_ev is not None and cacq.get("preregistration_receipt_sha256") != c1_prereg_ev.get("receipt_sha256"))
                            or (prereg_norm_alloc_clean is not None and ca_na != prereg_norm_alloc_clean)
                            or (prereg_hyp_alloc_clean is not None and ca_ha != prereg_hyp_alloc_clean)
                            or cacq.get("normoxia_family_matrix") != fam_mat["normoxia"]
                            or cacq.get("hypoxia_2pct_o2_family_matrix") != fam_mat["hypoxia_2pct_o2"]
                        ):
                            fails.append("FAIL_GATE_C1_COMMON_FAMILY_ACQUISITION_MISMATCH")
                        else:
                            c1_common_acq_sha_out = str(csha)
                # Composite Intersection-Union Test (IUT) Holm-5 guaranteeing <= 1% FWER on selecting ANY candidate!
                nb_p, nc_p = norm_res[5], norm_res[6]
                hb_p, hc_p = hyp_res[5], hyp_res[6]
                if len(nb_p) == 5 and len(nc_p) == 5 and len(hb_p) == 5 and len(hc_p) == 5 and target in C1_FAMILY_GENES:
                    iut_raw = {g: max(nb_p[g], nc_p[g], hb_p[g], hc_p[g]) for g in C1_FAMILY_GENES}
                    iut_holm = holm_bonferroni_adjust(iut_raw)[target]
                    if iut_holm >= 0.01:
                        fails.append("FAIL_GATE_C1_COMPOSITE_IUT_HOLM5_PVALUE_GE_0P01")

    # Gate C-2: globally unique resting/post-recovery assay record IDs + content-hashed per-lot proliferation receipts!
    c2_extras = frozenset({
        "assay_started_at_utc", "assay_completed_at_utc", "specimen_id",
        "basal_shield_retention_pct", "basal_shield_retention_by_component", "hour0_density_by_lineage",
        "granule_processing_preserved",
        "proinsulin_to_insulin_fold_vs_ctrl", "pcsk1_pct_ctrl", "pcsk2_pct_ctrl", "cpe_pct_ctrl",
        "chgb_pct_ctrl", "scg2_pct_ctrl",
        "soluble_iapp_pg_per_ieq", "soluble_iapp_matched_ctrl_assay",
        "iapp_amyloid_ratio_vs_ctrl", "resting_survival_protein_panel",
        "c2_per_lot_proliferation_records",
        "transient_target_engagement_record",
    })
    c2_ev = _validate_content_receipt(
        rec.get("c2_evidence"),
        expected_stage="C-2", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_candidate_gene=target, expected_comparator_nt_lot_id=nt_lot_id,
        expected_parent=c1_ev, min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev), ("DRUG_FREE_EXPOSURE", df_ev)],
        allowed_extra_keys=c2_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_C2_BASAL_SHIELD_GRANULE_MISSING",
        fail_code="FAIL_GATE_C2_BASAL_SHIELD_GRANULE_FAILED",
        mismatch_code="FAIL_GATE_C2_SCOPE_MISMATCH",
    )
    if c2_ev is not None:
        bs = c2_ev.get("basal_shield_retention_pct")
        iapp_pg = c2_ev.get("soluble_iapp_pg_per_ieq")
        iapp_rat = c2_ev.get("iapp_amyloid_ratio_vs_ctrl")
        if not (is_finite_num(bs) and 85.0 <= float(bs) <= 200.0):
            fails.append("FAIL_GATE_C2_BASAL_SHIELD_BELOW_85PCT")
        c2_smap = c2_ev.get("basal_shield_retention_by_component")
        req_c2_comp = SHIELD_COMPONENTS_BY_PRODUCT.get(prod_s, frozenset())
        if not isinstance(c2_smap, Mapping) or set(c2_smap.keys()) != req_c2_comp:
            fails.append("FAIL_GATE_C2_INCOMPLETE_COMPONENT_SHIELD_MAP")
        else:
            c2_comp_vals: list[float] = []
            for cname in sorted(req_c2_comp):
                cv = c2_smap.get(cname)
                if not (is_finite_num(cv) and 85.0 <= float(cv) <= 200.0):
                    fails.append(f"FAIL_GATE_C2_SHIELD_COMPONENT_BELOW_85PCT:{cname}")
                else:
                    c2_comp_vals.append(float(cv))
            if len(c2_comp_vals) == len(req_c2_comp) and is_finite_num(bs) and abs(float(bs) - min(c2_comp_vals)) > 1e-6:
                fails.append("FAIL_GATE_C2_BASAL_SHIELD_SCALAR_MISMATCH_VS_COMPONENTS")
        if spec is not None:
            _validate_lineage_hour0_density(
                spec, c2_ev.get("hour0_density_by_lineage"),
                required_lineages=REQUIRED_HOUR0_LINEAGES_FULL, fails=fails, prefix="GATE_C2",
            )
        pi_fold = c2_ev.get("proinsulin_to_insulin_fold_vs_ctrl")
        pcsk1 = c2_ev.get("pcsk1_pct_ctrl")
        pcsk2 = c2_ev.get("pcsk2_pct_ctrl")
        cpe = c2_ev.get("cpe_pct_ctrl")
        chgb = c2_ev.get("chgb_pct_ctrl")
        scg2 = c2_ev.get("scg2_pct_ctrl")
        if (
            not (is_strict_bool(c2_ev.get("granule_processing_preserved")) and c2_ev["granule_processing_preserved"])
            or not (is_finite_num(pi_fold) and 0.0 < float(pi_fold) <= 1.15)
            or not (is_finite_num(pcsk1) and 85.0 <= float(pcsk1) <= 200.0)
            or not (is_finite_num(pcsk2) and 85.0 <= float(pcsk2) <= 200.0)
            or not (is_finite_num(cpe) and 85.0 <= float(cpe) <= 200.0)
            or not (is_finite_num(chgb) and 85.0 <= float(chgb) <= 200.0)
            or not (is_finite_num(scg2) and 85.0 <= float(scg2) <= 200.0)
        ):
            fails.append("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED")
        if not (is_finite_num(iapp_pg) and float(iapp_pg) >= 0.0):
            fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MEASUREMENT_MISSING")
        # Draft C §5 matched-control soluble/oligomeric IAPP early screening bound (<= 1.25x matched NT control),
        # kept distinct from iapp_amyloid_ratio_vs_ctrl (<= 1.15x early amyloid aggregation signal)!
        sol_iapp_rec = c2_ev.get("soluble_iapp_matched_ctrl_assay")
        sol_iapp_keys = frozenset({
            "assay_species", "assay_record_id", "specimen_id", "specimen_lot_id",
            "comparator_nt_lot_id", "treated_soluble_iapp_pg_per_ieq",
            "matched_ctrl_soluble_iapp_pg_per_ieq", "soluble_iapp_ratio_vs_ctrl",
            "assay_receipt_sha256",
        })
        if sol_iapp_rec is None:
            holds.append("HOLD_GATE_C2_MISSING_SOLUBLE_IAPP_MATCHED_CONTROL_ASSAY")
        elif not isinstance(sol_iapp_rec, Mapping) or set(sol_iapp_rec.keys()) != sol_iapp_keys:
            fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MATCHED_CONTROL_MISMATCH")
        else:
            si_sha = sol_iapp_rec.get("assay_receipt_sha256")
            c2_sp_si = str(c2_ev.get("specimen_id")).strip().upper() if is_nonempty_str(c2_ev.get("specimen_id")) else None
            tr_si = sol_iapp_rec.get("treated_soluble_iapp_pg_per_ieq")
            ct_si = sol_iapp_rec.get("matched_ctrl_soluble_iapp_pg_per_ieq")
            rt_si = sol_iapp_rec.get("soluble_iapp_ratio_vs_ctrl")
            if (
                not is_valid_sha256_hex(si_sha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in sol_iapp_rec.items() if k != "assay_receipt_sha256"})) != str(si_sha)
                or sol_iapp_rec.get("assay_species") != "SOLUBLE_OLIGOMERIC_IAPP_ELISA_MATCHED_CTRL"
                or not all(is_nonempty_str(sol_iapp_rec.get(k)) for k in ("assay_record_id", "specimen_id", "specimen_lot_id", "comparator_nt_lot_id"))
                or (c2_sp_si is not None and str(sol_iapp_rec["specimen_id"]).strip().upper() != c2_sp_si)
                or (lot_s and str(sol_iapp_rec["specimen_lot_id"]).strip().upper() != lot_s.upper())
                or (is_nonempty_str(nt_lot_id) and str(sol_iapp_rec["comparator_nt_lot_id"]).strip().upper() != str(nt_lot_id).strip().upper())
                or not (is_finite_num(tr_si) and float(tr_si) >= 0.0 and is_finite_num(ct_si) and float(ct_si) > 0.0 and is_finite_num(rt_si))
                or (is_finite_num(iapp_pg) and abs(float(tr_si) - float(iapp_pg)) > 1e-6)
                or abs((float(tr_si) / float(ct_si)) - float(rt_si)) > 1e-4
            ):
                fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MATCHED_CONTROL_MISMATCH")
            elif (float(tr_si) / float(ct_si)) > 1.25:
                fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_RATIO_EXCEEDS_1P25")
        if not (is_finite_num(iapp_rat) and 0.0 < float(iapp_rat) <= 1.15):
            fails.append("FAIL_GATE_C2_IAPP_AMYLOID_RATIO_EXCEEDS_1P15")
        # Independent resting survival protein panel (Draft C §5: BCL2L1, MCL1, CD59 >= 80% matched NT control)!
        surv_panel = c2_ev.get("resting_survival_protein_panel")
        surv_panel_keys = frozenset({
            "specimen_id", "specimen_lot_id", "comparator_nt_lot_id", "assay_record_id",
            "bcl2l1_pct_ctrl", "mcl1_pct_ctrl", "cd59_pct_ctrl", "panel_receipt_sha256",
        })
        if surv_panel is None:
            holds.append("HOLD_GATE_C2_MISSING_RESTING_SURVIVAL_PROTEIN_PANEL")
        elif not isinstance(surv_panel, Mapping) or set(surv_panel.keys()) != surv_panel_keys:
            fails.append("FAIL_GATE_C2_RESTING_SURVIVAL_PROTEIN_PANEL_MISMATCH")
        else:
            sp_sha = surv_panel.get("panel_receipt_sha256")