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…

        "t_half_58h_att_0p80_t36h_on_60h_branch_passing_control": _solve_case(
            t_half_h=58.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=60.0
        ),
    }

    # BPR-16: barrier/tissue interface (z=70 um) vs nearest first-tissue cell center (z=72.5 um nominal)
    bpr16_comparison_rows = [
        _solve_case(t_half_h=68.0, t_eval_h=0.0, cat_ret_override=0.50, dz_um=5.0),
        _solve_case(t_half_h=34.0, t_eval_h=0.0, cat_ret_override=0.50, dz_um=5.0),
        _solve_case(t_half_h=36.0, t_eval_h=0.0, cat_ret_override=0.85, dz_um=5.0),
        _solve_case(t_half_h=24.0, t_eval_h=0.0, cat_ret_override=1.00, dz_um=5.0),
    ]

    all_rows = (
        burst_t0_100pct
        + burst_t0_50pct
        + acute_t18_100pct
        + third_coupling_o2_lag
        + bpr14_t50_36_att0p70
        + bpr14_t50_60_att0p70
        + bpr14_t50_60_att1p00_control
        + list(bpr14_interior_controls.values())
        + bpr16_comparison_rows
    )
    max_mb_err = max(max(r["h2o2_rel_mass_balance_error"], r["o2_rel_mass_balance_error"]) for r in all_rows)
    if max_mb_err > 1e-10:
        raise RuntimeError(f"3D FVM mass-balance tolerance violated: {max_mb_err:.3e}")

    k68 = math.log(2.0) / 68.0
    rel_0_24 = 1.0 - math.exp(-k68 * 24.0)
    rel_16_20 = math.exp(-k68 * 16.0) - math.exp(-k68 * 20.0)
    comp_factor = (0.80 * rel_0_24) / (rel_0_24 - rel_16_20)
    f72_const_0p80 = 0.80 * 0.45 * (1.0 - math.exp(-k68 * 72.0)) / (k68 * 72.0)
    f72_interrupted = (
        0.45 * (comp_factor * (rel_0_24 - rel_16_20) + 0.80 * (math.exp(-k68 * 24.0) - math.exp(-k68 * 72.0))) / (k68 * 72.0)
    )

    return {
        "geometry_spec": {
            "slab_thickness_um": 390.0,
            "central_lamina_um": 100.0,
            "planar_barrier_film_per_face_um": 20.0,
            "barrier_tissue_interface_z_um": 70.0,
            "nominal_first_tissue_cell_center_z_um": 72.5,
            "cluster_diam_um": 80.0,
            "areal_loading_ieq_cm2": 1500.0,
            "conserved_patient_cao2_mg": CONSERVED_CAO2_MG_TARGET,
            "full_active_catalase_t0_iu_333cm2": 73800.0,
            "worst_case_edge_bead_diam_um": 50.0,
            "nx_lateral": 36,
            "nz_vertical": 78,
        },
        "max_relative_mass_balance_error": max_mb_err,
        "hour0_burst_h2o2_100pct_catalase_sweep": burst_t0_100pct,
        "hour0_burst_h2o2_50pct_catalase_washout_sweep": burst_t0_50pct,
        "hour18_acute_bridge_coupled_sweep": acute_t18_100pct,
        "third_coupling_barrier_o2_lag_attenuation_t18h_sweep": third_coupling_o2_lag,
        "third_coupling_t18h_scope_note": (
            "Conditional on vascular_midpoint_horizon_h=36.0 at t=18.0 h; does NOT qualify the permitted 60 h delayed vascular branch "
            "(see bpr14_time_by_vascular_timing_by_delivery_matrix)."
        ),
        "bpr14_time_by_vascular_timing_by_delivery_matrix": {
            "scope_note": (
                "Quasi-steady 3D FVM worst-face pO2 (mmHg) across sampled hours at conserved 791.5 mg CaO2 inventory. "
                "Hour-18 clearance at 36 h / 0.70 (15.22 mmHg) does NOT carry over to the 60 h delayed branch (13.68 mmHg at hour 36). "
                "Acceptable sub-15 mmHg exposure duration and physical qualification require device-owner decision and measured whole-assembly traces."
            ),
            "branch_36h_delivery_0p70_t_half_68h": bpr14_t50_36_att0p70,
            "branch_60h_delivery_0p70_t_half_68h": bpr14_t50_60_att0p70,
            "branch_60h_delivery_1p00_t_half_68h_passing_control": bpr14_t50_60_att1p00_control,
            "interior_gate31_passing_controls": bpr14_interior_controls,
            "interrupted_delivery_aggregate_ambiguity": {
                "constant_delivery_factor": 0.80,
                "interruption_window_h": [16.0, 20.0],
                "day1_compensated_delivery_factor": round(comp_factor, 6),
                "constant_0_to_72h_demand_fraction": round(f72_const_0p80, 6),
                "interrupted_0_to_72h_demand_fraction": round(f72_interrupted, 6),
                "hour18_constant_0p80_po2_mmhg": _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=0.80)["worst_face_po2_min_mmhg"],
                "hour18_interrupted_0p00_po2_mmhg": _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=0.00)["worst_face_po2_min_mmhg"],
            },
        },
        "bpr16_interface_vs_cell_center_h2o2_audit": {
            "declared_primary_coordinate": "z = 70.0 um barrier/tissue interface (linear geometric reconstruction across equal-diffusivity bracketing cell centers)",
            "comparison_cases": bpr16_comparison_rows,
        },
    }


def _extract_ci(
    payload: Mapping[str, Any],
    mean_key: str,
    se_key: str,
    *,
    allow_zero_se: bool = False,
) -> Tuple[Optional[float], Optional[float], Optional[float], Optional[str]]:
    if mean_key not in payload or se_key not in payload:
        return None, None, None, f"MISSING_MEASUREMENT:{mean_key}/{se_key}"
    mv = payload.get(mean_key)
    sv = payload.get(se_key)
    if not _is_finite_real(mv) or not _is_finite_real(sv):
        return None, None, None, f"INVALID_NONFINITE_OR_TYPE:{mean_key}/{se_key}"
    m = float(mv)
    s = float(sv)
    if s < 0.0 or (s == 0.0 and not allow_zero_se):
        return None, None, None, f"INVALID_SE_NONPOSITIVE:{se_key}"
    lo = m - Z_95_TWO_SIDED * s
    hi = m + Z_95_TWO_SIDED * s
    return m, lo, hi, None


def evaluate_gate31c_paired_ratio_contrast_bpr17(
    payload: Mapping[str, Any],
    *,
    th_m: Optional[float],
    th_se: Optional[float],
    os_th_m: Optional[float],
    os_th_se: Optional[float],
    ratio_threshold: float = 0.50,
    confidence_mode: str = "two_sided_95",
) -> Dict[str, Any]:
    """
    Propagate uncertainty from BOTH open-sink numerator and limited-exchange denominator
    for Gate 31-C's ratio criterion (open_sink / limited_exchange >= 0.50) via the equivalent
    linear contrast d = open - 0.50 * limited >= 0 for positive denominators (BPR-17 / DEC-133).

    Supports three explicit modes:
      1. Raw paired blocks (`obs_paired_blocks`: list of {limited_h, open_sink_h}, n >= 2):
         exact Student-t two-sided & one-sided 95% lower bounds on block contrasts d_i.
      2. Summary moments with explicit pairing metadata (`obs_paired_blocks_n` >= 2 and
         `obs_open_limited_paired_corr` in [-1, 1]): exact paired Student-t lower bounds
         using SE_d = sqrt(SE_open^2 + 0.25*SE_lim^2 - 2*0.5*r*SE_open*SE_lim).
      3. Summary-only without pairing covariance: conservative worst-case Cauchy-Schwarz
         propagation (r = -1 => SE_d_worst = SE_open + 0.5*SE_lim) so an unavailable
         correlation never silently admits an inconclusive lot.
    """
    holds_out: List[str] = []
    if th_m is None or th_se is None or os_th_m is None or os_th_se is None:
        return {
            "mode": "UNAVAILABLE_MISSING_HALFLIFE_SUMMARY",
            "contrast_threshold": ratio_threshold,
            "clears_95pct_two_sided": False,
            "holds": [],
        }
    if th_m <= 0.0:
        holds_out.append(f"INVALID_NONPOSITIVE_LIMITED_HALFLIFE_MEAN:{th_m}")
        return {
            "mode": "INVALID_DENOMINATOR",
            "contrast_threshold": ratio_threshold,
            "clears_95pct_two_sided": False,
            "holds": holds_out,
        }

    legacy_shortcut_ratio = (os_th_m - Z_95_TWO_SIDED * os_th_se) / th_m

    # Mode 1: Raw paired block observations
    if "obs_paired_blocks" in payload and payload.get("obs_paired_blocks") is not None:
        raw_blocks = payload.get("obs_paired_blocks")
        if not isinstance(raw_blocks, list) or len(raw_blocks) < 2:
            holds_out.append("INVALID_OBS_PAIRED_BLOCKS_REQUIRES_LIST_LEN_GE_2")
            return {
                "mode": "PAIRED_BLOCKS_INVALID",
                "contrast_threshold": ratio_threshold,
                "clears_95pct_two_sided": False,
                "holds": holds_out,
            }
        lim_vals: List[float] = []
        op_vals: List[float] = []
        for idx, blk in enumerate(raw_blocks):
            if not isinstance(blk, Mapping):
                holds_out.append(f"INVALID_PAIRED_BLOCK_TYPE_AT_{idx}")
                return {"mode": "PAIRED_BLOCKS_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
            lv = blk.get("limited_h")
            ov = blk.get("open_sink_h")
            if not _is_finite_real(lv) or not _is_finite_real(ov) or float(lv) <= 0.0 or float(ov) <= 0.0:
                holds_out.append(f"INVALID_PAIRED_BLOCK_VALUE_AT_{idx}")
                return {"mode": "PAIRED_BLOCKS_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
            lim_vals.append(float(lv))
            op_vals.append(float(ov))
        arr_l = np.asarray(lim_vals, dtype=float)
        arr_o = np.asarray(op_vals, dtype=float)
        diffs = arr_o - ratio_threshold * arr_l
        n_blk = len(diffs)
        df = n_blk - 1
        d_mean = float(np.mean(diffs))
        d_sd = float(np.std(diffs, ddof=1))
        d_se = d_sd / math.sqrt(n_blk)
        t_two = _student_t_ppf_exact(0.975, df)
        t_one = _student_t_ppf_exact(0.95, df)
        d_l95_two = d_mean - t_two * d_se
        d_l95_one = d_mean - t_one * d_se
        corr = (
            float(np.corrcoef(arr_l, arr_o)[0, 1])
            if (np.std(arr_l, ddof=1) > 0.0 and np.std(arr_o, ddof=1) > 0.0)
            else None
        )
        clears_two = bool(d_l95_two >= 0.0)
        clears_one = bool(d_l95_one >= 0.0)
        clears = clears_one if confidence_mode == "one_sided_95" else clears_two
        if not clears:
            if confidence_mode == "one_sided_95":
                holds_out.append(
                    f"DEC134_OPEN_SINK_PAIRED_CONTRAST_ONE_SIDED_L95_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_one={d_l95_one:.4f}h,df={df}"
                )
            else:
                holds_out.append(
                    f"OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_two={d_l95_two:.4f}h,df={df}"
                )
        return {
            "mode": "PAIRED_BLOCKS_STUDENT_T",
            "n_blocks": n_blk,
            "df": df,
            "paired_correlation": round(corr, 6) if corr is not None else None,
            "contrast_mean_h": round(d_mean, 6),
            "contrast_se_h": round(d_se, 6),
            "contrast_l95_two_sided_h": round(d_l95_two, 6),
            "contrast_l95_one_sided_h": round(d_l95_one, 6),
            "legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
            "clears_95pct_two_sided": clears_two,
            "clears_95pct_one_sided": clears_one,
            "holds": holds_out,
        }

    # Mode 2: Summary moments with explicit pairing metadata (n_blocks + correlation)
    has_corr = "obs_open_limited_paired_corr" in payload and payload.get("obs_open_limited_paired_corr") is not None
    has_n = "obs_paired_blocks_n" in payload and payload.get("obs_paired_blocks_n") is not None
    if has_corr or has_n:
        raw_r = payload.get("obs_open_limited_paired_corr")
        raw_n = payload.get("obs_paired_blocks_n")
        if not has_corr or not _is_finite_real(raw_r) or not (-1.0 <= float(raw_r) <= 1.0):
            holds_out.append(f"INVALID_OR_MISSING_PAIRED_CORRELATION:{raw_r!r}")
            return {"mode": "PAIRED_SUMMARY_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
        if not has_n or not isinstance(raw_n, int) or isinstance(raw_n, bool) or raw_n < 2:
            holds_out.append(f"INVALID_OR_MISSING_PAIRED_BLOCKS_N:{raw_n!r}")
            return {"mode": "PAIRED_SUMMARY_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
        r_val = float(raw_r)
        df = raw_n - 1
        d_mean = os_th_m - ratio_threshold * th_m
        d_var = max(0.0, os_th_se**2 + (ratio_threshold * th_se) ** 2 - 2.0 * ratio_threshold * r_val * os_th_se * th_se)
        d_se = math.sqrt(d_var)
        t_two = _student_t_ppf_exact(0.975, df)
        t_one = _student_t_ppf_exact(0.95, df)
        d_l95_two = d_mean - t_two * d_se
        d_l95_one = d_mean - t_one * d_se
        clears_two = bool(d_l95_two >= 0.0)
        clears_one = bool(d_l95_one >= 0.0)
        clears = clears_one if confidence_mode == "one_sided_95" else clears_two
        if not clears:
            if confidence_mode == "one_sided_95":
                holds_out.append(
                    f"DEC134_OPEN_SINK_PAIRED_CONTRAST_ONE_SIDED_L95_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_one={d_l95_one:.4f}h,r={r_val:.3f},df={df}"