OpenIslet

scripts/verify_iip0033_bilayer_and_resp1.py

Deterministic Stage-0 Physics, Multi-Mesh 3D FVM & Respirometry Verifier (IIP-0033 / DEC-112)

script Release v0.8.0 gen-eb955f8266035aba 78 KB · 7 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_iip0033_bilayer_and_resp1.py · SHA-256: 45f1396930f3a6af…

#!/usr/bin/env python3
"""
Deterministic Stage-0 Physics, Multi-Mesh 3D FVM & Respirometry Verifier (IIP-0033 / DEC-112)
==============================================================================================
Self-contained replay script for OpenIslet public and audit checkouts. Depends ONLY on
`scripts/run_layer4_tissue_and_metabolic_twin.py`, `scripts/rank_islet1_stacks.py`,
`numpy`, and the Python standard library.

Run with:
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0033_bilayer_and_resp1.py
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0033_bilayer_and_resp1.py --write
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0033_bilayer_and_resp1.py --check

Verifies deterministically:
  1. Static Agilent 101122-100 islet capture microplate O2 mass balance across ALL THREE
     published Agilent chamber volumes (16.60 uL FluxPak 103518-100, 16.87 uL brochure
     5991-8657EN p. 9, and 9.87 uL XF24 support FAQ -> 6/10 IEQ caps where 9/16 IEQ drops to
     20.96/105.84 mmHg), plus 14.94 uL (-10% off 16.60 uL -> 9/16 IEQ with +0.61 mmHg air-FCCP
     margin), 14.00 uL screen-displaced sensitivity (9/15 IEQ), and obsolete 22.70 uL XF24 V7
     (Gerencser 2009 PMID:19555051, mouse-liver mitochondria n=4) under KRBH alpha = 1.27e-9
     mol/(cm^3*mmHg) vs low-salt/BSA (1.34e-9) and pure water (1.39e-9), alongside 125 um stock
     capture-screen pore retention calibration requirements.
  2. Primary flow-through 5% O2 perifusion modeled on Sweet et al. (2008 PMID:18021279; 750
     handpicked islets, glucose/carbachol) methodological precedent: Stage-0 modeled 200 IEQ
     @ 200 uL/min -> 32.07 / 30.28 / 28.49 / 26.70 mmHg across 1x-2.5x (SNR = 17.9x) with exact
     unrounded float threshold comparisons.
  3. Fixed-pitch (p = 104.1604 um, 1,500.0 IEQ/cm^2 nominal) 2x2 mixed-lot 65 um staggered
     bilayer multi-mesh 3D FVM (nx = 40, 60, 80) calling live OpenIslet l4 Newton-PCG solver:
       - PASS envelopes: Route 2 140 um staggered Design Z (Chr30 No-FBR & Chr35 15 um 3x FBR),
         Route 1 390 um CaO2 (nominal & coupled +10% OCR + 16.5 um standoff stress), Route 1 350 um
         nominal & pure +10% OCR at fixed 15.0 um standoff (15.03-15.06 mmHg), and p95 = 70 um
         on Route 1 390 um under pure +10% OCR at fixed 15.0 um standoff (15.21-15.24 mmHg).
       - HOLD/FAIL proofs: Route 1 350 um under coupled +10% OCR + 16.5 um standoff (14.62-14.64 mmHg
         < 15 mmHg), p95 = 70 um on Route 1 390 um under coupled +10% OCR + 16.5 um standoff
         (14.89-14.93 mmHg < 15 mmHg), 160 um aligned backup (exact 1,500, fixed 104.16 um mold, and
         3.1464 cap), and unconstrained d_rms3 = 68 um mold overload (1,717.4 IEQ/cm^2).
       - Explicit Day-0 Avascular (k_perf = 0, D_gel_acute) vs Chronic Perfused separation.
       - GY-027 monolayer fixed-pitch vs re-derived 75 um packing gap check (-1.35 vs +16.29 um).
  4. GY-028 cylindrical pre-vascularized channel traps at clinical 500,000 IEQ scale:
       - R = 500 um (1 mm ID) Day-0 core anoxia (0.0000 mmHg).
       - R = 120 um 30 um dense thrombus sleeve collapse (1.4106 / 0.5908 mmHg).
       - R = 100-120 um track length, surgical footprint, pull-out force, and VPIO jamming.
  5. Live OQ-016 2^12 baseline parity check (+0.00 pp live odds invariance).
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple

import numpy as np

sys.dont_write_bytecode = True

ROOT = Path(__file__).resolve().parents[1]
SCRIPTS_DIR = ROOT / "scripts"
if str(SCRIPTS_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPTS_DIR))

import rank_islet1_stacks as rank_mod  # noqa: E402
import run_layer4_tissue_and_metabolic_twin as l4  # noqa: E402

DEFAULT_OUT_PATH = ROOT / "data" / "extracted" / "iip0033_bilayer_and_respirometry_verification_v0.8.0.json"

# Canonical OpenIslet Layer-4 physical constants
ALPHA_LOW_SALT = float(l4.ALPHA_BUNSEN_MOL_CM3_MMHG)  # 1.34e-9 mol/(cm^3 * mmHg)
ALPHA_PURE_WATER_37C = 1.39e-9                        # 1.39e-9 mol/(cm^3 * mmHg)
ALPHA_KRBH = 1.27e-9                                  # 1.27e-9 mol/(cm^3 * mmHg)
D_GEL_ACUTE = float(l4.D_O2_HYDROGEL_CM2_S)           # 0.940254e-5 cm^2/s
D_GEL_CHRON = 1.50e-5                                 # cm^2/s
D_ISLET = float(l4.D_O2_ISLET_TISSUE_CM2_S)           # 1.30e-5 cm^2/s
VMAX_PURE = float(l4.VMAX_ISLET_PURE_MOL_CM3_S)       # 3.4e-8 mol/(cm^3 * s)
VOL_IEQ = float(l4.VOL_1_IEQ_CM3)                     # 1.7671458676442586e-6 cm^3
K_GEL_CHRON = D_GEL_CHRON * ALPHA_LOW_SALT
K_ISLET = D_ISLET * ALPHA_LOW_SALT
K_PERF_CHRON = 0.14 * 0.97                            # 0.1358 s^-1
DOSE_IEQ = 500_000.0
VOL_500K_CM3 = DOSE_IEQ * VOL_IEQ                     # 0.883573 cm^3


def _stable_mass_balance_err(raw_err: float) -> float:
    """Assert strict < 1e-10 mass-balance conservation while clamping sub-1e-10 BLAS/NumPy ULP noise for byte-exact cross-runtime --check."""
    err = abs(float(raw_err))
    assert math.isfinite(err) and err < 1e-10, f"Mass balance residual exceeded 1e-10: {raw_err!r}"
    return 0.0 if err < 1e-10 else round(err, 10)


def _is_valid_finite_number_iip0033(val: Any) -> bool:
    return not isinstance(val, bool) and isinstance(val, (int, float)) and math.isfinite(float(val))


def _require_positive_finite_iip0033(val: Any, name: str) -> float:
    if not _is_valid_finite_number_iip0033(val) or float(val) <= 0.0:
        raise ValueError(f"{name} must be a strictly positive finite number, got {val!r}")
    return float(val)


def compute_static_xfe24_101122_100_cap_iip0033(
    *,
    volume_uL: float = 14.94,
    alpha_mol_cm3_mmhg: float = 1.27e-9,
    ocr_whole_prep_pmol_min_ieq: float = 4.5479,
    read_min: float = 3.0,
) -> Dict[str, Any]:
    """Compute exact Agilent 101122-100 static microchamber O2 depletion and max IEQ/well caps (unrounded threshold comparison; IIP-0033 / DEC-112)."""
    volume_uL = _require_positive_finite_iip0033(volume_uL, "volume_uL")
    alpha_mol_cm3_mmhg = _require_positive_finite_iip0033(alpha_mol_cm3_mmhg, "alpha_mol_cm3_mmhg")
    ocr_whole_prep_pmol_min_ieq = _require_positive_finite_iip0033(ocr_whole_prep_pmol_min_ieq, "ocr_whole_prep_pmol_min_ieq")
    read_min = _require_positive_finite_iip0033(read_min, "read_min")
    p_5pct = 0.05 * (760.0 - 47.0)       # 35.6500 mmHg
    p_21pct = 0.2095 * (760.0 - 47.0)    # 149.3735 mmHg
    vol_cm3 = volume_uL * 1e-3
    ocr_mol_min_ieq = ocr_whole_prep_pmol_min_ieq * 1e-12
    dp_basal_per_ieq = (ocr_mol_min_ieq * read_min) / (vol_cm3 * alpha_mol_cm3_mmhg)
    return {
        "volume_uL": float(volume_uL),
        "alpha_mol_cm3_mmhg": float(alpha_mol_cm3_mmhg),
        "ocr_whole_prep_pmol_min_ieq": float(ocr_whole_prep_pmol_min_ieq),
        "read_min": float(read_min),
        "dp_basal_3min_mmhg_per_ieq": round(dp_basal_per_ieq, 4),
        "dp_basal_3min_mmhg_per_ieq_unrounded": float(dp_basal_per_ieq),
        "max_ieq_5pct_basal_ge25": int(math.floor((p_5pct - 25.0) / dp_basal_per_ieq)),
        "max_ieq_5pct_gsis_1p5x_ge25": int(math.floor((p_5pct - 25.0) / (1.5 * dp_basal_per_ieq))),
        "max_ieq_5pct_gsis_2p0x_ge25": int(math.floor((p_5pct - 25.0) / (2.0 * dp_basal_per_ieq))),
        "max_ieq_5pct_fccp_2p5x_ge25": int(math.floor((p_5pct - 25.0) / (2.5 * dp_basal_per_ieq))),
        "max_ieq_21pct_fccp_2p5x_ge120": int(math.floor((p_21pct - 120.0) / (2.5 * dp_basal_per_ieq))),
    }


def compute_sweet2008_flow_through_po2_out_iip0033(
    *,
    n_ieq: float = 200.0,
    flow_uL_min: float = 200.0,
    alpha_mol_cm3_mmhg: float = 1.27e-9,
    ocr_whole_prep_pmol_min_ieq: float = 4.5479,
    noise_floor_mmhg: float = 0.20,
) -> Dict[str, Any]:
    """Compute flow-through 5% O2 perifusion steady-state outflow pO2 (Sweet 2008 methodological precedent; exact unrounded threshold comparison; IIP-0033 / DEC-112)."""
    n_ieq = _require_positive_finite_iip0033(n_ieq, "n_ieq")
    flow_uL_min = _require_positive_finite_iip0033(flow_uL_min, "flow_uL_min")
    alpha_mol_cm3_mmhg = _require_positive_finite_iip0033(alpha_mol_cm3_mmhg, "alpha_mol_cm3_mmhg")
    ocr_whole_prep_pmol_min_ieq = _require_positive_finite_iip0033(ocr_whole_prep_pmol_min_ieq, "ocr_whole_prep_pmol_min_ieq")
    noise_floor_mmhg = _require_positive_finite_iip0033(noise_floor_mmhg, "noise_floor_mmhg")
    p_5pct = 0.05 * (760.0 - 47.0)  # 35.6500 mmHg
    q_cm3_min = flow_uL_min * 1e-3
    dp_basal = (n_ieq * ocr_whole_prep_pmol_min_ieq * 1e-12) / (q_cm3_min * alpha_mol_cm3_mmhg)
    p_b_raw = p_5pct - dp_basal
    p_15_raw = p_5pct - 1.5 * dp_basal
    p_20_raw = p_5pct - 2.0 * dp_basal
    p_25_raw = p_5pct - 2.5 * dp_basal
    return {
        "n_ieq": float(n_ieq),
        "flow_uL_min": float(flow_uL_min),
        "alpha_mol_cm3_mmhg": float(alpha_mol_cm3_mmhg),
        "delta_po2_basal_mmhg": round(dp_basal, 2),
        "snr_over_noise_floor": round(dp_basal / noise_floor_mmhg, 2),
        "p_out_5pct_basal_1p0x_mmhg": round(p_b_raw, 2),
        "p_out_5pct_gsis_1p5x_mmhg": round(p_15_raw, 2),
        "p_out_5pct_gsis_2p0x_mmhg": round(p_20_raw, 2),
        "p_out_5pct_fccp_2p5x_mmhg": round(p_25_raw, 2),
        "p_out_5pct_fccp_2p5x_unrounded_mmhg": float(p_25_raw),
        "all_4_states_ge_25mmhg": bool(p_25_raw >= 25.0),
        "passes_primary_spec": bool(p_25_raw >= 25.0 and dp_basal >= max(1.00, 5.0 * noise_floor_mmhg)),
    }


def compute_type7_finite_sample_cubic_mean_bounds_iip0033(
    *,
    d_min: float,
    p05: float,
    p95: float,
    d_max: float,
    sample_n: int | None = None,
) -> Dict[str, Any]:
    """Exact joint-constraint Hyndman-Fan Type-7 cubic-mean bounds over sorted d_min = x_0 <= ... <= x_{N-1} = d_max simultaneously satisfying both Type-7 linear interpolation equalities for any N >= 2 (IIP-0033 / DEC-112)."""
    d_min_f = _require_positive_finite_iip0033(d_min, "d_min")
    p05_f = _require_positive_finite_iip0033(p05, "p05")
    p95_f = _require_positive_finite_iip0033(p95, "p95")
    d_max_f = _require_positive_finite_iip0033(d_max, "d_max")
    if not (d_min_f <= p05_f <= p95_f <= d_max_f):
        raise ValueError(f"Non-monotonic quantiles: d_min={d_min_f}, p05={p05_f}, p95={p95_f}, d_max={d_max_f}")
    if sample_n is None:
        asymp_lb = (0.05 * (d_min_f ** 3) + 0.90 * (p05_f ** 3) + 0.05 * (p95_f ** 3)) ** (1.0 / 3.0)
        asymp_ub = (0.05 * (p05_f ** 3) + 0.90 * (p95_f ** 3) + 0.05 * (d_max_f ** 3)) ** (1.0 / 3.0)
        ext_lb_10k = ((9999.0 * (d_min_f ** 3) + 1.0 * (d_max_f ** 3)) / 10000.0) ** (1.0 / 3.0)
        ext_ub_10k = ((1.0 * (d_min_f ** 3) + 9999.0 * (d_max_f ** 3)) / 10000.0) ** (1.0 / 3.0)
        return {
            "sample_n": None,
            "feasible": True,
            "d_rms3_lb": float(max(asymp_lb, ext_lb_10k)),
            "d_rms3_ub": float(min(asymp_ub, ext_ub_10k)),
        }
    if isinstance(sample_n, bool) or not isinstance(sample_n, int) or sample_n < 2:
        raise ValueError(f"sample_n must be an integer >= 2 when provided, got {sample_n!r}")
    n = int(sample_n)
    tol = 1e-9 * max(1.0, abs(d_max_f))
    i05, r05 = divmod(n - 1, 20)
    i95, r95 = divmod(19 * (n - 1), 20)
    f05 = r05 / 20.0
    f95 = r95 / 20.0

    # Case 1: N == 2 (0 free variables: x_0 = d_min, x_1 = d_max)
    if n == 2:
        q05_exp = (1.0 - f05) * d_min_f + f05 * d_max_f
        q95_exp = (1.0 - f95) * d_min_f + f95 * d_max_f
        if abs(q05_exp - p05_f) > tol or abs(q95_exp - p95_f) > tol:
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}
        val = ((d_min_f ** 3 + d_max_f ** 3) / 2.0) ** (1.0 / 3.0)
        return {"sample_n": n, "feasible": True, "d_rms3_lb": float(val), "d_rms3_ub": float(val)}

    # Case 2: N == 3 (0 free variables: x_1 constrained by BOTH equations)
    if n == 3:
        x1_a = (p05_f - (1.0 - f05) * d_min_f) / f05
        x1_b = (p95_f - f95 * d_max_f) / (1.0 - f95)
        anchor_tol_3 = tol / min(f05, 1.0 - f95)
        if abs(x1_a - x1_b) > 2.0 * anchor_tol_3:
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}
        x1 = 0.5 * (x1_a + x1_b)
        if x1 < d_min_f - anchor_tol_3 or x1 > d_max_f + anchor_tol_3:
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}
        x1 = min(max(x1, d_min_f), d_max_f)
        if (
            abs((1.0 - f05) * d_min_f + f05 * x1 - p05_f) > tol
            or abs((1.0 - f95) * x1 + f95 * d_max_f - p95_f) > tol
        ):
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}
        val = ((d_min_f ** 3 + x1 ** 3 + d_max_f ** 3) / 3.0) ** (1.0 / 3.0)
        return {"sample_n": n, "feasible": True, "d_rms3_lb": float(val), "d_rms3_ub": float(val)}

    # Case 3: 4 <= N <= 20 (i05 == 0, i95 == n - 2; both interior anchors x_1 and x_{n-2} uniquely fixed;
    # propagate quantile tolerance tol through 1/f05 and 1/(1-f95) before final exact quantile residual check)
    if n <= 20:
        y1 = (p05_f - (1.0 - f05) * d_min_f) / f05
        y2 = (p95_f - f95 * d_max_f) / (1.0 - f95)
        anchor_tol = tol / min(f05, 1.0 - f95)
        if y1 < d_min_f - anchor_tol or y2 > d_max_f + anchor_tol or y1 > y2 + 2.0 * anchor_tol:
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}
        y1 = min(max(y1, d_min_f), d_max_f)
        y2 = min(max(y2, d_min_f), d_max_f)
        if y1 > y2:
            y1 = y2 = 0.5 * (y1 + y2)
        if (
            abs((1.0 - f05) * d_min_f + f05 * y1 - p05_f) > tol
            or abs((1.0 - f95) * y2 + f95 * d_max_f - p95_f) > tol
        ):
            return {"sample_n": n, "feasible": False, "d_rms3_lb": None, "d_rms3_ub": None}