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…

                prev_in = sec_ins
                for j in range(k_b):
                    cur = y[7 + pos + j]
                    d_tr[pos + j] = (prev_in - cur) / tau_b
                    prev_in = cur
                flux_out += w_b * y[7 + pos + k_b - 1]
                pos += k_b
            dIp_dt = flux_out - k_ip_clear * Ip
            dX_dt = k_x_decay * (max(0.0, Ip - 45.0) / 100.0 - X)
            dU_dt = (1.2 * lpf * M_sec - U) / 2.5
            sst_drive = lpf * (0.65 * U + 0.45 * ((G_pos ** 4) / (5.8 ** 4 + G_pos ** 4)))
            dS_dt = (sst_drive - S) / 1.5
            low_g = 1.0 / (1.0 + ((G_pos / 4.45) ** 6))
            ins_eff = Ip * (1.0 - g_s * (1.0 - ((G_pos / 4.20) ** 8))) if G_pos < 4.20 else Ip
            gcg_sec = 11.4 + (56.0 * v) * low_g / (1.0 + 0.018 * max(0.0, ins_eff - 52.0) + 0.35 * S_pos)
            dGcg_dt = gcg_sec - 0.20 * Gcg
            ex = ex_intensity if ex_start_min <= t <= ex_end_min else 0.0
            basal_tone = min(1.0, (max(0.0, Ip) / 25.0) ** 2)
            egp = max(0.010, 0.056 * (1.0 + 0.018 * (Gcg - 58.0)) / (1.0 + 0.26 * max(0.0, X)) + 0.068 * (1.0 - basal_tone))
            uptake_ind = 0.032 * (G_pos / (1.2 + G_pos)) * (1.0 + 0.48 * ex)
            uptake_ins = (0.0052 * basal_tone + 0.0135 * max(0.0, X)) * G_pos * (1.0 + 1.55 * ex)
            renal = 0.0065 * max(0.0, G_pos - 10.0)
            dG_dt = egp + _meal_app(t) - uptake_ind - uptake_ins - renal
            return np.concatenate(([dG_dt, dIp_dt, dX_dt, dU_dt, dS_dt, dGcg_dt, dM_dt], d_tr))

        rhs.integration_breakpoints = piecewise_events  # type: ignore[attr-defined]
        sol = rk4_integrate(rhs, (0.0, 1440.0), y0, t_grid, dt_max=dt_max)
        return float(np.min(sol[0, :]))

    specs = [
        ("published_two_equal_serial_stages", "baseline_control", pub_branches),
        ("one_exponential_passage_same_t50", "half_time_counterexample", one_exp_branches),
        ("two_parallel_80pct_fast_20pct_slow_same_t50", "half_time_counterexample", two_par_branches),
        ("mean_and_median_matched_50pct_erlang4_50pct_exp", "mean_median_positive_control", ctrl_e4_exp),
        ("mean_and_median_matched_85pct_erlang3_15pct_exp", "mean_median_positive_control", ctrl_e3_exp),
    ]
    rows: List[Dict[str, Any]] = []
    for name, role, branches in specs:
        mean_t = sum(w * k * tau for w, k, tau in branches)
        t50_chk = _solve_quantile(branches, 0.5)
        t90_chk = _solve_quantile(branches, 0.1)
        s15_pct = 100.0 * _mixture_survival(15.0, branches)
        nadir = _run_branches(branches)
        dec134_pass = bool(t50_chk <= 4.50 and mean_t <= 5.50 and t90_chk <= 11.0)
        rows.append({
            "curve_id": name,
            "role": role,
            "mean_transit_min": round(mean_t, 6),
            "step_down_t50_min": round(t50_chk, 6),
            "step_down_t90_min": round(t90_chk, 6),
            "fraction_remaining_at_15min_pct": round(s15_pct, 4),
            "simulated_exercise_glucose_nadir_mM": round(nadir, 6),
            "passes_3p50_mM_screen": bool(nadir >= 3.50),
            "passes_dec134_washout_tail_gate": dec134_pass,
        })

    return {
        "finding_id": "BPR-15",
        "decision_id": "DEC-133",
        "dec134_locked_washout_tail_gate": {
            "decision_id": "DEC-134",
            "t50_max_min": 4.50,
            "mean_transit_max_min": 5.50,
            "t90_max_min": 11.0,
            "required_end_remaining_fraction_max": 0.10,
            "min_observation_window_min": 15.0,
            "mass_recovery_fraction_range": [0.80, 1.20],
            "all_passing_controls_pass_dec134": all(
                r["passes_dec134_washout_tail_gate"] for r in rows if r["passes_3p50_mM_screen"]
            ),
            "all_failing_counterexamples_rejected_by_dec134": all(
                not r["passes_dec134_washout_tail_gate"] for r in rows if not r["passes_3p50_mM_screen"]
            ),
        },
        "conditional_scope": "HALF_TIME_SCREEN_CONDITIONAL_ON_ASSUMED_TWO_SERIAL_STAGE_TRANSFER_CURVE",
        "reference_t_pub_min": t_pub_min,
        "shared_step_down_t50_min": round(t50_target, 6),
        "viable_endocrine_fraction": v,
        "rk4_dt_max_min": dt_max,
        "curves": rows,
        "owner_boundary_note": (
            "DEC-134 locks the Stage-0 bench perifusion washout tail gate (trace run to <= 10% remaining with "
            "80-120% mass recovery, t50 <= 4.50 min, mean transit <= 5.50 min, t90 <= 11.0 min), revisable with "
            "physical whole-device perifusion data. Direct human exercise-challenge and multi-year CGM durability "
            "endpoints remain parked on the Stage 4-5 Pre-IND Clinical Checklist."
        ),
    }


def _validate_pde_coupling_regimes(regimes: List[Dict[str, Any]] | None) -> None:
    """Fail before metabolic execution when imported PDE states have invalid units/domains.

    Legacy rows remain readable, but only explicit strict Boolean qualifications
    may contribute to a complete-product conditional verdict.
    """
    if regimes is None:
        return
    if not isinstance(regimes, list):
        raise ValueError("pde_regimes must be a list of distinct regime objects")
    seen: set[str] = set()
    for row in regimes:
        if not isinstance(row, dict):
            raise ValueError("Each PDE coupling regime must be an object")
        name = row.get("regime_id")
        if not isinstance(name, str) or not name.strip() or name in seen:
            raise ValueError("PDE coupling regimes require unique nonempty regime_id values")
        seen.add(name)
        numeric_fields = {
            "min_120um_cluster_core_po2_mmhg": (0.0, None, True),
            "min_120um_cluster_core_po2_unrounded_mmhg": (0.0, None, False),
            "min_slab_po2_across_14_days_mmhg": (0.0, None, True),
            "min_slab_po2_unrounded_mmhg": (0.0, None, False),
            "max_interstitial_h2o2_uM": (0.0, None, True),
            "max_interstitial_h2o2_unrounded_uM": (0.0, None, False),
            "max_interstitial_ph": (0.0, 14.0, True),
            "max_interstitial_ph_unrounded": (0.0, 14.0, False),
            "coupled_dynamic_14d_viable_endocrine_fraction_v80_066": (0.0, 1.0, False),
            "coupled_dynamic_14d_viable_endocrine_fraction_unrounded": (0.0, 1.0, False),
        }
        for key, (lower, upper, required) in numeric_fields.items():
            if key not in row and not required:
                continue
            value = row.get(key)
            if (isinstance(value, (bool, np.bool_))
                    or not isinstance(value, (int, float, np.integer, np.floating))
                    or not math.isfinite(value) or value < lower
                    or (upper is not None and value > upper)):
                raise ValueError(f"PDE coupling field {key} must be a finite physical value")
        for key in (
            "passes_all_oxygen_peroxide_and_ph_gates",
            "passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate",
            "passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_gel_only",
        ):
            if key in row or key == "passes_all_oxygen_peroxide_and_ph_gates":
                if not isinstance(row.get(key), bool):
                    raise ValueError(f"PDE coupling qualification {key} must be a Boolean")
        audit = row.get("wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001", {})
        if not isinstance(audit, dict):
            raise ValueError("PDE coupling oxygen audit must be an object")
        for audit_key in (
            "two_zone_fv_gel_only_supply_120um_core_po2_unrounded_mmhg",
            "two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg",
            "two_zone_fv_gel_only_supply_surface_po2_mmhg",
        ):
            val = audit.get(audit_key)
            if val is not None and (
                isinstance(val, (bool, np.bool_))
                or not isinstance(val, (int, float, np.integer, np.floating))
                or not math.isfinite(val)
                or val < 0
            ):
                raise ValueError(f"PDE coupling oxygen audit field {audit_key} must be finite and nonnegative")


def solve_24h_paracrine_and_whole_body_metabolic_ode(
    pde_regimes: List[Dict[str, Any]] | None = None,
) -> Dict[str, Any]:
    """
    Solve a 24-hour (1,440-minute) coupled beta/alpha/delta paracrine & whole-body
    glucose-insulin-glucagon-somatostatin ODE system (`rk4_integrate`, dt=0.25 min)
    across 3 meals (75 g, 85 g, 90 g CHO), 60-min afternoon aerobic exercise (t = 600..660 min),
    and nocturnal fasting.
    Closes AUDIT-REF, AUDIT-REF, and AUDIT-REF:
      - Peripheral insulin-action clearance rate `k_x_decay = 0.035 min^-1` is held strictly
        identical across all 3 comparators.
      - `enable_low_g_sst_clamp` (< 4.2 mM quadratic GIRK clamp) is isolated from
        `enable_constitutive_sst_basal_suppression` (6.0 vs 6.8 pM/min basal tone), so deleting
        only the < 4.2 mM clamp leaves the standard trajectory (min_G = 4.59 mM > 4.2 mM)
        strictly unchanged (`min = 4.59 mM`, `mean = 5.71 mM`, `t50 = 4.93 min`), while a
        dedicated low-glucose challenge (`min_G < 4.2 mM`) tests the `< 4.2 mM` clamp directly.
      - All SST-attributed effects (`low_g_sst_clamp`, `enable_constitutive_sst_basal_suppression`,
        `sst_inhib`, and `tau_m_min` shut-off acceleration) depend on active somatostatin concentration
        `S > 0` (`sst_active_gate`), vanishing identically when `S(t) == 0`.
      - Reports sensitivity under common basal/shutoff constants (`5.23 / 5.31 / 4.37 min`) and
        couples Part A PDE viable endocrine fraction to Part B functional secretion capacity.
    """
    _validate_pde_coupling_regimes(pde_regimes)
    graft_models = [
        {
            "graft_id": "OPENISLET_60_30_10_TRIHORMONAL_G6PC2_WT",
            "description": "60% SC-beta (G6PC2 WT, K_0.5 = 7.2 mM) + 30% SC-alpha + 10% SC-delta (UCN3 -> CRHR2 delta SST paracrine brake + alpha GCG counter-regulation)",
            "beta_cell_fraction": 0.60,
            "alpha_cell_fraction": 0.30,
            "delta_cell_fraction": 0.10,
            "matched_functional_beta_ieq_dose_assumption": "500,000 IEQ functional beta-cell equivalent mass held constant across comparators to isolate paracrine topology and G6PC2 rheostat kinetics",
            "k05_gsis_mM": 7.2,
            "hill_gsis": 4.2,
            "has_ucn3_delta_sst_brake": True,
            "has_alpha_gcg_counterregulation": True,
        },
        {
            "graft_id": "BETA_ONLY_MONOCULTURE_NO_ALPHA_DELTA",
            "description": "95% SC-beta monoculture lacking delta-cell SST paracrine brake and alpha-cell glucagon counter-regulation",
            "beta_cell_fraction": 0.95,
            "alpha_cell_fraction": 0.00,
            "delta_cell_fraction": 0.00,
            "matched_functional_beta_ieq_dose_assumption": "500,000 IEQ functional beta-cell equivalent mass held constant across comparators to isolate paracrine topology and G6PC2 rheostat kinetics",
            "k05_gsis_mM": 7.2,
            "hill_gsis": 4.2,
            "has_ucn3_delta_sst_brake": False,
            "has_alpha_gcg_counterregulation": False,
        },
        {
            "graft_id": "G6PC2_KO_DISRUPTED_GLYCOLYTIC_RHEOSTAT_GY002",
            "description": "60:30:10 graft with G6PC2-/- knockout (left-shifted K_0.5 = 4.3 mM causing basal hyperinsulinemia and fasting/exercise hypoglycemia; Graveyard Rule GY-002)",
            "beta_cell_fraction": 0.60,
            "alpha_cell_fraction": 0.30,
            "delta_cell_fraction": 0.10,
            "matched_functional_beta_ieq_dose_assumption": "500,000 IEQ functional beta-cell equivalent mass held constant across comparators to isolate paracrine topology and G6PC2 rheostat kinetics",
            "k05_gsis_mM": 4.3,
            "hill_gsis": 3.4,
            "has_ucn3_delta_sst_brake": True,
            "has_alpha_gcg_counterregulation": True,
        },
    ]

    # Explicit meal carbohydrate mass balance (AUDIT-REF):
    #   MW_glucose = 180.156 g/mol -> 1 g CHO = 5.55074 mmol glucose.
    #   With gut bioavailability F_gut = 0.90 and extracellular distribution volume V_G = 13.16 L (0.188 L/kg for 70 kg),
    #   portal glucose appearance per gram CHO is (0.90 * 5.55074 mmol/g) / 13.16 L = 0.3796 mM/g CHO.
    #   Under normal splanchnic/hepatic first-pass extraction + glycogen synthesis (f_splanchnic = 0.7497366),
    #   net post-hepatic systemic appearance is 0.3796 * (1 - 0.7497366) = 0.0950 mM/g CHO.
    def meal_appearance_mM_min(
        t_min: float,
        meals_override: List[tuple[float, float]] | None = None,
        systemic_gain_mM_per_g: float = 0.095,
    ) -> float:
        meals = meals_override if meals_override is not None else [(60.0, 75.0), (360.0, 85.0), (780.0, 90.0)]
        r = 0.0
        tau_m = 34.0
        for t0, grams in meals:
            if t_min > t0:
                dt = t_min - t0
                amp = (grams * systemic_gain_mM_per_g) / (tau_m * tau_m)
                r += amp * dt * math.exp(-dt / tau_m)
        return r

    simulations = []
    # Evaluate shutoff on the 0.25-min reporting grid, with interpolation between samples.
    t_grid = np.linspace(0.0, 1440.0, 5761)
    k_x_decay_shared = 0.035  # Strictly identical peripheral insulin-action rate constant across all comparators (AUDIT-REF)
    comparison_states: Dict[tuple[str, bool], np.ndarray] = {}

    def _run_single_metabolic_ode_model(
        gm: Dict[str, Any],
        include_trajectory: bool = True,
        force_zero_sst: bool = False,
        force_common_basal_and_shutoff: bool = False,
        viable_endocrine_fraction: float = 1.0,
        low_glucose_challenge_mode: bool = False,