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…

            ode_surf_gsis_phys_v060_continuous_g0 = _run_single_metabolic_ode_model(
                graft_models[0],
                include_trajectory=False,
                viable_endocrine_fraction=f_viable_surf_gsis_phys_v060,
                source_pde_regime_id=pr["regime_id"],
                local_paracrine_preserved_systemic_scale=True,
                g0_override_mM=5.1,
                _integrator=_ORIGINAL_RK4_INTEGRATE,
                _skip_shutoff_half_time=True,
            )
            coupled_pde_ode_table.append(
                {
                    "pde_regime_id": pr["regime_id"],
                    "pde_regime": pr["regime_id"],
                    "source_pde_regime_id": ode_coupled["source_pde_regime_id"],
                    "pde_coupling_applied": True,
                    "evaluation_scope": ode_coupled["evaluation_scope"],
                    "pde_passes_all_oxygen_peroxide_and_ph_gates": pr["passes_all_oxygen_peroxide_and_ph_gates"],
                    "pde_passes_strict_gel_only_qualification": pr.get("passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate") is True,
                    "core_coupling_source": "gel_only_unrounded" if conservative_core is not None else "legacy_dirichlet_upper_bound_not_qualified",
                    "qualified_exact_product": False,
                    "coupled_viable_endocrine_fraction": round(f_viable, 4),
                    "coupled_viable_endocrine_fraction_unrounded": f_viable,
                    "prescribed_cluster_diameter_um": round(prescribed_diam, 2),
                    "f_gsis_surface_competency": round(f_gsis_surf, 4),
                    "dxb_100um_f_gsis_surface_competency": round(f_gsis_surf_100, 4),
                    "dxb_80um_f_gsis_surface_competency": round(f_gsis_surf_80, 4),
                    "surface_gsis_secretion_coupled_trajectory_sonnet55_r2": {
                        "effective_secretion_competent_fraction_f_viable_times_f_gsis_surf": round(f_viable_surf_gsis, 4),
                        "initial_glucose_g0_mM": ode_surf_gsis_coupled["initial_glucose_g0_mM"],
                        "coupled_24h_time_in_range_pct": ode_surf_gsis_coupled["time_in_tight_range_3p9_to_10p0_mM_pct"],
                        "coupled_24h_max_postprandial_glucose_mM": ode_surf_gsis_coupled["max_postprandial_glucose_mM"],
                        "coupled_24h_max_glucose_full_0_to_1440min_mM": ode_surf_gsis_coupled["max_glucose_full_0_to_1440min_mM"],
                        "coupled_24h_max_postprandial_glucose_after_60min_mM": ode_surf_gsis_coupled["max_postprandial_glucose_after_60min_mM"],
                        "coupled_24h_mean_glucose_mM": ode_surf_gsis_coupled["mean_glucose_mM"],
                        "coupled_24h_min_glucose_mM": ode_surf_gsis_coupled["min_glucose_mM"],
                        "physical_300k_beta_eq_dose_v0p60_times_f_viable_times_f_gsis_surf": round(f_viable_surf_gsis_phys_v060, 4),
                        "physical_300k_beta_eq_initial_glucose_g0_mM": ode_surf_gsis_phys_v060_coupled["initial_glucose_g0_mM"],
                        "physical_300k_beta_eq_paracrine_preserved_24h_time_in_range_pct": ode_surf_gsis_phys_v060_coupled["time_in_tight_range_3p9_to_10p0_mM_pct"],
                        "physical_300k_beta_eq_paracrine_preserved_24h_max_postprandial_after_60min_mM": ode_surf_gsis_phys_v060_coupled["max_postprandial_glucose_after_60min_mM"],
                        "physical_300k_beta_eq_paracrine_preserved_24h_min_glucose_mM": ode_surf_gsis_phys_v060_coupled["min_glucose_mM"],
                        "physical_300k_beta_eq_paracrine_preserved_passes_clinical_glycemic_safety_targets": ode_surf_gsis_phys_v060_coupled["passes_clinical_glycemic_safety_targets"],
                        "physical_300k_beta_eq_continuous_g0_5p1mM_time_in_range_pct_astra_r3": ode_surf_gsis_phys_v060_continuous_g0["time_in_tight_range_3p9_to_10p0_mM_pct"],
                        "physical_300k_beta_eq_continuous_g0_5p1mM_max_postprandial_after_60min_mM_astra_r3": ode_surf_gsis_phys_v060_continuous_g0["max_postprandial_glucose_after_60min_mM"],
                        "physical_300k_beta_eq_continuous_g0_5p1mM_min_glucose_mM_astra_r3": ode_surf_gsis_phys_v060_continuous_g0["min_glucose_mM"],
                        "initial_glucose_g0_discontinuity_at_v0p60_note_astra_r3": (
                            "Below v = 0.60, _run_single_metabolic_ode_model switches from normoglycemic fasting G(0) = 5.1 mM (at v >= 0.60) to the marginal-mass "
                            "decompensation ramp G(0) = 17.2 - 12.1*v (a +4.84 mM step jump at v = 0.60^- where G(0) -> 9.94 mM); both the default marginal-mass "
                            "ramp trajectory and the continuous G(0) = 5.1 mM comparator are reported above (AUDIT-REF)."
                        ),
                    },
                    "coupled_24h_time_in_range_pct": ode_coupled["time_in_tight_range_3p9_to_10p0_mM_pct"],
                    "coupled_24h_max_postprandial_glucose_mM": ode_coupled["max_postprandial_glucose_mM"],
                    "coupled_24h_mean_glucose_mM": ode_coupled["mean_glucose_mM"],
                    "coupled_metabolic_glycemic_gate_passed": ode_coupled["passes_clinical_glycemic_safety_targets"],
                    "wigner_seitz_cluster_surface_po2_uniform_mmhg": audit.get("two_zone_fv_uniform_supply_surface_po2_mmhg"),
                    "wigner_seitz_cluster_surface_po2_gel_only_mmhg": audit.get("two_zone_fv_gel_only_supply_surface_po2_mmhg"),
                    "coupled_survival_and_chemistry_screen_pass": bool(
                        pr["passes_all_oxygen_peroxide_and_ph_gates"]
                        and pr.get("passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate") is True
                        and conservative_core is not None and core_p >= 2.0
                        and slab_p >= 15.0 and h2o2_max <= 5.0 and ph_max <= 7.60
                        and ode_coupled["passes_clinical_glycemic_safety_targets"]
                    ),
                    "coupled_full_gsis_cluster_surface_15mmHg_qualified_pass": bool(
                        pr["passes_all_oxygen_peroxide_and_ph_gates"]
                        and pr.get("passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate") is True
                        and pr.get("passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_gel_only") is True
                        and conservative_core is not None and conservative_surf is not None
                        and core_p >= 2.0 and surf_p >= 15.0
                        and slab_p >= 15.0 and h2o2_max <= 5.0 and ph_max <= 7.60
                        and ode_coupled["passes_clinical_glycemic_safety_targets"]
                        and ode_surf_gsis_coupled["passes_clinical_glycemic_safety_targets"]
                        and ode_surf_gsis_phys_v060_coupled["passes_clinical_glycemic_safety_targets"]
                    ),
                    "cluster_surface_15mmHg_gsis_qualification_note": (
                        "Nominal 119 um central lamina (LEAD_CENTRAL_LAMINA_PDMS_CAO2_F045_PLUS_CATALASE, min slab P_O2 = 19.92 mmHg) clears macroscopic "
                        "slab >=15.0 mmHg and two-zone 120 um core >=2.0 mmHg (2.15 mmHg), so coupled_survival_and_chemistry_screen_pass = True; "
                        "however, Wigner-Seitz pericellular shell diffusion lowers local cluster-surface pO2 to 13.62 mmHg (uniform) / 12.78 mmHg (gel-only) "
                        "(<15.0 mmHg full first-phase GSIS threshold, so coupled_complete_product_pass = False). Design X thinned 100 um lamina "
                        "(a = 100/350, outer bands 125 um >= 120 um cluster diameter) raises local cluster-surface pO2 to 19.36 / 18.44 mmHg (>=15.0 mmHg) "
                        "and core pO2 to 7.23 mmHg, passing both coupled_survival_and_chemistry_screen_pass and coupled_complete_product_pass "
                        "(AUDIT-REF, AUDIT-REF, AUDIT-REF, AUDIT-REF & AUDIT-REF)."
                    ),
                    "coupled_complete_product_pass": bool(
                        pr["passes_all_oxygen_peroxide_and_ph_gates"]
                        and pr.get("passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate") is True
                        and pr.get("passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_gel_only") is True
                        and conservative_core is not None and conservative_surf is not None
                        and core_p >= 2.0 and surf_p >= 15.0
                        and slab_p >= 15.0 and h2o2_max <= 5.0 and ph_max <= 7.60
                        and ode_coupled["passes_clinical_glycemic_safety_targets"]
                        and ode_surf_gsis_coupled["passes_clinical_glycemic_safety_targets"]
                        and ode_surf_gsis_phys_v060_coupled["passes_clinical_glycemic_safety_targets"]
                    ),
                }
            )

    oat1_exact_match = bool(np.array_equal(
        comparison_states[(graft_models[0]["graft_id"], False)],
        comparison_states[(oat_specs[0]["graft_id"], False)]))
    zero_sst_exact_match = bool(np.array_equal(
        comparison_states[(graft_models[0]["graft_id"], True)],
        comparison_states[(graft_models[1]["graft_id"], False)]))
    lead_0p25_min = low_g_lead["full_5761_step_0p25min_grid_verification_v80_025"]["min_glucose_0p25min_unrounded_mM"]
    oat1_0p25_min = low_g_oat1["full_5761_step_0p25min_grid_verification_v80_025"]["min_glucose_0p25min_unrounded_mM"]
    # Runtime self-verification of mathematical & clinical invariants (AUDIT-REF & 098):
    if not oat1_exact_match:
        raise RuntimeError("OAT_1 invariant violated on standard protocol (min_G > 4.2 mM).")
    if not zero_sst_exact_match:
        raise RuntimeError("Zero-SST collapse invariant violated.")
    if not (lead_0p25_min >= 3.90 and oat1_0p25_min < 3.90):
        raise RuntimeError(
            f"Low-glucose challenge invariant violated: lead_0p25={lead_0p25_min} vs oat1_0p25={oat1_0p25_min}"
        )

    pp_v060_t95332 = next(
        row for row in paracrine_preserved_sweep if row["systemic_export_fraction_v"] == 0.60 and row["total_transport_lag_T_min"] == 9.5332
    )
    r_v060_t517_lowg = _run_single_metabolic_ode_model(
        graft_models[0],
        include_trajectory=False,
        viable_endocrine_fraction=0.60,
        low_glucose_challenge_mode=True,
        extravascular_insulin_lag_total_min=5.17,
        _integrator=_ORIGINAL_RK4_INTEGRATE,
        _skip_shutoff_half_time=True,
    )
    r_v060_t5179_lowg = _run_single_metabolic_ode_model(
        graft_models[0],
        include_trajectory=False,
        viable_endocrine_fraction=0.60,
        low_glucose_challenge_mode=True,
        extravascular_insulin_lag_total_min=5.179,
        _integrator=_ORIGINAL_RK4_INTEGRATE,
        _skip_shutoff_half_time=True,
    )
    min_g_t517_unrounded = float(r_v060_t517_lowg["full_5761_step_0p25min_grid_verification_v80_025"]["min_glucose_0p25min_unrounded_mM"])
    min_g_t5179_unrounded = float(r_v060_t5179_lowg["full_5761_step_0p25min_grid_verification_v80_025"]["min_glucose_0p25min_unrounded_mM"])
    gb_lin_v060 = round(0.60 * (14.88 / 15.0), 4)
    gb_hill_v060 = round(0.60 * ((14.88 ** 2.7) / (14.88 ** 2.7 + 7.5 ** 2.7)), 4)
    r_gb_lin_t517_pp = _run_single_metabolic_ode_model(
        graft_models[0],
        include_trajectory=False,
        viable_endocrine_fraction=gb_lin_v060,
        low_glucose_challenge_mode=True,
        extravascular_insulin_lag_total_min=5.17,
        local_paracrine_preserved_systemic_scale=True,
        _integrator=_ORIGINAL_RK4_INTEGRATE,
        _skip_shutoff_half_time=True,
    )
    r_gb_lin_t95332_pp = _run_single_metabolic_ode_model(
        graft_models[0],
        include_trajectory=False,
        viable_endocrine_fraction=gb_lin_v060,
        low_glucose_challenge_mode=True,
        extravascular_insulin_lag_total_min=9.5332,
        local_paracrine_preserved_systemic_scale=True,
        _integrator=_ORIGINAL_RK4_INTEGRATE,
        _skip_shutoff_half_time=True,
    )
    r_gb_hill_t517_pp = _run_single_metabolic_ode_model(
        graft_models[0],
        include_trajectory=False,
        viable_endocrine_fraction=gb_hill_v060,
        low_glucose_challenge_mode=True,
        extravascular_insulin_lag_total_min=5.17,
        local_paracrine_preserved_systemic_scale=True,
        _integrator=_ORIGINAL_RK4_INTEGRATE,
        _skip_shutoff_half_time=True,
    )

    return {
        "solver_method": "7-state coupled nonlinear ODE system integrated via 4th-order Runge-Kutta (rk4_integrate, dt=0.25 min) over 1,440 minutes",
        "numerical_time_integration_diagnostics": {
            "status": "FIXED_STEP_NOT_ERROR_CERTIFIED",
            "requested_dt_max_minutes": 0.25,
            "adaptive_error_control": False,
            "step_refinement_performed_in_this_run": False,
            "safety_gate_time_grid_minutes": 0.25,
            "continuous_time_safety_certified": False,
            "scheduled_exercise_discontinuities_resolved": True,
            "exact_match_scope": "COMPLETE_UNROUNDED_7_STATE_REPORTING_GRID",
        },
        "clinical_protocol_simulated": "70-kg T1D recipient: Breakfast (75g CHO @ 01:00h), Lunch (85g CHO @ 06:00h), Aerobic Exercise (60% VO2max @ 10:00-11:00h), Dinner (90g CHO @ 13:00h), Overnight Fast",
        "meal_mass_balance_and_distribution_volume_provenance_v80_008": {
            "glucose_molecular_weight_g_mol": 180.156,
            "gut_carbohydrate_bioavailability_F_gut": 0.90,
            "extracellular_glucose_distribution_volume_liters": 13.16,
            "portal_appearance_per_gram_cho_mM": 0.3796,
            "hepatic_first_pass_splanchnic_extraction_fraction": 0.7497,
            "oral_meal_splanchnic_glucose_plus_glycogen_lumped_retention_fraction": 0.7497,
            "net_post_hepatic_systemic_appearance_per_gram_cho_mM": 0.0950,
            "physiological_scope_note_sonnet55_r4": (
                "hepatic_first_pass_splanchnic_extraction_fraction (0.7497 = 1 - 0.0950/0.3796) is the 1-compartment oral-meal gut-to-plasma glucose retention parameter "
                "multiplying meal_appearance_mM_min (lumping ~24-35% initial splanchnic glucose uptake with fast hepatic/muscle glycogen disposal in a single V_G = 13.16 L plasma compartment), "
                "NOT hepatic first-pass insulin extraction (which is 0.00 for a subcutaneous/pre-peritoneal systemic-venous pouch and ~0.50 for a portal-draining omental pouch in the 13-state hepatic/peripheral split model; AUDIT-REF & DEC-078)."
            ),
            "splanchnic_first_pass_extraction_sensitivity_audit_astra6_r4": (
                lambda: {
                    "primary_citations": ["PMID:3891471", "PMID:6862113", "PMID:17926672"],
                    "parameterization_note": (
                        "In the single-compartment plasma glucose ODE (V_G = 13.16 L), the effective systemic appearance gain 0.0950 mM/g CHO lumps "
                        "initial splanchnic/hepatic first-pass extraction (~24-35% in dual-tracer oral glucose clamps; Ferrannini et al. 1985 PMID:3891471; "
                        "Katz et al. 1983 PMID:6862113) with fast-equilibrating interstitial-to-intracellular hepatic/muscle glycogen partitioning "
                        "that is modeled via explicit 2-compartment glucose exchange in full UVA/Padova (Dalla Man et al. 2007 PMID:17926672). "
                        "Below we report the live 24-h ODE sensitivity across unlumped single-compartment gains spanning f_splanchnic in {74.97%, 50.0%, 35.0%, 24.0%}."
                    ),
                    "sweep_by_splanchnic_extraction_fraction": [
                        {
                            "f_splanchnic_extraction": f_sp,
                            "systemic_gain_mM_per_g_cho": round(0.3796 * (1.0 - f_sp), 4),
                            "v1p00_500k_beta_eq": (
                                lambda r: {
                                    "mean_glucose_mM": r["mean_glucose_mM"],
                                    "min_glucose_mM": r["min_glucose_mM"],
                                    "max_postprandial_glucose_mM": r["max_postprandial_glucose_mM"],
                                    "time_in_tight_range_3p9_to_10p0_mM_pct": r["time_in_tight_range_3p9_to_10p0_mM_pct"],
                                }
                            )(
                                _run_single_metabolic_ode_model(
                                    graft_models[0],
                                    include_trajectory=False,
                                    viable_endocrine_fraction=1.0,
                                    systemic_gain_mM_per_g=0.3796 * (1.0 - f_sp),
                                    _integrator=_ORIGINAL_RK4_INTEGRATE,
                                    _skip_shutoff_half_time=True,
                                )
                            ),
                            "v0p60_300k_beta_eq_paracrine_preserved": (
                                lambda r: {
                                    "mean_glucose_mM": r["mean_glucose_mM"],
                                    "min_glucose_mM": r["min_glucose_mM"],
                                    "max_postprandial_glucose_mM": r["max_postprandial_glucose_mM"],
                                    "time_in_tight_range_3p9_to_10p0_mM_pct": r["time_in_tight_range_3p9_to_10p0_mM_pct"],
                                }
                            )(
                                _run_single_metabolic_ode_model(
                                    graft_models[0],
                                    include_trajectory=False,
                                    viable_endocrine_fraction=0.60,
                                    local_paracrine_preserved_systemic_scale=True,
                                    systemic_gain_mM_per_g=0.3796 * (1.0 - f_sp),
                                    _integrator=_ORIGINAL_RK4_INTEGRATE,
                                    _skip_shutoff_half_time=True,
                                )
                            ),
                        }
                        for f_sp in (0.7497366, 0.50, 0.35, 0.24)
                    ],