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…

                                    eff_l95_min_by_i.append(min(ep_l95s))
                                if ereps_ok:
                                    idxs_le_ec = [i for i in range(len(cg)) if cg[i] <= ec50_u95 + 1e-9]
                                    if not idxs_le_ec or eff_l95_min_by_i[idxs_le_ec[-1]] < 50.0:
                                        holds.append("HOLD_GATE_B0A_EC50_U95_UNSUBSTANTIATED_BY_EFFICACY_REPLICATES"); b0a_ok = False
                                    elif any(eff_l95_min_by_i[i_w] < 50.0 for i_w in range(idxs_le_ec[-1], len(cg)) if cg[i_w] <= csafe_bench + 1e-9):
                                        holds.append("HOLD_GATE_B0A_NONMONOTONIC_INTERIOR_EFFICACY_DIP"); b0a_ok = False

    if phase == "ROUTE_FREE_B0A":
        verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_ROUTE_FREE_B0A_ONLY")
        return {
            "gate": "GATE-41", "phase": phase, "scope_track": scope_track, "verdict": verdict,
            "release_authorizing": False, "live_ledger_authenticated": False,
            "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": None, "required_switch": None, "failures": fails, "holds": holds,
        }

    prod_s = str(rec.get("product_id", "")).strip()
    bank_s = str(rec.get("bank_id", "")).strip()
    lot_s = str(rec.get("lot_id", "")).strip()
    route_s = str(rec.get("route_id", "")).strip().upper()

    b0b_ev = _validate_content_receipt(
        b0b_raw,
        expected_stage="B-0b", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_parent=b0a_ev,
        allowed_extra_keys=COATING_IDENTITY_KEYS | frozenset({
            "coating_thickness_um", "worst_face_o2_mmhg", "local_ph_min", "local_ph_max",
            "mass_balance_margin_verified",
            "route_clearance_l_per_day", "target_total_conc_nM", "active_duration_days",
            "loaded_api_mass_mg", "usable_recovery_fraction",
            "provisional_pk_model_receipt",
        }),
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B0B_SIZING_O2_MISSING",
        fail_code="FAIL_GATE_B0B_SIZING_O2_FAILED",
        mismatch_code="FAIL_GATE_B0B_SCOPE_MISMATCH",
    )
    b0b_ok = b0b_ev is not None and b0b_ev.get("verdict") == "PASS"
    if b0b_ev is not None:
        coat_id = _extract_and_validate_coating_identity(b0b_ev, expected=None, fails=fails, stage="B-0b")
        if coat_id is None:
            b0b_ok = False
        th = b0b_ev.get("coating_thickness_um")
        o2 = b0b_ev.get("worst_face_o2_mmhg")
        ph_lo = b0b_ev.get("local_ph_min")
        ph_hi = b0b_ev.get("local_ph_max")
        if not (is_finite_num(th) and 0.0 < float(th) <= 5.0):
            fails.append("FAIL_GATE_B0B_COATING_THICKNESS_GT_5UM"); b0b_ok = False
        if not (is_finite_num(o2) and float(o2) >= 40.0):
            fails.append("FAIL_GATE_B0B_WORST_FACE_O2_BELOW_40MMHG"); b0b_ok = False
        if not (is_finite_num(ph_lo) and is_finite_num(ph_hi) and 7.25 <= float(ph_lo) <= float(ph_hi) <= 7.45):
            fails.append("FAIL_GATE_B0B_LOCAL_PH_OUTSIDE_7P25_7P45"); b0b_ok = False
        if not (is_strict_bool(b0b_ev.get("mass_balance_margin_verified")) and b0b_ev["mass_balance_margin_verified"]):
            fails.append("FAIL_GATE_B0B_MASS_BALANCE_MARGIN_UNVERIFIED"); b0b_ok = False
        rc_l = b0b_ev.get("route_clearance_l_per_day")
        tc_nm = b0b_ev.get("target_total_conc_nM")
        dur_d = b0b_ev.get("active_duration_days")
        ld_mg = b0b_ev.get("loaded_api_mass_mg")
        u_rec = b0b_ev.get("usable_recovery_fraction")
        rc_bounds_by_route = {"R3P": (3.0, 12.0), "R1": (3.0, 12.0), "R2": (10.0, 50.0)}
        rc_lo_r, rc_hi_r = rc_bounds_by_route.get(route_s, (3.0, 50.0))
        if not (
            all(is_finite_num(x) for x in (rc_l, tc_nm, dur_d, ld_mg, u_rec))
            and float(rc_l) > 0.0 and float(tc_nm) > 0.0 and float(dur_d) >= 10.0
            and float(ld_mg) > 0.0 and 0.0 < float(u_rec) <= 1.0
        ):
            fails.append("FAIL_GATE_B0B_MISSING_QUANTITATIVE_MASS_BALANCE_INPUTS"); b0b_ok = False
        else:
            if not (rc_lo_r <= float(rc_l) <= rc_hi_r):
                fails.append("FAIL_GATE_B0B_ROUTE_CLEARANCE_OUT_OF_RANGE"); b0b_ok = False
            if float(u_rec) > 0.85 + 1e-12:
                fails.append("FAIL_GATE_B0B_USABLE_RECOVERY_EXCEEDS_85PCT"); b0b_ok = False
            # Deucravacitinib MW = 425.47 g/mol -> req_mg = L/d * nmol/L * 1e-9 * 425470 mg/mol * days
            req_api_mg = float(rc_l) * float(tc_nm) * 1e-9 * 425470.0 * float(dur_d)
            if float(ld_mg) * float(u_rec) + 1e-9 < req_api_mg:
                fails.append("FAIL_GATE_B0B_LOADED_API_BELOW_QUANTITATIVE_MASS_REQUIREMENT"); b0b_ok = False

        # B-0a-bound provisional PK & exposure feasibility gate (must pass before authorizing bench B-1/B-2!)
        pk_mod = b0b_ev.get("provisional_pk_model_receipt")
        pk_mod_keys = frozenset({
            "b0a_receipt_sha256", "pk_model_protocol_sha256",
            "modeled_day1_burst_pct",
            "modeled_days0_10_parent_l95_free_nM",
            "modeled_days0_21_combined_peak_u95_free_nM",
            "modeled_systemic_combined_cmax_u95_total_nM",
            "alpha_conc", "alpha_fu_parent", "alpha_fu_bmt",
            "used_marginal_u95_sum", "lloq_censoring_allocated",
            "model_receipt_sha256",
        })
        if pk_mod is None:
            holds.append("HOLD_GATE_B0B_PROVISIONAL_PK_MODEL_MISSING"); b0b_ok = False
        elif not isinstance(pk_mod, Mapping) or set(pk_mod.keys()) != pk_mod_keys:
            fails.append("FAIL_GATE_B0B_PROVISIONAL_PK_MODEL_INVALID"); b0b_ok = False
        else:
            pm_sha = pk_mod.get("model_receipt_sha256")
            b0a_pin = pk_mod.get("b0a_receipt_sha256")
            prot_sha = pk_mod.get("pk_model_protocol_sha256")
            m_burst = pk_mod.get("modeled_day1_burst_pct")
            m_d10_l95 = pk_mod.get("modeled_days0_10_parent_l95_free_nM")
            m_d21_pk = pk_mod.get("modeled_days0_21_combined_peak_u95_free_nM")
            m_sys_pk = pk_mod.get("modeled_systemic_combined_cmax_u95_total_nM")
            m_ac = pk_mod.get("alpha_conc")
            m_afp = pk_mod.get("alpha_fu_parent")
            m_afb = pk_mod.get("alpha_fu_bmt")
            if (
                not is_valid_sha256_hex(pm_sha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in pk_mod.items() if k != "model_receipt_sha256"})) != str(pm_sha)
                or not is_valid_sha256_hex(prot_sha)
                or not is_valid_sha256_hex(b0a_pin)
                or (b0a_ev is not None and str(b0a_pin) != str(b0a_ev.get("receipt_sha256")))
                or not (is_strict_bool(pk_mod.get("used_marginal_u95_sum")) and pk_mod["used_marginal_u95_sum"] is False)
                or not (is_strict_bool(pk_mod.get("lloq_censoring_allocated")) and pk_mod["lloq_censoring_allocated"] is True)
                or not all(is_finite_num(x) for x in (m_burst, m_d10_l95, m_d21_pk, m_sys_pk, m_ac, m_afp, m_afb))
                or not (float(m_ac) > 0.0 and float(m_afp) > 0.0 and float(m_afb) > 0.0 and float(m_ac) + float(m_afp) + float(m_afb) <= 0.05 + 1e-12)
                or float(m_d10_l95) <= 0.0 or float(m_d21_pk) < float(m_d10_l95) or float(m_sys_pk) < 0.0
            ):
                fails.append("FAIL_GATE_B0B_PROVISIONAL_PK_MODEL_INVALID"); b0b_ok = False
            else:
                if not (0.0 < float(m_burst) <= 20.0):
                    fails.append("FAIL_GATE_B0B_MODELED_DAY1_BURST_GT_20PCT"); b0b_ok = False
                if float(m_sys_pk) >= 0.5:
                    fails.append("FAIL_GATE_B0B_MODELED_SYSTEMIC_CMAX_GE_0P5NM"); b0b_ok = False
                if ec50_u95 is not None and float(m_d10_l95) < ec50_u95:
                    fails.append("FAIL_GATE_B0B_MODELED_DAYS0_10_PARENT_BELOW_B0A_EC50_U95"); b0b_ok = False
                if csafe_bench is not None and float(m_d21_pk) >= csafe_bench:
                    fails.append("FAIL_GATE_B0B_MODELED_DAYS0_21_PEAK_GE_B0A_CSAFE_BENCH"); b0b_ok = False
                if (
                    b0a_ev is not None and isinstance(b0a_ev.get("fu_parent_by_matrix"), Mapping)
                    and is_finite_num(b0a_ev["fu_parent_by_matrix"].get("human_serum_100pct"))
                    and all(is_finite_num(x) for x in (rc_l, dur_d, ld_mg, u_rec))
                ):
                    fu_s = float(b0a_ev["fu_parent_by_matrix"]["human_serum_100pct"])
                    if fu_s > 0.0:
                        req_from_modeled_mg = float(rc_l) * (float(m_d10_l95) / fu_s) * 1e-9 * 425470.0 * float(dur_d)
                        if float(ld_mg) * float(u_rec) + 1e-9 < req_from_modeled_mg:
                            fails.append("FAIL_GATE_B0B_LOADED_API_BELOW_QUANTITATIVE_MASS_REQUIREMENT"); b0b_ok = False

    b1_extras = frozenset({
        "elution_started_at_utc", "day1_burst_pct", "day21_effluent_total_nM",
        "day21_effluent_free_nM", "day21_depot_depletion_pct",
        "day21_elution_verified", "terminal_mass_recovery_pct",
        "analytical_sample_ledger",
    })
    b1_ev = _validate_content_receipt(
        rec.get("b1_evidence"),
        expected_stage="B-1", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=b0b_ev, allowed_extra_keys=b1_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B1_21D_ELUTION_MISSING",
        fail_code="FAIL_GATE_B1_21D_ELUTION_FAILED",
        mismatch_code="FAIL_GATE_B1_SCOPE_MISMATCH",
    )
    b1_ok = b1_ev is not None and b1_ev.get("verdict") == "PASS"
    if b1_ev is not None:
        t_el = parse_utc_iso_ts(b1_ev.get("elution_started_at_utc"))
        t_b1 = parse_utc_iso_ts(b1_ev.get("recorded_at_utc"))
        t_b0b = parse_utc_iso_ts(b0b_ev.get("recorded_at_utc")) if b0b_ev is not None else None
        if t_el is None or t_b1 is None:
            fails.append("FAIL_GATE_B1_MISSING_ELUTION_START_UTC"); b1_ok = False
        else:
            if t_b0b is not None and t_el < t_b0b:
                fails.append("FAIL_GATE_B1_ELUTION_STARTED_BEFORE_B0B"); b1_ok = False
            if (t_b1 - t_el) < timedelta(days=21):
                fails.append("FAIL_GATE_B1_ELAPSED_ELUTION_DURATION_LT_21_DAYS"); b1_ok = False
        burst = b1_ev.get("day1_burst_pct")
        d21_tot = b1_ev.get("day21_effluent_total_nM")
        d21_fr = b1_ev.get("day21_effluent_free_nM")
        depl = b1_ev.get("day21_depot_depletion_pct")
        mr = b1_ev.get("terminal_mass_recovery_pct")
        if not (is_strict_bool(b1_ev.get("day21_elution_verified")) and b1_ev["day21_elution_verified"]):
            fails.append("FAIL_GATE_B1_DAY21_ELUTION_UNVERIFIED"); b1_ok = False
        if not (is_finite_num(burst) and 0.0 <= float(burst) <= 20.0):
            fails.append("FAIL_GATE_B1_DAY1_BURST_GT_20PCT"); b1_ok = False
        if not (is_finite_num(d21_tot) and is_finite_num(d21_fr) and 0.0 <= float(d21_fr) <= float(d21_tot) and float(d21_tot) < 10.0 and float(d21_fr) < 2.0):
            fails.append("FAIL_GATE_B1_DAY21_EFFLUENT_EXHAUSTION_FAILED"); b1_ok = False
        if not (is_finite_num(depl) and 85.0 <= float(depl) <= 100.0):
            fails.append("FAIL_GATE_B1_DAY21_DEPOT_DEPLETION_LT_85PCT"); b1_ok = False
        if not is_finite_num(mr) or not (90.0 <= float(mr) <= 110.0):
            fails.append("FAIL_GATE_B1_MASS_RECOVERY_OUT_OF_90_110"); b1_ok = False
        b1_ledger = b1_ev.get("analytical_sample_ledger")
        b1_ledger_map: dict[str, tuple[float, str, str, str, str]] = {}
        ledger_entry_keys = frozenset({"sample_id", "hour_h", "source_stage", "assay_matrix", "recirc_assay_matrix", "biological_unit_id", "raw_analytical_row_sha256"})
        if not isinstance(b1_ledger, list) or len(b1_ledger) < 3:
            holds.append("HOLD_GATE_B1_MISSING_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False
        else:
            for _lrow in b1_ledger:
                if (
                    not isinstance(_lrow, Mapping) or set(_lrow.keys()) != ledger_entry_keys
                    or not is_nonempty_str(_lrow.get("sample_id"))
                    or _lrow.get("assay_matrix") not in REQUIRED_3_MATRICES
                    or _lrow.get("recirc_assay_matrix") not in REQUIRED_3_MATRICES
                    or not is_nonempty_str(_lrow.get("biological_unit_id"))
                    or _lrow.get("source_stage") != "B-1"
                    or not (is_finite_num(_lrow.get("hour_h")) and float(_lrow["hour_h"]) > 0.0)
                    or not is_valid_sha256_hex(_lrow.get("raw_analytical_row_sha256"))
                ):
                    fails.append("FAIL_GATE_B1_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False; break
                _sid = str(_lrow["sample_id"]).strip().upper()
                if _sid in b1_ledger_map:
                    fails.append("FAIL_GATE_B1_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False; break
                b1_ledger_map[_sid] = (float(_lrow["hour_h"]), str(_lrow["raw_analytical_row_sha256"]).lower(), str(_lrow["assay_matrix"]).strip(), str(_lrow["recirc_assay_matrix"]).strip(), str(_lrow["biological_unit_id"]).strip().upper())
    else:
        b1_ledger_map = {}

    # Gate B-2: RAW paired vehicle-vs-coated donor_records (recomputing physically bounded % reductions!),
    # whitespace/case-normalized unique donor IDs, derived control validity, structured exclusions, LOO sensitivity!
    b2_extras = frozenset({
        "enrolled_donors_n", "excluded_invalid_donors_n", "invalid_donor_exclusion_log",
        "donor_records", "analytical_sample_ledger",
        "iec_sprouting_pct_ctrl", "iec_birc5_viability_pct", "iec_txnip_fold",
        "iec_ros_fold", "iec_cd274_pct_ctrl", "iec_hlae_pct_ctrl",
        "iec_pgf_pct_ctrl", "iec_c3_fold_vs_ctrl",
    })
    b2_ev = _validate_content_receipt(
        rec.get("b2_evidence"),
        expected_stage="B-2", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=b1_ev, allowed_extra_keys=b2_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B2_CHANDLER_LOOP_MISSING",
        fail_code="FAIL_GATE_B2_CHANDLER_LOOP_FAILED",
        mismatch_code="FAIL_GATE_B2_SCOPE_MISMATCH",
    )
    b2_ok = b2_ev is not None and b2_ev.get("verdict") == "PASS"
    if b2_ev is not None:
        enr_d = b2_ev.get("enrolled_donors_n")
        exc_d = b2_ev.get("excluded_invalid_donors_n")
        exc_log = b2_ev.get("invalid_donor_exclusion_log")
        drecs = b2_ev.get("donor_records")
        if not (is_strict_int(enr_d) and is_strict_int(exc_d) and int(exc_d) >= 0):
            fails.append("FAIL_GATE_B2_ENROLLMENT_OR_EXCLUSION_LOG_INVALID"); b2_ok = False
        if not isinstance(drecs, list) or len(drecs) < 6:
            fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False
        else:
            seen_d_norm: set[str] = set()
            tat_reds: list[float] = []
            c3a_reds: list[float] = []
            plt_recs: list[float] = []
            d_allowed = frozenset({
                "donor_id",
                "pos_ctrl_tat_fold", "pos_ctrl_c3a_fold", "pos_ctrl_plt_drop_pct",
                "neg_ctrl_tat_fold", "neg_ctrl_plt_retention_pct",
                "tat_vehicle_ng_ml", "tat_coated_ng_ml",
                "c3a_vehicle_ng_ml", "c3a_coated_ng_ml",
                "platelet_baseline_k_ul", "platelet_vehicle_k_ul", "platelet_coated_k_ul",
            })