OpenIslet

scripts/verify_iip0045_cao2_coupled_gate31.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Lot Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 68 KB · 6 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_iip0045_cao2_coupled_gate31.py · SHA-256: 00443954dd735914…

        holds.append("HOLD_SEALED_CHAMBER_ONLY_OPEN_SINK_REQUIRED")
    elif assay_regime != "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK":
        holds.append(f"MISSING_OR_INVALID_KINETICS_ASSAY_REGIME:{assay_regime!r}")

    os_th_m, os_th_l95, os_th_u95, err = _extract_ci(
        payload, "obs_open_sink_cao2_half_life_h", "obs_open_sink_cao2_half_life_se_h"
    )
    th_se_val = float(payload["obs_cao2_release_half_life_se_h"]) if (th_m is not None and _is_finite_real(payload.get("obs_cao2_release_half_life_se_h"))) else None
    os_th_se_val = float(payload["obs_open_sink_cao2_half_life_se_h"]) if (os_th_m is not None and _is_finite_real(payload.get("obs_open_sink_cao2_half_life_se_h"))) else None
    paired_contrast_eval: Dict[str, Any] = {}
    if err:
        holds.append(err)
    else:
        assert os_th_l95 is not None and os_th_u95 is not None
        if os_th_l95 < 34.0:
            hard_stops.append(f"OPEN_SINK_HALFLIFE_BURST_BELOW_34H_FLOOR:l95={os_th_l95:.4f}")
        if t50_valid and t_half_upper_limit is not None:
            if os_th_u95 > t_half_upper_limit:
                hard_stops.append(f"OPEN_SINK_HALFLIFE_EXCEEDS_UPPER_WINDOW:u95={os_th_u95:.4f}")
        elif os_th_u95 > 87.0:
            hard_stops.append(f"OPEN_SINK_HALFLIFE_EXCEEDS_UPPER_WINDOW_BOTH_TIMINGS:u95={os_th_u95:.4f}>87.0")
        paired_contrast_eval = evaluate_gate31c_paired_ratio_contrast_bpr17(
            payload,
            th_m=th_m,
            th_se=th_se_val,
            os_th_m=os_th_m,
            os_th_se=os_th_se_val,
            ratio_threshold=0.50,
        )
        holds.extend(paired_contrast_eval.get("holds", []))

    os_h2_m, _, os_h2_u95, err = _extract_ci(
        payload, "obs_open_sink_islet_plane_h2o2_max_uM", "obs_open_sink_islet_plane_h2o2_max_se_uM"
    )
    if err:
        holds.append(err)
    elif os_h2_u95 is not None:
        if os_h2_u95 > 5.0:
            hard_stops.append(f"OPEN_SINK_H2O2_BREACHES_5P0UM_TIER2_HARD_STOP:u95={os_h2_u95:.4f}")
        elif os_h2_u95 > 2.5:
            holds.append(f"OPEN_SINK_H2O2_EXCEEDS_2P5UM_TIER1_TARGET:u95={os_h2_u95:.4f}")

    diagnostics.update({
        "design_family": design,
        "product_route_id": route,
        "lot_id": lot_id,
        "vascular_midpoint_horizon_h": t50_horizon if t50_valid else None,
        "vascular_midpoint_horizon_valid": t50_valid,
        "t_half_passing_window_h": [34.0, t_half_upper_limit] if (t50_valid and t_half_upper_limit is not None) else None,
        "obs_microbead_d99_u95_um": round(d99_u95, 4) if d99_u95 is not None else None,
        "obs_t_half_95ci_h": [round(th_l95, 4), round(th_u95, 4)] if (th_l95 is not None and th_u95 is not None) else None,
        "obs_open_sink_t_half_95ci_h": (
            [round(os_th_l95, 4), round(os_th_u95, 4)] if (os_th_l95 is not None and os_th_u95 is not None) else None
        ),
        "obs_hour0_to_24h_o2_l95": round(o2_24_l95, 4) if o2_24_l95 is not None else None,
        "obs_cumulative_72h_o2_l95": round(o2_72_l95, 4) if o2_72_l95 is not None else None,
        "obs_islet_plane_h2o2_u95_uM": round(h2o2_u95, 4) if h2o2_u95 is not None else None,
        "obs_open_sink_h2o2_u95_uM": round(os_h2_u95, 4) if os_h2_u95 is not None else None,
        "gate31c_paired_ratio_contrast_bpr17": paired_contrast_eval,
    })

    # Fail-first precedence: hard stops always override holds
    if hard_stops:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "FAIL_HARD_STOP_GATE_31_COUPLED_CAO2_LOT",
            "exit_code": 3,
            "release_authorizing": False,
            "hard_stops": hard_stops,
            "holds": holds,
            "diagnostics": diagnostics,
        }
    if holds:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "HOLD_GATE_31_INCOMPLETE_OR_TIER1_MARGIN",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": holds,
            "diagnostics": diagnostics,
        }
    return {
        "gate_id": GATE_ID,
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "verdict": "PASS_GATE_31_COUPLED_CAO2_LOT",
        "exit_code": 0,
        "release_authorizing": True,
        "hard_stops": [],
        "holds": [],
        "diagnostics": diagnostics,
    }


def _reference_passing_lot_fixture() -> Dict[str, Any]:
    return {
        "design_family": "X",
        "product_route_id": "ROUTE_1_CAO2_390UM_EXPANDED_PLANAR_BARRIER",
        "lot_id": "LOT-GATE31-REF-001",
        "bead_psd_lot_id": "LOT-GATE31-REF-001",
        "barrier_film_lot_id": "LOT-GATE31-REF-001",
        "kinetics_336h_lot_id": "LOT-GATE31-REF-001",
        "open_sink_lot_id": "LOT-GATE31-REF-001",
        "barrier_geometry_mode": "PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM",
        "reconciled_slab_geometry_mode": "EXPANDED_390UM_2X125UM_BANDS",
        "catalase_uniprot_accession": "P04040",
        "obs_microbead_volume_d99_um": 46.2,
        "obs_microbead_volume_d99_se": 1.1,
        "obs_microbead_volume_d50_um": 31.5,
        "obs_microbead_volume_d50_se": 0.8,
        "obs_cao2_crystal_d99_um": 14.0,
        "obs_cao2_crystal_d99_se": 0.6,
        "obs_planar_barrier_film_um_per_face": 22.4,
        "obs_planar_barrier_film_se_um": 0.5,
        "conserved_patient_cao2_inventory_mg": 791.5,
        "vascular_midpoint_horizon_h": 36.0,
        "obs_cao2_release_half_life_h": 58.0,
        "obs_cao2_release_half_life_se_h": 2.5,
        "obs_cao2_kinetic_law_code": 0,
        "obs_hour0_to_24h_o2_delivery_ratio": 0.94,
        "obs_hour0_to_24h_o2_delivery_ratio_se": 0.03,
        "obs_cumulative_0_to_72h_o2_demand_fraction": 0.31,
        "obs_cumulative_0_to_72h_o2_demand_fraction_se": 0.015,
        "obs_islet_plane_h2o2_max_uM": 1.25,
        "obs_islet_plane_h2o2_max_se_uM": 0.15,
        "obs_day7_catalase_retention_pct": 82.0,
        "obs_day7_catalase_retention_se_pct": 2.0,
        "obs_day14_retained_catalase_iu_333cm2": 79500.0,
        "obs_day14_retained_catalase_se_iu": 1500.0,
        "pre_cure_catalase_load_iu_333cm2": 148000.0,
        "kinetics_assay_regime": "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK",
        "obs_open_sink_cao2_half_life_h": 46.5,
        "obs_open_sink_cao2_half_life_se_h": 2.2,
        "obs_open_sink_islet_plane_h2o2_max_uM": 1.65,
        "obs_open_sink_islet_plane_h2o2_max_se_uM": 0.18,
    }


def _reference_dec134_stage0_release_lot_fixture() -> Dict[str, Any]:
    """Reference Stage-0 release fixture complying with all DEC-134 locked bench specs (BPR-14..18)."""
    base = _reference_passing_lot_fixture()
    base.update({
        "vascular_midpoint_horizon_h": 60.0,
        "obs_cao2_release_half_life_h": 56.0,
        "obs_cao2_release_half_life_se_h": 2.0,
        "obs_po2_below_15mmhg_cumulative_h": 0.0,
        "obs_po2_min_mmhg": 16.15,
        "obs_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "obs_h2o2_z_um": 70.0,
        "obs_open_sink_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "obs_open_sink_h2o2_z_um": 70.0,
        "obs_open_sink_cao2_half_life_h": 46.5,
        "obs_open_sink_cao2_half_life_se_h": 1.8,
        "obs_paired_blocks": [
            {"limited_h": 54.0, "open_sink_h": 44.5},
            {"limited_h": 55.2, "open_sink_h": 45.8},
            {"limited_h": 56.0, "open_sink_h": 46.4},
            {"limited_h": 56.5, "open_sink_h": 47.0},
            {"limited_h": 57.1, "open_sink_h": 47.4},
            {"limited_h": 57.2, "open_sink_h": 47.9},
        ],
    })
    return base


def evaluate_gate31_stage0_release_dec134(payload: Any) -> Dict[str, Any]:
    """
    DEC-134 locked Stage-0 bench release evaluator for Gate 31 (BPR-14, BPR-16, BPR-17, BPR-18).

    Enforces all baseline Gate 31 coupled checks plus maintainer-locked DEC-134 bench rules:
      - BPR-14: Requires conservative 60.0 h vascular-midpoint branch for release authorization
        (36.0 h is logged strictly as an optimistic sensitivity reference -> HOLD); caps cumulative
        sub-15.0 mmHg excursion at <= 4.0 h and enforces a hard hypoxia floor >= 10.0 mmHg.
      - BPR-16: Designates the barrier/tissue interface plane (z = 70.0 um,
        BARRIER_TISSUE_INTERFACE_Z_70P0_UM) as the authoritative peroxide release coordinate.
      - BPR-17: Requires n >= 6 paired open-vs-limited blocks (raw blocks or paired summary with
        explicit correlation) clearing the one-sided 95% Student-t lower confidence bound >= 0.0 h
        on open - 0.50 * limited (unpaired Cauchy-Schwarz remains fail-safe only, non-releasing).
      - BPR-18: Records zero legacy physical wet-lab lots admitted under the removed 36 h default.
    """
    if not isinstance(payload, dict):
        res = evaluate_gate31_coupled_cao2_lot(payload)
        res["policy_decision_id"] = "DEC-134"
        return res

    base = evaluate_gate31_coupled_cao2_lot(payload)
    if base["verdict"] == "HOLD_GATE31_OUT_OF_SCOPE_NON_CAO2_ROUTE":
        base["policy_decision_id"] = "DEC-134"
        return base

    hard_stops = list(base["hard_stops"])
    # Drop the two-sided Gate 31-C hold from base and re-evaluate under locked DEC-134 one-sided 95% n>=6 rule
    holds = [h for h in base["holds"] if not h.startswith("OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:") and not h.startswith("OPEN_SINK_RATIO_UNPAIRED_DENOMINATOR_UNCERTAINTY_INCONCLUSIVE:")]
    diag = dict(base["diagnostics"])

    # BPR-14: Locked 60 h primary release branch + sub-15 mmHg duration & 10 mmHg floor
    raw_t50 = payload.get("vascular_midpoint_horizon_h")
    if _is_finite_real(raw_t50) and float(raw_t50) == 36.0:
        holds.append("DEC134_36H_IS_SENSITIVITY_ONLY_60H_PRIMARY_REQUIRED")

    sub15_h = payload.get("obs_po2_below_15mmhg_cumulative_h")
    if not _is_finite_real(sub15_h) or float(sub15_h) < 0.0:
        holds.append(f"DEC134_MISSING_OR_INVALID_PO2_BELOW_15MMHG_CUMULATIVE_H:{sub15_h!r}")
    elif float(sub15_h) > 4.0:
        hard_stops.append(f"DEC134_PO2_BELOW_15MMHG_EXCURSION_EXCEEDS_4H_CAP:hours={float(sub15_h):.3f}")

    po2_min = payload.get("obs_po2_min_mmhg")
    if not _is_finite_real(po2_min) or float(po2_min) < 0.0:
        holds.append(f"DEC134_MISSING_OR_INVALID_PO2_MIN_MMHG:{po2_min!r}")
    elif float(po2_min) < 10.0:
        hard_stops.append(f"DEC134_PO2_MIN_BREACHES_10MMHG_HARD_FLOOR:po2_min={float(po2_min):.3f}")

    # BPR-16: Authoritative peroxide coordinate at z = 70.0 um barrier/tissue interface plane
    for site_key, z_key, lbl in (
        ("obs_h2o2_measurement_site", "obs_h2o2_z_um", "LIMITED_EXCHANGE"),
        ("obs_open_sink_h2o2_measurement_site", "obs_open_sink_h2o2_z_um", "OPEN_SINK"),
    ):
        site_val = payload.get(site_key)
        z_val = payload.get(z_key)
        if site_val != "BARRIER_TISSUE_INTERFACE_Z_70P0_UM" or not _is_finite_real(z_val) or not math.isclose(float(z_val), 70.0, abs_tol=1e-6):
            holds.append(f"DEC134_H2O2_NOT_AT_Z70P0_INTERFACE:{lbl}:site={site_val!r},z_um={z_val!r}")

    # BPR-17: Paired open-vs-limited blocks n >= 6 with one-sided 95% Student-t LCB >= 0.0 h
    th_m = float(payload["obs_cao2_release_half_life_h"]) if _is_finite_real(payload.get("obs_cao2_release_half_life_h")) else None
    th_se = float(payload["obs_cao2_release_half_life_se_h"]) if _is_finite_real(payload.get("obs_cao2_release_half_life_se_h")) else None
    os_m = float(payload["obs_open_sink_cao2_half_life_h"]) if _is_finite_real(payload.get("obs_open_sink_cao2_half_life_h")) else None
    os_se = float(payload["obs_open_sink_cao2_half_life_se_h"]) if _is_finite_real(payload.get("obs_open_sink_cao2_half_life_se_h")) else None
    dec134_g31c = evaluate_gate31c_paired_ratio_contrast_bpr17(
        payload,
        th_m=th_m,
        th_se=th_se,
        os_th_m=os_m,
        os_th_se=os_se,
        ratio_threshold=0.50,
        confidence_mode="one_sided_95",
    )
    if dec134_g31c.get("mode") not in ("PAIRED_BLOCKS_STUDENT_T", "PAIRED_SUMMARY_STUDENT_T"):
        holds.append(f"DEC134_GATE31C_REQUIRES_PAIRED_BLOCKS_N_GE_6:mode={dec134_g31c.get('mode')}")
    else:
        n_blk = int(dec134_g31c.get("n_blocks", 0))
        if n_blk < 6:
            holds.append(f"DEC134_GATE31C_REQUIRES_PAIRED_BLOCKS_N_GE_6:n_blocks={n_blk}")
        holds.extend(dec134_g31c.get("holds", []))

    diag["dec134_stage0_bench_policy"] = {