scripts/run_layer4_tissue_and_metabolic_twin.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer4_tissue_and_metabolic_twin.py · SHA-256: 624a491d5e418a7d…
"two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg": bvp_prescribed["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"],
"two_zone_fv_gel_only_supply_core_po2_mmhg": bvp_prescribed["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_mmhg"],
"two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg": bvp_prescribed["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"],
"passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate": bool(
slab_solvers_converged
and _required_oxygen_solvers_converged(bvp_prescribed)
and min_po2_over_all_t >= 15.0
and bvp_prescribed["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"] >= 2.0
and max_h2o2_uM_with_cat_decay_over_all_t <= 5.0
and max_ph_over_all_t <= 7.60
and min_closed_pocket_acidic_ph_over_all_t >= 7.20
),
"passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_gel_only": bool(
slab_solvers_converged
and _required_oxygen_solvers_converged(bvp_prescribed)
and bvp_prescribed["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"] >= 15.0
),
},
"min_300um_cluster_core_po2_mmhg": bvp_r150["core_po2_nonlinear_mm_mmhg"],
"min_300um_cluster_core_po2_zero_order_krogh_mmhg": bvp_r150["core_po2_zero_order_krogh_mmhg"],
"spherical_300um_bvp_solver_diagnostics": bvp_r150["spherical_bvp_solver_diagnostics"],
"max_interstitial_h2o2_uM": round(max_h2o2_uM_over_all_t, 3),
"max_interstitial_h2o2_unrounded_uM": max_h2o2_uM_over_all_t,
"max_interstitial_h2o2_at_lamina_interface_uM": round(max_h2o2_at_lamina_interface_uM_over_all_t, 2),
"max_interstitial_h2o2_at_lamina_interface_unrounded_uM": max_h2o2_at_lamina_interface_uM_over_all_t,
"max_interstitial_h2o2_at_lamina_interface_nearest_node_um": round(float(z_int_abs[lamina_if_int_idx]) * 1e4, 2),
"max_interstitial_h2o2_at_lamina_interface_interpolated_uM": round(max_h2o2_at_lamina_interface_interp_uM_over_all_t, 2),
"max_interstitial_h2o2_at_lamina_interface_interpolated_unrounded_uM": max_h2o2_at_lamina_interface_interp_uM_over_all_t,
"two_scale_ocr_propagated_120um_wigner_seitz_audit_astra_s3": {
"areal_loading_ieq_cm2": round(sigma_loading, 4),
"local_phi_islet_for_wigner_seitz": round(local_phi_islet, 7),
"demand_multiplier_extra_applied_to_radial_bvp": round(float(effective_ocr_mult), 6),
"two_zone_fv_gel_only_supply_surface_po2_mmhg": bvp_r60_ocr_propagated["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_mmhg"],
"two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg": bvp_r60_ocr_propagated["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"],
"two_zone_fv_gel_only_supply_120um_core_po2_mmhg": bvp_r60_ocr_propagated["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_mmhg"],
"two_zone_fv_gel_only_supply_120um_core_po2_unrounded_mmhg": bvp_r60_ocr_propagated["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"],
"slab_only_unscaled_radial_bvp_comparator": {
"two_zone_fv_gel_only_supply_surface_po2_mmhg": bvp_r60_slab_only_unscaled["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_mmhg"],
"two_zone_fv_gel_only_supply_120um_core_po2_mmhg": bvp_r60_slab_only_unscaled["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_mmhg"],
},
},
"max_interstitial_ph": round(max_ph_over_all_t, 3),
"max_interstitial_ph_unrounded": max_ph_over_all_t,
"closed_pocket_unresupplied_co2_max_ph_v80_021": round(max_closed_pocket_ph_over_all_t, 3),
"closed_pocket_metabolic_acidification_min_ph_v80_095": round(min_closed_pocket_acidic_ph_over_all_t, 3),
"closed_pocket_metabolic_acidification_min_ph_unrounded": min_closed_pocket_acidic_ph_over_all_t,
"coupled_dynamic_14d_viable_endocrine_fraction_v80_066": round(f_viable_dynamic, 4),
"coupled_dynamic_14d_viable_endocrine_fraction_unrounded": f_viable_dynamic,
"slab_oxygen_solver_diagnostics": {"converged": slab_solvers_converged,
"max_residual_inf_mmhg_s": max_slab_residual_mmhg_s},
"required_120um_oxygen_solvers_converged": slab_solvers_converged and _required_oxygen_solvers_converged(bvp_r60),
"passes_all_oxygen_peroxide_and_ph_gates": bool(
slab_solvers_converged and _required_oxygen_solvers_converged(bvp_r60)
and min_po2_over_all_t >= 15.0
and bvp_r60["spherical_bvp_solver_diagnostics"]["raw_core_po2_mmhg"] >= 2.0
and bvp_r60["wigner_seitz_two_zone_fv_uniform_supply_core_po2_unrounded_mmhg"] >= 2.0
and max_h2o2_uM_over_all_t <= 5.0
and max_h2o2_uM_with_cat_decay_over_all_t <= 5.0
and max_ph_over_all_t <= 7.60
and min_closed_pocket_acidic_ph_over_all_t >= 7.20
),
"strict_nonoxygen_gates_passed": bool(
max_h2o2_uM_with_cat_decay_over_all_t <= 5.0
and max_ph_over_all_t <= 7.60
and min_closed_pocket_acidic_ph_over_all_t >= 7.20
),
"passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate": bool(
slab_solvers_converged and _required_oxygen_solvers_converged(bvp_r60)
and min_po2_over_all_t >= 15.0
and bvp_r60["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"] >= 2.0
and max_h2o2_uM_with_cat_decay_over_all_t <= 5.0
and max_ph_over_all_t <= 7.60
and min_closed_pocket_acidic_ph_over_all_t >= 7.20
),
"passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_uniform": bool(
slab_solvers_converged and _required_oxygen_solvers_converged(bvp_r60)
and bvp_r60["wigner_seitz_two_zone_fv_uniform_supply_surface_po2_unrounded_mmhg"] >= 15.0
),
"passes_cluster_surface_15mmHg_full_first_phase_gsis_gate_gel_only": bool(
slab_solvers_converged and _required_oxygen_solvers_converged(bvp_r60)
and bvp_r60["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"] >= 15.0
),
"trajectory_0h_to_336h": time_series,
}
if _include_hourly_slab_po2_vector:
result["hourly_min_slab_po2_unrounded_mmhg"] = hourly_min_slab_po2_mmhg
core_raw = bvp_r60["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"]
assessment = {"status": ("NUMERICAL_SOLVER_UNRESOLVED" if not result["required_120um_oxygen_solvers_converged"] else
"FAILED_PHYSICAL_GATE" if not result["passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate"] else "MARGIN_SCREENED_NOT_REFINEMENT_CERTIFIED"),
"raw_core_margin_over_2mmHg": core_raw - 2.0,
"refinement_applied": False}
# A near-threshold pass is never certified from rounded/coarse values. The 201/401 mesh
# difference is a numerical allowance, not a proof of continuum accuracy or physical validity.
if _assess_numerical_gate and (abs(core_raw - 2.0) <= 0.5 or abs(min_po2_over_all_t - 15.0) <= 0.5):
refs = [_run_single_pouch_pde_regime(
regime_id, f_chem_initial, spatial_mode, cao2_half_life_h, catalase_present,
iec_max_perfusion_fraction, boundary_po2_mmhg=boundary_po2_mmhg,
inosculation_t50_h=inosculation_t50_h, demand_multiplier_extra=demand_multiplier_extra,
release_kinetics_law=release_kinetics_law, gb_regularization_mode=gb_regularization_mode, nz_override=n,
k_perf_max_s_override=k_perf_max_s_override, demand_spatial_mode=demand_spatial_mode,
lamina_d_o2_scale=lamina_d_o2_scale, catalase_half_life_h=catalase_half_life_h,
acid_pocket_residence_time_s=acid_pocket_residence_time_s,
lamina_half_width_fraction=a_frac,
catalase_spatial_mode=catalase_spatial_mode,
catalase_k1_override_s_inv=catalase_k1_override_s_inv,
d_o2_hydrogel_override_cm2_s=d_o2_hydrogel_override_cm2_s,
perfusion_spatial_mode=perfusion_spatial_mode,
external_standoff_um=external_standoff_um,
areal_loading_ieq_cm2=sigma_loading,
cell_intrinsic_ocr_multiplier=effective_ocr_mult,
prescribed_cluster_diameter_um=prescribed_cluster_diameter_um,
zero_internal_vascular_state=zero_internal_vascular_state,
_assess_numerical_gate=False)
for n in (201, 401)]
def raw_core(r):
return r["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]["two_zone_fv_gel_only_supply_120um_core_po2_unrounded_mmhg"]
fine = refs[-1]
estimate = max(abs(raw_core(refs[1]) - raw_core(refs[0])), 1e-6)
core_lo, core_hi = raw_core(fine)-estimate, raw_core(fine)+estimate
slab_error = max(abs(refs[1]["min_slab_po2_unrounded_mmhg"] - refs[0]["min_slab_po2_unrounded_mmhg"]), 1e-6)
slab_lo = fine["min_slab_po2_unrounded_mmhg"] - slab_error
if not all(ref["required_120um_oxygen_solvers_converged"] for ref in refs):
status = "NUMERICAL_SOLVER_UNRESOLVED"
elif not fine["strict_nonoxygen_gates_passed"]:
status = "FAILED_PHYSICAL_GATE"
elif core_lo >= 2.0 and slab_lo >= 15.0:
status = "PASS_WITH_REFINEMENT_ALLOWANCE"
elif core_hi < 2.0 or fine["min_slab_po2_unrounded_mmhg"] + slab_error < 15.0:
status = "FAIL_WITH_REFINEMENT_ALLOWANCE"
else:
status = "NUMERICALLY_UNRESOLVED"
result["passes_strict_gel_only_two_zone_fv_2p0mmHg_core_gate"] = status == "PASS_WITH_REFINEMENT_ALLOWANCE"
assessment = {"status": status, "refinement_applied": True,
"reference_mesh_nodes": [201, 401], "reference_401_core_unrounded_mmhg": raw_core(fine),
"estimated_core_discretization_error_mmhg": estimate,
"reference_core_interval_mmhg": [core_lo, core_hi],
"reference_slab_lower_allowance_mmhg": slab_lo,
"raw_core_margin_over_2mmHg": raw_core(fine)-2.0,
"qualification": "201/401 mesh difference allowance; not empirical validation or a rigorous continuum error bound"}
result["strict_gel_only_numerical_gate_assessment"] = assessment
result["physical_layout_qualification"] = {
"status": "PREREGISTERED_PENDING",
"exact_120um_outer_band_geometry_feasible": (
geometry_ledger["diameter_120um_fits_wholly_in_outer_band"]
if demand_spatial_mode == "outer_annulus" else None),
"qualified_exact_product": False,
"note": "Numerical oxygen/chemistry gates do not qualify material packing, finite-cluster placement, perfusion, or exact-product function.",
}
return result
def _realized_half_plateau_perfusion_time_hours(target_midpoint_t50_h: float, iec_max_perfusion_fraction: float = 0.97) -> float:
"""Compute the realized time (hours) when v_perf(t) reaches 0.5 * iec_max_perfusion_fraction under the 3h lag ODE."""
if iec_max_perfusion_fraction <= 0.0:
return math.nan
t_dense = [0.05 * i for i in range(int(336.0 / 0.05) + 1)]
def _target(t_h: float) -> float:
exponent = -(t_h - target_midpoint_t50_h) / 8.0
return 0.0 if exponent > math.log(sys.float_info.max) else iec_max_perfusion_fraction / (1.0 + math.exp(exponent))
def _ode(t_h: float, y: np.ndarray) -> np.ndarray:
return np.array([(_target(t_h) - y[0]) / 3.0])
v_vec = rk4_integrate(_ode, (0.0, 336.0), np.array([0.01]), t_dense, dt_max=0.05)[0]
half_target = 0.5 * iec_max_perfusion_fraction
idx = int(np.searchsorted(v_vec, half_target))
if 0 < idx < len(t_dense):
v0, v1 = float(v_vec[idx - 1]), float(v_vec[idx])
t0, t1 = float(t_dense[idx - 1]), float(t_dense[idx])
return t0 + (half_target - v0) * (t1 - t0) / max(1e-15, v1 - v0)
return float(t_dense[-1])
def _build_formulation_specific_cao2_half_life_sensitivity_iip_0010() -> Dict[str, Any]:
"""Build the IIP-0010 fixed-inventory two-sided CaO2 half-life x kinetic-law x formulation sensitivity grid."""
half_lives_h = [24.0, 34.0, 48.0, 68.0, 87.0, 110.0, 130.0]
laws = ["first_order", "shrinking_core", "ginstling_brounshtein"]
timings_t50_h = [36.0, 60.0]
formulations = [
{
"formulation_id": "LAYOUT_B_31P25WT_119UM_LAMINA_DESIGNS_A_AND_B",
"cao2_wt_pct": 31.25,
"cao2_solid_vol_pct": 13.86,
"lamina_thickness_um": 119.0,
"outer_band_thickness_each_um": 115.5,
"lamina_half_width_fraction": CENTRAL_LAMINA_HALF_WIDTH_FRACTION,
"catalase_spatial_mode": "uniform_slab",
"catalase_k1_override_s_inv": None,
},
{
"formulation_id": "STAGE0_DESIGN_X_46P39WT_100UM_LAMINA_LOCALIZED_CATALASE",
"cao2_wt_pct": 46.39,
"cao2_solid_vol_pct": 23.45,
"lamina_thickness_um": 100.0,
"outer_band_thickness_each_um": 125.0,
"lamina_half_width_fraction": 100.0 / 350.0,
"catalase_spatial_mode": "central_lamina_masked",
"catalase_k1_override_s_inv": 18.0 * 0.42,
},
]
phi_slab_2500 = (2500.0 * VOL_1_IEQ_CM3) / 0.0350
rows: list[Dict[str, Any]] = []
passing_windows: list[Dict[str, Any]] = []
for form in formulations:
a_frac = float(form["lamina_half_width_fraction"])
local_phi = phi_slab_2500 / (1.0 - a_frac)
for law in laws:
for t50_h in timings_t50_h:
passing_hl: list[float] = []
for hl_h in half_lives_h:
r = _run_single_pouch_pde_regime(
f"IIP0010_{form['formulation_id']}_{law.upper()}_T50_{int(t50_h)}H_HL_{int(hl_h)}H",
0.45,
"central",
hl_h,
True,
0.97,
inosculation_t50_h=t50_h,
release_kinetics_law=law,
nz_override=51,
demand_spatial_mode="outer_annulus",
lamina_d_o2_scale=0.42 ** 1.5,
lamina_half_width_fraction=a_frac,
catalase_spatial_mode=str(form["catalase_spatial_mode"]),
catalase_k1_override_s_inv=form["catalase_k1_override_s_inv"],
_assess_numerical_gate=False,
)
min_slab = float(r["min_slab_po2_unrounded_mmhg"])
ws120 = r["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]
surf120 = float(ws120["two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"])
core120 = float(ws120["two_zone_fv_gel_only_supply_120um_core_po2_unrounded_mmhg"])
bvp100 = solve_spherical_cluster_po2_bvp(min_slab, 0.0050, phi_islet_in_slab=local_phi)
surf100 = float(bvp100["wigner_seitz_two_zone_fv_gel_only_supply_surface_po2_unrounded_mmhg"])
core100 = float(bvp100["wigner_seitz_two_zone_fv_gel_only_supply_core_po2_unrounded_mmhg"])
max_h2o2 = float(r["max_interstitial_h2o2_unrounded_uM"])
max_ph = float(r["max_interstitial_ph_unrounded"])
passes_100um = bool(surf100 >= 15.0 and core100 >= 2.0 and max_h2o2 <= 5.0 and max_ph <= 7.50)
if passes_100um:
passing_hl.append(hl_h)
rows.append({
"formulation_id": form["formulation_id"],
"cao2_wt_pct": form["cao2_wt_pct"],
"cao2_solid_vol_pct": form["cao2_solid_vol_pct"],
"lamina_thickness_um": form["lamina_thickness_um"],
"release_kinetics_law": law,
"inosculation_t50_h": t50_h,
"cao2_half_life_h": hl_h,