scripts/run_layer4_tissue_and_metabolic_twin.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer4_tissue_and_metabolic_twin.py · SHA-256: 624a491d5e418a7d…
#!/usr/bin/env python3
"""
Layer 4: Multi-Scale Tissue, Vascular & Metabolic Digital Twin Plane (v0.8.0)
=============================================================================
True numerical differential-equation solver (`numpy` 4th-order Runge-Kutta +
51-node finite-difference Newton-Raphson BVP, zero lookup tables) modeling
two coupled physiological scales:
Part A — 336-Hour (14-Day) Spatial Reaction-Diffusion PDE Solver (`350 um` Pouch
Slab & `120 um` [`R = 60 um`] Clusters):
Solves coupled partial differential equations across spatial depth z in [-L, +L]
(2L = 350 um, N_z = 51 finite-difference nodes) and time t in [0, 336 h]:
1. Dissolved oxygen pO2(z, t) with Michaelis-Menten islet + iEC/pericyte
consumption, Fickian diffusion, PDMS-CaO2 slow-release hydrolysis source,
and sigmoidal iEC microvessel anastomosis (t_50 = 36.0 h nominal in 14-day
pre-vascularized bed; t_50 = 60.0 h evaluated in sensitivity analysis).
2. Exact boundary-value verification of central-core vs uniform PDMS-CaO2
source fractions (`f_chem_uniform = 1 - sigma_passive / sigma` vs
`f_chem_central = 1 - sqrt(sigma_passive / sigma)`, closing V70-12 & R05),
plus explicit reconciliation of `f_chem_initial` (0.45), `f_chem_72h_integrated`
(0.3188), and `f_chem_total_inventory` (0.6131) (closing AUDIT-REF).
3. Spatial 51-node H2O2(z, t) reaction-diffusion BVP (`CaO2 + 2 H2O -> Ca(OH)2 + H2O2`),
co-formulated Catalase enzymatic clearance (`2 H2O2 -> 2 H2O + O2`), and
interstitial pH buffering (`25 mM HCO3-` + `20 mM HEPES`, `beta_buf = 28.0 mM/pH`
held strictly identical across catalase-positive and catalase-negative arms,
closing AUDIT-REF & R06).
4. Intra-cluster nonlinear spherical Michaelis-Menten radial BVP solver inside
`120 um` (`R = 60 um`) vs `300 um` (`R = 150 um`) spheroids driven by the
slab's minimum boundary pO2 (closing AUDIT-REF).
Part B — 24-Hour `UVA/Padova`-Style Coupled Beta/Alpha/Delta Paracrine & Whole-Body
Glucose-Insulin-Glucagon-Somatostatin ODE Simulator:
Integrates a coupled nonlinear ODE system (`rk4_integrate`, dt=0.25 min)
across 1,440 minutes (3 meals + 60-min afternoon aerobic exercise + overnight fast)
with identical peripheral insulin-action clearance (`p2 = 0.035 min^-1`) across all
arms and trajectory-derived post-glucose-drop insulin shut-off half-time `t_50`
(closing AUDIT-REF):
1. `OpenIslet_60_30_10_TriHormonal_G6PC2_WT` (60% beta : 30% alpha : 10% delta,
UCN3 -> delta SST feedback + alpha GCG counter-regulation + WT G6PC2 rheostat).
2. `Beta_Only_Monoculture_Graft` (95% beta, lacking UCN3 -> delta SST brake and
alpha GCG counter-regulation; cites PMID:39169271 as in-vivo mouse glycemic control and in-vitro human pseudoislet GSIS counter-evidence).
3. `G6PC2_KO_Disrupted_Rheostat_Graft` (G6PC2-/- left-shifted K_0.5 = 4.3 mM,
testing Graveyard Rule GY-002).
Outputs:
- data/extracted/layer4_tissue_and_metabolic_twin_atlas.json
"""
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
from typing import Any, Dict, List
import numpy as np
def _strict_numeric_float_iip0024(val: object, name: str) -> float:
if isinstance(val, (bool, np.bool_)) or not isinstance(val, (int, float, np.integer, np.floating)):
raise ValueError(f"{name} must be a strict numeric int/float (not bool/str), got {val!r} (IIP-0024; DEC-103)")
fv = float(val)
if not math.isfinite(fv):
raise ValueError(f"{name} must be finite (not NaN/Inf), got {val!r} (IIP-0024; DEC-103)")
return fv
def _segment_duration_below_iip0024(dt: float, g0: float, g1: float, thresh: float) -> float:
if g0 < thresh and g1 < thresh:
return dt
if g0 >= thresh and g1 >= thresh:
return 0.0
if g0 < thresh and g1 >= thresh:
return dt * ((thresh - g0) / (g1 - g0))
return dt * ((thresh - g1) / (g0 - g1))
def _segment_duration_in_closed_band_iip0024(dt: float, g0: float, g1: float, lo: float, hi: float) -> float:
if abs(g1 - g0) <= 1e-15:
return dt if (lo <= g0 <= hi) else 0.0
dg = g1 - g0
s_lo = (lo - g0) / dg
s_hi = (hi - g0) / dg
s_min = max(0.0, min(s_lo, s_hi))
s_max = min(1.0, max(s_lo, s_hi))
return dt * max(0.0, s_max - s_min)
def _segment_duration_above_iip0024(dt: float, g0: float, g1: float, threshold: float) -> float:
"""Exact linear-interpolation duration spent strictly above `threshold` on [0, dt] (BPR-11 / DEC-133)."""
if g0 > threshold and g1 > threshold:
return dt
if g0 <= threshold and g1 <= threshold:
return 0.0
if abs(g1 - g0) <= 1e-15:
return dt if g0 > threshold else 0.0
s_cross = (threshold - g0) / (g1 - g0)
s_cross = max(0.0, min(1.0, s_cross))
return dt * (s_cross if g0 > threshold else (1.0 - s_cross))
def compute_exact_elapsed_glycemic_metrics_iip_0024(
times_min: Any,
glucose_mM: Any,
*,
min_duration_min: float = 1440.0,
min_points: int = 289,
max_interval_gap_min: float = 15.0,
) -> Dict[str, Any]:
"""
Exact continuous linear-crossing elapsed-duration glycaemic classifier (Battelino et al. 2019
PMID:31177185; IIP-0024; DEC-103):
- Rejects raw summary dicts, strings, booleans, NaN/Inf, or non-positive glucose.
- Enforces >= min_points (default 289 -> <=5-min 24-h cadence), strictly increasing timestamps
(0 < dt <= max_interval_gap_min, default 15.0 min), and elapsed span >= min_duration_min (1440.0 min).
- Computes exact linear threshold-crossing elapsed duration for TBR < 3.9 mM, severe TBR < 3.0 mM,
and TIR [3.9, 10.0] mM, comparing unrounded thresholds (< 4.0%, < 1.0% fragile, == 0.0% < 3.0 mM).
"""
if not isinstance(times_min, (list, tuple, np.ndarray)) or not isinstance(glucose_mM, (list, tuple, np.ndarray)):
raise ValueError("times_min and glucose_mM must be explicit numeric sequence trajectories (IIP-0024; DEC-103)")
if isinstance(times_min, np.ndarray) and times_min.ndim != 1:
raise ValueError("times_min ndarray must be 1-dimensional (IIP-0024; DEC-103)")
if isinstance(glucose_mM, np.ndarray) and glucose_mM.ndim != 1:
raise ValueError("glucose_mM ndarray must be 1-dimensional (IIP-0024; DEC-103)")
if len(times_min) != len(glucose_mM):
raise ValueError(f"Trajectory length mismatch: len(times_min)={len(times_min)} != len(glucose_mM)={len(glucose_mM)} (IIP-0024; DEC-103)")
if len(times_min) < min_points:
raise ValueError(f"Trajectory has {len(times_min)} points; requires >= {min_points} points (IIP-0024; DEC-103)")
max_gap = _strict_numeric_float_iip0024(max_interval_gap_min, "max_interval_gap_min")
if max_gap <= 0.0:
raise ValueError("max_interval_gap_min must be > 0 (IIP-0024; DEC-103)")
t_vals = [_strict_numeric_float_iip0024(v, f"times_min[{i}]") for i, v in enumerate(times_min)]
g_vals = [_strict_numeric_float_iip0024(v, f"glucose_mM[{i}]") for i, v in enumerate(glucose_mM)]
for i, gv in enumerate(g_vals):
if gv <= 0.0:
raise ValueError(f"glucose_mM[{i}]={gv} must be > 0.0 mM (IIP-0024; DEC-103)")
total_dt = 0.0
max_obs_dt = 0.0
below_3p9 = 0.0
below_3p0 = 0.0
in_band = 0.0
above_10p0 = 0.0
above_13p9 = 0.0
for i in range(len(t_vals) - 1):
dt = t_vals[i + 1] - t_vals[i]
if dt <= 0.0:
raise ValueError(f"Non-monotonic timestamp step at interval {i}: {t_vals[i]} -> {t_vals[i + 1]} (IIP-0024; DEC-103)")
if dt > max_gap + 1e-12:
raise ValueError(f"Timestamp interval gap {dt} min exceeds max_interval_gap_min={max_gap} min at interval {i} (IIP-0024; DEC-103)")
if dt > max_obs_dt:
max_obs_dt = dt
g0, g1 = g_vals[i], g_vals[i + 1]
total_dt += dt
below_3p9 += _segment_duration_below_iip0024(dt, g0, g1, 3.9)
below_3p0 += _segment_duration_below_iip0024(dt, g0, g1, 3.0)
in_band += _segment_duration_in_closed_band_iip0024(dt, g0, g1, 3.9, 10.0)
above_10p0 += _segment_duration_above_iip0024(dt, g0, g1, 10.0)
above_13p9 += _segment_duration_above_iip0024(dt, g0, g1, 13.9)
if total_dt + 1e-9 < min_duration_min:
raise ValueError(f"Elapsed trajectory span {total_dt:.6f} min < required {min_duration_min:.1f} min (IIP-0024; DEC-103)")
tbr39_pct = 100.0 * below_3p9 / total_dt
tbr30_pct = 100.0 * below_3p0 / total_dt
tir_pct = 100.0 * in_band / total_dt
tar10_pct = 100.0 * above_10p0 / total_dt
tar139_pct = 100.0 * above_13p9 / total_dt
sample_tbr39_pct = 100.0 * sum(1 for gv in g_vals if gv < 3.9) / float(len(g_vals))
nadir_mM = min(g_vals)
peak_mM = max(g_vals)
passes_layer4_model_gate = bool(
tir_pct >= 85.0 and tbr39_pct < 4.0 and tbr30_pct == 0.0 and nadir_mM >= 3.5
)
# BPR-11 / DEC-133: full adult international CGM consensus (Battelino et al. 2019 PMID:31177185 Table 3):
# TIR [3.9, 10.0] >= 70%, TBR < 3.9 < 4%, Level-2 TBR < 3.0 < 1%, TAR > 10.0 < 25%, Level-2 TAR > 13.9 < 5%.
passes_adult_consensus_full = bool(
tir_pct >= 70.0
and tbr39_pct < 4.0
and tbr30_pct < 1.0
and tar10_pct < 25.0
and tar139_pct < 5.0
)
passes_adult_consensus_tir_and_low_time_only_partial = bool(
tir_pct >= 70.0 and tbr39_pct < 4.0 and tbr30_pct == 0.0 and nadir_mM >= 3.0
)
passes_fragile_tbr_lt_1pct = bool(
tbr39_pct < 1.0 and tbr30_pct == 0.0 and nadir_mM >= 3.5
)
return {
"n_points": len(t_vals),
"n_intervals": len(t_vals) - 1,
"elapsed_duration_min": round(total_dt, 9),
"max_interval_gap_min": round(max_obs_dt, 9),
"tir_3p9_10p0_pct": round(tir_pct, 6),
"tbr_lt_3p9_pct": round(tbr39_pct, 6),
"tbr_lt_3p0_pct": round(tbr30_pct, 6),
"level2_biochemical_hypoglycemia_lt_3p0_pct": round(tbr30_pct, 6),
"tar_gt_10p0_pct": round(tar10_pct, 6),
"tar_gt_13p9_pct": round(tar139_pct, 6),
"sample_fraction_lt_3p9_pct": round(sample_tbr39_pct, 6),
"tbr39_elapsed_unrounded_pct": tbr39_pct,
"tbr30_elapsed_unrounded_pct": tbr30_pct,
"tir_elapsed_unrounded_pct": tir_pct,
"tar10_elapsed_unrounded_pct": tar10_pct,
"tar139_elapsed_unrounded_pct": tar139_pct,
"nadir_mM": round(nadir_mM, 6),
"peak_mM": round(peak_mM, 6),
"passes_layer4_model_gate": passes_layer4_model_gate,
"passes_adult_consensus_context": passes_adult_consensus_full,
"passes_adult_consensus_full_tir_tbr_tar": passes_adult_consensus_full,
"passes_adult_consensus_tir_and_low_time_only_partial": passes_adult_consensus_tir_and_low_time_only_partial,
"passes_fragile_tbr_lt_1pct": passes_fragile_tbr_lt_1pct,
"hypoglycemia_terminology_note_bpr11": (
"tbr_lt_3p0_pct (<3.0 mmol/L / 54 mg/dL) measures Level-2 biochemical hypoglycemia, NOT Level-3 severe hypoglycemia "
"(which is defined clinically by requiring external assistance regardless of glucose reading)."
),
}
def rk4_integrate(
rhs_fn,
t_span: tuple[float, float],
y0: np.ndarray,
t_eval: List[float] | np.ndarray,
dt_max: float = 0.25,
) -> np.ndarray:
"""
Pure-NumPy 4th-order Runge-Kutta (RK4) differential equation integrator with sub-stepping
(dt <= dt_max), ensuring zero external dependencies beyond NumPy so `/usr/bin/python3`
executes deterministically in any audit environment.
A callback may declare ``integration_breakpoints``. Steps stop exactly at
those known changes, using the right-hand RHS at an interval's start and
the left-hand RHS at its end. Endpoint values of a jump have zero measure;
ordinary RK4 endpoint samples would otherwise add spurious exposure.
"""
if isinstance(dt_max, bool) or not isinstance(dt_max, (int, float)) or not math.isfinite(dt_max) or dt_max <= 0:
raise ValueError("dt_max must be finite and positive")
if len(t_span) != 2 or not all(isinstance(t, (int, float)) and not isinstance(t, bool) and math.isfinite(t) for t in t_span):
raise ValueError("t_span must contain two finite numeric times")
if t_span[1] < t_span[0]:
raise ValueError("t_span must be nondecreasing")
raw_targets = list(t_eval)
if any(isinstance(t, (bool, np.bool_)) or not isinstance(t, (int, float, np.integer, np.floating)) for t in raw_targets):
raise ValueError("t_eval must contain real numeric times, not boolean or string values")
t_targets = [float(t) for t in raw_targets]
if any(not math.isfinite(t) or t < t_span[0] or t > t_span[1] for t in t_targets) or any(b < a for a, b in zip(t_targets, t_targets[1:])):