OpenIslet

scripts/run_layer4_tissue_and_metabolic_twin.py

Layer 4: Multi-Scale Tissue, Vascular & Metabolic Digital Twin Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 713 KB · 47 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/run_layer4_tissue_and_metabolic_twin.py · SHA-256: 624a491d5e418a7d…

        meals_sched = [(60.0, 75.0), (360.0, 85.0), (780.0, 90.0)]

    ex_start = 448.0 if low_glucose_challenge_mode else 600.0
    ex_end = 536.0 if low_glucose_challenge_mode else 660.0
    ex_int = 1.51 if low_glucose_challenge_mode else 1.0

    def meal_app(t_min: float) -> float:
        r_m = 0.0
        tau_m = 34.0
        for t0, grams in meals_sched:
            if t_min > t0:
                dt = t_min - t0
                amp = (grams * 0.095) / (tau_m * tau_m)
                r_m += amp * dt * math.exp(-dt / tau_m)
        return r_m

    def sst_occ(s_val: float) -> float:
        sp = max(0.0, s_val)
        return (sp / (1e-4 + sp)) if sp > 0.0 else 0.0

    def fluxes(g_val: float, s_val: float, m_val: float, qp_val: float, qr_val: float, a_pot_val: float) -> Dict[str, float]:
        gp = max(0.5, g_val)
        sp = max(0.0, s_val)
        gs = sst_occ(sp)
        base_rate = 6.8 - 0.8 * gs

        if is_invivo and gp < 4.20:
            clamp_raw = (gp / 4.20) ** 8
            low_g_clamp = 1.0 - gs * (1.0 - clamp_raw)
        else:
            low_g_clamp = 0.85 + 0.15 * _smoothstep01_iip0029((gp - 2.0) / 2.2)

        p_norm = max(0.0, qp_val) / max(1e-15, qp0)
        r_norm = max(0.0, qr_val) / max(1e-15, qr0)
        r_avail_gate = _smoothstep01_iip0029(r_norm / 0.05) if r_norm > 0.0 else 0.0

        unclamped_autonomous_leak = max(0.0, params.basal_leak_multiplier - 1.0)
        j_basal_sys_pm = v * base_rate * (low_g_clamp * min(1.0, params.basal_leak_multiplier) + unclamped_autonomous_leak) * r_avail_gate
        j_exo_sys_pm = v * 88.0 * max(0.0, m_val) * (low_g_clamp if is_invivo else 1.0) * p_norm
        sec_ins_sys_pm = j_basal_sys_pm + j_exo_sys_pm

        j_basal_iu = alpha_prehep_iu_per_pm * j_basal_sys_pm
        j_exo_iu = alpha_prehep_iu_per_pm * j_exo_sys_pm

        g_eff = max(0.0, gp - 3.5)
        k_eff = k05 - 3.5
        phi_glc = (g_eff ** nh) / ((k_eff ** nh) + (g_eff ** nh))

        p_cap = 1.0 + max(0.0, a_pot_val)
        refill_deficit = max(0.0, p_cap - p_norm)
        j_refill_iu = (qp0 / params.tau_refill_min) * r_norm * (1.0 + params.gamma_amp * phi_glc) * refill_deficit

        if params.enable_biosyn:
            phi_maint = _smoothstep01_iip0029((gp - 2.0) / 0.8)
            cap_gate = 1.0 - _smoothstep01_iip0029((qr_val - qr0) / max(1e-15, 1e-4 * qr0)) if qr_val > qr0 else 1.0
            g_trans = max(0.0, gp - 2.5)
            phi_trans = (g_trans ** 4) / ((3.0 ** 4) + (g_trans ** 4))
            j_biosyn_iu = phi_maint * cap_gate * j_basal_iu + phi_trans * max(0.0, qr0 - qr_val) / params.tau_biosyn_min
        else:
            j_biosyn_iu = 0.0

        return {
            "sec_ins_sys_pm": sec_ins_sys_pm,
            "j_sys_iu": ALPHA_SYS_INSULIN_IU_PER_PM_IIP0029 * sec_ins_sys_pm,
            "j_basal_iu": j_basal_iu,
            "j_exo_iu": j_exo_iu,
            "j_sec_prehep_iu": j_basal_iu + j_exo_iu,
            "j_refill_iu": j_refill_iu,
            "j_biosyn_iu": j_biosyn_iu,
            "phi_glc": phi_glc,
        }

    has_lag = is_invivo and (lag_f > 0.0)

    def rhs(t: float, y: np.ndarray) -> np.ndarray:
        if has_lag:
            G, Ip, X, U, S, Gcg, M_sec, Q_P, Q_R, A_pot, CumPre, CumBio, CumSys, I1, I2 = y
        else:
            G, Ip, X, U, S, Gcg, M_sec, Q_P, Q_R, A_pot, CumPre, CumBio, CumSys = y

        gp = max(0.5, G)
        sp = max(0.0, S)
        gs = sst_occ(sp)
        flx = fluxes(gp, sp, M_sec, Q_P, Q_R, A_pot)
        phi_glc = flx["phi_glc"]
        sst_inhib = 1.0 / (1.0 + 1.50 * sp * gs)
        m_target = phi_glc * sst_inhib

        if m_target < M_sec:
            if is_invivo:
                tau_sst = 1.85 / (1.0 + 0.8 * sp)
                if gp < 4.20:
                    tau_sst = tau_sst * ((gp / 4.20) ** 4)
            else:
                tau_sst = 0.85 / (1.0 + 0.6 * sp)
            tau_m = 6.80 * (1.0 - gs) + tau_sst * gs
        else:
            tau_m = 2.00 if is_invivo else 1.35
        dM_dt = (m_target - M_sec) / tau_m

        sec_sys = flx["sec_ins_sys_pm"]
        if has_lag:
            tau_tr = 0.5 * lag_f
            dI1_dt = (sec_sys - I1) / tau_tr
            dI2_dt = (I1 - I2) / tau_tr
            dIp_dt = I2 - k_ip_clear * Ip
        else:
            dIp_dt = sec_sys - k_ip_clear * Ip

        dX_dt = k_x_decay * (max(0.0, Ip - 45.0) / 100.0 - X)
        dU_dt = (1.2 * loc_f * M_sec - U) / 2.5
        sst_drive = loc_f * (0.65 * U + 0.45 * ((gp ** 4) / (5.8 ** 4 + gp ** 4)))
        dS_dt = (sst_drive - S) / 1.5

        low_g_drive = 1.0 / (1.0 + ((gp / 4.45) ** 6))
        ins_eff_block = Ip * (1.0 - gs * (1.0 - ((gp / 4.20) ** 8))) if (is_invivo and gp < 4.20) else Ip
        ins_paracrine_block = 0.018 * max(0.0, ins_eff_block - 52.0)
        gcg_sec = 11.4 + (56.0 * v) * low_g_drive / (1.0 + ins_paracrine_block + 0.35 * sp)
        dGcg_dt = gcg_sec - 0.20 * Gcg

        if is_invivo:
            ex = ex_int if ex_start <= t <= ex_end else 0.0
            basal_ins_tone = min(1.0, (max(0.0, Ip) / 25.0) ** 2)
            egp_base = 0.056 * (1.0 + 0.018 * (Gcg - 58.0)) / (1.0 + 0.26 * max(0.0, X))
            egp_t1d = 0.068 * (1.0 - basal_ins_tone)
            egp = max(0.010, egp_base + egp_t1d)
            uptake_indep = 0.032 * (gp / (1.2 + gp)) * (1.0 + 0.48 * ex)
            uptake_ins = (0.0052 * basal_ins_tone + 0.0135 * max(0.0, X)) * gp * (1.0 + 1.55 * ex)
            renal = 0.0065 * max(0.0, gp - 10.0)
            dG_dt = egp + meal_app(t) - uptake_indep - uptake_ins - renal
        else:
            dG_dt = 0.0

        dQP_dt = flx["j_refill_iu"] - flx["j_exo_iu"]
        dQR_dt = flx["j_biosyn_iu"] - flx["j_refill_iu"] - flx["j_basal_iu"]
        dApot_dt = (params.g_pot * phi_glc - A_pot) / params.tau_pot_min
        dCumPre_dt = flx["j_sec_prehep_iu"]
        dCumBio_dt = flx["j_biosyn_iu"]
        dCumSys_dt = flx["j_sys_iu"]

        if has_lag:
            return np.array(
                [dG_dt, dIp_dt, dX_dt, dU_dt, dS_dt, dGcg_dt, dM_dt, dQP_dt, dQR_dt, dApot_dt, dCumPre_dt, dCumBio_dt, dCumSys_dt, dI1_dt, dI2_dt],
                dtype=np.float64,
            )
        return np.array(
            [dG_dt, dIp_dt, dX_dt, dU_dt, dS_dt, dGcg_dt, dM_dt, dQP_dt, dQR_dt, dApot_dt, dCumPre_dt, dCumBio_dt, dCumSys_dt],
            dtype=np.float64,
        )

    g0 = 5.1 if v >= 0.6 else 17.2 - 12.1 * v
    s0 = 0.12 * loc_f
    m0 = 0.08 * loc_f if is_invivo else 0.0
    s_ins0 = fluxes(g0, s0, m0, qp0, qr0, 0.0)["sec_ins_sys_pm"]
    base_y0 = [g0, 48.0 * v, 0.03 * v, 0.08 * loc_f if is_invivo else 0.0, s0, 60.0, m0, qp0, qr0, 0.0, 0.0, 0.0, 0.0]
    if has_lag:
        base_y0.extend([s_ins0, s_ins0])

    # Uncapped stiffness-rate bound covering Q_P turnover, 1/tau_chamber, and 2/tau_vasc:
    lam_qp_upper = (alpha_prehep_iu_per_pm * v * 88.0 / max(1e-15, qp0)) + ((1.0 + params.gamma_amp) / params.tau_refill_min)
    lam_chamber = (1.0 / params.tau_chamber_min) if (not is_invivo and params.tau_chamber_min > 0.0) else 0.0
    lam_vasc = (2.0 / lag_f) if has_lag else 0.0
    max_lam_upper = max(lam_qp_upper, lam_chamber, lam_vasc) + 0.5 * min(lam_qp_upper, max(lam_chamber, lam_vasc))

    return {
        "rhs": rhs,
        "fluxes": fluxes,
        "y0": np.array(base_y0, dtype=np.float64),
        "c0_iu": c0_iu,
        "qp0_iu": qp0,
        "qr0_iu": qr0,
        "v_eff": v,
        "f_hepatic_eff": f_hep_eff,
        "max_stiff_rate_min_inv": max_lam_upper,
        "ex_start": ex_start,
        "ex_end": ex_end,
    }


def courant_safe_rk4_integrate_iip_0029(
    rhs: Any,
    y0: np.ndarray,
    t_grid: np.ndarray,
    max_stiff_rate: float,
    breakpoints: tuple[float, ...] = (),
    courant_target: float = 0.18,
) -> np.ndarray:
    """Explicit 4th-order Runge-Kutta integrator with uncapped stiffness-rate substepping and breakpoint handling."""
    out = np.zeros((len(y0), len(t_grid)), dtype=np.float64)
    out[:, 0] = y0.copy()
    cur = y0.copy()
    bp_set = {float(b) for b in breakpoints}

    for idx in range(len(t_grid) - 1):
        t0 = float(t_grid[idx])
        t1 = float(t_grid[idx + 1])
        span = t1 - t0
        if span <= 0.0:
            out[:, idx + 1] = cur
            continue
        n_sub = max(1, int(math.ceil(span * max(1.0, float(max_stiff_rate)) / float(courant_target))))
        h = span / float(n_sub)
        tc = t0
        for _ in range(n_sub):
            t_eval_mid = tc + 0.5 * h
            t_r1 = math.nextafter(tc, t1) if tc in bp_set else tc
            t_r4 = math.nextafter(tc + h, tc) if (tc + h) in bp_set else (tc + h)
            k1 = rhs(t_r1, cur)
            k2 = rhs(t_eval_mid, cur + 0.5 * h * k1)
            k3 = rhs(t_eval_mid, cur + 0.5 * h * k2)
            k4 = rhs(t_r4, cur + h * k3)
            cur = cur + (h / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
            tc += h
        out[:, idx + 1] = cur
    return out


def replay_mode_b_v2_perifusion_iip_0029(
    params: ModeBV2GranuleStoreParams,
    low_mM: float,
    high_mM: float,
    pre_low_min: float,
    high_durations: List[float],
    low_gaps: List[float],
    dt_out: float = 0.1,
) -> Dict[str, Any]:
    """
    Imposed-glucose repeated-challenge perifusion replay under exploratory Mode B v2.
    Uses the pre-pulse steady basal reference for step-down shut-off so truncated short low
    intervals return censored None rather than an artificial fast t90.
    """
    sys_b = build_mode_b_v2_granule_store_system_iip_0029(params, assay_context="in_vitro_perifusion")
    rhs_cell = sys_b["rhs"]
    flux_fn = sys_b["fluxes"]
    tau_ch = params.tau_chamber_min
    use_chamber = tau_ch > 1e-9

    y0_cell = sys_b["y0"].copy()
    y0_cell[0] = float(low_mM)
    sec0 = flux_fn(float(low_mM), y0_cell[4], y0_cell[6], y0_cell[7], y0_cell[8], y0_cell[9])["sec_ins_sys_pm"]
    state = np.concatenate([y0_cell, [float(low_mM), sec0]]) if use_chamber else y0_cell.copy()

    def run_seg(st_in: np.ndarray, g_inlet: float, dur: float) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        n_steps = max(1, int(round(dur / dt_out)))
        t_vec = np.linspace(0.0, float(dur), n_steps + 1)
        if use_chamber:
            def _aug_rhs(t: float, ya: np.ndarray) -> np.ndarray:
                yc = ya[:13].copy()
                g_ch, c_eff = float(ya[13]), float(ya[14])
                yc[0] = g_ch