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…


def _solve_two_zone_fv_wigner_seitz_bvp(
    mean_po2_mmhg: float,
    radius_cm: float,
    phi_islet_in_slab: float = 0.1262247,
    n_per_zone: int = 100,
    supply_closure: str = "uniform",
    d_hydrogel_override: float | None = None,
    ocr_multiplier: float = 1.0,
) -> Dict[str, Any]:
    """
    Conservative two-zone radial finite-volume (FV) spherical unit-cell BVP solver across
    r in [0, R_c] (islet core, D = D_islet) and r in [R_c, R_ws] (pericellular hydrogel shell,
    D = D_hydrogel, R_ws = R_c * phi^(-1/3) = 119.6106 um at R_c = 60 um, phi = 0.1262247),
    enforcing exact interfacial harmonic flux continuity at r = R_c, no-flux outer boundary at r = R_ws,
    and constrained cell-volume-mean oxygen <p>_ws = mean_po2_mmhg under declared supply closures:
      - 'uniform': macroscopic O2 supply distributed uniformly across the unit cell, or
      - 'gel_only': macroscopic O2 supply restricted exclusively to the extracellular hydrogel shell [R_c, R_ws].
    Directly closes AUDIT-REF and AUDIT-REF.
    """
    for name, value, lower, upper in (
        ("mean_po2_mmhg", mean_po2_mmhg, 0.0, None),
        ("radius_cm", radius_cm, 0.0, None),
        ("phi_islet_in_slab", phi_islet_in_slab, 0.0, 1.0),
        ("ocr_multiplier", ocr_multiplier, 0.0, None),
    ):
        if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value):
            raise ValueError(f"{name} must be finite")
        if value < lower or (name != "mean_po2_mmhg" and value == lower) or (upper is not None and value > upper):
            raise ValueError(f"{name} outside the physical domain")
    if not isinstance(n_per_zone, int) or isinstance(n_per_zone, bool) or n_per_zone < 2:
        raise ValueError("n_per_zone must be an integer >= 2")
    if supply_closure not in {"uniform", "gel_only"}:
        raise ValueError("unsupported supply_closure")
    if d_hydrogel_override is not None and (isinstance(d_hydrogel_override, bool)
            or not isinstance(d_hydrogel_override, (int, float))
            or not math.isfinite(d_hydrogel_override) or d_hydrogel_override <= 0):
        raise ValueError("d_hydrogel_override must be finite and positive")
    if phi_islet_in_slab == 1.0 and supply_closure == "gel_only":
        raise ValueError("gel_only supply has no hydrogel compartment at phi=1; use uniform for the homogeneous limit")
    if mean_po2_mmhg <= 1e-5:
        return {
            "supply_closure": supply_closure,
            "n_per_zone": n_per_zone,
            "wigner_seitz_outer_radius_um": round(radius_cm * (phi_islet_in_slab ** (-1.0 / 3.0)) * 1e4, 4),
            "surface_po2_mmhg": 0.0,
            "core_po2_mmhg": 0.0,
            "core_po2_unrounded_mmhg": 0.0,
            "outer_shell_po2_mmhg": 0.0,
            **_zero_oxygen_shortcut_diagnostics(mean_po2_mmhg, 1e-5, "volume_mean"),
            "mean_constraint_error_mmhg": -mean_po2_mmhg,
        }
    phi_clamped = phi_islet_in_slab
    r_ws_cm = radius_cm * (phi_clamped ** (-1.0 / 3.0))
    d_gel = d_hydrogel_override if d_hydrogel_override is not None else D_O2_HYDROGEL_CM2_S
    q_mmhg_s = (VMAX_ISLET_PURE_MOL_CM3_S * float(ocr_multiplier)) / ALPHA_BUNSEN_MOL_CM3_MMHG
    n = n_per_zone
    if phi_clamped == 1.0:
        edges = np.linspace(0.0, radius_cm, n + 1)
    else:
        n_outer = n if phi_clamped <= 0.5 else max(1, int(round(n * (r_ws_cm - radius_cm) / radius_cm)))
        edges = np.r_[np.linspace(0.0, radius_cm, n + 1), np.linspace(radius_cm, r_ws_cm, n_outer + 1)[1:]]
    r_centers = 0.5 * (edges[:-1] + edges[1:])
    vol = np.diff(edges ** 3) / 3.0
    weights = vol / float(np.sum(vol))
    inner = r_centers < radius_cm
    d_zone = np.where(inner, D_O2_ISLET_TISSUE_CM2_S, d_gel)
    conduct = (edges[1:-1] ** 2) / (
        (edges[1:-1] - r_centers[:-1]) / d_zone[:-1] + (r_centers[1:] - edges[1:-1]) / d_zone[1:]
    )

    total_n = len(r_centers)
    lo_l = np.zeros(total_n - 1, dtype=np.float64)
    diag_l = np.zeros(total_n, dtype=np.float64)
    up_l = np.zeros(total_n - 1, dtype=np.float64)
    for i, c in enumerate(conduct):
        diag_l[i] -= c / vol[i]
        up_l[i] = c / vol[i]
        lo_l[i] = c / vol[i + 1]
        diag_l[i + 1] -= c / vol[i + 1]

    if phi_clamped == 1.0:
        w_supply = (
            np.ones(total_n, dtype=np.float64)
            if supply_closure == "uniform"
            else np.r_[np.zeros(total_n - 1, dtype=np.float64), 1.0]
        )
        s_rate = float(q_mmhg_s if supply_closure == "uniform" else q_mmhg_s / weights[-1])
    else:
        w_supply = np.ones(total_n, dtype=np.float64) if supply_closure == "uniform" else (~inner).astype(np.float64)
        s_rate = float(q_mmhg_s * phi_clamped / (1.0 if supply_closure == "uniform" else max(1e-6, 1.0 - phi_clamped)))
    p = np.full(total_n, mean_po2_mmhg, dtype=np.float64)
    iterations = 0
    res = np.zeros(total_n, dtype=np.float64)
    mr = 0.0
    def diffusion_residual(state: np.ndarray) -> np.ndarray:
        flux = conduct * np.diff(state)
        laplacian = np.zeros(total_n, dtype=np.float64)
        laplacian[:-1] += flux / vol[:-1]
        laplacian[1:] -= flux / vol[1:]
        return laplacian

    for it in range(100):
        iterations = it + 1
        sink = np.where(inner, q_mmhg_s * p / (KM_O2_MMHG + p), 0.0)
        lap_p = diffusion_residual(p)
        res = lap_p - sink + s_rate * w_supply
        mr = float(np.dot(weights, p) - mean_po2_mmhg)
        if max(float(np.max(np.abs(res))), abs(mr)) < 1e-8:
            break
        sink_derivative = np.where(inner, q_mmhg_s * KM_O2_MMHG / ((KM_O2_MMHG + p) ** 2), 0.0)
        j_diag = diag_l - sink_derivative
        dp, ds = _mean_constrained_newton_step(
            lo_l, j_diag, up_l, sink_derivative, weights, w_supply, res, mr)
        fac = 1.0
        while (np.min(p + fac * dp) <= 0.0 or s_rate + fac * ds < 0.0) and fac > 1e-8:
            fac *= 0.5
        p = np.maximum(1e-12, p + fac * dp)
        s_rate = max(0.0, s_rate + fac * ds)

    if phi_clamped == 1.0:
        p_surf = (
            float(p[-1])
            if supply_closure == "uniform"
            else float(p[-1] + (p[-1] - p[-2]) * (radius_cm - r_centers[-1]) / (r_centers[-1] - r_centers[-2]))
        )
    else:
        idx_if = n - 1
        c_if = conduct[idx_if]
        flux_if = c_if * (p[idx_if + 1] - p[idx_if])
        p_surf = float(p[idx_if] + flux_if * (radius_cm - r_centers[idx_if]) / (d_zone[idx_if] * (radius_cm ** 2)))
    lap_final = diffusion_residual(p)
    final_sink = np.where(inner, q_mmhg_s * p / (KM_O2_MMHG + p), 0.0)
    final_res = lap_final - final_sink + s_rate * w_supply
    final_mean_error = float(np.dot(weights, p) - mean_po2_mmhg)
    out_dict: Dict[str, Any] = {
        "supply_closure": supply_closure,
        "n_per_zone": n_per_zone,
        "wigner_seitz_outer_radius_um": round(r_ws_cm * 1e4, 4),
        "surface_po2_mmhg": round(p_surf, 4),
        "surface_po2_unrounded_mmhg": p_surf,
        "core_po2_mmhg": round(float(p[0]), 4),
        "core_po2_unrounded_mmhg": float(p[0]),
        "outer_shell_po2_mmhg": round(p_surf if phi_clamped == 1.0 else float(p[-1]), 4),
        "converged": bool(max(float(np.max(np.abs(final_res))), abs(final_mean_error)) < 1e-7),
        "iterations": iterations,
        "residual_inf_mmhg_s": float(np.max(np.abs(final_res))),
        "mean_constraint_error_mmhg": final_mean_error,
        "oxygen_consumption_volume_mean_mmhg_s": float(np.dot(weights, final_sink)),
        "oxygen_supply_volume_mean_mmhg_s": float(s_rate * np.dot(weights, w_supply)),
        "integrated_mass_balance_error_mmhg_s": float(np.dot(weights, s_rate * w_supply - final_sink)),
    }
    if phi_clamped < 1.0:
        out_dict["interface_flux_balance_error_mmhg_cm3_s"] = float(4.0 * math.pi * (
            flux_if - np.dot(vol[inner], final_sink[inner] - s_rate * w_supply[inner])))
    if phi_clamped == 1.0:
        core_h, _, _ = _solve_fixed_surface_spherical_bvp_with_diagnostics(mean_po2_mmhg, radius_cm)
        out_dict["homogenized_dirichlet_upper_bound_core_po2_mmhg"] = round(core_h, 4)
    return out_dict


def _solve_peroxide_slab_bvp(
    source_uM_s: np.ndarray, dz_cm: float, catalytic_rate_s_inv: float | np.ndarray,
    perfusion_rate_s_inv: float | np.ndarray, *, km_uM: float | None = None,
) -> Dict[str, Any]:
    """Solve local peroxide clearance with zero-concentration host boundaries.

    Michaelis-Menten clearance is evaluated at every node of the solved state;
    the returned decomposition rate is also the stoichiometric oxygen source.
    Supports both scalar and nodewise 1D spatial profiles for catalytic_rate_s_inv and perfusion_rate_s_inv.
    """
    source = np.asarray(source_uM_s)
    if (source.ndim != 1 or not len(source)
            or not (np.issubdtype(source.dtype, np.integer) or np.issubdtype(source.dtype, np.floating))
            or not np.all(np.isfinite(source)) or np.any(source < 0)):
        raise ValueError("Peroxide source must be a finite nonnegative real vector")
    if (isinstance(dz_cm, bool) or not isinstance(dz_cm, (int, float)) or not math.isfinite(dz_cm) or dz_cm <= 0):
        raise ValueError("dz_cm outside its finite physical domain")
    if isinstance(perfusion_rate_s_inv, np.ndarray):
        perf_vec = np.asarray(perfusion_rate_s_inv, dtype=float)
        if (perf_vec.ndim != 1 or len(perf_vec) != len(source)
                or not np.all(np.isfinite(perf_vec)) or np.any(perf_vec < 0)):
            raise ValueError("perfusion_rate_s_inv vector outside its finite nonnegative physical domain")
    else:
        if (isinstance(perfusion_rate_s_inv, bool) or not isinstance(perfusion_rate_s_inv, (int, float))
                or not math.isfinite(perfusion_rate_s_inv) or perfusion_rate_s_inv < 0):
            raise ValueError("perfusion_rate_s_inv outside its finite physical domain")
        perf_vec = np.full(len(source), float(perfusion_rate_s_inv), dtype=float)
    if isinstance(catalytic_rate_s_inv, np.ndarray):
        cat_vec = np.asarray(catalytic_rate_s_inv, dtype=float)
        if (cat_vec.ndim != 1 or len(cat_vec) != len(source)
                or not np.all(np.isfinite(cat_vec)) or np.any(cat_vec < 0)):
            raise ValueError("catalytic_rate_s_inv vector outside its finite nonnegative physical domain")
    else:
        if (isinstance(catalytic_rate_s_inv, bool) or not isinstance(catalytic_rate_s_inv, (int, float))
                or not math.isfinite(catalytic_rate_s_inv) or catalytic_rate_s_inv < 0):
            raise ValueError("catalytic_rate_s_inv outside its finite physical domain")
        cat_vec = np.full(len(source), float(catalytic_rate_s_inv), dtype=float)
    if km_uM is not None and (isinstance(km_uM, bool) or not isinstance(km_uM, (int, float))
                             or not math.isfinite(km_uM) or km_uM <= 0):
        raise ValueError("km_uM must be finite and positive")
    source = source.astype(float, copy=False)
    try:
        diffusion = D_H2O2_HYDROGEL_CM2_S / (dz_cm * dz_cm)
    except (ZeroDivisionError, OverflowError) as exc:
        raise ValueError("Peroxide grid is outside representable numeric range") from exc
    if not math.isfinite(diffusion) or diffusion <= 0:
        raise ValueError("Peroxide grid is outside representable numeric range")
    off = np.full(len(source)-1, diffusion)
    linear_diag = -2.0*diffusion - perf_vec - cat_vec
    h = _tridiag_thomas_solve(off, linear_diag, off, -source)
    tolerance = 1e-8 + 1e-10*max(1.0, float(np.max(source)))
    converged = False
    residual_inf = math.inf
    for iteration in range(80):
        saturation = np.ones_like(h) if km_uM is None else 1.0 + h/km_uM
        decomposition = cat_vec * (h/saturation)
        residual = (-2.0*diffusion-perf_vec)*h - decomposition + source
        residual[:-1] += diffusion*h[1:]
        residual[1:] += diffusion*h[:-1]
        if not np.all(np.isfinite(h)) or np.any(h < 0) or not np.all(np.isfinite(residual)):
            raise ValueError("Peroxide solve left its finite nonnegative domain")
        residual_inf = float(np.max(np.abs(residual)))
        if residual_inf <= tolerance:
            converged = True
            break
        derivative = cat_vec / saturation / saturation
        diagonal = -2.0*diffusion-perf_vec-derivative
        step = _tridiag_thomas_solve(off, diagonal, off, -residual)
        factor = 1.0
        while np.any(h+factor*step < 0) and factor > 1e-12:
            factor *= 0.5
        h = h+factor*step
    if not converged:
        raise ValueError("Peroxide nonlinear BVP did not converge")
    return {"concentration_uM": h, "decomposition_uM_s": decomposition,
            "converged": True, "iterations": iteration+1,
            "residual_inf_uM_s": residual_inf,
            "kinetics": "NODEWISE_MICHAELIS_MENTEN" if km_uM is not None else "LINEAR_FIRST_ORDER"}


def _required_oxygen_solvers_converged(bvp: Dict[str, Any]) -> bool:
    """A favorable oxygen value is insufficient when any required solve is unresolved."""
    required = ("spherical_bvp_solver_diagnostics",
                "wigner_seitz_two_zone_fv_uniform_supply_exact",
                "wigner_seitz_two_zone_fv_gel_only_supply_exact")
    return all(isinstance(bvp.get(key), dict) and bvp[key].get("converged") is True for key in required)