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…

#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Lot Evaluator for
IIP-0045 / DEC-125 / GATE-31 / GY-031:
  "Bead size and oxygen-release half-life are one coupled gate, not two"
  (Community submission by giufra / @frafra013; GitHub Issue #45)

Capabilities:
  1. Verifies strict Zero-LIMS-Touch SHA-256 invariance (scripts/wetlab_contract.py,
     scripts/ingest_wetlab_results.py, data/protocols/wetlab_endpoint_contract_v0.8.0.json,
     Playbook §4.1.20 canonical body, DEC-132 refreshed Pareto pin 460ebc19...) without importing
     wetlab_contract.py.
  2. Executes live exact Layer-4 3D finite-volume reaction-diffusion replays
     (PureNumpy3DFVOperator, _solve_3d_h2o2_strict_iip_0019, _solve_3d_oxygen_strict_iip_0019)
     in the conserved 791.5 mg patient-CaO2 per-mass frame:
       - Per-bead 20 um conformal shell geometric unbuildability proof (5.832x-12.704x volume)
       - Conserved-inventory Hour-0 / Hour-18 / Hour-36 burst-H2O2 & acute-O2 sweep
         across t_1/2 in {4, 8, 12, 18, 24, 34, 68, 87} h at 100% and 50% catalase
       - Third-coupling barrier-induced O2 lag/attenuation sweep (1.00x down to 0.00x)
  3. Provides fail-closed, strict-JSON executable Stage-0 lot adjudication
     (`evaluate_gate31_coupled_cao2_lot`) across Gate 31-Scope, Gate 31-A, Gate 31-B,
     and Gate 31-C with zero uncaught tracebacks (exit codes: 0 PASS, 2 HOLD, 3 FAIL).
  4. Audits 68.0 h provenance, GY-013 / GY-031 graveyard sync, and stage0_decision_tree_v1.json
     append-only block parity.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Tuple

import numpy as np


def _betacf_exact(a: float, b: float, x: float) -> float:
    """Continued fraction (Lentz) for regularized incomplete beta I_x(a, b)."""
    eps = 1e-15
    fpmin = 1e-300
    qab = a + b
    qap = a + 1.0
    qam = a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < fpmin:
        d = fpmin
    d = 1.0 / d
    h = d
    for m in range(1, 201):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < eps:
            break
    return h


def _betainc_exact(a: float, b: float, x: float) -> float:
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x))
    if x < (a + 1.0) / (a + b + 2.0):
        return bt * _betacf_exact(a, b, x) / a
    return 1.0 - bt * _betacf_exact(b, a, 1.0 - x) / b


def _student_t_ppf_exact(p: float, df: int) -> float:
    """Pure-Python float64-exact Student-t quantile (zero external scipy dependency)."""
    if df < 1:
        raise ValueError(f"df must be >= 1, got {df}")
    if not (0.5 < p < 1.0):
        raise ValueError(f"p must be in (0.5, 1.0), got {p}")
    target_tail = 1.0 - p
    lo, hi = 0.0, 1.0
    while 0.5 * _betainc_exact(0.5 * df, 0.5, df / (df + hi * hi)) > target_tail:
        hi *= 2.0
    for _ in range(100):
        mid = 0.5 * (lo + hi)
        tail = 0.5 * _betainc_exact(0.5 * df, 0.5, df / (df + mid * mid))
        if tail > target_tail:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-13 * max(1.0, hi):
            break
    return 0.5 * (lo + hi)

SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
REPO_ROOT = SCRIPT_DIR.parent

GENERATED_DATE = "2026-12-01"
CONTRIBUTION_ID = "IIP-0045"
DECISION_ID = "DEC-125"
GATE_ID = "GATE-31"
GRAVEYARD_CARD_ID = "GY-031"
GRAVEYARD_GUARDRAIL_ID = "OFFGRID_GUARD_021_DECOUPLED_CAO2_BEAD_SIZE_AND_RELEASE_HALFLIFE_GATING"

SIDE_CONTRACT_REL = "data/protocols/iip0045_cao2_coupled_gate31_side_contract_v0.8.0.json"
VERIFICATION_REL = "data/extracted/iip0045_cao2_coupled_gate31_verification_v0.8.0.json"
PROTOCOL_DOC_REL = "docs/GATE-31-CAO2-BEAD-HALFLIFE-BARRIER-COUPLED-PROTOCOL.md"
DECISION_TREE_REL = "data/protocols/stage0_decision_tree_v1.json"
DECISION_TREE_KEY = "cao2_coupled_bead_halflife_barrier_gate31_iip_0045"
GRAVEYARD_REL = "data/graveyard/idea_graveyard_v0.5.json"
PLAYBOOK_REL = "docs/STAGE-0-EXECUTION-PLAYBOOK.md"

FROZEN_LIMS_SHA256: Dict[str, str] = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
}
EXPECTED_PARETO_SHA256 = "460ebc1939eb98b38627eaa7d6603c086e5a75c127fc1ddeced0d5a325305f40"
EXPECTED_PLAYBOOK_SEC4120_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

ALLOWED_CAO2_ROUTES = frozenset({
    "SUPRAFASCIAL_350UM_CAO2_CATALASE_POUCH",
    "ROUTE_1_CAO2_390UM_EXPANDED_PLANAR_BARRIER",
    "ROUTE_1_CAO2_350UM_COMPRESSED_PLANAR_BARRIER",
})
ALLOWED_CAO2_DESIGNS = frozenset({"A", "X"})
EXCLUDED_NON_CAO2_DESIGNS = frozenset({"B", "Y", "D1", "Z"})

ALLOWED_BARRIER_MODES = frozenset({"PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM"})
FORBIDDEN_BARRIER_MODES = frozenset({
    "PER_BEAD_CONFORMAL_SHELL",
    "HYDROPHOBIC_PDMS_RATE_LIMITING_SHELL",
    "UNCOATED_NO_BARRIER",
})
ALLOWED_SLAB_MODES = frozenset({
    "EXPANDED_390UM_2X125UM_BANDS",
    "FIXED_350UM_2X105UM_BANDS",
})

CONSERVED_CAO2_MG_TARGET = 791.49
CONSERVED_CAO2_MG_MIN = 751.9
CONSERVED_CAO2_MG_MAX = 831.1
Z_95_TWO_SIDED = 1.959963984540054


class StrictJsonError(ValueError):
    """Raised on malformed, duplicate-key, or non-finite JSON input."""


def _reject_nonfinite_constant(tok: str) -> Any:
    raise StrictJsonError(f"Non-finite JSON constant rejected: {tok}")


def _reject_duplicate_keys_pairs_hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
    out: Dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise StrictJsonError(f"Duplicate JSON object key rejected: {k!r}")
        out[k] = v
    return out


def strict_json_loads(raw_text: str) -> Any:
    try:
        return json.loads(
            raw_text,
            parse_constant=_reject_nonfinite_constant,
            object_pairs_hook=_reject_duplicate_keys_pairs_hook,
        )
    except StrictJsonError:
        raise
    except Exception as exc:
        raise StrictJsonError(f"Malformed JSON payload: {exc}") from exc


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


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


def _extract_playbook_sec4120_sha256(repo_root: Path) -> str:
    pb_norm = (repo_root / PLAYBOOK_REL).read_text(encoding="utf-8").replace("\r\n", "\n").replace("\r", "\n")
    start_marker = "#### 4.1.20 Preregistered Autologous `D1b-Auto-C v2`"
    end_marker = "<!-- END_IIP0035_PLAYBOOK_SECTION_4_1_20 -->"
    start_idx = pb_norm.find(start_marker)
    end_idx = pb_norm.find(end_marker, start_idx if start_idx >= 0 else 0)
    if start_idx == -1 or end_idx == -1:
        raise RuntimeError("Playbook §4.1.20 canonical boundaries not found")
    body = pb_norm[start_idx:end_idx].strip()
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def compute_per_bead_shell_unbuildability_ledger() -> Dict[str, Any]:
    """Exact volumetric proof that a 20 um conformal shell on <=50 um beads cannot fit in the lamina."""
    rho_cao2 = 2.91
    rho_pdms = 1.03
    m_cao2_mg = CONSERVED_CAO2_MG_TARGET
    v_cao2_cm3 = (m_cao2_mg / 1000.0) / rho_cao2
    rcp_limit = 0.64

    rows: List[Dict[str, Any]] = []
    for form_id, wt_pct, lam_um, lam_vol_cm3 in (
        ("Layout_B_31p25wt_119um_Lamina", 31.25, 119.0, 2.3800),
        ("Design_X_46p39wt_100um_Lamina", 46.3906, 100.0, 2.0000),
    ):
        m_pdms_mg = m_cao2_mg * (100.0 - wt_pct) / wt_pct
        v_pdms_cm3 = (m_pdms_mg / 1000.0) / rho_pdms
        v_beads_cm3 = v_cao2_cm3 + v_pdms_cm3
        phi_bare = v_beads_cm3 / lam_vol_cm3
        for d_bead in (50.0, 40.0, 30.0):
            d_coated = d_bead + 40.0
            vol_mult = (d_coated / d_bead) ** 3
            v_coated = v_beads_cm3 * vol_mult
            phi_coated = v_coated / lam_vol_cm3
            rows.append({
                "formulation_id": form_id,
                "cao2_wt_pct": wt_pct,
                "lamina_thickness_um": lam_um,
                "lamina_volume_200cm2_cm3": lam_vol_cm3,
                "bare_bead_diameter_um": d_bead,
                "conformal_20um_shell_outer_diameter_um": d_coated,
                "volume_expansion_multiplier": round(vol_mult, 4),
                "bare_beads_volume_cm3": round(v_beads_cm3, 4),
                "bare_beads_lamina_volume_fraction": round(phi_bare, 4),
                "coated_beads_volume_cm3": round(v_coated, 4),
                "coated_beads_lamina_volume_fraction": round(phi_coated, 4),
                "ratio_to_random_close_packing_0p64": round(phi_coated / rcp_limit, 4),
                "physically_buildable_in_lamina": bool(phi_coated <= rcp_limit),
            })