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…

    pwr_022 = round(_one_sided_paired_t_power_l4_iip_0028((math.log(0.90) - math.log(ocr_fix_1p00)) / 0.022, 8), 4)
    pwr_035 = round(_one_sided_paired_t_power_l4_iip_0028((math.log(0.90) - math.log(ocr_fix_1p00)) / 0.035, 8), 4)
    pwr_050 = round(_one_sided_paired_t_power_l4_iip_0028((math.log(0.90) - math.log(ocr_fix_1p00)) / 0.050, 8), 4)

    return {
        "contribution_id": "IIP-0028",
        "decision_id": "DEC-106",
        "graveyard_card_id": "GY-023",
        "headline_single_design_and_portfolio_odds_unchanged": True,
        "measured_potency_loading_and_ocr": {
            "loading_formula": "(6/7) * (output_per_beta_A / output_per_beta_B) * 1500.0 IEQ/cm^2",
            "measured_composition_and_dose_response_qualification_note": (
                "The nominal 6/7 factor holds only when achieved post-aggregation beta fractions match 70% vs 60% at "
                "equal viable endocrine cells per IEQ and linear output scaling; Stage-0 advancement requires measured "
                "starting beta/alpha/delta fractions, viable cell counts, propagated potency uncertainty, and fresh-lot "
                "equal-output verification across n = 8 confirmation blocks disjoint from n >= 3 fixed-input selection blocks."
            ),
            "alpha_cell_stoichiometry_note": {
                "m1_70_20_10_vs_60_30_10_alpha_count_ratio_at_equal_beta_dose": round(4.0 / 7.0, 6),
                "m1_70_20_10_alpha_fraction_label": "4/7 (57.14% of reference alpha-cell count)",
                "m2_70_25_5_vs_60_30_10_alpha_count_ratio_at_equal_beta_dose": round(5.0 / 7.0, 6),
                "m2_70_25_5_alpha_fraction_label": "5/7 (71.43% of reference alpha-cell count)",
                "implication": "Retained insulin output at 1,285.71 IEQ/cm^2 can coexist with materially lower alpha-cell count, requiring empirical L95_t(GCG_AUC_B/A) >= 0.85, absolute low-glucose glucagon output, and Readout 2 >= 2.0x fold gates.",
            },
            "potency_1p00_areal_loading_ieq_cm2": round(load_1p00, 4),
            "potency_0p95_areal_loading_ieq_cm2": round(load_0p95, 4),
            "potency_0p90_areal_loading_ieq_cm2": round(load_0p90, 4),
            "ocr_ratio_1p00_fixed_vs_coscaled": [round(ocr_fix_1p00, 6), round(ocr_cos_1p00, 6)],
            "ocr_ratio_0p95_fixed_vs_coscaled": [round(ocr_fix_0p95, 6), round(ocr_cos_0p95, 6)],
            "ocr_ratio_0p95_rounded_5dec": [round(ocr_fix_0p95, 5), round(ocr_cos_0p95, 5)],
            "ocr_ratio_0p90_fixed_vs_coscaled": [round(ocr_fix_0p90, 6), round(ocr_cos_0p90, 6)],
            "point_threshold_0p90_respiration_ratio_crossings_r_star": {
                "fixed_vascular_0p15D_226_over_161": round(r_star_fix_015d, 6),
                "fixed_vascular_absolute_41_over_28": round(r_star_fix_abs, 6),
                "endocrine_only_12_over_7": round(r_star_endo_only, 6),
                "whole_graft_coscaled_0p15D_246_over_131": round(r_star_cos_015d, 6),
            },
        },
        "dual_band_worst_face_3d_fvm_oxygen_sweep": {
            "stress_definition": "Joint +10% intrinsic OCR (1.097 * 1.10) and +10% physical vessel standoff (16.5 um vs 15.0 um nominal) on 350-um slab with 100-um central lamina and 2 x 20-um catalase barrier films",
            "nx40_nz70": fvm_nx40,
            "nx60_nz105": fvm_nx60,
            "matched_plus10_stress_100um_summary_mmhg": {
                "modeA_1500_nx40_nx60": [
                    fvm_nx40["modeA_100um_350barrier_plus10stress_pb35"]["dual_band_worst_face_min_mmhg"],
                    fvm_nx60["modeA_100um_350barrier_plus10stress_pb35"]["dual_band_worst_face_min_mmhg"],
                ],
                "modeB_1p00_fixed_vascular_nx40_nx60": [
                    fvm_nx40["modeB_1p00_100um_350barrier_plus10stress_fixedV_pb35"]["dual_band_worst_face_min_mmhg"],
                    fvm_nx60["modeB_1p00_100um_350barrier_plus10stress_fixedV_pb35"]["dual_band_worst_face_min_mmhg"],
                ],
                "modeB_1p00_coscaled_nx40_nx60": [
                    fvm_nx40["modeB_1p00_100um_350barrier_plus10stress_coscV_pb35"]["dual_band_worst_face_min_mmhg"],
                    fvm_nx60["modeB_1p00_100um_350barrier_plus10stress_coscV_pb35"]["dual_band_worst_face_min_mmhg"],
                ],
            },
            "boundary_po2_34mmhg_narrow_margin_80um_plus10_stress_mmhg": {
                "fixed_vascular_1p00_nx40_nx60": [
                    fvm_nx40["modeB_1p00_80um_350barrier_plus10stress_fixedV_pb34"]["dual_band_worst_face_min_mmhg"],
                    fvm_nx60["modeB_1p00_80um_350barrier_plus10stress_fixedV_pb34"]["dual_band_worst_face_min_mmhg"],
                ],
                "coscaled_1p00_nx40_nx60": [
                    fvm_nx40["modeB_1p00_80um_350barrier_plus10stress_coscV_pb34"]["dual_band_worst_face_min_mmhg"],
                    fvm_nx60["modeB_1p00_80um_350barrier_plus10stress_coscV_pb34"]["dual_band_worst_face_min_mmhg"],
                ],
                "passes_15mmhg_floor_at_34mmhg_fixed_vascular": False,
            },
        },
        "rk4_24h_exercise_ode_elapsed_tbr_and_glucagon_sensitivities": ode_cases,
        "boundary_231_reading_3p60mM_elapsed_tbr_checks": {
            "background_4p22mM_elapsed_tbr_pct": round(float(b231_4p22["tbr39_elapsed_unrounded_pct"]), 6),
            "background_5p00mM_elapsed_tbr_pct": round(float(b231_5p00["tbr39_elapsed_unrounded_pct"]), 6),
            "both_exceed_4pct_tbr_cap": bool(
                float(b231_4p22["tbr39_elapsed_unrounded_pct"]) >= 4.0 and float(b231_5p00["tbr39_elapsed_unrounded_pct"]) >= 4.0
            ),
        },
        "n8_confirmation_single_endpoint_fixed_vascular_ocr_power": {
            "paired_log_sd_0p022": pwr_022,
            "paired_log_sd_0p035": pwr_035,
            "paired_log_sd_0p050": pwr_050,
            "scope_note": "Single-endpoint one-sided paired-t OCR power at alpha = 0.05 across n = 8 independent blocks; distinct from joint multi-endpoint advancement power",
        },
        "primary_citations": [
            "PMID:39169271",
            "PMID:40782792",
            "PMID:31068696",
            "PMID:8971076",
            "PMID:30830873",
            "PMID:26076035",
            "PMID:40404627",
            "PMID:37188763",
            "PMID:35241836",
            "PMID:31177185",
        ],
    }
# === END_IIP_0028_MEASURED_POTENCY_DEC084_MIXTURE_AND_GLUCAGON_AUDIT ===


# === BEGIN_IIP_0029_EXPLORATORY_MODE_B_V2_GRANULE_STORE_SENSITIVITY ===
ALPHA_SYS_INSULIN_IU_PER_PM_IIP0029 = 1.0 / 600.0


def _trapezoid_iip0029(y: np.ndarray, x: np.ndarray) -> float:
    if hasattr(np, "trapezoid"):
        return float(np.trapezoid(y, x=x))
    return float(np.trapz(y, x=x))


def _smoothstep01_iip0029(u: float) -> float:
    x = min(1.0, max(0.0, float(u)))
    return x * x * (3.0 - 2.0 * x)


class ModeBV2GranuleStoreParams:
    """
    Physiological parameter bundle for the strictly opt-in exploratory conserved two-pool
    (RRP Q_P + Reserve Q_R) Mode B v2 sensitivity comparator (IIP-0029; DEC-108).
    Enforces strict finite non-bool physical bounds (0 < f_rrp < 1, tau_chamber == 0 or >= 0.01 min,
    0 <= f_hepatic < 0.90) and scales intracellular inventory linearly with beta-cell equivalents
    (beta_cell_fraction / 0.60) * (implanted_total_ieq / 500,000).
    """

    def __init__(
        self,
        c0_ref_iu_at_300k_beta_eeq: float = 89.9,
        beta_cell_fraction: float = 0.60,
        implanted_total_ieq: float = 500_000.0,
        f_hepatic: float = 0.50,
        f_rrp: float = 0.0045,
        tau_refill_min: float = 16.5,
        gamma_amp: float = 0.08,
        g_pot: float = 0.0,
        tau_pot_min: float = 35.0,
        tau_biosyn_min: float = 180.0,
        enable_biosyn: bool = True,
        basal_leak_multiplier: float = 1.0,
        tau_chamber_min: float = 0.35,
    ) -> None:
        checked = {}
        for nm, val in (
            ("c0_ref_iu_at_300k_beta_eeq", c0_ref_iu_at_300k_beta_eeq),
            ("beta_cell_fraction", beta_cell_fraction),
            ("implanted_total_ieq", implanted_total_ieq),
            ("f_hepatic", f_hepatic),
            ("f_rrp", f_rrp),
            ("tau_refill_min", tau_refill_min),
            ("gamma_amp", gamma_amp),
            ("g_pot", g_pot),
            ("tau_pot_min", tau_pot_min),
            ("tau_biosyn_min", tau_biosyn_min),
            ("basal_leak_multiplier", basal_leak_multiplier),
            ("tau_chamber_min", tau_chamber_min),
        ):
            checked[nm] = _strict_numeric_float_iip0024(val, nm)
        if not isinstance(enable_biosyn, bool):
            raise ValueError("enable_biosyn must be a strict bool (IIP-0029; DEC-108)")
        if not (0.0 <= checked["f_hepatic"] < 0.90):
            raise ValueError("f_hepatic must lie in [0.0, 0.90) (IIP-0029; DEC-108)")
        if not (0.0 < checked["beta_cell_fraction"] <= 1.0):
            raise ValueError("beta_cell_fraction must lie in (0.0, 1.0] (IIP-0029; DEC-108)")
        if checked["implanted_total_ieq"] <= 0.0 or checked["c0_ref_iu_at_300k_beta_eeq"] <= 0.0:
            raise ValueError("implanted_total_ieq and c0_ref_iu_at_300k_beta_eeq must be > 0 (IIP-0029; DEC-108)")
        if not (0.0 < checked["f_rrp"] < 1.0):
            raise ValueError("f_rrp must lie strictly inside (0.0, 1.0) so Q_R0 > 0 (IIP-0029; DEC-108)")
        if checked["tau_refill_min"] <= 0.0 or checked["tau_pot_min"] <= 0.0 or checked["tau_biosyn_min"] <= 0.0:
            raise ValueError("tau_refill_min, tau_pot_min, and tau_biosyn_min must be > 0 (IIP-0029; DEC-108)")
        if checked["basal_leak_multiplier"] < 0.0 or checked["gamma_amp"] < 0.0 or checked["g_pot"] < 0.0:
            raise ValueError("basal_leak_multiplier, gamma_amp, and g_pot must be >= 0 (IIP-0029; DEC-108)")
        tc = checked["tau_chamber_min"]
        if tc < 0.0 or (0.0 < tc < 0.01):
            raise ValueError("tau_chamber_min must be 0.0 (ideal cellular limit) or >= 0.01 min (IIP-0029; DEC-108)")

        self.c0_ref_iu_at_300k_beta_eeq = checked["c0_ref_iu_at_300k_beta_eeq"]
        self.beta_cell_fraction = checked["beta_cell_fraction"]
        self.implanted_total_ieq = checked["implanted_total_ieq"]
        self.f_hepatic = checked["f_hepatic"]
        self.f_rrp = checked["f_rrp"]
        self.tau_refill_min = checked["tau_refill_min"]
        self.gamma_amp = checked["gamma_amp"]
        self.g_pot = checked["g_pot"]
        self.tau_pot_min = checked["tau_pot_min"]
        self.tau_biosyn_min = checked["tau_biosyn_min"]
        self.enable_biosyn = enable_biosyn
        self.basal_leak_multiplier = checked["basal_leak_multiplier"]
        self.tau_chamber_min = tc

    @property
    def beta_eeq_count(self) -> float:
        return self.implanted_total_ieq * self.beta_cell_fraction

    @property
    def beta_scale_vs_300k_ref(self) -> float:
        return self.beta_eeq_count / 300_000.0

    @property
    def total_store_c0_iu(self) -> float:
        return self.c0_ref_iu_at_300k_beta_eeq * self.beta_scale_vs_300k_ref


def build_mode_b_v2_granule_store_system_iip_0029(
    params: ModeBV2GranuleStoreParams,
    assay_context: str = "in_vivo_metabolic_twin",
    viable_endocrine_fraction_override: float | None = None,
    local_paracrine_preserved_systemic_scale: bool = False,
    extravascular_insulin_lag_total_min: float = 0.0,
    low_glucose_challenge_mode: bool = False,
    meals_override: List[tuple[float, float]] | None = None,
) -> Dict[str, Any]:
    """
    Construct the conserved two-pool (Q_P + Q_R) Mode B v2 ODE system with uncapped stiffness-rate
    bounds covering RRP exocytosis, chamber mixing (1/tau_chamber), and extravascular lag (2/tau_vasc).
    First-pass hepatic extraction f_hepatic is owned solely by Mode B v2 to debit total pre-hepatic
    secretion from intracellular stores while delivering (1 - f_hepatic) systemically, remaining
    strictly distinct from Layer 4's 13-state f_sys_ins insulin-action scaling.
    """
    if not isinstance(params, ModeBV2GranuleStoreParams):
        raise ValueError("params must be a ModeBV2GranuleStoreParams instance (IIP-0029; DEC-108)")
    if assay_context not in ("in_vivo_metabolic_twin", "in_vitro_perifusion"):
        raise ValueError(f"Unknown assay_context: {assay_context!r} (IIP-0029; DEC-108)")
    lag_f = _strict_numeric_float_iip0024(extravascular_insulin_lag_total_min, "extravascular_insulin_lag_total_min")
    if lag_f < 0.0 or (0.0 < lag_f < 0.05):
        raise ValueError("extravascular_insulin_lag_total_min must be 0.0 or >= 0.05 min (IIP-0029; DEC-108)")

    is_invivo = assay_context == "in_vivo_metabolic_twin"
    if viable_endocrine_fraction_override is not None:
        v = _strict_numeric_float_iip0024(viable_endocrine_fraction_override, "viable_endocrine_fraction_override")
        if v <= 0.0:
            raise ValueError("viable_endocrine_fraction_override must be > 0 (IIP-0029; DEC-108)")
        c0_iu = params.c0_ref_iu_at_300k_beta_eeq * (v / 0.60)
    else:
        v = 0.60 * params.beta_scale_vs_300k_ref
        c0_iu = params.total_store_c0_iu

    f_hep_eff = params.f_hepatic if is_invivo else 0.0
    alpha_prehep_iu_per_pm = ALPHA_SYS_INSULIN_IU_PER_PM_IIP0029 / (1.0 - f_hep_eff)

    loc_f = 1.0 if (local_paracrine_preserved_systemic_scale or not is_invivo) else v
    k05 = 7.2
    nh = 4.2
    k_ip_clear = 0.14
    k_x_decay = 0.035

    qp0 = params.f_rrp * c0_iu
    qr0 = (1.0 - params.f_rrp) * c0_iu

    if meals_override is not None:
        meals_sched = list(meals_override)
    elif low_glucose_challenge_mode:
        meals_sched = [(60.0, 60.0), (360.0, 60.0), (840.0, 80.0)]
    else: