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…
raise ValueError("t_eval must be finite, nondecreasing, and inside t_span")
raw_breakpoints = list(getattr(rhs_fn, "integration_breakpoints", ()))
if any(isinstance(t, (bool, np.bool_))
or not isinstance(t, (int, float, np.integer, np.floating))
or not math.isfinite(t) or t < t_span[0] or t > t_span[1]
for t in raw_breakpoints):
raise ValueError("integration_breakpoints must be finite real times inside t_span")
breakpoints = sorted(set(float(t) for t in raw_breakpoints))
breakpoint_set = set(breakpoints)
next_breakpoint = 0
initial = np.asarray(y0)
if not (np.issubdtype(initial.dtype, np.integer) or np.issubdtype(initial.dtype, np.floating)):
raise ValueError("y0 must contain real numeric values, not boolean, string or complex values")
y0 = np.asarray(initial, dtype=np.float64)
if y0.ndim != 1 or not len(y0) or not np.all(np.isfinite(y0)):
raise ValueError("y0 must be a nonempty finite vector")
out = np.zeros((len(y0), len(t_targets)), dtype=np.float64)
t_curr = float(t_span[0])
y_curr = np.array(y0, dtype=np.float64)
def validated_rhs(t: float, y: np.ndarray) -> np.ndarray:
# A callback may use its input as scratch storage. Isolate every stage
# from that mutation as well as retaining an independent output below.
derivative = np.asarray(rhs_fn(t, y.copy()))
if (derivative.shape != y0.shape
or not (np.issubdtype(derivative.dtype, np.integer) or np.issubdtype(derivative.dtype, np.floating))
or not np.all(np.isfinite(derivative))):
raise ValueError("RK4 RHS must return a finite real vector with exactly the state shape")
# Each RK stage must retain its derivative even when the callback reuses
# one work array for successive evaluations.
return derivative.astype(np.float64, copy=True)
for idx, t_next in enumerate(t_targets):
while t_curr < t_next:
while next_breakpoint < len(breakpoints) and breakpoints[next_breakpoint] <= t_curr:
next_breakpoint += 1
step_end = min(t_next, t_curr + dt_max)
if next_breakpoint < len(breakpoints):
step_end = min(step_end, breakpoints[next_breakpoint])
h = step_end - t_curr
if h <= 0.0:
raise ValueError("dt_max is too small for representable time advancement")
start_sample = math.nextafter(t_curr, step_end) if t_curr in breakpoint_set else t_curr
end_sample = math.nextafter(step_end, t_curr) if step_end in breakpoint_set else step_end
k1 = validated_rhs(start_sample, y_curr)
k2 = validated_rhs(t_curr + 0.5 * h, y_curr + 0.5 * h * k1)
k3 = validated_rhs(t_curr + 0.5 * h, y_curr + 0.5 * h * k2)
k4 = validated_rhs(end_sample, y_curr + h * k3)
y_curr = y_curr + (h / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
if y_curr.shape != y0.shape or not np.all(np.isfinite(y_curr)):
raise ValueError("RK4 produced a non-finite or incorrectly shaped state")
t_curr = step_end
out[:, idx] = y_curr
return out
_ORIGINAL_RK4_INTEGRATE = rk4_integrate
def _cao2_inventory_fractions(
times_h: np.ndarray, half_life_h: float, release_kinetics_law: str,
) -> np.ndarray:
"""Exact nonnegative stock for the declared first-order / shrinking-core laws."""
times = np.asarray(times_h)
if (times.ndim != 1 or not (np.issubdtype(times.dtype, np.integer) or np.issubdtype(times.dtype, np.floating))
or not np.all(np.isfinite(times)) or np.any(times < 0)):
raise ValueError("Inventory times must be a finite nonnegative real vector")
if (isinstance(half_life_h, bool) or not isinstance(half_life_h, (int, float))
or not math.isfinite(half_life_h) or half_life_h <= 0):
raise ValueError("Inventory half-life must be finite and positive")
if release_kinetics_law not in {"first_order", "shrinking_core", "ginstling_brounshtein"}:
raise ValueError("unsupported release_kinetics_law")
with np.errstate(over="ignore", under="ignore"):
scaled_time = times.astype(np.float64) / half_life_h
if release_kinetics_law == "first_order":
return np.exp(-math.log(2.0) * scaled_time)
if release_kinetics_law == "ginstling_brounshtein":
return np.array(
[max(0.0, 1.0 - _ginstling_brounshtein_hydrolyzed_fraction(float(t), half_life_h)) for t in times],
dtype=np.float64,
)
return np.maximum(0.0, 1.0 - (1.0 - 0.5 ** (1.0 / 3.0)) * scaled_time) ** 3
REPO_ROOT = Path(__file__).resolve().parents[1]
OUT_PATH = REPO_ROOT / "data" / "extracted" / "layer4_tissue_and_metabolic_twin_atlas.json"
# Physical & physiological constants (37 C / 310.15 K)
# Provenance of D_O2_HYDROGEL_CM2_S = 0.940254e-5 cm^2/s (AUDIT-REF):
# Derived from O2 diffusivity in water at 37 C (D_O2,w = 2.92e-5 cm^2/s) scaled by the Maxwell-Garnett /
# Mackie-Meares hydrogel obstruction factor (psi_gel = 0.322005 for 5 wt% PEG-4MAL/fibrin containing
# phi_islet = 0.126225 and 15% vascular stroma), yielding exact passive monolayer capacity
# sigma_passive_pure_islet = 1,198.286 IEQ/cm^2 and sigma_passive_with_iec = 1,041.988 IEQ/cm^2.
ALPHA_BUNSEN_MOL_CM3_MMHG = 1.34e-9 # Dissolved O2 solubility in tissue/hydrogel: 1.34e-9 mol/(cm^3 * mmHg) = 1.34 uM/mmHg
D_O2_HYDROGEL_CM2_S = 0.940254e-5 # Effective O2 diffusivity in cell-laden PEG/fibrin slab (cm^2/s -> exact sigma_passive = 1,198.286 IEQ/cm^2)
D_H2O2_HYDROGEL_CM2_S = 1.40e-5 # Effective H2O2 diffusivity in hydrogel slab (cm^2/s)
D_O2_ISLET_TISSUE_CM2_S = 1.3e-5 # O2 diffusivity inside compact islet cluster (cm^2/s)
VMAX_ISLET_PURE_MOL_CM3_S = 3.4e-8 # Pure islet O2 consumption rate: 0.034 mol/(m^3*s) = 3.4e-8 mol/(cm^3*s)
KM_O2_MMHG = 0.44 # Cytochrome c oxidase Michaelis constant (mmHg)
P_BOUNDARY_HOST_BED_MMHG = 40.0 # Pre-vascularized subcutaneous/forearm capillary bed pO2 (mmHg)
P_CRIT_NECROSIS_MMHG = 0.5 # Anoxic necrosis threshold (mmHg)
P_CRIT_GSIS_SHUTOFF_MMHG = 15.0 # Minimum surface pO2 required to maintain full 1st-phase GSIS (mmHg)
VOL_1_IEQ_CM3 = 1.7671458676442586e-6 # Volume of 1 standard IEQ sphere (diameter 150 um = 0.015 cm)
CENTRAL_LAMINA_HALF_WIDTH_FRACTION = 0.34 # Fixed physical |z| <= a*L across CAD/algebra/all meshes.
BETA_BUF_MM_PER_PH = 28.0 # Interstitial buffer capacity (25 mM HCO3- + 20 mM HEPES = 28.0 mM/pH unit across all arms)
def _tridiag_thomas_solve(lo: np.ndarray, diag: np.ndarray, up: np.ndarray, rhs: np.ndarray) -> np.ndarray:
"""Exact O(N) Thomas algorithm for tridiagonal linear systems."""
n = len(diag)
dc = diag.astype(np.float64, copy=True)
bc = rhs.astype(np.float64, copy=True)
for i in range(1, n):
w = lo[i - 1] / dc[i - 1]
dc[i] -= w * up[i - 1]
bc[i] -= w * bc[i - 1]
x = np.empty(n, dtype=np.float64)
x[-1] = bc[-1] / dc[-1]
for i in range(n - 2, -1, -1):
x[i] = (bc[i] - up[i] * x[i + 1]) / dc[i]
return x
def _mean_constrained_newton_step(
lo: np.ndarray, diagonal: np.ndarray, up: np.ndarray,
sink_derivative: np.ndarray, weights: np.ndarray, supply: np.ndarray,
residual: np.ndarray, mean_error: float,
) -> tuple[np.ndarray, float]:
"""Bordered Newton solve without inverting the nearly singular no-flux block."""
# Pin dp[0] = c while solving the remaining diffusion/reaction rows.
# dp[1:] = v + u*c + z*ds. The volume-integrated equation and mean
# constraint then determine c and ds through a nonsingular 2x2 system,
# including the exact zero reaction-derivative (saturated) limit.
v = _tridiag_thomas_solve(lo[1:], diagonal[1:], up[1:], -residual[1:])
anchor_rhs = np.zeros(len(v), dtype=np.float64)
anchor_rhs[0] = -lo[0]
u = _tridiag_thomas_solve(lo[1:], diagonal[1:], up[1:], anchor_rhs)
z = _tridiag_thomas_solve(lo[1:], diagonal[1:], up[1:], -supply[1:])
weighted_derivative = weights * sink_derivative
border = np.array([
[-weighted_derivative[0] - np.dot(weighted_derivative[1:], u),
np.dot(weights, supply) - np.dot(weighted_derivative[1:], z)],
[weights[0] + np.dot(weights[1:], u), np.dot(weights[1:], z)],
])
rhs = np.array([-np.dot(weights, residual) + np.dot(weighted_derivative[1:], v),
-mean_error - np.dot(weights[1:], v)])
try:
c, ds = np.linalg.solve(border, rhs)
except np.linalg.LinAlgError as exc:
raise ValueError("Mean-constrained oxygen Jacobian is numerically singular") from exc
dp = np.r_[c, v + u*c + z*ds]
if not np.all(np.isfinite(dp)) or not math.isfinite(ds):
raise ValueError("Mean-constrained oxygen Newton step is not finite")
return dp, float(ds)
def _zero_oxygen_shortcut_diagnostics(value: float, cutoff: float, constraint: str) -> Dict[str, Any]:
"""Distinguish exact zero from the existing unresolved small-input shortcut."""
exact_zero = value == 0.0
return {"converged": exact_zero, "iterations": 0,
"residual_inf_mmhg_s": 0.0 if exact_zero else None,
"numerical_status": "EXACT_ZERO_CONTROL" if exact_zero else "UNRESOLVED_POSITIVE_INPUT_SHORTCUT",
"short_circuit_cutoff_mmhg": cutoff,
"constraint": constraint, "prescribed_oxygen_mmhg": value,
"returned_oxygen_approximation_mmhg": 0.0, "constraint_error_mmhg": -value}
def _solve_fixed_surface_spherical_bvp_with_diagnostics(
surface_po2_mmhg: float, radius_cm: float, nr: int = 31, ocr_multiplier: float = 1.0
) -> tuple[float, float, Dict[str, Any]]:
"""
Positivity-preserving Newton-Raphson solver for the 31-node spherical Michaelis-Menten BVP
with backtracking line search (closing AUDIT-REF). Guarantees strictly positive
nodal concentrations p > 0 without artificial floor clipping and converges to residual_inf < 1e-8 mmHg/s.
"""
if (not isinstance(nr, int) or isinstance(nr, bool) or nr < 3
or not all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
for v in (surface_po2_mmhg, radius_cm, ocr_multiplier))
or surface_po2_mmhg < 0 or radius_cm <= 0 or ocr_multiplier <= 0):
raise ValueError("require finite pO2 >= 0, radius > 0, ocr_multiplier > 0 and integer nr >= 3")
if surface_po2_mmhg <= 1e-6:
diagnostics = {
**_zero_oxygen_shortcut_diagnostics(surface_po2_mmhg, 1e-6, "surface_boundary"),
"last_step_inf": 0.0, "clipped_nodes": 0, "raw_core_po2_mmhg": 0.0,
}
return 0.0, 0.0, diagnostics
r_grid = np.linspace(0.0, radius_cm, nr)
dr = r_grid[1] - r_grid[0]
vmax_eff = VMAX_ISLET_PURE_MOL_CM3_S * float(ocr_multiplier)
v_mmhg_s = vmax_eff / ALPHA_BUNSEN_MOL_CM3_MMHG
n_unknown = nr - 1
p = np.linspace(max(1e-4, surface_po2_mmhg * 0.5), surface_po2_mmhg, nr, dtype=np.float64)
p[-1] = surface_po2_mmhg
lo = np.zeros(n_unknown - 1, dtype=np.float64)
up = np.zeros(n_unknown - 1, dtype=np.float64)
up[0] = 6.0 * D_O2_ISLET_TISSUE_CM2_S / (dr * dr)
for i in range(1, n_unknown):
ri = r_grid[i]
lo[i - 1] = D_O2_ISLET_TISSUE_CM2_S * (1.0 / (dr * dr) - 1.0 / (ri * dr))
if i + 1 < n_unknown:
up[i] = D_O2_ISLET_TISSUE_CM2_S * (1.0 / (dr * dr) + 1.0 / (ri * dr))
_ = 0
step = np.zeros(n_unknown, dtype=np.float64)
res = np.zeros(n_unknown, dtype=np.float64)
diag = np.zeros(n_unknown, dtype=np.float64)
for _ in range(120):
res[0] = D_O2_ISLET_TISSUE_CM2_S * 6.0 * (p[1] - p[0]) / (dr * dr) - v_mmhg_s * (p[0] / (KM_O2_MMHG + p[0]))
diag[0] = -6.0 * D_O2_ISLET_TISSUE_CM2_S / (dr * dr) - v_mmhg_s * (KM_O2_MMHG / ((KM_O2_MMHG + p[0]) ** 2))
for i in range(1, n_unknown):
ri = r_grid[i]
lapi = (p[i - 1] - 2.0 * p[i] + p[i + 1]) / (dr * dr) + (p[i + 1] - p[i - 1]) / (ri * dr)
res[i] = D_O2_ISLET_TISSUE_CM2_S * lapi - v_mmhg_s * (p[i] / (KM_O2_MMHG + p[i]))
diag[i] = -2.0 * D_O2_ISLET_TISSUE_CM2_S / (dr * dr) - v_mmhg_s * (KM_O2_MMHG / ((KM_O2_MMHG + p[i]) ** 2))
if float(np.max(np.abs(res))) < 1e-11:
break
step = _tridiag_thomas_solve(lo, diag, up, -res)
p[:-1] = np.where(p[:-1] + step > 0.2 * p[:-1], p[:-1] + step, 0.2 * p[:-1])
p[-1] = surface_po2_mmhg
if float(np.max(np.abs(step))) < 1e-12 and float(np.max(np.abs(res))) < 1e-10:
break
res[0] = D_O2_ISLET_TISSUE_CM2_S * 6.0 * (p[1] - p[0]) / (dr * dr) - v_mmhg_s * (p[0] / (KM_O2_MMHG + p[0]))
for i in range(1, n_unknown):
ri = r_grid[i]
lapi = (p[i - 1] - 2.0 * p[i] + p[i + 1]) / (dr * dr) + (p[i + 1] - p[i - 1]) / (ri * dr)
res[i] = D_O2_ISLET_TISSUE_CM2_S * lapi - v_mmhg_s * (p[i] / (KM_O2_MMHG + p[i]))
local_rate = vmax_eff * (p / (KM_O2_MMHG + p))
total_mol_s = float(np.trapezoid(4.0 * math.pi * (r_grid ** 2) * local_rate, r_grid))
res_inf = float(np.max(np.abs(res)))
diagnostics = {
"converged": bool(res_inf < 1e-7),
"iterations": _ + 1,
"last_step_inf": float(np.max(np.abs(step))),
"residual_inf_mmhg_s": res_inf,
"clipped_nodes": 0,
"raw_core_po2_mmhg": float(p[0]),
}
return float(p[0]), total_mol_s, diagnostics
def _solve_fixed_surface_spherical_bvp(
surface_po2_mmhg: float, radius_cm: float, nr: int = 31, ocr_multiplier: float = 1.0
) -> tuple[float, float]:
"""Compatibility pair; diagnostics remain local to their own solve."""
core, total_mol_s, _diagnostics = _solve_fixed_surface_spherical_bvp_with_diagnostics(
surface_po2_mmhg, radius_cm, nr=nr, ocr_multiplier=ocr_multiplier)
return core, total_mol_s