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…

    )
    if att_ev is not None:
        if not (is_strict_bool(att_ev.get("stage1_cytokine_window_positive")) and att_ev["stage1_cytokine_window_positive"]):
            fails.append("FAIL_IIP0049_STAGE1_WINDOW_NOT_POSITIVE")
        s1_drop = att_ev.get("stage1_cytokine_drop_pp")
        if not (is_finite_num(s1_drop) and 10.0 <= float(s1_drop) <= 100.0):
            fails.append("FAIL_IIP0049_STAGE1_CYTOKINE_DROP_BELOW_10PP")
        s2_persists = att_ev.get("stage2_il1_independent_apoptosis_persists")
        if s2_persists is False:
            fails.append("FAIL_NO_RESIDUAL_APOPTOSIS_ON_MATCHED_BACKGROUND")
        elif s2_persists is not True:
            fails.append("FAIL_IIP0049_STAGE2_OUTCOME_MISSING")
        drop_pp = att_ev.get("residual_viable_beta_drop_pp")
        if not (is_finite_num(drop_pp) and 10.0 <= float(drop_pp) <= 100.0):
            fails.append("FAIL_IIP0049_RESIDUAL_DROP_BELOW_10PP_OR_OUT_OF_DOMAIN")
        if not (is_strict_bool(att_ev.get("concurrent_controls_valid")) and att_ev["concurrent_controls_valid"]):
            fails.append("FAIL_IIP0049_CONCURRENT_CONTROLS_INVALID")
        if not (is_strict_bool(att_ev.get("t0_original_plated_denominators_used")) and att_ev["t0_original_plated_denominators_used"]):
            fails.append("FAIL_IIP0049_T0_DENOMINATORS_MISSING")
        # Full canonical IIP-0049 Stage-1 raw viability+caspase-3/7 + Stage-2 5-background x 5-condition x 2-O2 matrix!
        # (docs/TNFA-IFNG-INTRINSIC-APOPTOSIS-QUALIFICATION-NOTE.md:50-61)
        ref_bgs = att_ev.get("reference_comparator_backgrounds")
        ref_bg_clean: list[str] = []
        if not (isinstance(ref_bgs, list) and len(ref_bgs) >= 5 and all(is_nonempty_str(x) for x in ref_bgs)):
            fails.append("FAIL_IIP0049_MISSING_REFERENCE_COMPARATOR_BACKGROUNDS")
        else:
            ref_bg_clean = [str(x).strip() for x in ref_bgs]
            if len(set(ref_bg_clean)) != len(ref_bg_clean) or not (REQUIRED_IIP0049_REFERENCE_BACKGROUNDS <= set(ref_bg_clean)):
                fails.append("FAIL_IIP0049_MISSING_REFERENCE_COMPARATOR_BACKGROUNDS")
        s1_rec = att_ev.get("stage1_gatekeeper_record")
        t_s1_dec: Optional[datetime] = None
        s1_dec_id: Optional[str] = None
        t_att = parse_utc_iso_ts(att_ev.get("recorded_at_utc"))
        t_att_floor_list = [
            parse_utc_iso_ts(pr.get("recorded_at_utc"))
            for _, pr in att_prereqs if pr is not None
        ]
        t_att_floor = max((t for t in t_att_floor_list if t is not None), default=None)
        s1_cond_keys = frozenset({"vehicle", "il1b_ifng", "isolated_tnfa_ifng"})
        foundry_s1_req = (not is_design_a) and (spec is not None and bool(spec["foundry_v2_biologics_eligible"]))
        s1_req_keys = {
            "batch_id", "decision_id", "assay_acquired_at_utc", "decision_recorded_at_utc",
            "parental_il1b_ifng_drop_pp", "edited_il1b_ifng_drop_pp", "edited_isolated_tnfa_ifng_drop_pp",
            "unmodified_isogenic_viability_pct_by_cond", "unmodified_isogenic_caspase3_7_fold_by_cond",
            "edited_chassis_viability_pct_by_cond", "edited_chassis_caspase3_7_fold_by_cond",
        }
        if foundry_s1_req:
            s1_req_keys |= {
                "edited_chassis_plus_foundry_v2_viability_pct_by_cond",
                "edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond",
            }
        if not isinstance(s1_rec, Mapping) or set(s1_rec.keys()) != s1_req_keys:
            fails.append("FAIL_IIP0049_MISSING_STAGE1_GATEKEEPER_RECORD")
        else:
            t_s1_acq = parse_utc_iso_ts(s1_rec.get("assay_acquired_at_utc"))
            t_s1_dec = parse_utc_iso_ts(s1_rec.get("decision_recorded_at_utc"))
            s1_dec_id = str(s1_rec.get("decision_id", "")).strip() if is_nonempty_str(s1_rec.get("decision_id")) else None
            pv = s1_rec.get("unmodified_isogenic_viability_pct_by_cond")
            pc37 = s1_rec.get("unmodified_isogenic_caspase3_7_fold_by_cond")
            ev_ch = s1_rec.get("edited_chassis_viability_pct_by_cond")
            ec37_ch = s1_rec.get("edited_chassis_caspase3_7_fold_by_cond")
            ev_act = s1_rec.get("edited_chassis_plus_foundry_v2_viability_pct_by_cond") if foundry_s1_req else ev_ch
            ec37_act = s1_rec.get("edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond") if foundry_s1_req else ec37_ch
            s1_v_maps = (pv, ev_ch, ev_act) if foundry_s1_req else (pv, ev_ch)
            s1_c_maps = (pc37, ec37_ch, ec37_act) if foundry_s1_req else (pc37, ec37_ch)
            raw_s1_ok = (
                all(isinstance(m, Mapping) and set(m.keys()) == s1_cond_keys for m in s1_v_maps + s1_c_maps)
                and all(is_finite_num(m[k]) and 0.0 <= float(m[k]) <= 100.0 for m in s1_v_maps for k in s1_cond_keys)
                and all(is_finite_num(m[k]) and float(m[k]) > 0.0 for m in s1_c_maps for k in s1_cond_keys)
            )
            if (
                not raw_s1_ok
                or not is_nonempty_str(s1_rec.get("batch_id")) or s1_dec_id is None
                or t_s1_acq is None or t_s1_dec is None
                or t_s1_acq > t_s1_dec
                or (t_att is not None and t_s1_dec > t_att)
                or not (is_finite_num(s1_rec["parental_il1b_ifng_drop_pp"]) and float(s1_rec["parental_il1b_ifng_drop_pp"]) >= 15.0)
                or not (is_finite_num(s1_rec["edited_il1b_ifng_drop_pp"]) and 0.0 <= float(s1_rec["edited_il1b_ifng_drop_pp"]) < 10.0)
                or not (is_finite_num(s1_rec["edited_isolated_tnfa_ifng_drop_pp"]) and float(s1_rec["edited_isolated_tnfa_ifng_drop_pp"]) >= 10.0)
            ):
                fails.append("FAIL_IIP0049_STAGE1_GATEKEEPER_CONTROLS_FAILED")
            else:
                # Derive Stage-1 escalation drop directly from the EXACT active arm (edited_chassis_plus_foundry_v2 when Foundry-eligible!)
                derived_act_il1_drop = float(ev_act["vehicle"]) - float(ev_act["il1b_ifng"])
                derived_act_tnf_drop = float(ev_act["vehicle"]) - float(ev_act["isolated_tnfa_ifng"])
                if (
                    abs((float(pv["vehicle"]) - float(pv["il1b_ifng"])) - float(s1_rec["parental_il1b_ifng_drop_pp"])) > 0.1
                    or abs(derived_act_il1_drop - float(s1_rec["edited_il1b_ifng_drop_pp"])) > 0.1
                    or abs(derived_act_tnf_drop - float(s1_rec["edited_isolated_tnfa_ifng_drop_pp"])) > 0.1
                    or (is_finite_num(s1_drop) and abs(derived_act_tnf_drop - float(s1_drop)) > 0.1)
                    or derived_act_tnf_drop < 10.0
                    or float(pc37["il1b_ifng"]) < 2.0
                    or float(ec37_act["il1b_ifng"]) > 1.5
                    or float(ec37_act["isolated_tnfa_ifng"]) < 2.0
                ):
                    fails.append("FAIL_IIP0049_STAGE1_RAW_VIABILITY_OR_CASP37_CONTRADICTS_ESCALATION")
            if t_s1_acq is not None and t_att_floor is not None and t_s1_acq < t_att_floor:
                fails.append("FAIL_IIP0049_STAGE1_ACQUIRED_BEFORE_EXPOSURE_OR_FOUNDRY")

        ab_n = att_ev.get("biological_blocks_n")
        if not (is_strict_int(ab_n) and int(ab_n) >= 3):
            fails.append("FAIL_IIP0049_ATTRIBUTION_BLOCKS_LT_3")
        else:
            n_ab = int(ab_n)
            s2_man = att_ev.get("stage2_block_manifest")
            s2_manifest_bids: list[str] = []
            if not isinstance(s2_man, list) or len(s2_man) != n_ab:
                fails.append("FAIL_IIP0049_MISSING_STAGE2_BLOCK_MANIFEST")
            else:
                seen_s2b: set[str] = set()
                seen_s2batch: set[str] = set()
                for idx_m, mrow in enumerate(s2_man):
                    if not isinstance(mrow, Mapping) or set(mrow.keys()) != {
                        "block_id", "differentiation_batch_id", "stage1_decision_id", "study_start_utc", "harvest_utc",
                    }:
                        fails.append(f"FAIL_IIP0049_MALFORMED_BLOCK_MANIFEST:{idx_m}"); break
                    bid_m = str(mrow.get("block_id", "")).strip().upper()
                    bat_m = str(mrow.get("differentiation_batch_id", "")).strip().upper()
                    dec_m = str(mrow.get("stage1_decision_id", "")).strip()
                    t_sm = parse_utc_iso_ts(mrow.get("study_start_utc"))
                    t_hm = parse_utc_iso_ts(mrow.get("harvest_utc"))
                    if (
                        not bid_m or not bat_m or bid_m in seen_s2b or bat_m in seen_s2batch
                        or t_sm is None or t_hm is None or t_sm > t_hm
                        or (t_att is not None and t_hm > t_att)
                    ):
                        fails.append(f"FAIL_IIP0049_INVALID_OR_NONINDEPENDENT_BLOCK_MANIFEST:{idx_m}"); break
                    if s1_dec_id is not None and dec_m != s1_dec_id:
                        fails.append(f"FAIL_IIP0049_STAGE2_MISSING_STAGE1_DECISION_BINDING:{idx_m}")
                    if t_s1_dec is not None and t_sm < t_s1_dec:
                        fails.append(f"FAIL_IIP0049_STAGE2_STARTED_BEFORE_STAGE1_DECISION:{idx_m}")
                    if t_att_floor is not None and t_sm < t_att_floor:
                        fails.append(f"FAIL_IIP0049_STAGE2_STARTED_BEFORE_EXPOSURE_OR_FOUNDRY:{idx_m}")
                    seen_s2b.add(bid_m); seen_s2batch.add(bat_m)
                    s2_manifest_bids.append(bid_m)

            # Validate full canonical 5-condition x 2-oxygen (normoxia + hypoxia_15mmhg) measurements for EVERY reference comparator!
            ref_meas = att_ev.get("reference_comparator_measurements")
            parental_il1_drops_by_o2: dict[str, list[float]] = {}
            if not isinstance(ref_meas, Mapping) or not ref_bg_clean or set(ref_meas.keys()) != set(ref_bg_clean):
                fails.append("FAIL_IIP0049_MISSING_KEYED_REFERENCE_COMPARATOR_MEASUREMENTS")
            else:
                rc_o2_allowed = frozenset({
                    "block_ids",
                    "cond1_vehicle_beta_t0_pct_by_block",
                    "cond2_ifng_alone_beta_t0_pct_by_block",
                    "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                    "cond4_il1b_ifng_beta_t0_pct_by_block",
                    "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                })
                for bg_k, bg_m in ref_meas.items():
                    if (
                        not isinstance(bg_m, Mapping) or set(bg_m.keys()) != {"normoxia", "hypoxia_15mmhg"}
                        or not isinstance(bg_m["normoxia"], Mapping) or not isinstance(bg_m["hypoxia_15mmhg"], Mapping)
                    ):
                        fails.append(f"FAIL_IIP0049_MALFORMED_COMPARATOR_MEASUREMENTS:{bg_k}"); continue
                    if dict(bg_m["normoxia"]) == dict(bg_m["hypoxia_15mmhg"]):
                        fails.append(f"FAIL_IIP0049_COMPARATOR_IDENTICAL_NORMOXIA_HYPOXIA:{bg_k}"); continue
                    for o2k in ("normoxia", "hypoxia_15mmhg"):
                        om = bg_m[o2k]
                        if not isinstance(om, Mapping) or set(om.keys()) != rc_o2_allowed:
                            fails.append(f"FAIL_IIP0049_MALFORMED_COMPARATOR_O2_PANEL:{bg_k}:{o2k}"); continue
                        obids = om.get("block_ids")
                        if not (isinstance(obids, list) and len(obids) == n_ab and all(is_nonempty_str(x) for x in obids)) or (s2_manifest_bids and [str(x).strip().upper() for x in obids] != s2_manifest_bids):
                            fails.append(f"FAIL_IIP0049_COMPARATOR_BLOCK_IDS_MISMATCH:{bg_k}:{o2k}"); continue
                        c_vecs = [om[ck] for ck in (
                            "cond1_vehicle_beta_t0_pct_by_block",
                            "cond2_ifng_alone_beta_t0_pct_by_block",
                            "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                            "cond4_il1b_ifng_beta_t0_pct_by_block",
                            "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                        )]
                        if not all(isinstance(v, list) and len(v) == n_ab and all(is_finite_num(x) and 0.0 <= float(x) <= 100.0 for x in v) for v in c_vecs):
                            fails.append(f"FAIL_IIP0049_INVALID_COMPARATOR_ARRAYS:{bg_k}:{o2k}"); continue
                        f1, f2, f3, f4, f5 = ([float(x) for x in v] for v in c_vecs)
                        if bg_k == "PARENTAL_UNEDITED":
                            p_drops = [f1[i] - f4[i] for i in range(n_ab)]
                            parental_il1_drops_by_o2[o2k] = p_drops
                            if (sum(p_drops) / n_ab) < 15.0 or any(d < 15.0 for d in p_drops):
                                fails.append(f"FAIL_IIP0049_PARENTAL_COMPARATOR_IL1_SENSITIVITY_BELOW_15PP:{o2k}")
                        elif bg_k in ("MULTI_MIR_IL1R1_FAS_REFERENCE", "CD64T_IL1RN_REFERENCE"):
                            if (sum(f1[i] - f4[i] for i in range(n_ab)) / n_ab) >= 10.0 or (sum(f1[i] - f3[i] for i in range(n_ab)) / n_ab) < 10.0:
                                fails.append(f"FAIL_IIP0049_IL1_SHIELD_COMPARATOR_ATTRIBUTION_INCONSISTENT:{bg_k}:{o2k}")
            mp_allowed = frozenset({
                "block_ids",
                "cond1_vehicle_beta_t0_pct_by_block",
                "cond2_ifng_alone_beta_t0_pct_by_block",
                "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                "cond4_il1b_ifng_beta_t0_pct_by_block",
                "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                "cleaved_caspase8_fold_by_block", "cleaved_caspase9_fold_by_block",
                "cytochrome_c_release_pct_by_block", "pmlkl_ratio_by_block",
                "bim_dp5_puma_induction_fold_by_block",
                "il1_pathway_positive_control_verified",
                "il1_positive_control_parental_drop_pp_by_block",
                "cxcl10_assay_lod_mfi", "cxcl10_matched_ctrl_24h_mfi_by_block",
                "cxcl10_0h_mfi_by_block", "cxcl10_24h_mfi_by_block",
                "cxcl10_0h_vs_24h_shield_retention_pct_by_block",
                "serpinb9_pct_matched_ctrl_by_block", "pdl1_pct_matched_ctrl_by_block",
                "post_washout_gsis_si_by_block",
                "post_washout_gsis_z2_by_block",
                "post_washout_gsis_stepdown_t50_min_by_block",
                "lineage_survival_pct_by_lineage",
            })
            p_norm = att_ev.get("stage2_normoxia_mechanism_panel")
            p_hyp = att_ev.get("stage2_hypoxia_15mmhg_mechanism_panel")
            norm_tnf_drop_mean: Optional[float] = None
            for ptag, panel in (("NORMOXIA", p_norm), ("HYPOXIA15", p_hyp)):
                if not isinstance(panel, Mapping):
                    fails.append(f"FAIL_IIP0049_MISSING_SEPARATED_MECHANISM_PANEL:{ptag}"); continue
                _check_allowed_keys(panel, mp_allowed, fails, f"IIP0049_{ptag}")
                pbids = panel.get("block_ids")
                if not (isinstance(pbids, list) and len(pbids) == n_ab and all(is_nonempty_str(x) for x in pbids)) or (s2_manifest_bids and [str(x).strip().upper() for x in pbids] != s2_manifest_bids):
                    fails.append(f"FAIL_IIP0049_PANEL_BLOCK_IDS_MISMATCH:{ptag}")
                c1v = panel.get("cond1_vehicle_beta_t0_pct_by_block")
                c2v = panel.get("cond2_ifng_alone_beta_t0_pct_by_block")
                c3v = panel.get("cond3_isolated_tnfa_ifng_beta_t0_pct_by_block")
                c4v = panel.get("cond4_il1b_ifng_beta_t0_pct_by_block")
                c5v = panel.get("cond5_pooled_triple_cytokine_beta_t0_pct_by_block")
                c8v = panel.get("cleaved_caspase8_fold_by_block")
                c9v = panel.get("cleaved_caspase9_fold_by_block")
                bh3v = panel.get("bim_dp5_puma_induction_fold_by_block")
                shv = panel.get("cxcl10_0h_vs_24h_shield_retention_pct_by_block")
                gsisv = panel.get("post_washout_gsis_si_by_block")
                lmap = panel.get("lineage_survival_pct_by_lineage")
                all_vecs = (c1v, c2v, c3v, c4v, c5v, c8v, c9v, bh3v, shv, gsisv)
                if not all(isinstance(v, list) and len(v) == n_ab and all(is_finite_num(x) for x in v) for v in all_vecs):
                    fails.append(f"FAIL_IIP0049_INCOMPLETE_5COND_OR_MECHANISM_VECTORS:{ptag}"); continue
                c1f = [float(x) for x in c1v]
                c2f = [float(x) for x in c2v]
                c3f = [float(x) for x in c3v]
                c4f = [float(x) for x in c4v]
                c5f = [float(x) for x in c5v]
                if any(not (0.0 <= x <= 100.0) for x in c1f + c2f + c3f + c4f + c5f):
                    fails.append(f"FAIL_IIP0049_BETA_SURVIVAL_OUT_OF_0_100:{ptag}"); continue
                tnf_drops = [c1f[i] - c3f[i] for i in range(n_ab)]
                tnf_over_ifng = [c2f[i] - c3f[i] for i in range(n_ab)]
                il1_drops = [c1f[i] - c4f[i] for i in range(n_ab)]
                triple_drops = [c1f[i] - c5f[i] for i in range(n_ab)]
                # Reconcile causal attribution directly from the 5-condition controls:
                # (1) Isolated TNFa+IFNg causes >= 10 pp drop vs vehicle (L95 > 0) AND >= 10 pp incremental loss OVER paired IFNg-only control (L95 > 0)!
                # (2) IL-1b+IFNg drop is protected (< 10 pp & materially lower than TNFa+IFNg) with positive IL-1 pathway control verified!
                # (3) Pooled triple also reflects >= 10 pp drop.
                ts_tnf = paired_t_summary(tnf_drops)
                ts_tnf_vs_ifng = paired_t_summary(tnf_over_ifng)
                mean_tnf = sum(tnf_drops) / n_ab
                mean_tnf_over_ifng = sum(tnf_over_ifng) / n_ab
                mean_il1 = sum(il1_drops) / n_ab
                mean_trip = sum(triple_drops) / n_ab
                if ptag == "NORMOXIA":