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…
"status": "TAIL_WINDOW_BOUNDED_FOR_SHAPE_EVALUATION",
"tail_bounded": True,
"observation_window_min": round(obs_window, 6),
"remaining_fraction_at_end": round(end_remaining, 6),
"mass_recovery_fraction": float(mass_recovery_fraction),
"reasons": [],
}
def evaluate_whole_device_washout_gate_dec134(
times_min: List[float],
remaining_fraction: List[float],
*,
mass_recovery_fraction: Optional[float] = None,
t50_max_min: float = 4.50,
mean_transit_max_min: float = 5.50,
t90_max_min: float = 11.0,
) -> Dict[str, Any]:
"""
DEC-134 locked Stage-0 whole-device insulin perifusion washout tail gate (BPR-15).
Requires a complete washout trace (window >= 15.0 min, end remaining <= 0.10, mass recovery
in [0.80, 1.20]) AND simultaneous clearance of t50 <= 4.50 min, mean transit <= 5.50 min,
and t90 <= 11.0 min (separating passing >3.50 mM controls from heavy-tail <3.50 mM shapes).
"""
comp = evaluate_measured_washout_trace_completeness_bpr15(
times_min,
remaining_fraction,
mass_recovery_fraction=mass_recovery_fraction,
required_tail_bound_fraction=0.10,
min_observation_window_min=15.0,
)
if not comp.get("tail_bounded"):
return {
"decision_id": "DEC-134",
"verdict": "HOLD_DEC134_INCOMPLETE_WASHOUT_TRACE",
"passes_gate": False,
"trace_completeness": comp,
"t50_min": None,
"mean_transit_min": None,
"t90_min": None,
"failures": list(comp.get("reasons", [])),
}
t_arr = [float(x) for x in times_min]
s_arr = [float(x) for x in remaining_fraction]
# Shift to t0 = 0 for elapsed washout quantiles & trapezoidal survival integral E[T] = int_0^inf S(t) dt
t0 = t_arr[0]
dt_arr = [t - t0 for t in t_arr]
def _interp_crossing(target_s: float) -> Optional[float]:
if s_arr[0] <= target_s:
return 0.0
for i in range(len(s_arr) - 1):
s0_i, s1_i = s_arr[i], s_arr[i + 1]
if s0_i >= target_s >= s1_i and s0_i > s1_i:
frac = (s0_i - target_s) / (s0_i - s1_i)
return dt_arr[i] + frac * (dt_arr[i + 1] - dt_arr[i])
return None
t50 = _interp_crossing(0.50)
t90 = _interp_crossing(0.10)
mean_tr = 0.0
for i in range(len(dt_arr) - 1):
mean_tr += 0.5 * (s_arr[i] + s_arr[i + 1]) * (dt_arr[i + 1] - dt_arr[i])
# Conservative residual tail integral if s_end > 0 using local log-slope over last positive segment
if s_arr[-1] > 1e-9 and s_arr[-2] > s_arr[-1]:
k_tail = math.log(s_arr[-2] / s_arr[-1]) / (dt_arr[-1] - dt_arr[-2])
if k_tail > 0.0:
mean_tr += s_arr[-1] / k_tail
failures: List[str] = []
if t50 is None or t50 > t50_max_min:
failures.append(f"t50_min={t50!r} > {t50_max_min:.2f}")
if mean_tr > mean_transit_max_min:
failures.append(f"mean_transit_min={mean_tr:.4f} > {mean_transit_max_min:.2f}")
if t90 is None or t90 > t90_max_min:
failures.append(f"t90_min={t90!r} > {t90_max_min:.2f}")
passes = len(failures) == 0
return {
"decision_id": "DEC-134",
"verdict": "PASS_DEC134_WASHOUT_TAIL_GATE" if passes else "FAIL_DEC134_WASHOUT_TAIL_EXCEEDED",
"passes_gate": passes,
"thresholds": {
"t50_max_min": t50_max_min,
"mean_transit_max_min": mean_transit_max_min,
"t90_max_min": t90_max_min,
"end_remaining_max": 0.10,
"min_window_min": 15.0,
},
"t50_min": round(t50, 6) if t50 is not None else None,
"mean_transit_min": round(mean_tr, 6),
"t90_min": round(t90, 6) if t90 is not None else None,
"trace_completeness": comp,
"failures": failures,
}
def evaluate_device_insulin_transit_shape_sensitivity_bpr15(
*,
t_pub_min: float = 5.17,
viable_endocrine_fraction: float = 0.60,
dt_max: float = 0.25,
) -> Dict[str, Any]:
"""
Evaluate identifiability of Layer-4 exercise glucose nadirs across unit-gain device
insulin transfer curves sharing the IDENTICAL step-down half-time t_50 = 4.338527 min
(BPR-15 / DEC-133).
Demonstrates:
- Published 2 equal serial stages (T=5.17 min, t90=10.055 min, S(15)=2.05%): clears 3.50 mM.
- 1 exponential passage (identical t50, t90=14.412 min, S(15)=9.10%): reverses verdict (< 3.50 mM).
- 2 parallel passages 80%/20% (identical t50, t90=19.173 min, S(15)=14.01%): reverses verdict (< 3.50 mM).
- Mean (5.17 min) + median (4.338527 min) + unit-gain matched positive controls clear >= 3.50 mM.
All half-time screens are explicitly labeled conditional on the assumed transfer curve shape.
"""
tau_pub = 0.5 * t_pub_min
def _erlang_survival(t_val: float, k_stages: int, tau_stage: float) -> float:
x = t_val / tau_stage
acc = 0.0
term = 1.0
for j in range(k_stages):
if j > 0:
term *= x / j
acc += term
return acc * math.exp(-x)
def _mixture_survival(t_val: float, branches: List[Tuple[float, int, float]]) -> float:
return sum(w * _erlang_survival(t_val, k, tau) for w, k, tau in branches)
def _solve_quantile(branches: List[Tuple[float, int, float]], target_s: float) -> float:
lo, hi = 0.0, 1.0
while _mixture_survival(hi, branches) > target_s:
hi *= 2.0
for _ in range(90):
mid = 0.5 * (lo + hi)
if _mixture_survival(mid, branches) > target_s:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
pub_branches = [(1.0, 2, tau_pub)]
t50_target = _solve_quantile(pub_branches, 0.5)
# Counterexample 1: single exponential matching exact t50
one_exp_branches = [(1.0, 1, t50_target / math.log(2.0))]
# Counterexample 2: two parallel exponentials (80% fast, 20% slow) matching exact t50
tau_slow_par = 5.0 * t50_target
tau_fast_par = -t50_target / math.log((0.5 - 0.2 * math.exp(-t50_target / tau_slow_par)) / 0.8)
two_par_branches = [(0.8, 1, tau_fast_par), (0.2, 1, tau_slow_par)]
# Mean + median + unit-gain matched positive controls: w*Erlang(k, tau_e) + (1-w)*Exp(tau_x)
def _solve_mean_median_control(w_e: float, k_e: int) -> List[Tuple[float, int, float]]:
def f_err(tau_e: float) -> float:
tau_x = (t_pub_min - w_e * k_e * tau_e) / (1.0 - w_e)
return _mixture_survival(t50_target, [(w_e, k_e, tau_e), (1.0 - w_e, 1, tau_x)]) - 0.5
max_tau_e = (t_pub_min / (w_e * k_e)) * 0.999
lo_t, hi_t = 0.2, max_tau_e
# Find sign change across grid
grid = [lo_t + (hi_t - lo_t) * idx / 200.0 for idx in range(201)]
vals = [f_err(g) for g in grid]
bracket = None
for idx in range(len(grid) - 1):
if vals[idx] == 0.0:
bracket = (grid[idx], grid[idx])
break
if vals[idx] * vals[idx + 1] < 0.0:
bracket = (grid[idx], grid[idx + 1])
break
if bracket is None:
raise RuntimeError(f"Failed to bracket mean+median control (w={w_e}, k={k_e})")
a_b, b_b = bracket
fa = f_err(a_b)
for _ in range(90):
mid = 0.5 * (a_b + b_b)
fm = f_err(mid)
if fa * fm <= 0.0:
b_b = mid
else:
a_b, fa = mid, fm
tau_e_star = 0.5 * (a_b + b_b)
tau_x_star = (t_pub_min - w_e * k_e * tau_e_star) / (1.0 - w_e)
return [(w_e, k_e, tau_e_star), (1.0 - w_e, 1, tau_x_star)]
ctrl_e4_exp = _solve_mean_median_control(0.50, 4)
ctrl_e3_exp = _solve_mean_median_control(0.85, 3)
# Shared low-glucose exercise ODE (identical to Layer 4 lead v=0.60, low_glucose_challenge_mode=True)
meals_sched = [(60.0, 60.0), (360.0, 60.0), (840.0, 80.0)]
ex_start_min, ex_end_min, ex_intensity = 448.0, 536.0, 1.51
k05, nh, g_thresh = 7.2, 4.2, 3.5
k_ip_clear = 0.14
k_x_decay = 0.035
v = float(viable_endocrine_fraction)
lpf = v
t_grid = np.linspace(0.0, 1440.0, 5761)
piecewise_events = (ex_start_min, ex_end_min)
def _meal_app(t_min: float) -> float:
r = 0.0
for t0, grams in meals_sched:
if t_min > t0:
dt_m = t_min - t0
r += ((grams * 0.095) / (34.0 * 34.0)) * dt_m * math.exp(-dt_m / 34.0)
return r
def _sec_ins(G_val: float, S_val: float, M_val: float) -> float:
G_pos = max(0.5, G_val)
S_pos = max(0.0, S_val)
g_s = (S_pos / (1e-4 + S_pos)) if S_pos > 0.0 else 0.0
base_rate = 6.8 - 0.8 * g_s
tail_clamp = (1.0 - g_s * (1.0 - ((G_pos / 4.20) ** 8))) if G_pos < 4.20 else 1.0
return v * (base_rate * tail_clamp + 88.0 * max(0.0, M_val) * tail_clamp)
def _run_branches(branches: List[Tuple[float, int, float]]) -> float:
n_tr = sum(k for _, k, _ in branches)
s0 = 0.12 * lpf
g0 = 5.1
m0 = 0.08 * lpf
s_ins0 = _sec_ins(g0, s0, m0)
y0 = np.array([g0, 48.0 * v, 0.03 * v, m0, s0, 60.0, m0] + [s_ins0] * n_tr, dtype=np.float64)
def rhs(t: float, y: np.ndarray) -> np.ndarray:
G, Ip, X, U, S, Gcg, M_sec = y[0], y[1], y[2], y[3], y[4], y[5], y[6]
G_pos = max(0.5, G)
S_pos = max(0.0, S)
g_s = (S_pos / (1e-4 + S_pos)) if S_pos > 0.0 else 0.0
g_eff = max(0.0, G_pos - g_thresh)
k_eff = max(1.0, k05 - g_thresh)
hill = (g_eff ** nh) / ((k_eff ** nh) + (g_eff ** nh))
m_target = hill / (1.0 + 1.50 * S_pos * g_s)
if m_target < M_sec:
tau_sst = 1.85 / (1.0 + 0.8 * S_pos)
if G_pos < 4.20:
tau_sst = tau_sst * ((G_pos / 4.20) ** 4)
tau_m = 6.80 * (1.0 - g_s) + tau_sst * g_s
else:
tau_m = 2.00
dM_dt = (m_target - M_sec) / tau_m
sec_ins = _sec_ins(G_pos, S_pos, M_sec)
d_tr = np.zeros(n_tr, dtype=np.float64)
flux_out = 0.0
pos = 0
for w_b, k_b, tau_b in branches: