OpenIslet

scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py

OpenIslet Wave-6 Round-14 Prospective Candidate W6-C2 (Staged Slot IIP-0047 -> Provisional

script Release v0.8.0 gen-eb955f8266035aba 466 KB · 37 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_iip0056_route4_omentum_and_exvivo_rest.py · SHA-256: 25e12d578ba80b55…

#!/usr/bin/env python3
"""
OpenIslet Wave-6 Round-14 Prospective Candidate W6-C2 (Staged Slot IIP-0047 -> Provisional
IIP-0056 / DEC-137 / GATE-35 / GY-034; Preserving Live IIP-0047/DEC-127, Live GATE-32/DEC-130
Islet-SHIELD Debris Recall, Live GATE-33/DEC-131 hTMPK/AZT PK, and Live GY-032) Verification Engine
====================================================================================================
Prospective Stage-0 Head-to-Head Visceral R4-Omentum Candidate vs Incumbent Route 3P
(GY-027(1) Clean, Canonical Arm Manifest Enforced, GMP Plasma-Thrombin / Resorbable Fibrin,
40-65 um Sieved Clusters in Staggered Bilayer H=100-120 um with |z_c|>=20 um & Live GY-028
Confocal Wall Clearance H/2 - |z_c| - d_max/2 >= 7.5 um Minimum, Actual Max-Leaf Steric Packing,
Per-Leaf Measured Area/IEQ Reconciliation, Scope-Bound scale_mode, & Matrix Coverage,
Tier-1 [<=1,200 IEQ/cm^2 @ min bilateral bed >=35 mmHg & fibrin <=10 um] UNION
Tier-2 [<=1,500 IEQ/cm^2 @ min bilateral bed >=40 mmHg & fibrin <=12 um],
Lot OCR <=1.097x, Face/Core O2 >=15/5 mmHg; +0.00 pp live odds credit pending Stage-0/1 clearance)
+ Demotion of R4-SARS-Free to Secondary Backup (SubARS Clinical Collapse Proof,
  <=1,200 IEQ/cm^2 planar carrier, Dual-FailSafe Y-v3 / Z-EnSC ONLY; D1b barred)
+ Kill of In-Vivo 72-h Diazoxide Under GY-014 & Salvage as H4-6-ExVivo
  (Primary H4 credit = 0.000 pending paired wet-lab; +1.5 pp sensitivity on all
   eligible non-A arms B/X/Y/D/Z; Design A strictly frozen with zero drugs, zero
   ex-vivo rest, and zero additional biologics beyond pre-existing passive
   CaO2-PDMS + >=20 um planar P04040 catalase hydrogel)
+ External Hash-Verified Wave-6 Master Contract & Canonical Arm Manifest Parity
  (<1e-12 unrounded float64 AND exact 4-decimal display; paired discovery; explicit
   separation of conditional C2-given-C1 +4.4782 pp vs combined C1+C2 +6.4772 pp)
+ Fail-Closed Gate-35 Adjudicator with v2_round5_unified Trusted Upstream (GATE-34, GATE-0V,
  Live Blueprint Section 7 GATE-5 OQ-012) & Current-Assay (GATE-35) Archived Receipts:
  - Collision-free gate sources: upstream W6-C1 MUST be GATE-34 (rejecting live GATE-32
    role collision); current-assay record MUST be GATE-35 (rejecting live GATE-33 collision).
  - Live Blueprint Section 7 Gate 5 OQ-012 exact-Decimal stringency: survivor_count_k == 0
    (ANY k >= 1 -> FAIL), explicit tested_cells_n, clonogenic_fraction_f in (0, 1],
    spike_in_detection_efficiency_eta in [0.30, 1.0] (<0.30 -> FAIL), effective_clonogenic_trials_n_eff
    <= floor(n*f*eta), omitted recovery denominator -> HOLD, k==0 & n_eff < 299,573,228 -> HOLD,
    clinical PASS requires k==0, n_eff >= 299,573,228, and exact 75-digit Decimal U95 <= 1e-8.
  - Decoupled partial-responder post-explant C-peptide extinction (paired pre-explant > LLOQ
    dropping to post-explant <= LLOQ within exact Decimal [0, 14] days) vs full insulin
    independence (residual_exogenous_insulin_u_kg_d == 0).
  - Primary live DEC-009 0-NHP primate-free pathway (porcine R4O-04 + Pillars 1-3) alongside
    conditional FDA CBER INTERACT/Pre-IND exception NHP cohort (fail-closed whenever NHP records supplied).
  - End-to-end exact context-independent Decimal arithmetic across ALL policy thresholds (zero float()).

Strictly READ-ONLY on OpenIslet,
OpenIslet-Website, and shared/.
Zero ast.Assert nodes (100% fail-closed under both -B and -O -B).
Zero wetlab_contract / ingest_wetlab_results imports (Zero-LIMS-Touch).
Zero network calls at runtime.

Run examples:
  PYTHONDONTWRITEBYTECODE=1 python3 -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone --check
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone --check-portable
"""
from __future__ import annotations

import argparse
from decimal import Context, Decimal, DecimalException, InvalidOperation, MAX_EMAX, localcontext
from fractions import Fraction
import hashlib
import json
import math
import re
import sys
import time
import unicodedata
from pathlib import Path
from typing import Any, Callable, Dict, FrozenSet, List, Mapping, Optional, Sequence, Tuple

import numpy as np

sys.dont_write_bytecode = True

SCRIPT_PATH = Path(__file__).resolve()
PKG_ROOT = SCRIPT_PATH.parents[1]
DEFAULT_OUT_PATH = PKG_ROOT / "data" / "extracted" / "iip0056_route4_omentum_and_exvivo_rest_v0.9.0.json"


def resolve_release_relative_contract_path(filename: str) -> Path:
    """Resolve contract/manifest across staged (../shared) and flattened (data/protocols, shared) checkouts."""
    script_dir = Path(__file__).resolve().parent
    pkg_root = script_dir.parent
    candidates = [
        pkg_root.parent / "shared" / filename,
        pkg_root / "data" / "protocols" / filename,
        pkg_root / "shared" / filename,
    ]
    for cand in candidates:
        if cand.is_file():
            return cand
    return candidates[0]


def resolve_paired_contract_paths(
    master_contract_path: Optional[Path] = None,
    manifest_path: Optional[Path] = None,
) -> Tuple[Path, Path]:
    """Resolve paired master-contract & arm-manifest paths fail-closed (Review Shared #4).

    - When master_contract_path is explicitly provided without manifest_path, resolve
      wave6_canonical_arm_manifest.json STRICTLY as its sibling in master_contract_path.parent
      (fail closed if missing; never fall back to stage-relative).
    - When neither is provided, discover wave6_master_contract.json across supported
      release layouts [../shared, data/protocols, shared] and use its sibling manifest.
    - When manifest_path is explicitly provided, honor it as an explicit override.
    """
    if master_contract_path is not None:
        c_path = master_contract_path.expanduser().resolve()
        m_path = (
            manifest_path.expanduser().resolve()
            if manifest_path is not None
            else c_path.parent / "wave6_canonical_arm_manifest.json"
        )
    else:
        c_path = resolve_release_relative_contract_path("wave6_master_contract.json")
        m_path = (
            manifest_path.expanduser().resolve()
            if manifest_path is not None
            else c_path.parent / "wave6_canonical_arm_manifest.json"
        )
    return c_path, m_path


DEFAULT_MASTER_CONTRACT_PATH, DEFAULT_ARM_MANIFEST_PATH = resolve_paired_contract_paths()

SCHEMA_VERSION = "iip0056_route4_omentum_and_exvivo_rest_v0.9.0_r14"
UPSTREAM_RECEIPT_SCHEMA_REVISION = "v2_round5_unified"
STAGED_SLOT_ID = "IIP-0047"
CONTRIBUTION_ID = "IIP-0056"
DECISION_ID = "DEC-137"
GATE_ID = "GATE-35"
UPSTREAM_W6C1_GATE_SOURCE = "GATE-34"
GRAVEYARD_ID = "GY-034"

EXPECTED_CANONICAL_MANIFEST_SHA256 = "0a051b69687bd791feeaf55e97c07d993e27cdd7c453e6e3b67b599d243a4235"
EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256 = "9e84e0b64925f9fdeb9450b364728a4076fa43cf8b46085ba2215722541f0d50"
EXPECTED_MASTER_CONTRACT_FILE_SHA256 = "2108aa272bfe657c2767ba0f10961443fa280d5f074a84d5578d42c204fff35a"
EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256 = "53f90447f1f32213adff883f26d30aa1268f4848e6d3d1d946c03d9c7c8a8b42"
EXPECTED_MASTER_CONTRACT_SHA256 = EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256

MAX_SAFE_INT_ABS = 10 ** 100
MAX_SAFE_FLOAT_ABS = 1e100
MAX_SAFE_DECIMAL_ABS = Decimal("1e100")
MAX_SAFE_DECIMAL_ADJUSTED = 100
MIN_SAFE_DECIMAL_ADJUSTED = -10_000
MIN_GATE5_TESTED_CELLS = 1
MIN_GATE5_EFFECTIVE_TRIALS = 299_573_228
MIN_GATE5_DETECTION_EFFICIENCY_ETA_DEC = Decimal("0.30")
MAX_GATE5_OQ012_U95_DEC = Decimal("1e-8")
MAX_CLONOGENIC_CELLS = 10 ** 12
MIN_GY028_WALL_CLEARANCE_UM_DEC = Decimal("7.5")
MIN_RESIDUAL_SAMPLING_FRACTION = 0.01
SINGLE_LEAF_MAX_TOTAL_IEQ = 100_000.0
ZERO_DEC = Decimal("0")
ONE_DEC = Decimal("1")
MIN_RESIDUAL_SAMPLING_FRACTION_DEC = Decimal("0.01")
SINGLE_LEAF_MAX_TOTAL_IEQ_DEC = Decimal("100000")

# Pinned canonical NW-08 / Layer-4 / IIP-0034 biophysical constants
PINNED_NW08_CONSTANTS: Dict[str, Any] = {
    "alpha_o2_nominal_mol_cm3_mmhg": 1.34e-9,
    "alpha_o2_krbh_mol_cm3_mmhg": 1.27e-9,
    "d_o2_gel_chronic_cm2_s": 1.50e-5,
    "d_o2_gel_acute_cm2_s": 0.940254e-5,
    "d_o2_islet_cm2_s": 1.30e-5,
    "d_o2_fibrin_0p5x_cm2_s": 0.75e-5,
    "vmax_islet_pure_mol_cm3_s": 3.40e-8,
    "km_o2_mmhg": 0.44,
    "po2_gsis_face_floor_mmhg": 15.0,
    "po2_core_floor_mmhg": 5.0,
    "po2_anoxia_floor_mmhg": 0.5,
    "vol_1_ieq_cm3": (4.0 / 3.0) * math.pi * ((75.0e-4) ** 3),
    "ocr_mult_nominal_stimulated": 1.097,
    "ocr_mult_nw08_vasc_stress": 1.097 * 1.20,
    "stromal_ocr_fraction": 0.15,
    "d_insulin_hydrogel_cm2_s": 5.0e-7,
    "d_insulin_free_interstitial_cm2_s": 1.0e-6,
    "insulin_intrinsic_t50_min": 1.75,
    "insulin_target_t50_min": 3.0,
}

# Exact low-D modeled matrix O2 diffusivity floor (SI m^2/s = cm^2/s * 1e-4)
D_O2_LOW_MODELED_CM2_S: float = float(PINNED_NW08_CONSTANTS["d_o2_gel_acute_cm2_s"])
D_O2_LOW_MODELED_M2_S: float = D_O2_LOW_MODELED_CM2_S * 1e-4  # 9.40254e-10 m^2/s
D_O2_MAX_AQUEOUS_M2_S: float = 3.5e-9  # physical upper bound (pure water O2 at 37 C ~2.5-3.0e-9 m^2/s)
D_O2_LOW_MODELED_M2_S_DEC: Decimal = Decimal("9.40254e-10")
D_O2_MAX_AQUEOUS_M2_S_DEC: Decimal = Decimal("3.5e-9")

# Pinned canonical IIP-0034 Route 3P 3D FVM references (nx=28, nz=32)
PINNED_IIP0034_REFS: Dict[str, float] = {
    "Hybrid333_H180_Day0_Clean_65um_PASS": 20.1252,
    "Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL": 14.7151,
    "Hybrid333_H180_Day0_15umFibrin_0p5D_65um": 12.0792,
    "Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_Alpha1p27e9_FACE_FAIL": 14.4198,
}

# Live-verified PMID registry for IIP-0047
VERIFIED_PMIDS: List[str] = [
    "9535004",   # Grimmsmann & Rustenbeck 1998 Br J Pharmacol (DZ Complex II -29% ATP @ 500 uM, 1 datum)
    "17130499",  # Sweet & Gilbert 2006 Diabetes (Ca2+ influx / diazoxide -30% OCR in rat islets)
    "17503968",  # MacDonald et al. 2007 PLoS Biol (alpha-cell glucagon suppression >=30 uM DZ)
    "19276268",  # Verbrugge et al. 2009 Clin Cancer Res (APO010 hexameric FasL hepatotoxicity)
    "20541525",  # Lee et al. 2010 BBRC (TUDCA porcine islet chemical chaperone)
    "21054943",  # Svensson et al. 2011 Cell Transplant (striated muscle hypoxia/fibrosis vs renal)
    "21183510",  # Eisele et al. 2011 Neuro Oncol (APO010 FasL systemic window)
    "23935835",  # Ma et al. 2013 PLoS One (rat 22 h necrosis/OCR & hypoxia-associated apoptosis not reversed by DZ; human pilot 22 h/325 uM; human xenograft 48 h/325 uM 14 d mice)
    "24225943",  # Engin et al. 2013 Sci Transl Med (mouse TUDCA UPR restoration; author-spelling correction notice)
    "25194818",  # Lyon et al. 2014 Nat Biotechnol (maleimide retro-Michael plasma shedding)
    "28489987",  # Baidal et al. 2017 NEJM (N=1 omentum plasma-thrombin case report, NCT02213003)
    "29789532",  # Bruni et al. 2018 Cell Death Dis (Fer-1 tool compound, zero human IND)
    "32433410",  # Wang Y et al. 2020 Pancreas (8 h / 150 uM DZ whole NHP pancreas preservation -> diabetic mouse efficacy)
    "34735732",  # Van Hulle et al. 2022 AJT (N=7 omentum biopsy: ductal impurity + polyglactin FBR)
    "35227510",  # Saudek et al. 2022 Transplant Proc (N=2 omentum plasma-fibrin low 1-yr C-pep)
    "35241836",  # Balboa et al. 2022 Nat Biotechnol (SC-islet mitochondrial/KATP maturation gap)
    "35559682",  # Lei et al. 2022 Sci Adv (NHP omentum SA-FasL microgels comparator)
    "35676866",  # Verhoeff et al. 2022 Transplantation (N=264: 9 extrahepatic [4 om/3 subQ/2 gas], 1-3 mo pooled stimulated C-pep 0.05 vs 1.2 nmol/L)
    "36624157",  # Liang et al. 2023 Nat Metab (n=4 diabetic NHPs sub-ARS within n=8 total under xenogeneic IS)
    "36863336",  # Deng H et al. 2023 Cell Rep Med (n=3 NHP omentum: insulin through Day 28, 2/3 sustained II under IS)
    "38321214",  # Hu et al. 2024 Cell Death Differ (ISRIB tool compound, zero human IND)
    "38848367",  # Burke et al. 2024 Sci Adv (separate 4-animal PPCN-only ~20% visual residual @ 3 mo vs 2 partial-pancreatectomy+ablation autologous graft NHPs, 0/2 II)
    "39326417",  # Wang et al. 2024 Cell (N=1 sub-ARS CiPSC: 1.49M IEQ + chronic tacrolimus)
    "40544428",  # Reichman et al. 2025 NEJM (zimislecel intraportal benchmark under systemic IS)
]

_SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
_CANONICAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")
_STRICT_DECIMAL_STR_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")


# =============================================================================
# 0. Fail-Closed Helpers & Strict Duplicate-Key / Finite JSON Parsing
# =============================================================================
def require_cond(cond: bool, message: str) -> None:
    if not cond:
        raise RuntimeError(message)


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def load_strict_json_text(text: str, source_name: str = "input") -> Any:
    """Fail-closed JSON parser rejecting duplicate keys & non-finite constants and preserving exact lexical
    decimal tokens via parse_float=Decimal (NEVER rounding through IEEE-754 float64; Audit R9-06).
    """
    def _no_dup_pairs(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
        out: Dict[str, Any] = {}
        for k, v in pairs:
            if k in out:
                raise ValueError(f"Duplicate JSON key {k!r} rejected (fail-closed) in {source_name}")