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…

        raise ValueError("lamina_d_o2_scale must be finite and positive")
    central_mask = geometry["central_mask"]
    s_prof = (geometry["central_source"] if spatial_mode == "central" else
              (np.ones(nz) if spatial_mode == "uniform" else np.zeros(nz)))
    d_prof = geometry["outer_demand"] if demand_spatial_mode == "outer_annulus" else np.ones(nz)
    d_prof_int = d_prof[1:-1]
    cv_weights = geometry["widths"] / (2.0 * half_L)
    geometry_ledger = {
        "central_lamina_half_width_fraction": a_frac,
        "nz_nodes": nz,
        "lamina_volume_cm3": float(np.dot(central_mask, cv_weights) * active_slab_vol_cm3),
        "assigned_chemical_source_relative_integral": float(np.dot(s_prof, cv_weights)),
        "assigned_total_demand_relative_integral": float(np.dot(d_prof, cv_weights)),
        "integration_scope": "assigned continuum profiles; Dirichlet host boundaries exchange mass with the reservoir",
    }
    # Wigner-Seitz packing must use the region that actually contains the clusters.
    cell_region_fraction = 1.0 - a_frac if demand_spatial_mode == "outer_annulus" else 1.0
    local_phi_islet = phi_islet / cell_region_fraction
    geometry_ledger.update({
        "areal_loading_ieq_cm2": round(sigma_loading, 4),
        "cell_intrinsic_ocr_multiplier": round(effective_ocr_mult, 6),
        "global_islet_volume_fraction": phi_islet,
        "cell_containing_region_volume_fraction": cell_region_fraction,
        "local_islet_volume_fraction_for_unit_cell": local_phi_islet,
        "outer_band_thickness_um_each": half_L * 1e4 * (1.0 - a_frac),
        "diameter_120um_fits_wholly_in_outer_band": bool(120.0 <= half_L * 1e4 * (1.0 - a_frac)),
        "spatial_model_scope": "1D planar slab/outer bands; no explicit 3D annular ring or cluster-interface overlap",
    })

    # Conserve explicit molar CaO2 inventory n_CaO2(0) across regimes (AUDIT-REF & AUDIT-REF):
    k_ref_s = math.log(2.0) / (68.0 * 3600.0)
    r_o2_0_mol_s = f_chem_initial * (phi_islet_ref_2500 * VMAX_ISLET_PURE_MOL_CM3_S * 1.15) * active_slab_vol_cm3
    n_cao2_initial_mmol = (2.0 * r_o2_0_mol_s / k_ref_s) * 1e3  # mmol CaO2 in 7.00 cm^3 slab (10.981 mmol at f_chem=0.45)
    cao2_mass_initial_mg = n_cao2_initial_mmol * 72.078         # MW CaO2 = 72.078 g/mol (791.5 mg at f_chem=0.45)

    k_hyd_h = math.log(2.0) / cao2_half_life_h
    k_hyd_s = k_hyd_h / 3600.0
    t_eval_hours_report = {0.0, 2.0, 6.0, 12.0, 24.0, 48.0, 72.0, 96.0, 120.0, 168.0, 336.0}
    t_hourly_grid = [float(h) for h in range(337)]

    def perfusion_target(t_h: float) -> float:
        exponent = -(t_h - inosculation_t50_h) / 8.0
        # At exponents beyond log(float_max), the target is effectively zero;
        # preserve ordinary-path arithmetic without overflowing for a delayed control.
        return 0.0 if exponent > math.log(sys.float_info.max) else iec_max_perfusion_fraction / (1.0 + math.exp(exponent))

    def perfusion_ode(t_h: float, y: np.ndarray) -> np.ndarray:
        v_perf = y[0]
        v_target = perfusion_target(t_h)
        dv_dt = (v_target - v_perf) / 3.0
        return np.array([dv_dt])

    k_sc_h = 3.0 * (1.0 - (0.5 ** (1.0 / 3.0))) / cao2_half_life_h

    perfusion_y = (
        np.zeros(len(t_hourly_grid), dtype=np.float64)
        if zero_internal_vascular_state
        else rk4_integrate(perfusion_ode, (0.0, 336.0), np.array([0.01]), t_hourly_grid, dt_max=0.25)[0]
    )
    # The source is the derivative of these exact stocks. Resolving stock with
    # explicit RK4 can step through finite-time depletion or become unstable for
    # half-lives shorter than the fixed perfusion time step.
    sol_y_fo = np.vstack((n_cao2_initial_mmol * _cao2_inventory_fractions(
        np.asarray(t_hourly_grid), cao2_half_life_h, "first_order"), perfusion_y))
    sol_y_sc = np.vstack((n_cao2_initial_mmol * _cao2_inventory_fractions(
        np.asarray(t_hourly_grid), cao2_half_life_h, "shrinking_core"), perfusion_y))
    if release_kinetics_law == "ginstling_brounshtein":
        if gb_regularization_mode == "exact_piecewise_conserving":
            gb_rem_vec = np.array(
                [max(0.0, 1.0 - _ginstling_brounshtein_piecewise_regularized_hydrolyzed_fraction(float(t), cao2_half_life_h, 0.05)) for t in t_hourly_grid],
                dtype=np.float64,
            )
            sol_y = np.vstack((n_cao2_initial_mmol * gb_rem_vec, perfusion_y))
        else:
            sol_y = np.vstack((n_cao2_initial_mmol * _cao2_inventory_fractions(
                np.asarray(t_hourly_grid), cao2_half_life_h, "ginstling_brounshtein"), perfusion_y))
    elif release_kinetics_law == "shrinking_core":
        sol_y = sol_y_sc
    else:
        sol_y = sol_y_fo
    k_gb_h = (
        _ginstling_brounshtein_piecewise_regularized_integral(0.5, 0.05) / cao2_half_life_h
        if (release_kinetics_law == "ginstling_brounshtein" and gb_regularization_mode == "exact_piecewise_conserving")
        else (1.0 - (2.0 / 3.0) * 0.5 - (0.5 ** (2.0 / 3.0))) / cao2_half_life_h
    )

    # Spatially varying diffusivity profile D_O2(z) for Bruggeman central-lamina tortuosity tests (AUDIT-REF):
    d_o2_faces = _slab_oxygen_face_diffusivities(
        z_grid,
        lamina_d_o2_scale,
        lamina_half_width_fraction=a_frac,
        d_o2_hydrogel_override_cm2_s=d_o2_hydrogel_override_cm2_s,
    )
    standoff_cm = float(external_standoff_um) * 1e-4
    robin_boundary_factor = float(dz / (dz + standoff_cm)) if standoff_cm > 0.0 else 1.0

    time_series = []
    hourly_min_slab_po2_mmhg: list[float] = []
    min_po2_over_all_t = math.inf
    time_of_min_po2_h = 0.0
    max_h2o2_uM_over_all_t = 0.0
    max_h2o2_at_lamina_interface_uM_over_all_t = 0.0
    max_h2o2_at_lamina_interface_interp_uM_over_all_t = 0.0
    max_h2o2_uM_with_cat_decay_over_all_t = 0.0
    z_int_abs = np.abs(z_grid[1:-1])
    lamina_half_cm = a_frac * half_L
    lamina_if_int_idx = int(np.argmin(np.abs(z_int_abs - lamina_half_cm)))
    z_int_pos = z_grid[1:-1]
    max_ph_over_all_t = 7.40
    max_closed_pocket_ph_over_all_t = 7.40
    min_closed_pocket_acidic_ph_over_all_t = 7.40
    hour0_h2o2_to_o2_yield_fraction = 0.0
    f_viable_dynamic = 1.0  # Coupled 336h hypoxic/peroxide/pH dynamic tissue viability state (AUDIT-REF)
    n_int = nz - 2
    max_peroxide_residual_uM_s = 0.0
    max_peroxide_iterations = 0
    max_slab_residual_mmhg_s = 0.0
    slab_solvers_converged = True

    for idx, t_h in enumerate(t_hourly_grid):
        n_rem_mmol = max(0.0, float(sol_y[0, idx]))
        m_rem_frac = max(0.0, (n_rem_mmol / n_cao2_initial_mmol)) if n_cao2_initial_mmol > 0 else 0.0
        v_perf = float(sol_y[1, idx])
        k_perf_s = k_perf_max_s_override * v_perf

        if release_kinetics_law == "shrinking_core":
            o2_gen_mean_mol_cm3_s = (
                0.5
                * (k_sc_h / 3600.0)
                * (n_cao2_initial_mmol * 1e-3)
                * (max(0.0, m_rem_frac) ** (2.0 / 3.0))
                / active_slab_vol_cm3
            )
        elif release_kinetics_law == "ginstling_brounshtein":
            # In Ginstling-Brounshtein 3D diffusion-controlled shrinking-core kinetics,
            # d(alpha)/dt = (3/2) * k_gb / ((1 - alpha)^(-1/3) - 1), regularized by finite initial PDMS surface shell resistance eps_shell = 0.05 at t -> 0:
            denom_gb = max(0.05, (max(1e-9, m_rem_frac) ** (-1.0 / 3.0)) - 1.0) if m_rem_frac > 0.0 else math.inf
            rate_gb_s = (1.5 * (k_gb_h / 3600.0) / denom_gb) if math.isfinite(denom_gb) else 0.0
            o2_gen_mean_mol_cm3_s = 0.5 * rate_gb_s * (n_cao2_initial_mmol * 1e-3) / active_slab_vol_cm3
        else:
            o2_gen_mean_mol_cm3_s = 0.5 * k_hyd_s * (n_rem_mmol * 1e-3) / active_slab_vol_cm3

        # 1. Solve spatial reaction-diffusion BVP for H2O2(z) in uM FIRST:
        s_h2o2_uM_s = 2.0 * o2_gen_mean_mol_cm3_s * 1e9 * s_prof
        # Solve the declared local kinetic equation, including enzyme decay.
        # A single rate derived from a preliminary peak concentration does not
        # satisfy nodewise Michaelis-Menten clearance when substrate saturates.
        cat_active_frac = math.exp(-math.log(2.0) * t_h / catalase_half_life_h) if catalase_present else 1.0
        base_k1 = (float(catalase_k1_override_s_inv) if catalase_k1_override_s_inv is not None else 18.0) if catalase_present else 0.008
        if catalase_present and catalase_spatial_mode == "central_lamina_masked":
            k1_profile: float | np.ndarray = 0.008 + (base_k1 * cat_active_frac - 0.008) * central_mask[1:-1]
        else:
            k1_profile = base_k1 * cat_active_frac if catalase_present else 0.008
        k_perf_profile: float | np.ndarray = (
            k_perf_s * (1.0 - central_mask[1:-1])
            if perfusion_spatial_mode in {"outer_annulus_masked", "outer_annulus_masked_all_species"}
            else k_perf_s
        )
        peroxide = _solve_peroxide_slab_bvp(
            s_h2o2_uM_s[1:-1], float(dz),
            k1_profile,
            k_perf_profile, km_uM=25000.0 if catalase_present else None)
        h2o2_int_operative = peroxide["concentration_uM"]
        h2o2_peak_operative_uM = float(np.max(h2o2_int_operative))
        h2o2_if_operative_uM = float(h2o2_int_operative[lamina_if_int_idx])
        h2o2_if_interp_uM = float(np.interp(lamina_half_cm, z_int_pos, h2o2_int_operative))
        max_h2o2_uM_over_all_t = max(max_h2o2_uM_over_all_t, h2o2_peak_operative_uM)
        max_h2o2_at_lamina_interface_uM_over_all_t = max(max_h2o2_at_lamina_interface_uM_over_all_t, h2o2_if_operative_uM)
        max_h2o2_at_lamina_interface_interp_uM_over_all_t = max(max_h2o2_at_lamina_interface_interp_uM_over_all_t, h2o2_if_interp_uM)
        max_h2o2_uM_with_cat_decay_over_all_t = max(max_h2o2_uM_with_cat_decay_over_all_t, h2o2_peak_operative_uM)
        max_peroxide_residual_uM_s = max(max_peroxide_residual_uM_s, peroxide["residual_inf_uM_s"])
        max_peroxide_iterations = max(max_peroxide_iterations, peroxide["iterations"])

        # Same local decomposition reaction supplies exactly 0.5 mol O2 per mol H2O2.
        o2_local_source_int_mol_cm3_s = 0.5 * peroxide["decomposition_uM_s"] * 1e-9
        q_source_int_mmhg_s = o2_local_source_int_mol_cm3_s / ALPHA_BUNSEN_MOL_CM3_MMHG
        if idx == 0:
            theo_int = float(np.trapezoid(o2_gen_mean_mol_cm3_s * s_prof[1:-1], z_grid[1:-1]))
            actual_int = float(np.trapezoid(o2_local_source_int_mol_cm3_s, z_grid[1:-1]))
            hour0_h2o2_to_o2_yield_fraction = (actual_int / theo_int) if theo_int > 1e-18 else 0.0

        # 2. Solve spatial reaction-diffusion BVP for pO2(z) driven by coupled H2O2 disproportionation O2 source:
        p = np.full(nz, boundary_po2_mmhg, dtype=np.float64)
        d_left = (d_o2_faces[:-1] / (dz * dz)).copy()
        d_right = (d_o2_faces[1:] / (dz * dz)).copy()
        if standoff_cm > 0.0:
            d_left[0] *= robin_boundary_factor
            d_right[-1] *= robin_boundary_factor
        k_perf_o2: float | np.ndarray = k_perf_profile
        for _ in range(80):
            p[0] = boundary_po2_mmhg
            p[-1] = boundary_po2_mmhg
            diff_term = d_left * (p[:-2] - p[1:-1]) + d_right * (p[2:] - p[1:-1])
            p_int = p[1:-1]
            cons = v_demand_mmhg_s * d_prof_int * (p_int / (KM_O2_MMHG + p_int))
            res = diff_term - cons + q_source_int_mmhg_s + k_perf_o2 * (boundary_po2_mmhg - p_int)
            jac_diag = (
                -(d_left + d_right)
                - v_demand_mmhg_s * d_prof_int * (KM_O2_MMHG / ((KM_O2_MMHG + p_int) ** 2))
                - k_perf_o2
            )
            mat = (
                np.diag(jac_diag)
                + np.diag(d_right[:-1], 1)
                + np.diag(d_left[1:], -1)
            )
            step = np.linalg.solve(mat, -res)
            damping = 0.8
            while np.any(p[1:-1] + damping * step < 0.0) and damping > 1e-12:
                damping *= 0.5
            p[1:-1] = np.maximum(0.0, p[1:-1] + damping * step)
            if float(np.max(np.abs(step))) < 1e-6:
                break

        final_slab_residual = (d_left * (p[:-2] - p[1:-1]) + d_right * (p[2:] - p[1:-1])
            - v_demand_mmhg_s * d_prof_int * (p[1:-1] / (KM_O2_MMHG + p[1:-1]))
            + q_source_int_mmhg_s + k_perf_o2 * (boundary_po2_mmhg - p[1:-1]))
        if standoff_cm > 0.0:
            p[0] = robin_boundary_factor * boundary_po2_mmhg + (1.0 - robin_boundary_factor) * p[1]
            p[-1] = robin_boundary_factor * boundary_po2_mmhg + (1.0 - robin_boundary_factor) * p[-2]
        slab_residual = float(np.max(np.abs(final_slab_residual)))
        finite_slab = bool(np.all(np.isfinite(p)) and np.all(p >= 0.0) and math.isfinite(slab_residual))
        if not finite_slab:
            raise ValueError("Slab oxygen BVP left its finite nonnegative domain")
        max_slab_residual_mmhg_s = max(max_slab_residual_mmhg_s, slab_residual)
        slab_solvers_converged = slab_solvers_converged and slab_residual < 1e-6

        min_p = float(np.min(p))
        hourly_min_slab_po2_mmhg.append(min_p)
        center_p = float(p[nz // 2])
        if min_p < min_po2_over_all_t:
            min_po2_over_all_t = min_p
            time_of_min_po2_h = t_h

        # 3. Coupled Henderson-Hasselbalch CO2/HCO3-/HEPES interstitial pH BVP & Closed-Pocket Acidic/Alkaline Bounds (AUDIT-REF):
        oh_source_mM_s = 4.0 * o2_gen_mean_mol_cm3_s * 1e6 * s_prof
        d_oh_eff = 1.5e-5  # Effective OH-/HCO3- counter-diffusion coefficient (cm^2/s)
        oh_diag = np.full(n_int, -2.0 * d_oh_eff / (dz * dz)) - k_perf_profile
        oh_mat = (
            np.diag(oh_diag)
            + np.diag(np.full(n_int - 1, d_oh_eff / (dz * dz)), 1)
            + np.diag(np.full(n_int - 1, d_oh_eff / (dz * dz)), -1)
        )
        oh_accum_mM = np.linalg.solve(oh_mat, -oh_source_mM_s[1:-1])
        peak_oh_mM = float(np.max(np.maximum(0.0, oh_accum_mM)))
        delta_ph = peak_oh_mM / BETA_BUF_MM_PER_PH
        if peak_oh_mM > 0.35 * BETA_BUF_MM_PER_PH:
            excess_mM = peak_oh_mM - 0.35 * BETA_BUF_MM_PER_PH
            delta_ph += 1.45 * math.log1p(excess_mM)
        local_ph = min(12.45, 7.40 + delta_ph)