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…

                        "fixed_cao2_inventory_mmol": round(float(r["cao2_initial_molar_inventory_mmol"]), 4),
                        "fixed_cao2_inventory_mg": round(float(r["cao2_initial_mass_mg_in_7cm3_slab"]), 2),
                        "min_slab_po2_mmhg": round(min_slab, 3),
                        "time_of_min_slab_po2_hours": r["time_of_min_slab_po2_hours"],
                        "gel_only_120um_surface_po2_mmhg": round(surf120, 3),
                        "gel_only_120um_core_po2_mmhg": round(core120, 3),
                        "gel_only_100um_surface_po2_mmhg": round(surf100, 3),
                        "gel_only_100um_core_po2_mmhg": round(core100, 3),
                        "max_interstitial_h2o2_uM": round(max_h2o2, 3),
                        "max_interstitial_ph": round(max_ph, 3),
                        "passes_100um_15mmHg_surface_2mmHg_core_5uM_h2o2_gate": passes_100um,
                    })
                passing_windows.append({
                    "formulation_id": form["formulation_id"],
                    "cao2_wt_pct": form["cao2_wt_pct"],
                    "cao2_solid_vol_pct": form["cao2_solid_vol_pct"],
                    "release_kinetics_law": law,
                    "inosculation_t50_h": t50_h,
                    "passing_half_lives_h_for_100um_clusters": passing_hl,
                    "min_passing_half_life_on_grid_h": min(passing_hl) if passing_hl else None,
                    "max_passing_half_life_on_grid_h": max(passing_hl) if passing_hl else None,
                })

    return {
        "iip_id": "IIP-0010",
        "decision_id": "DEC-088",
        "open_question_id": "OQ-005",
        "credit": "giufra (GitHub @frafra013; https://github.com/openislet/openislet/issues/10)",
        "parameter_status_of_68h": "unvalidated_formulation_specific_reference_target_not_conserved_across_wt_pct_or_microbead_psd",
        "fixed_inventory_constraint": "Conserves n_CaO2(0) = 10.9811 mmol (791.49 mg in 7.00 cm^3 active slab) across all half-lives, laws, and formulations so shorter t_1/2 raises early H2O2 flux and accelerates pre-anastomosis depletion whereas longer t_1/2 reduces Hour-0 O2 flux.",
        "particle_and_microbead_psd_status": {
            "cao2_crystal_particle_size_distribution_um": "unknown_pending_stage0_measurement",
            "pdms_cao2_composite_microbead_diameter_distribution_um": "unknown_pending_stage0_measurement",
            "primary_literature_anchors": [
                "Pedraza et al. 2012 PNAS PMID:22371586 (25 wt% CaO2 monolithic PDMS disk)",
                "Accolla et al. 2023 Adv Healthc Mater PMID:36971050 (microscale OxySite PDMS-CaO2 microbeads)",
                "Ke et al. 2022 Int J Mol Sci PMID:35743287 (tunable CaO2 microparticle oxygen release)",
            ],
        },
        "half_life_grid_hours": half_lives_h,
        "passing_half_life_windows_by_formulation_law_and_t50": passing_windows,
        "grid_rows": rows,
    }


def _build_joint_vascular_timing_and_exchange_sensitivity_iip_0002() -> Dict[str, Any]:
    """Build the IIP-0002 joint vascular timing-by-exchange sensitivity grid and provenance audit."""
    phi_lead = (2500.0 * VOL_1_IEQ_CM3) / 0.0350  # 0.1262247

    def _bisect_slab_po2_for_cluster_threshold(key: str, threshold_mmhg: float) -> float:
        lo, hi = 0.0, 40.0
        for _ in range(44):
            mid = 0.5 * (lo + hi)
            val = float(solve_spherical_cluster_po2_bvp(mid, 0.0060, phi_islet_in_slab=phi_lead)[key])
            if val < threshold_mmhg:
                lo = mid
            else:
                hi = mid
        return 0.5 * (lo + hi)

    slab_po2_crit_gel_surf_15mmhg = _bisect_slab_po2_for_cluster_threshold(
        "wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg", 15.0
    )
    slab_po2_crit_gel_core_2p0mmhg = _bisect_slab_po2_for_cluster_threshold(
        "wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg", 2.0
    )
    slab_po2_crit_gel_core_0p5mmhg = _bisect_slab_po2_for_cluster_threshold(
        "wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg", 0.5
    )

    bvp_cache: dict[float, Dict[str, Any]] = {}

    def _cached_r60_bvp(p_slab_mmhg: float) -> Dict[str, Any]:
        key = round(float(p_slab_mmhg), 8)
        if key not in bvp_cache:
            bvp_cache[key] = solve_spherical_cluster_po2_bvp(float(p_slab_mmhg), 0.0060, phi_islet_in_slab=phi_lead)
        return bvp_cache[key]

    timings_t50_h = [36.0, 40.0, 44.0, 48.0, 52.0, 56.0, 60.0, 96.0, 168.0]
    kp_values = [0.0944, 0.1100, 0.1400, 0.1800]
    release_laws = ["first_order", "shrinking_core"]
    realized_t50_map = {t50: _realized_half_plateau_perfusion_time_hours(t50, 0.97) for t50 in timings_t50_h}
    sample_hours_export = [0, 2, 6, 12, 24, 48, 72, 96, 120, 168, 336]

    def _summarize_regime_row(
        r: Dict[str, Any],
        *,
        law: str,
        t50_h: float | None,
        kp: float,
        timing_scope: str,
        include_cluster_trajectory: bool,
    ) -> Dict[str, Any]:
        ws = r["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]
        hourly_slab = r.get("hourly_min_slab_po2_unrounded_mmhg")
        has_hourly_slab = isinstance(hourly_slab, list) and len(hourly_slab) > 0
        min_slab_raw = float(r["min_slab_po2_unrounded_mmhg"])
        gel_surf_raw = float(ws["two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"])
        gel_core_raw = float(ws["two_zone_fv_gel_only_supply_120um_core_po2_unrounded_mmhg"])
        uni_surf_raw = float(ws["two_zone_fv_uniform_supply_surface_po2_unrounded_mmhg"])
        uni_core_raw = float(
            ws.get(
                "two_zone_fv_uniform_supply_120um_core_po2_unrounded_mmhg",
                ws["two_zone_fv_uniform_supply_120um_core_po2_mmhg"],
            )
        )
        dir_core_raw = float(r["min_120um_cluster_core_po2_unrounded_mmhg"])
        converged = bool(r["required_120um_oxygen_solvers_converged"])
        row: Dict[str, Any] = {
            "regime_id": r["regime_id"],
            "release_kinetics_law": law,
            "timing_scope": timing_scope,
            "target_curve_midpoint_t50_h": t50_h,
            "realized_half_plateau_perfusion_time_h": (
                round(realized_t50_map[t50_h], 4) if t50_h is not None else None
            ),
            "realized_minus_target_midpoint_lag_h": (
                round(realized_t50_map[t50_h] - t50_h, 4) if t50_h is not None else None
            ),
            "coupled_internal_vascular_exchange_kp_s_inv": kp,
            "iec_max_perfusion_fraction": 0.0 if kp == 0.0 else 0.97,
            "zero_internal_vascular_state_enforced": bool(kp == 0.0),
            "cell_intrinsic_ocr_multiplier_gy004_consistent": 1.0,
            "vascular_stromal_demand_overhead_multiplier": 1.15,
            "time_of_min_slab_po2_hours": r["time_of_min_slab_po2_hours"],
            "min_slab_po2_mmhg": round(min_slab_raw, 3),
            "min_slab_po2_unrounded_mmhg": min_slab_raw,
            "gel_only_120um_surface_po2_mmhg": round(gel_surf_raw, 3),
            "gel_only_120um_surface_po2_unrounded_mmhg": gel_surf_raw,
            "gel_only_120um_core_po2_mmhg": round(gel_core_raw, 3),
            "gel_only_120um_core_po2_unrounded_mmhg": gel_core_raw,
            "uniform_120um_surface_po2_mmhg": round(uni_surf_raw, 3),
            "uniform_120um_surface_po2_unrounded_mmhg": uni_surf_raw,
            "uniform_120um_core_po2_mmhg": round(uni_core_raw, 3),
            "uniform_120um_core_po2_unrounded_mmhg": uni_core_raw,
            "dirichlet_upper_bound_120um_core_po2_mmhg": round(dir_core_raw, 3),
            "dirichlet_upper_bound_120um_core_po2_unrounded_mmhg": dir_core_raw,
            "max_interstitial_h2o2_uM": r["max_interstitial_h2o2_uM"],
            "max_interstitial_h2o2_unrounded_uM": r["max_interstitial_h2o2_unrounded_uM"],
            "max_interstitial_ph": r["max_interstitial_ph"],
            "max_interstitial_ph_unrounded": r["max_interstitial_ph_unrounded"],
            "min_closed_pocket_acidic_ph": r["closed_pocket_metabolic_acidification_min_ph_v80_095"],
            "min_closed_pocket_acidic_ph_unrounded": r.get(
                "closed_pocket_metabolic_acidification_min_ph_unrounded",
                r["closed_pocket_metabolic_acidification_min_ph_v80_095"],
            ),
            "coupled_dynamic_14d_viable_endocrine_fraction": r["coupled_dynamic_14d_viable_endocrine_fraction_v80_066"],
            "coupled_dynamic_14d_viable_endocrine_fraction_unrounded": r["coupled_dynamic_14d_viable_endocrine_fraction_unrounded"],
            "hours_below_15mmHg_slab_gate": (
                int(sum(1 for p_h in hourly_slab if p_h < 15.0)) if has_hourly_slab else None
            ),
            "hours_below_15mmHg_gel_only_surface_gate": (
                int(sum(1 for p_h in hourly_slab if p_h < slab_po2_crit_gel_surf_15mmhg)) if has_hourly_slab else None
            ),
            "hours_below_2p0mmHg_gel_only_core_gate": (
                int(sum(1 for p_h in hourly_slab if p_h < slab_po2_crit_gel_core_2p0mmhg)) if has_hourly_slab else None
            ),
            "hours_below_0p5mmHg_gel_only_core_gate": (
                int(sum(1 for p_h in hourly_slab if p_h < slab_po2_crit_gel_core_0p5mmhg)) if has_hourly_slab else None
            ),
            "required_120um_oxygen_solvers_converged": converged,
            "passes_15mmHg_slab_po2_gate": bool(converged and min_slab_raw >= 15.0),
            "passes_15mmHg_gel_only_cluster_surface_gsis_gate": bool(converged and gel_surf_raw >= 15.0),
            "passes_strict_2p0mmHg_gel_only_120um_core_gate": bool(
                converged and min_slab_raw >= 15.0 and gel_core_raw >= 2.0 and r["strict_nonoxygen_gates_passed"]
            ),
            "passes_2p0mmHg_uniform_120um_core_gate": bool(
                converged and min_slab_raw >= 15.0 and uni_core_raw >= 2.0 and r["strict_nonoxygen_gates_passed"]
            ),
            "passes_0p5mmHg_gel_only_anoxic_necrosis_core_gate": bool(converged and gel_core_raw >= 0.5),
        }
        if include_cluster_trajectory and has_hourly_slab:
            min_h_int = max(0, min(len(hourly_slab) - 1, int(round(float(r["time_of_min_slab_po2_hours"])))))
            hours_to_sample = sorted(set(sample_hours_export + [min_h_int]))
            traj_samples = []
            for h_idx in hours_to_sample:
                if 0 <= h_idx < len(hourly_slab):
                    p_h = float(hourly_slab[h_idx])
                    bvp_h = _cached_r60_bvp(p_h)
                    traj_samples.append(
                        {
                            "time_hours": float(h_idx),
                            "min_slab_po2_unrounded_mmhg": p_h,
                            "gel_only_120um_surface_po2_unrounded_mmhg": float(
                                bvp_h["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"]
                            ),
                            "gel_only_120um_core_po2_unrounded_mmhg": float(
                                bvp_h["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"]
                            ),
                            "uniform_120um_surface_po2_unrounded_mmhg": float(
                                bvp_h["wigner_seitz_two_zone_fv_uniform_supply_surface_po2_unrounded_mmhg"]
                            ),
                            "uniform_120um_core_po2_unrounded_mmhg": float(
                                bvp_h["wigner_seitz_two_zone_fv_uniform_supply_core_po2_unrounded_mmhg"]
                            ),
                        }
                    )
            row["unrounded_trajectory_samples"] = traj_samples
        return row

    joint_grid_rows: list[Dict[str, Any]] = []
    near_threshold_refinement_rows: list[Dict[str, Any]] = []
    for law in release_laws:
        for t50_h in timings_t50_h:
            scope = (
                "hypothetical_extreme_delay_stress_test"
                if t50_h in {96.0, 168.0}
                else ("primary_2x2_endpoint" if t50_h in {36.0, 60.0} else "intermediate_4h_step_gate_flip_resolution")
            )
            for kp in kp_values:
                r_cell = _run_single_pouch_pde_regime(
                    regime_id=f"IIP0002_{law.upper()}_T50_{int(t50_h)}H_KP_{kp:.4f}",
                    f_chem_initial=0.45,
                    spatial_mode="central",
                    cao2_half_life_h=68.0,
                    catalase_present=True,
                    iec_max_perfusion_fraction=0.97,
                    boundary_po2_mmhg=40.0,
                    inosculation_t50_h=t50_h,
                    demand_multiplier_extra=1.0,
                    release_kinetics_law=law,
                    k_perf_max_s_override=kp,
                    _include_hourly_slab_po2_vector=True,
                    _assess_numerical_gate=False,
                )
                row_summary = _summarize_regime_row(
                    r_cell,
                    law=law,
                    t50_h=t50_h,
                    kp=kp,
                    timing_scope=scope,
                    include_cluster_trajectory=(t50_h in {36.0, 60.0} or math.isclose(kp, 0.14, rel_tol=1e-9)),
                )
                joint_grid_rows.append(row_summary)

                # Grid-refinement check (Nz = 51, 101, 201) for any cell within 0.15 mmHg of 15.0 mmHg slab or 2.0/0.5 mmHg core gates:
                slab_val = row_summary["min_slab_po2_unrounded_mmhg"]
                gel_core_val = row_summary["gel_only_120um_core_po2_unrounded_mmhg"]
                uni_core_val = row_summary["uniform_120um_core_po2_unrounded_mmhg"]
                if (
                    abs(slab_val - 15.0) <= 0.15
                    or abs(gel_core_val - 2.0) <= 0.15
                    or abs(gel_core_val - 0.5) <= 0.10
                    or abs(uni_core_val - 2.0) <= 0.15
                ):
                    mesh_receipts = {}
                    for nz_ref in (51, 101, 201):
                        r_ref = (
                            r_cell
                            if nz_ref == 51