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…
[
g0_init,
ip0_init,
0.03 * viable_endocrine_fraction,
0.08 * local_paracrine_factor,
s0_init,
60.0,
0.08 * local_paracrine_factor,
s_ins_init,
s_ins_init,
gcg_sec_init,
gcg_sec_init,
g0_init,
],
dtype=np.float64,
)
elif extravascular_insulin_lag_total_min > 0.0:
s_ins_init = compute_sec_ins(g0_init, s0_init, 0.08 * local_paracrine_factor)
y0 = np.array(
[
g0_init,
ip0_init,
0.03 * viable_endocrine_fraction,
0.08 * local_paracrine_factor,
s0_init,
60.0,
0.08 * local_paracrine_factor,
s_ins_init,
s_ins_init,
],
dtype=np.float64,
)
else:
y0 = np.array(
[g0_init, ip0_init, 0.03 * viable_endocrine_fraction, 0.08 * local_paracrine_factor, s0_init, 60.0, 0.08 * local_paracrine_factor],
dtype=np.float64,
)
# Resolve known forcing changes with the one-sided RK4 endpoint rule.
# This preserves the specified exercise duration independently of dt.
ode_rhs.integration_breakpoints = (ex_start_min, ex_end_min)
integrator_fn = _integrator if _integrator is not None else rk4_integrate
sol_y = integrator_fn(ode_rhs, (0.0, 1440.0), y0, t_grid, dt_max=0.25)
if (not low_glucose_challenge_mode and not force_common_basal_and_shutoff
and viable_endocrine_fraction == 1.0 and source_pde_regime_id is None
and extravascular_insulin_lag_total_min <= 0.0
and (gm["graft_id"], force_zero_sst) not in comparison_states
and gm["graft_id"] in {graft_models[0]["graft_id"], graft_models[1]["graft_id"],
"OAT_1_REMOVE_ONLY_LOW_G_BASAL_SST_CLAMP"}):
comparison_states[(gm["graft_id"], force_zero_sst)] = sol_y
# Sample at 1-minute intervals (indices 0, 4, 8, ..., 5760) for standard 1,440-minute metrics
idx_1min = np.arange(0, 5761, 4)
G_traj = sol_y[0, idx_1min]
Ip_traj = sol_y[1, idx_1min]
Gcg_traj = sol_y[5, idx_1min]
# Compute beta-cell secretion trajectory S_ins(t) on the 0.25-min grid across exercise onset (t = 600..660 min)
# to measure post-glucose-drop insulin secretion shut-off half-time directly from the ODE trajectory (AUDIT-REF):
ex_start_idx = int(ex_start_min * 4)
ex_end_idx = int(ex_end_min * 4)
if extravascular_insulin_lag_total_min <= 0.0 and not _skip_shutoff_half_time:
sec_traj_ex = np.array(
[
compute_sec_ins(float(sol_y[0, k]), float(sol_y[4, k]), float(sol_y[6, k]))
for k in range(ex_start_idx, ex_end_idx + 1)
],
dtype=np.float64,
)
half_drop = _trajectory_half_drop_time(t_grid[ex_start_idx:ex_end_idx + 1], sec_traj_ex, ex_start_min, ex_end_min)
else:
half_drop = None
shutoff_half_time_min = None if half_drop is None else round(half_drop, 2)
min_g_mM = float(np.min(G_traj))
max_g_mM = float(np.max(G_traj))
max_g_after_60min_mM = float(np.max(G_traj[60:]))
mean_g_mM = float(np.mean(G_traj))
glucose_sd_mM = float(np.std(G_traj))
glucose_cv_pct = float(100.0 * glucose_sd_mM / mean_g_mM)
tir_3p9_to_10_pct = float(100.0 * np.mean((G_traj >= 3.9) & (G_traj <= 10.0)))
time_below_3p9_mM_pct = float(100.0 * np.mean(G_traj < 3.9))
time_below_3p0_mM_pct = float(100.0 * np.mean(G_traj < 3.0))
peak_gcg_during_exercise = float(np.max(Gcg_traj[int(ex_start_min):int(ex_end_min + 30.) + 1]))
t_1min = np.linspace(0.0, 1440.0, len(G_traj))
auc_hypo_lt_3p9 = float(np.trapezoid(np.maximum(0.0, 3.9 - G_traj), t_1min))
auc_severe_hypo_lt_3p0 = float(np.trapezoid(np.maximum(0.0, 3.0 - G_traj), t_1min))
g_mg_dl = G_traj * 18.0182
f_bg = 1.509 * ((np.log(np.maximum(20.0, g_mg_dl)) ** 1.084) - 5.381)
r_bg = 10.0 * (f_bg ** 2)
lbgi = float(np.mean(np.where(f_bg < 0.0, r_bg, 0.0)))
hbgi = float(np.mean(np.where(f_bg > 0.0, r_bg, 0.0)))
bgri = lbgi + hbgi
# Full 5,761-step 0.25-min resolution verification (AUDIT-REF & IIP-0024; DEC-103):
G_0p25 = sol_y[0, :]
t_0p25 = [0.25 * idx for idx in range(len(G_0p25))]
elapsed_gly_0p25 = compute_exact_elapsed_glycemic_metrics_iip_0024(t_0p25, G_0p25)
min_g_0p25_mM = float(np.min(G_0p25))
max_g_0p25_mM = float(np.max(G_0p25))
mean_g_0p25_mM = float(np.mean(G_0p25))
tir_0p25_pct = float(100.0 * np.mean((G_0p25 >= 3.9) & (G_0p25 <= 10.0)))
tbr39_0p25_pct = float(100.0 * np.mean(G_0p25 < 3.9))
out_entry: Dict[str, Any] = {
"graft_id": gm["graft_id"],
"description": gm["description"],
"beta_cell_fraction": gm.get("beta_cell_fraction", 0.60),
"alpha_cell_fraction": gm.get("alpha_cell_fraction", 0.30),
"delta_cell_fraction": gm.get("delta_cell_fraction", 0.10),
"pde_coupling_applied": source_pde_regime_id is not None,
"evaluation_scope": ("MATCHED_PDE_VIABLE_MASS" if source_pde_regime_id is not None else "REFERENCE_FIXED_FUNCTIONAL_BETA_IEQ_NOT_PDE_DERIVED"),
"source_pde_regime_id": source_pde_regime_id,
"recipient_treatment_model_scope": {
"insulin_source": "GRAFT_INSULIN_ONLY",
"supplemental_insulin_delivery_and_absorption": "NOT_MODELLED",
"external_glucose_infusion_and_rescue": "NOT_MODELLED",
"sensor_and_treatment_controller": "NOT_MODELLED",
"insulin_supported_staging_applicability": "NOT_ESTABLISHED_BY_THIS_SIMULATION",
},
**({"viable_endocrine_fraction_coupled": round(viable_endocrine_fraction, 4)} if source_pde_regime_id is not None
else {"assumed_reference_functional_fraction": round(viable_endocrine_fraction, 4)}),
"peripheral_insulin_action_clearance_p2_min_inv": k_x_decay_shared,
"mean_glucose_mM": round(mean_g_mM, 2),
"mean_glucose_mg_dL": round(mean_g_mM * 18.0182, 1),
"initial_glucose_g0_mM": round(float(g0_init), 2),
"glucose_sd_mM": round(glucose_sd_mM, 2),
"glucose_cv_pct": round(glucose_cv_pct, 2),
"min_glucose_mM": round(min_g_mM, 2),
"min_glucose_mg_dL": round(min_g_mM * 18.0182, 1),
"max_postprandial_glucose_mM": round(max_g_mM, 2),
"max_glucose_full_0_to_1440min_mM": round(max_g_mM, 2),
"max_postprandial_glucose_after_60min_mM": round(max_g_after_60min_mM, 2),
"max_postprandial_glucose_mg_dL": round(max_g_mM * 18.0182, 1),
"time_in_tight_range_3p9_to_10p0_mM_pct": round(tir_3p9_to_10_pct, 2),
"time_below_range_lt_3p9_mM_70_mg_dL_pct": round(time_below_3p9_mM_pct, 2),
"time_level2_biochemical_hypoglycemia_lt_3p0_mM_54_mg_dL_pct": round(time_below_3p0_mM_pct, 2),
"time_severe_hypoglycemia_lt_3p0_mM_54_mg_dL_pct": round(time_below_3p0_mM_pct, 2),
"hypoglycemic_auc_below_3p9_mM_min": round(auc_hypo_lt_3p9, 2),
"level2_biochemical_hypoglycemia_auc_below_3p0_mM_min": round(auc_severe_hypo_lt_3p0, 2),
"severe_hypoglycemic_auc_below_3p0_mM_min": round(auc_severe_hypo_lt_3p0, 2),
"level3_severe_hypoglycemia_events_clinician_adjudicated": None,
"level2_vs_level3_hypoglycemia_label_note_bpr11": (
"Legacy keys time_severe_hypoglycemia_lt_3p0_mM_54_mg_dL_pct / severe_hypoglycemic_auc_below_3p0_mM_min "
"are retained for backwards schema compatibility only and measure Level-2 biochemical hypoglycemia (<3.0 mmol/L / 54 mg/dL). "
"Level-3 severe hypoglycemia is defined clinically by requiring assistance and requires clinician adjudication."
),
"kovatchev_low_bg_risk_index_lbgi": round(lbgi, 3),
"kovatchev_high_bg_risk_index_hbgi": round(hbgi, 3),
"kovatchev_total_bg_risk_index_bgri": round(bgri, 3),
"peak_exercise_glucagon_pg_mL": round(peak_gcg_during_exercise, 1),
"insulin_secretion_shutoff_half_time_min": shutoff_half_time_min,
"shutoff_half_time_derivation": f"computed_directly_from_simulated_S_ins_trajectory_after_t{ex_start_min:g}min_exercise_onset_with_sub_0p25min_linear_interpolation",
"insulin_secretion_shutoff_measurement_window_min": [ex_start_min, ex_end_min],
"insulin_secretion_shutoff_measurement_status": ("SIMULATED_DECLINE_HALF_TIME" if half_drop is not None else "NO_SECRETION_DECLINE_IN_SIMULATED_WINDOW"),
"glucagon_peak_measurement_window_including_30min_recovery_min": [ex_start_min, ex_end_min + 30.],
"full_5761_step_0p25min_grid_verification_v80_025": {
"min_glucose_0p25min_mM": round(min_g_0p25_mM, 4),
"min_glucose_0p25min_unrounded_mM": min_g_0p25_mM,
"max_glucose_0p25min_mM": round(max_g_0p25_mM, 4),
"mean_glucose_0p25min_mM": round(mean_g_0p25_mM, 4),
"time_in_tight_range_0p25min_pct": round(tir_0p25_pct, 2),
"time_below_3p9mM_0p25min_pct": round(tbr39_0p25_pct, 2),
"tbr39_elapsed_0p25min_pct": elapsed_gly_0p25["tbr_lt_3p9_pct"],
"tbr30_elapsed_0p25min_pct": elapsed_gly_0p25["tbr_lt_3p0_pct"],
"tir_3p9_to_10_elapsed_0p25min_pct": elapsed_gly_0p25["tir_3p9_10p0_pct"],
"passes_fragile_tbr_lt_1pct": elapsed_gly_0p25["passes_fragile_tbr_lt_1pct"],
},
"passes_clinical_glycemic_safety_targets": bool(
tir_0p25_pct >= 85.0
and elapsed_gly_0p25["tbr39_elapsed_unrounded_pct"] < 4.0
and elapsed_gly_0p25["tbr30_elapsed_unrounded_pct"] == 0.0
and not np.any(G_0p25 < 3.0)
and min_g_0p25_mM >= 3.5
),
}
if include_trajectory:
out_entry["sampled_hourly_trajectory"] = [
{
"hour": int(m // 60),
"glucose_mM": round(float(G_traj[m]), 2),
"plasma_insulin_pM": round(float(Ip_traj[m]), 1),
"plasma_glucagon_pg_mL": round(float(Gcg_traj[m]), 1),
}
for m in range(0, 1441, 120)
]
return out_entry
for gm in graft_models:
simulations.append(_run_single_metabolic_ode_model(gm, include_trajectory=True))
# One-Mechanism-At-a-Time (OAT) Paracrine Sub-Mechanism Ablation Table (closing AUDIT-REF & AUDIT-REF):
oat_specs = [
{
"graft_id": "OAT_1_REMOVE_ONLY_LOW_G_BASAL_SST_CLAMP",
"description": "Ablates the below-4.2 mM low-glucose SST reflex while retaining constitutive SST basal tone (6.0 pM/min), suprabasal Hill attenuation, calcineurin shut-off acceleration, and alpha-cell glucagon rescue",
"k05_gsis_mM": 7.2,
"hill_gsis": 4.2,
"has_ucn3_delta_sst_brake": True,
"has_alpha_gcg_counterregulation": True,
"enable_low_g_sst_clamp": False,
"enable_constitutive_sst_basal_suppression": True,
"enable_sst_suprabasal_gain_attenuation": True,
"enable_sst_calcineurin_shutoff_accel": True,
},
{
"graft_id": "OAT_1A_REMOVE_STRICTLY_BETA_CELL_LOW_G_CLAMP_ONLY",
"description": "Single-mechanism isolation ablating strictly the beta-cell <4.2 mM octic GIRK secretion clamp (enable_low_g_sst_beta_clamp=False) while holding <4.2 mM tau_sst shutoff acceleration and alpha-cell insulin-block relief fixed",
"k05_gsis_mM": 7.2,
"hill_gsis": 4.2,
"has_ucn3_delta_sst_brake": True,
"has_alpha_gcg_counterregulation": True,
"enable_low_g_sst_clamp": True,
"enable_low_g_sst_beta_clamp": False,
"enable_low_g_sst_shutoff_accel": True,
"enable_low_g_alpha_insulin_unblock": True,
"enable_constitutive_sst_basal_suppression": True,
"enable_sst_suprabasal_gain_attenuation": True,
"enable_sst_calcineurin_shutoff_accel": True,
},
{
"graft_id": "OAT_1B_REMOVE_CONSTITUTIVE_SST_BASAL_SUPPRESSION",
"description": "Ablates constitutive delta-cell SST tonic basal insulin suppression (6.0 -> 6.8 pM/min) while retaining the <4.2 mM low-glucose clamp, suprabasal Hill attenuation, calcineurin shut-off acceleration, and alpha-cell glucagon rescue",
"k05_gsis_mM": 7.2,
"hill_gsis": 4.2,
"has_ucn3_delta_sst_brake": True,
"has_alpha_gcg_counterregulation": True,
"enable_low_g_sst_clamp": True,
"enable_constitutive_sst_basal_suppression": False,
"enable_sst_suprabasal_gain_attenuation": True,
"enable_sst_calcineurin_shutoff_accel": True,
},
{
"graft_id": "OAT_2_REMOVE_ONLY_SST_SUPRABASAL_HILL_ATTENUATION",
"description": "Ablates only delta-cell SST attenuation of suprabasal Hill insulin gain (1 / (1 + 1.5*S)) while retaining low-glucose basal clamp, constitutive basal tone, calcineurin shut-off acceleration, and alpha-cell glucagon rescue",
"k05_gsis_mM": 7.2,
"hill_gsis": 4.2,
"has_ucn3_delta_sst_brake": True,
"has_alpha_gcg_counterregulation": True,
"enable_low_g_sst_clamp": True,
"enable_constitutive_sst_basal_suppression": True,
"enable_sst_suprabasal_gain_attenuation": False,
"enable_sst_calcineurin_shutoff_accel": True,
},
{
"graft_id": "OAT_3_REMOVE_ONLY_SST_CALCINEURIN_SHUTOFF_ACCELERATION",
"description": "Ablates only delta-cell SST calcineurin de-priming acceleration of beta-cell exocytotic shut-off (tau_m = 6.80 min instead of 1.85 / (1 + 0.8*S)) while retaining basal clamp, Hill gain attenuation, and alpha-cell glucagon rescue",
"k05_gsis_mM": 7.2,
"hill_gsis": 4.2,
"has_ucn3_delta_sst_brake": True,
"has_alpha_gcg_counterregulation": True,