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…

                frac = (target_h - tf[i]) / (tf[i + 1] - tf[i])
                return cf[i] + frac * (cf[i + 1] - cf[i])
        return None

    def _validate_pfd_release_trace_and_peak(
        ev: Mapping[str, Any], *, min_horizon_h: float, tag: str,
    ) -> Optional[tuple[float, list[float], list[float], float]]:
        """Validate unified loading + time-resolved intact-parent trace & recompute supremum burst 1-compartment C_max."""
        load_mg = ev.get("initial_pirfenidone_loading_mg")
        th = ev.get("elution_time_hours")
        cm = ev.get("cumulative_intact_parent_released_mg")
        thalf = ev.get("assumed_human_t_half_h")
        vdl = ev.get("assumed_human_vd_l")
        if not (
            is_finite_num(load_mg) and float(load_mg) > 0.0
            and isinstance(th, list) and isinstance(cm, list) and len(th) == len(cm) and len(th) >= 7
            and all(is_finite_num(x) for x in th + cm)
            and is_finite_num(thalf) and is_finite_num(vdl)
        ):
            fails.append(f"FAIL_{tag}_MISSING_TIME_RESOLVED_RELEASE_TRACE_OR_PK_PARAMS"); return None
        tf = [float(x) for x in th]
        cf = [float(x) for x in cm]
        lf = float(load_mg)
        if tf[0] != 0.0 or cf[0] != 0.0 or any(tf[i] >= tf[i + 1] for i in range(len(tf) - 1)) or any(cf[i + 1] < cf[i] for i in range(len(cf) - 1)):
            fails.append(f"FAIL_{tag}_INVALID_RELEASE_TRACE_MONOTONICITY"); return None
        if cf[-1] <= 0.0 or cf[-1] > 1.10 * lf:
            fails.append(f"FAIL_{tag}_ZERO_OR_CONTRADICTORY_RELEASE_TRACE"); return None
        # Dense burst sampling required (<= 1 h, <= 3 h, <= 6 h, <= 24 h) through min_horizon_h
        if not (any(0.0 < t <= 1.0 for t in tf) and any(1.0 < t <= 3.0 for t in tf) and any(3.0 < t <= 6.0 for t in tf) and any(12.0 <= t <= 24.0 for t in tf) and tf[-1] >= min_horizon_h):
            fails.append(f"FAIL_{tag}_RELEASE_TRACE_INSUFFICIENT_BURST_OR_HORIZON_COVERAGE"); return None
        # Require explicit endpoint timestamps at 24.0 h and min_horizon_h (336.0 h or 840.0 h) for exact mass balance!
        if not any(abs(t - 24.0) <= 1e-9 for t in tf) or not any(abs(t - min_horizon_h) <= 1e-9 for t in tf):
            fails.append(f"FAIL_{tag}_RELEASE_TRACE_MISSING_EXPLICIT_24H_OR_HORIZON_ENDPOINT"); return None
        # Conservative human pirfenidone PK bounds (FDA/PMDA label: t_half 2.4-4.0 h, Vd 35-65 L)
        if not (2.4 <= float(thalf) <= 4.0 and 35.0 <= float(vdl) <= 65.0):
            fails.append(f"FAIL_{tag}_INVALID_HUMAN_PK_ENVELOPE_THALF_OR_VD"); return None
        # Evaluate BOTH stated (t_half, Vd) AND worst-case conservative joint PK corner (t_half=4.0 h, Vd=35.0 L)!
        cmax_stated = _recompute_pirfenidone_peak_systemic_cmax_ug_ml(tf, cf, t_half_h=float(thalf), vd_l=float(vdl))
        cmax_worst = _recompute_pirfenidone_peak_systemic_cmax_ug_ml(tf, cf, t_half_h=4.0, vd_l=35.0)
        cmax = max(cmax_stated, cmax_worst)
        if cmax >= 0.20:
            fails.append(f"FAIL_{tag}_RECOMPUTED_PEAK_SYSTEMIC_CMAX_CAP_BREACH")
        # Dossier §5 lines 116 & 118: require >= 3 distinct manufacturing lots with lot-specific validated release traces!
        mlots = ev.get("manufacturing_lot_release_records")
        mlot_keys = frozenset({
            "coating_lot_id", "initial_pirfenidone_loading_mg",
            "elution_time_hours", "cumulative_intact_parent_released_mg", "lot_trace_sha256",
        })
        if mlots is None:
            holds.append(f"HOLD_{tag}_MISSING_3_MANUFACTURING_LOT_RELEASE_RECORDS"); return None
        if not isinstance(mlots, list) or len(mlots) < 3:
            fails.append(f"FAIL_{tag}_REQUIRES_AT_LEAST_3_DISTINCT_MANUFACTURING_LOTS"); return None
        seen_mlots: set[str] = set()
        active_lot_present = False
        for m_i, mlr in enumerate(mlots):
            if (
                not isinstance(mlr, Mapping) or set(mlr.keys()) != mlot_keys
                or not is_nonempty_str(mlr.get("coating_lot_id"))
                or not is_valid_sha256_hex(mlr.get("lot_trace_sha256"))
                or sha256_bytes(canonical_json_bytes({k: v for k, v in mlr.items() if k != "lot_trace_sha256"})) != str(mlr["lot_trace_sha256"])
            ):
                fails.append(f"FAIL_{tag}_MALFORMED_MANUFACTURING_LOT_RELEASE_RECORD:{m_i}"); return None
            mlid = str(mlr["coating_lot_id"]).strip()
            if mlid.upper() in seen_mlots:
                fails.append(f"FAIL_{tag}_DUPLICATE_MANUFACTURING_LOT_ID:{mlid}"); return None
            seen_mlots.add(mlid.upper())
            if coat_id is not None and mlid == coat_id.get("coating_lot_id"):
                active_lot_present = True
            ml_load = mlr.get("initial_pirfenidone_loading_mg")
            ml_t = mlr.get("elution_time_hours")
            ml_c = mlr.get("cumulative_intact_parent_released_mg")
            if not (
                is_finite_num(ml_load) and float(ml_load) > 0.0
                and isinstance(ml_t, list) and isinstance(ml_c, list) and len(ml_t) == len(ml_c) and len(ml_t) >= 7
                and all(is_finite_num(x) for x in ml_t + ml_c)
            ):
                fails.append(f"FAIL_{tag}_INVALID_LOT_RELEASE_TRACE:{mlid}"); return None
            ml_tf = [float(x) for x in ml_t]
            ml_cf = [float(x) for x in ml_c]
            if (
                ml_tf[0] != 0.0 or ml_cf[0] != 0.0
                or any(ml_tf[k] >= ml_tf[k + 1] for k in range(len(ml_tf) - 1))
                or any(ml_cf[k + 1] < ml_cf[k] for k in range(len(ml_cf) - 1))
                or ml_cf[-1] <= 0.0 or ml_cf[-1] > 1.10 * float(ml_load)
                or ml_tf[-1] < min_horizon_h
                or not any(abs(t - 24.0) <= 1e-9 for t in ml_tf)
                or not any(abs(t - min_horizon_h) <= 1e-9 for t in ml_tf)
            ):
                fails.append(f"FAIL_{tag}_INVALID_LOT_RELEASE_TRACE:{mlid}"); return None
            ml_c24 = _interp_cum_at_hour(ml_tf, ml_cf, 24.0)
            if ml_c24 is None or (100.0 * ml_c24 / float(ml_load)) > 15.0 + 1e-9:
                fails.append(f"FAIL_{tag}_LOT_DAY1_BURST_GT_15PCT:{mlid}"); return None
            ml_cmax = max(
                _recompute_pirfenidone_peak_systemic_cmax_ug_ml(ml_tf, ml_cf, t_half_h=float(thalf), vd_l=float(vdl)),
                _recompute_pirfenidone_peak_systemic_cmax_ug_ml(ml_tf, ml_cf, t_half_h=4.0, vd_l=35.0),
            )
            if ml_cmax >= 0.20:
                fails.append(f"FAIL_{tag}_LOT_PEAK_SYSTEMIC_CMAX_CAP_BREACH:{mlid}"); return None
        if coat_id is not None and not active_lot_present:
            fails.append(f"FAIL_{tag}_ACTIVE_COATING_LOT_MISSING_FROM_3LOT_PANEL"); return None
        return cmax, tf, cf, lf

    # Gate A-0b: coating identity + >= 14 d + unified loading/trace burst reconciliation & supremum C_max < 0.20 ug/mL!
    a0b_extras = COATING_IDENTITY_KEYS | frozenset({
        "study_start_utc", "initial_pirfenidone_loading_mg",
        "coating_thickness_um", "day1_burst_pct", "modeled_systemic_plasma_ug_ml",
        "elution_time_hours", "cumulative_intact_parent_released_mg",
        "assumed_human_t_half_h", "assumed_human_vd_l",
        "worst_face_o2_mmhg", "day14_viability_pct", "day14_sprouting_pct",
        "cc10_free_14d_l95_uM", "c_sprout_max_free_14d_l95_uM",
        "c_upper_provisional_14d_l95_uM", "sustained_free_parent_lower_uM",
        "peak_free_parent_u95_uM", "day14_sustained_free_parent_u95_uM",
        "added_coating_water_equiv_diff_path_um", "water_equiv_diff_path_um",
        "local_ph_min", "local_ph_max",
        "a0b_14d_safety_replicates_by_conc", "a0b_fit_artifact_receipt",
        "a0b_matrix_fu_by_assay",
        "a0b_local_exposure_timepoints", "a0b_local_pk_envelope",
        "a0b_local_ph_timepoints",
        "manufacturing_lot_release_records", "a0b_limits_already_fu_adjusted",
    })
    a0b_ev = _validate_content_receipt(
        a0b_raw,
        expected_stage="A-0b", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_parent=a0a_ev, allowed_extra_keys=a0b_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A0B_RECEIPT_MISSING",
        fail_code="FAIL_GATE_A0B_FAILED",
        mismatch_code="FAIL_GATE_A0B_SCOPE_MISMATCH",
    )
    a0b_ok = a0b_ev is not None and a0b_ev.get("verdict") == "PASS"
    all4_ceiling_val: Optional[float] = None
    if a0b_ev is not None:
        coat_id = _extract_and_validate_coating_identity(a0b_ev, expected=None, fails=fails, stage="A-0b")
        if coat_id is None:
            a0b_ok = False
        t_a0b_st = parse_utc_iso_ts(a0b_ev.get("study_start_utc"))
        t_a0b_end = parse_utc_iso_ts(a0b_ev.get("recorded_at_utc"))
        t_a0a_end = parse_utc_iso_ts(a0a_ev.get("recorded_at_utc")) if a0a_ev is not None else None
        if t_a0b_st is None or t_a0b_end is None:
            fails.append("FAIL_GATE_A0B_MISSING_STUDY_START_UTC"); a0b_ok = False
        else:
            if t_a0a_end is not None and t_a0b_st < t_a0a_end:
                fails.append("FAIL_GATE_A0B_STARTED_BEFORE_A0A_COMPLETION"); a0b_ok = False
            if (t_a0b_end - t_a0b_st) < timedelta(days=14):
                fails.append("FAIL_GATE_A0B_ELAPSED_OBSERVATION_LT_14_DAYS"); a0b_ok = False
        th = a0b_ev.get("coating_thickness_um")
        burst = a0b_ev.get("day1_burst_pct")
        plasma = a0b_ev.get("modeled_systemic_plasma_ug_ml")
        o2_b = a0b_ev.get("worst_face_o2_mmhg")
        v14 = a0b_ev.get("day14_viability_pct")
        s14 = a0b_ev.get("day14_sprouting_pct")
        cc14 = a0b_ev.get("cc10_free_14d_l95_uM")
        sp14 = a0b_ev.get("c_sprout_max_free_14d_l95_uM")
        c14_up = a0b_ev.get("c_upper_provisional_14d_l95_uM")
        sust_lo = a0b_ev.get("sustained_free_parent_lower_uM")
        pk_u95 = a0b_ev.get("peak_free_parent_u95_uM")
        d14_u95 = a0b_ev.get("day14_sustained_free_parent_u95_uM")
        added_wp = a0b_ev.get("added_coating_water_equiv_diff_path_um")
        wpath = a0b_ev.get("water_equiv_diff_path_um")
        ph_lo = a0b_ev.get("local_ph_min")
        ph_hi = a0b_ev.get("local_ph_max")
        if not (is_finite_num(th) and 0.0 < float(th) <= 10.0):
            fails.append("FAIL_GATE_A0B_COATING_THICKNESS_INVALID"); a0b_ok = False
        if not (is_finite_num(burst) and 0.0 <= float(burst) <= 15.0):
            fails.append("FAIL_GATE_A0B_DAY1_BURST_INVALID_OR_GT_15PCT"); a0b_ok = False
        if not (is_finite_num(plasma) and 0.0 <= float(plasma) < 0.20):
            fails.append("FAIL_GATE_A0B_SYSTEMIC_PLASMA_CAP_BREACH"); a0b_ok = False
        tr_0b = _validate_pfd_release_trace_and_peak(a0b_ev, min_horizon_h=336.0, tag="GATE_A0B")
        if tr_0b is None:
            a0b_ok = False
        else:
            cmax_0b, tf_0b, cf_0b, lf_0b = tr_0b
            if cmax_0b >= 0.20:
                a0b_ok = False
            elif is_finite_num(plasma) and float(plasma) + 1e-6 < cmax_0b:
                fails.append("FAIL_GATE_A0B_MODELED_PLASMA_UNDERSTATES_BURST_CMAX"); a0b_ok = False
            cum24 = _interp_cum_at_hour(tf_0b, cf_0b, 24.0)
            if cum24 is None or cum24 <= 0.0:
                fails.append("FAIL_GATE_A0B_ZERO_OR_CONTRADICTORY_DAY1_TRACE"); a0b_ok = False
            else:
                recomp_burst_pct = 100.0 * cum24 / lf_0b
                if recomp_burst_pct > 15.0 or (is_finite_num(burst) and abs(float(burst) - recomp_burst_pct) > 0.5):
                    fails.append("FAIL_GATE_A0B_DAY1_BURST_MISMATCH_WITH_RELEASE_TRACE"); a0b_ok = False
        if not all(is_finite_num(x) for x in (o2_b, v14, s14, cc14, sp14, c14_up, sust_lo, pk_u95, d14_u95, added_wp, wpath, ph_lo, ph_hi)):
            holds.append("HOLD_GATE_A0B_MISSING_EXPOSURE_VASCULAR_PATH_OR_PH_METRICS"); a0b_ok = False
        else:
            if float(o2_b) < 40.0:
                fails.append("FAIL_GATE_A0B_WORST_FACE_O2_BELOW_40MMHG"); a0b_ok = False
            if float(v14) < 90.0 or float(v14) > 100.0:
                fails.append("FAIL_GATE_A0B_DAY14_VIABILITY_BELOW_90PCT"); a0b_ok = False
            if float(s14) < 90.0:
                fails.append("FAIL_GATE_A0B_DAY14_SPROUTING_BELOW_90PCT"); a0b_ok = False
            if float(added_wp) <= 0.0 or float(added_wp) > 5.0:
                fails.append("FAIL_GATE_A0B_ADDED_COATING_DIFF_PATH_GT_5UM"); a0b_ok = False
            if float(wpath) <= 0.0 or float(wpath) > 50.0 or float(added_wp) > float(wpath) + 1e-12:
                fails.append("FAIL_GATE_A0B_WATER_EQUIV_DIFF_PATH_GT_50UM"); a0b_ok = False
            if float(ph_lo) < 7.25 or float(ph_hi) > 7.45 or float(ph_lo) > float(ph_hi):
                fails.append("FAIL_GATE_A0B_LOCAL_PH_OUTSIDE_7P25_7P45"); a0b_ok = False
            a0b_ph_tps = a0b_ev.get("a0b_local_ph_timepoints")
            if a0b_ph_tps is None:
                holds.append("HOLD_GATE_A0B_MISSING_14D_TIME_RESOLVED_PH"); a0b_ok = False
            elif not isinstance(a0b_ph_tps, list) or len(a0b_ph_tps) < 3:
                fails.append("FAIL_GATE_A0B_TIME_RESOLVED_PH_INVALID_OR_OUT_OF_RANGE"); a0b_ok = False
            else:
                _ph_rk = frozenset({"hour_h", "coating_lot_id", "ph_min", "ph_max"})
                _ph_prev = -1.0
                _ph_obs_min = float("inf")
                _ph_obs_max = float("-inf")
                _ph0b_ok = True
                _exp_clot0b = str(coat_id.get("coating_lot_id", "")).strip() if coat_id is not None else ""
                for _pr in a0b_ph_tps:
                    if not (
                        isinstance(_pr, Mapping) and set(_pr.keys()) == _ph_rk
                        and is_finite_num(_pr.get("hour_h")) and float(_pr["hour_h"]) > _ph_prev and float(_pr["hour_h"]) > 0.0
                        and is_nonempty_str(_pr.get("coating_lot_id"))
                        and (not _exp_clot0b or str(_pr["coating_lot_id"]).strip() == _exp_clot0b)
                        and is_finite_num(_pr.get("ph_min")) and is_finite_num(_pr.get("ph_max"))
                        and 7.25 <= float(_pr["ph_min"]) <= float(_pr["ph_max"]) <= 7.45
                    ):
                        _ph0b_ok = False; break
                    if _ph_prev >= 0.0 and (float(_pr["hour_h"]) - _ph_prev) > 168.0 + 1e-9:
                        _ph0b_ok = False; break
                    _ph_prev = float(_pr["hour_h"])
                    _ph_obs_min = min(_ph_obs_min, float(_pr["ph_min"]))
                    _ph_obs_max = max(_ph_obs_max, float(_pr["ph_max"]))
                if (
                    not _ph0b_ok
                    or float(a0b_ph_tps[0]["hour_h"]) > 24.0 + 1e-9
                    or float(a0b_ph_tps[-1]["hour_h"]) < 336.0 - 1e-9
                    or float(ph_lo) > _ph_obs_min + 1e-6
                    or float(ph_hi) < _ph_obs_max - 1e-6
                ):
                    fails.append("FAIL_GATE_A0B_TIME_RESOLVED_PH_INVALID_OR_OUT_OF_RANGE"); a0b_ok = False
            if float(pk_u95) < float(d14_u95) - 1e-12 or float(d14_u95) < float(sust_lo) - 1e-12:
                fails.append("FAIL_GATE_A0B_INVALID_EXPOSURE_ORDERING"); a0b_ok = False
            eff_floor_0b = ic50_u95_op if ic50_u95_op is not None else ic50_u95_val
            c7d_ceil_0b = c_up_7d_op if c_up_7d_op is not None else c_up_7d_val
            a0b_already_fu_adj = False
            if "a0b_limits_already_fu_adjusted" in a0b_ev:
                if not is_strict_bool(a0b_ev["a0b_limits_already_fu_adjusted"]):
                    fails.append("FAIL_GATE_A0B_INVALID_FU_ADJUSTED_FLAG"); a0b_ok = False
                else:
                    a0b_already_fu_adj = bool(a0b_ev["a0b_limits_already_fu_adjusted"])
            if eff_floor_0b is not None and float(sust_lo) < eff_floor_0b:
                fails.append("FAIL_GATE_A0B_SUSTAINED_FREE_BELOW_IC50_U95"); a0b_ok = False
            exp_14d_min = min(float(cc14), float(sp14))
            if exp_14d_min <= 0.0 or abs(float(c14_up) - exp_14d_min) > 1e-9:
                fails.append("FAIL_GATE_A0B_14D_CEILING_NOT_MIN_OF_VIABILITY_AND_SPROUTING"); a0b_ok = False
            # Assay-specific 14-day equilibrium-dialysis f_u & nominal-to-free exposure reconciliation on A-0b!
            a0b_mfu = a0b_ev.get("a0b_matrix_fu_by_assay")