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…

                u_sk = max(hi for _, hi in sys_intervals)
            u_sys_series.append(u_sk)
            if any(not b for b in lb_blq):
                any_quant_loc_bmt = True
                recomp_u_loc_bmt_tot = max(recomp_u_loc_bmt_tot, u_lbt_cens)
            if any(not b for b in rb_blq):
                any_quant_rec_bmt = True
                recomp_u_rec_bmt_tot = max(recomp_u_rec_bmt_tot, u_rbt_cens)
            raw_max_loc_bmt_tot = max(raw_max_loc_bmt_tot, max(lbf_r))
            raw_max_rec_bmt_tot = max(raw_max_rec_bmt_tot, max(rbf_r))
            recomp_u_loc_bmt_free = max(recomp_u_loc_bmt_free, u_lbt_cens * u_fb_r)
            recomp_u_rec_bmt_free = max(recomp_u_rec_bmt_free, u_rbt_cens * u_fb_rec_r)
            raw_max_loc_bmt_free = max(raw_max_loc_bmt_free, max(lbf_r) * u_fb_r)
            raw_max_rec_bmt_free = max(raw_max_rec_bmt_free, max(rbf_r) * u_fb_rec_r)
        digest_mismatch = False
        if upstream_sample_ledger is None or not upstream_sample_ledger:
            ledger_issue = True
        else:
            if set(seen_b2b_sample_hours.keys()) != set(upstream_sample_ledger.keys()):
                ledger_issue = True
            elif any(abs(seen_b2b_sample_hours[k] - float(upstream_sample_ledger[k][0])) > 1e-6 for k in upstream_sample_ledger):
                ledger_issue = True
            elif any(
                seen_b2b_sample_matrices.get(k) != str(upstream_sample_ledger[k][2])
                or seen_b2b_sample_rec_matrices.get(k) != str(upstream_sample_ledger[k][3])
                or seen_b2b_sample_units.get(k) != str(upstream_sample_ledger[k][4])
                for k in upstream_sample_ledger
            ):
                ledger_issue = True
            else:
                for k_sid, (_, exp_row_sha, _, _, _) in upstream_sample_ledger.items():
                    if seen_b2b_sample_digests.get(k_sid) != str(exp_row_sha).lower():
                        digest_mismatch = True; break
        if ledger_issue:
            holds.append(f"HOLD_{prefix}_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE"); ok = False
        if digest_mismatch:
            holds.append(f"HOLD_{prefix}_UPSTREAM_ANALYTICAL_ROW_DIGEST_MISMATCH"); ok = False

    if not (is_strict_bool(ev.get("censoring_audit_passed")) and ev["censoring_audit_passed"]):
        fails.append(f"FAIL_{prefix}_CENSORING_AUDIT_MISSING"); ok = False
    if not (is_strict_bool(ev.get("intersample_peak_envelope_justified")) and ev["intersample_peak_envelope_justified"]):
        fails.append(f"FAIL_{prefix}_INTERSAMPLE_PEAK_UNJUSTIFIED"); ok = False
    env_res = _validate_and_apply_continuous_pk_envelope(
        ev.get("intersample_pk_envelope"),
        hours_seen=hours_seen, u_local_series=u_local_series,
        l_parent_all_series=l_parent_all_series,
        u_sys_series=u_sys_series, max_efficacy_start_h=0.0,
        expected_coating_article_id=(expected_coating_identity.get("coating_article_id") if expected_coating_identity else None),
        expected_evidence_scope=expected_scope,
        expected_compartment_id="BENCH_ELUTION_RECIRCULATION",
        fails=fails, holds=holds, prefix=prefix,
    )
    cont_ratio_min = float("inf")
    cont_ratio_max = 0.0
    cont_unbounded = False
    if env_res is None:
        ok = False
        enveloped_peak, enveloped_floor, enveloped_sys = float("inf"), -1.0, float("inf")
    else:
        enveloped_peak, enveloped_floor, enveloped_sys = env_res
        if tp_valid:
            cont_ratio_min, cont_ratio_max, cont_unbounded = _compute_continuous_bmt_parent_ratio_bounds(
                hours_seen, u_bmt_free_series, l_bmt_free_series, l_parent_all_series, u_parent_all_series,
                ev.get("intersample_pk_envelope"), fails=fails, prefix=prefix,
            )
    eff_unbounded_bmt_ratio = unbounded_bmt_ratio or cont_unbounded
    eff_obs_free_ratio_min = min(0.0 if obs_free_ratio_min == float("inf") else obs_free_ratio_min, cont_ratio_min)
    eff_obs_free_ratio_max = max(obs_free_ratio_max, cont_ratio_max)
    if not (is_strict_bool(ev.get("systemic_exposure_below_cap")) and ev["systemic_exposure_below_cap"]):
        fails.append(f"FAIL_{prefix}_SYSTEMIC_EXPOSURE_UNVERIFIED"); ok = False

    # Evaluate ALL 4 BMT triggers & bind mixture-specific therapeutic window covering full observed free ratio range!
    eff_loc_tot = max(float(bmt_loc_tot), raw_max_loc_bmt_tot, recomp_u_loc_bmt_tot)
    eff_loc_free = max(float(bmt_loc_free), raw_max_loc_bmt_free, recomp_u_loc_bmt_free)
    eff_rec_tot = max(float(bmt_rec_tot), raw_max_rec_bmt_tot, recomp_u_rec_bmt_tot)
    eff_rec_free = max(float(bmt_rec_free), raw_max_rec_bmt_free, recomp_u_rec_bmt_free)
    local_trig = any_quant_loc_bmt or (eff_loc_tot >= lloq_b_loc_min) or (eff_loc_free >= 0.10 * ceiling_l95)
    recirc_trig = any_quant_rec_bmt or (eff_rec_tot >= lloq_b_rec_min) or (eff_rec_free >= 0.10 * ceiling_l95)
    eff_ec50 = ec50_u95
    eff_ceiling = ceiling_l95
    if eff_unbounded_bmt_ratio and not (local_trig or recirc_trig):
        if ev.get("mixture_requalification_receipt") is None:
            holds.append(f"HOLD_{prefix}_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ"); ok = False
    if local_trig or recirc_trig or (eff_unbounded_bmt_ratio and ev.get("mixture_requalification_receipt") is not None):
        mix_ok, m_ec50, m_csafe = _validate_mixture_requal_receipt(
            ev.get("mixture_requalification_receipt"),
            expected_prod=expected_prod, expected_bank=expected_bank,
            expected_lot=expected_lot, expected_route=expected_route,
            expected_scope=expected_scope,
            expected_coating_identity=expected_coating_identity,
            parent_recorded_at_utc=parse_utc_iso_ts(ev.get("recorded_at_utc")),
            observed_bmt_to_parent_ratio_min=eff_obs_free_ratio_min,
            observed_bmt_to_parent_ratio_max=eff_obs_free_ratio_max,
            unbounded_ratio_under_parent_blq=eff_unbounded_bmt_ratio,
            fails=fails, holds=holds, prefix=prefix,
        )
        if not mix_ok or m_ec50 is None or m_csafe is None:
            ok = False
        else:
            eff_ec50 = max(eff_ec50, m_ec50)
            eff_ceiling = min(eff_ceiling, m_csafe)
            if float(u95_joint) >= eff_ceiling or float(parent_lo) < eff_ec50:
                fails.append(f"FAIL_{prefix}_EXPOSURE_BREACHES_TRIGGERED_MIXTURE_WINDOW"); ok = False

    if tp_valid and env_res is not None:
        if not (hours_seen[0] <= 24.0 and any(abs(h - 240.0) <= 12.0 for h in hours_seen) and washout_u_joint is not None):
            fails.append(f"FAIL_{prefix}_TIMEPOINT_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WASHOUT"); ok = False
        if float(u95_joint) + 1e-4 < enveloped_peak or enveloped_peak >= eff_ceiling:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_SIMULTANEOUS_PEAK_EXCEEDS_CLAIMED_OR_CSAFE"); ok = False
        if enveloped_floor < 0.0 or float(parent_lo) - 1e-4 > enveloped_floor or enveloped_floor < eff_ec50:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_PARENT_FLOOR_MISMATCH_OR_BELOW_EC50"); ok = False
        if washout_u_joint is not None and (washout_u_joint >= 2.0 or washout_u_joint >= eff_ec50):
            fails.append(f"FAIL_{prefix}_DAY21_REPLICATE_WASHOUT_NOT_EXHAUSTED"); ok = False
        if enveloped_sys >= 0.5:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_SYSTEMIC_U95_GE_0P5NM"); ok = False
        if float(bmt_loc_tot) + 1e-4 < recomp_u_loc_bmt_tot or float(bmt_loc_free) + 1e-4 < recomp_u_loc_bmt_free:
            fails.append(f"FAIL_{prefix}_CLAIMED_LOCAL_BMT_UNDERSTATES_RAW_REPLICATES"); ok = False
        if float(bmt_rec_tot) + 1e-4 < recomp_u_rec_bmt_tot or float(bmt_rec_free) + 1e-4 < recomp_u_rec_bmt_free:
            fails.append(f"FAIL_{prefix}_CLAIMED_RECIRC_BMT_UNDERSTATES_RAW_REPLICATES"); ok = False
    return ok


def evaluate_gate41_deucravacitinib_tyk2(rec: Mapping[str, Any]) -> dict[str, Any]:
    """GATE-41 (IIP-0063): Fail-closed 3-phase deucravacitinib adjudicator with raw analytical B-0a/B-2b, raw paired B-2, coating-bound B-0a-exact, matched-vehicle B-3, & gap-checked B-4."""
    phase = str(rec.get("phase", "EXACT_PRODUCT")).strip().upper()
    if phase not in ("ROUTE_FREE_B0A", "BENCH_UNEDITED", "EXACT_PRODUCT"):
        return {
            "gate": "GATE-41", "verdict": "FAIL", "release_authorizing": False,
            "live_ledger_authenticated": False, "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": rec.get("product_id"), "required_switch": None,
            "failures": ["FAIL_INVALID_PHASE"], "holds": [],
        }

    fails: list[str] = []
    holds: list[str] = []
    spec: Optional[Mapping[str, Any]] = None
    scope_track = "ROUTE_FREE_B0A"
    mat_ev = sw_ev = g0v_ev = g31_ev = None

    b0b_raw = rec.get("b0b_evidence")
    coat_id: Optional[dict[str, str]] = None
    if phase != "ROUTE_FREE_B0A" and isinstance(b0b_raw, Mapping):
        if all(is_nonempty_str(b0b_raw.get(k)) for k in COATING_IDENTITY_KEYS):
            coat_id = {k: str(b0b_raw[k]).strip() for k in sorted(COATING_IDENTITY_KEYS)}

    if phase == "ROUTE_FREE_B0A":
        _check_allowed_keys(rec, GATE41_B0A_KEYS, fails, "GATE41_B0A")
    else:
        spec, scope_track, b_fails, b_holds, mat_ev, sw_ev, g0v_ev, g31_ev = _validate_canonical_binding_v6(
            rec, allow_design_a=False, coating_gate=True, phase=phase,
            expected_coating_identity=coat_id,
        )
        fails.extend(b_fails)
        holds.extend(b_holds)
        if phase == "BENCH_UNEDITED":
            _check_forbidden_keys(rec, GATE41_EXACT_ONLY_KEYS, fails, "FAIL_BENCH_PHASE_FORBIDS_EXACT_OR_INVIVO_FIELDS")
            _check_allowed_keys(rec, GATE41_BENCH_KEYS, fails, "GATE41_BENCH")
        else:
            _check_allowed_keys(rec, GATE41_EXACT_KEYS, fails, "GATE41")

    # Gate B-0a: raw measured f_u maps + raw 7-point concentration-response bracketing + analysis_record_sha256!
    b0a_extras = frozenset({
        "endpoints_bracketed", "analysis_record_sha256",
        "lloq_parent_by_matrix_nM", "lloq_bmt_by_matrix_nM",
        "fu_parent_by_matrix", "fu_bmt_by_matrix",
        "tested_free_conc_grid_nM", "efficacy_inhibition_pct_grid",
        "efficacy_beta_protection_pct_grid", "efficacy_nk_suppression_pct_grid", "efficacy_iec_ibmir_pct_grid",
        "safety_sprouting_pct_grid", "safety_nkg2a_pct_grid",
        "safety_cd94_pct_grid", "safety_il10_retention_pct_grid",
        "safety_replicates_by_conc",
        "efficacy_replicates_by_conc", "b0a_analysis_receipt",
        "ec50_eff_u95_free_nM", "c_safe_max_bench_l95_free_nM",
    })
    b0a_ev = _validate_content_receipt(
        rec.get("b0a_evidence"),
        expected_stage="B-0a", expected_prod=None, expected_bank=None,
        expected_lot=None, expected_route=None, forbid_route=True,
        expected_scope="route_free", allowed_extra_keys=b0a_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B0A_RECEIPT_MISSING",
        fail_code="FAIL_GATE_B0A_FAILED",
        mismatch_code="FAIL_GATE_B0A_SCOPE_MISMATCH",
    )
    b0a_ok = b0a_ev is not None and b0a_ev.get("verdict") == "PASS"
    ec50_u95: Optional[float] = None
    csafe_bench: Optional[float] = None
    lloq_bmt_min: Optional[float] = None
    lloq_parent_map_f: Optional[dict[str, float]] = None
    lloq_bmt_map_f: Optional[dict[str, float]] = None
    fu_parent_map_f: Optional[dict[str, float]] = None
    fu_bmt_map_f: Optional[dict[str, float]] = None
    if b0a_ev is not None:
        if not (is_strict_bool(b0a_ev.get("endpoints_bracketed")) and b0a_ev["endpoints_bracketed"]):
            fails.append("FAIL_GATE_B0A_ENDPOINTS_UNBRACKETED"); b0a_ok = False
        if not is_valid_sha256_hex(b0a_ev.get("analysis_record_sha256")):
            fails.append("FAIL_GATE_B0A_MISSING_ANALYSIS_RECORD_SHA256"); b0a_ok = False
        lp_map = b0a_ev.get("lloq_parent_by_matrix_nM")
        lb_map = b0a_ev.get("lloq_bmt_by_matrix_nM")
        fp_map = b0a_ev.get("fu_parent_by_matrix")
        fb_map = b0a_ev.get("fu_bmt_by_matrix")
        if not (isinstance(lp_map, Mapping) and set(lp_map.keys()) == REQUIRED_3_MATRICES and isinstance(lb_map, Mapping) and set(lb_map.keys()) == REQUIRED_3_MATRICES):
            fails.append("FAIL_GATE_B0A_MISSING_PER_MATRIX_LLOQ_MAP"); b0a_ok = False
        else:
            vals_p = list(lp_map.values())
            vals_b = list(lb_map.values())
            if not all(is_finite_num(x) and 0.0 < float(x) <= 0.2 for x in vals_p + vals_b):
                fails.append("FAIL_GATE_B0A_LLOQ_INVALID_OR_GT_0P2NM"); b0a_ok = False
            else:
                lloq_parent_map_f = {str(k): float(v) for k, v in lp_map.items()}
                lloq_bmt_map_f = {str(k): float(v) for k, v in lb_map.items()}
                lloq_bmt_min = min(lloq_bmt_map_f.values())
        if not (isinstance(fp_map, Mapping) and set(fp_map.keys()) == REQUIRED_3_MATRICES and isinstance(fb_map, Mapping) and set(fb_map.keys()) == REQUIRED_3_MATRICES and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in list(fp_map.values()) + list(fb_map.values()))):
            fails.append("FAIL_GATE_B0A_MISSING_OR_INVALID_MEASURED_FU_BY_MATRIX"); b0a_ok = False
        else:
            fu_parent_map_f = {str(k): float(v) for k, v in fp_map.items()}
            fu_bmt_map_f = {str(k): float(v) for k, v in fb_map.items()}
        e50 = b0a_ev.get("ec50_eff_u95_free_nM")
        csb = b0a_ev.get("c_safe_max_bench_l95_free_nM")
        if not (is_finite_num(e50) and is_finite_num(csb)):
            holds.append("HOLD_GATE_B0A_MISSING_BENCH_WINDOW"); b0a_ok = False
        elif float(e50) <= 0.0 or float(csb) <= 0.0:
            fails.append("FAIL_GATE_B0A_NONPOSITIVE_CONCENTRATION"); b0a_ok = False
        else:
            ec50_u95, csafe_bench = float(e50), float(csb)
            if csafe_bench / ec50_u95 < 2.0:
                fails.append("FAIL_GATE_B0A_MARGIN_BELOW_2X"); b0a_ok = False
            # Verify raw concentration-response observations actually bracket BOTH EC50_eff_U95 AND C_safe_max_L95!
            cgrid = b0a_ev.get("tested_free_conc_grid_nM")
            egrid = b0a_ev.get("efficacy_inhibition_pct_grid")
            eb_g = b0a_ev.get("efficacy_beta_protection_pct_grid")
            en_g = b0a_ev.get("efficacy_nk_suppression_pct_grid")
            ei_g = b0a_ev.get("efficacy_iec_ibmir_pct_grid")
            s_sp = b0a_ev.get("safety_sprouting_pct_grid")
            s_nk = b0a_ev.get("safety_nkg2a_pct_grid")
            s_cd94 = b0a_ev.get("safety_cd94_pct_grid")
            s_il = b0a_ev.get("safety_il10_retention_pct_grid")
            if not (
                isinstance(cgrid, list) and len(cgrid) >= 7
                and all(isinstance(g, list) and len(g) == len(cgrid) and all(is_finite_num(x) for x in g) for g in (cgrid, egrid, eb_g, en_g, ei_g, s_sp, s_nk, s_cd94, s_il))
            ):
                fails.append("FAIL_GATE_B0A_MISSING_RAW_CONC_RESPONSE_GRID"); b0a_ok = False
            else:
                cg = [float(x) for x in cgrid]
                eg = [float(x) for x in egrid]
                ebg = [float(x) for x in eb_g]
                eng = [float(x) for x in en_g]
                eig = [float(x) for x in ei_g]
                ss = [float(x) for x in s_sp]
                sn = [float(x) for x in s_nk]
                sc94 = [float(x) for x in s_cd94]