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…
def _sample_rsa_2d_iip_0019(n_cl: int, side_cm: float, min_dist_cm: float, rng: np.random.Generator) -> List[np.ndarray]:
pts: List[np.ndarray] = []
for _ in range(n_cl):
for _ in range(8000):
cand = rng.uniform(-0.5 * side_cm, 0.5 * side_cm, size=2)
if all(
float(
np.hypot(
min(abs(cand[0] - q[0]), side_cm - abs(cand[0] - q[0])),
min(abs(cand[1] - q[1]), side_cm - abs(cand[1] - q[1])),
)
)
>= min_dist_cm
for q in pts
):
pts.append(cand)
break
_req_iip_0019(len(pts) == n_cl, "RSA packing failed")
return pts
def _generate_deterministic_rsa_tiles_iip_0019() -> List[Dict[str, Any]]:
rad_cm = 0.0050
vol_sph = (4.0 / 3.0) * math.pi * (rad_cm ** 3)
n_per_face = 8
side_cm = math.sqrt(n_per_face / (0.5 * ((1500.0 * VOL_1_IEQ_CM3) / vol_sph)))
side_um = side_cm * 1e4
rng = np.random.default_rng(20261115)
tiles_out: List[Dict[str, Any]] = []
for tile_idx in range(10):
top_pts = _sample_rsa_2d_iip_0019(n_per_face, side_cm, 2.02 * rad_cm, rng)
bot_pts = _sample_rsa_2d_iip_0019(n_per_face, side_cm, 2.02 * rad_cm, rng)
min_gaps: List[float] = []
for pts in (top_pts, bot_pts):
mg = 1e9
for i in range(n_per_face):
for j in range(i + 1, n_per_face):
dxp = min(abs(float(pts[i][0] - pts[j][0])), side_cm - abs(float(pts[i][0] - pts[j][0])))
dyp = min(abs(float(pts[i][1] - pts[j][1])), side_cm - abs(float(pts[i][1] - pts[j][1])))
mg = min(mg, (math.hypot(dxp, dyp) - 2.0 * rad_cm) * 1e4)
min_gaps.append(round(mg, 2))
merged = dict(_IIP0019_RSA_PRECOMPUTED_TILE_METRICS[tile_idx])
merged["tile_side_um"] = round(side_um, 2)
merged["top_centers_um"] = [[round(float(p[0]) * 1e4, 2), round(float(p[1]) * 1e4, 2)] for p in top_pts]
merged["bot_centers_um"] = [[round(float(p[0]) * 1e4, 2), round(float(p[1]) * 1e4, 2)] for p in bot_pts]
merged["min_top_edge_gap_um"] = min_gaps[0]
merged["min_bot_edge_gap_um"] = min_gaps[1]
tiles_out.append(merged)
return tiles_out
def build_explicit_3d_clumping_and_microbead_h2o2_audit_iip_0019(lead_regime: Dict[str, Any]) -> Dict[str, Any]:
"""
Execute live 3D solver verification (Gate 3D-V), ordered unit-cell reconciliations,
barrier-film coupled O2+H2O2 cross-section checks, and deterministic RSA manifest generation.
"""
p_krogh_acute = D_O2_HYDROGEL_CM2_S * ALPHA_BUNSEN_MOL_CM3_MMHG
p_krogh_chronic = 1.50e-5 * ALPHA_BUNSEN_MOL_CM3_MMHG
p_krogh_islet = D_O2_ISLET_TISSUE_CM2_S * ALPHA_BUNSEN_MOL_CM3_MMHG
iu_per_cm3_per_sinv = 27000.0 / 18.0
rule_s6_area_cm2 = 1000.0 / 3.0
# 1. Gate 3D-V (6-check numerical benchmark + 3 negative controls)
ref_o2_18h = float(lead_regime["min_slab_po2_unrounded_mmhg"])
nz_1d = 70
dz_1d = 0.0350 / nz_1d
zc_1d = -0.0175 + (np.arange(nz_1d) + 0.5) * dz_1d
lam_mask_1d = (np.abs(zc_1d) <= 0.34 * 0.0175).astype(np.float64)
lam_frac_1d = float(np.mean(lam_mask_1d))
phi_base_1d = (2500.0 * VOL_1_IEQ_CM3) / 0.0350
q_dem_full_1d = phi_base_1d * VMAX_ISLET_PURE_MOL_CM3_S * 1.15
r_o2_0_mean_1d = 0.45 * q_dem_full_1d
perf_18h = float(
rk4_integrate(
lambda t, y: np.array([(0.97 / (1.0 + math.exp(-(t - 36.0) / 8.0)) - y[0]) / 3.0]),
(0.0, 18.0),
np.array([0.01]),
[0.0, 18.0],
dt_max=0.25,
)[0, -1]
)
k_perf_18h = 0.14 * perf_18h
o2_gen_mean_18h = r_o2_0_mean_1d * math.exp(-math.log(2.0) * 18.0 / 68.0)
s_h2o2_18h = (2.0 * o2_gen_mean_18h * 1e9) * (lam_mask_1d / lam_frac_1d)
diff_h_18 = np.full((2, 2, nz_1d), D_H2O2_HYDROGEL_CM2_S, dtype=np.float64)
h_res_18h = _solve_3d_h2o2_strict_iip_0019(
diff_h_18,
np.broadcast_to(s_h2o2_18h, (2, 2, nz_1d)).copy(),
np.full((2, 2, nz_1d), 18.0 * math.exp(-math.log(2.0) * 18.0 / 168.0), dtype=np.float64),
np.full((2, 2, nz_1d), k_perf_18h, dtype=np.float64),
0.0010,
0.0010,
dz_1d,
)
res_pl_o2 = _solve_3d_oxygen_strict_iip_0019(
np.full((2, 2, nz_1d), p_krogh_acute, dtype=np.float64),
np.full((2, 2, nz_1d), q_dem_full_1d, dtype=np.float64),
0.5 * h_res_18h["decomp_uM_s"] * 1e-9,
np.full((2, 2, nz_1d), k_perf_18h, dtype=np.float64),
0.0010,
0.0010,
dz_1d,
P_BOUNDARY_HOST_BED_MMHG,
standoff_z_cm=0.0,
p_ext=None,
)
planar_o2_3d_min = float(np.min(res_pl_o2["p_3d"]))
planar_o2_rel_pct = 100.0 * abs(planar_o2_3d_min - ref_o2_18h) / ref_o2_18h
_req_iip_0019(planar_o2_rel_pct < 0.5, f"Gate 3D-V planar O2 error {planar_o2_rel_pct:.4f}% >= 0.5%")
s_h2o2_0h = (2.0 * r_o2_0_mean_1d * 1e9) * (lam_mask_1d / lam_frac_1d)
kcat_layb = np.broadcast_to(0.008 + (18.0 * 0.17538946 - 0.008) * lam_mask_1d, (2, 2, nz_1d)).copy()
res_pl_h = _solve_3d_h2o2_strict_iip_0019(
diff_h_18,
np.broadcast_to(s_h2o2_0h, (2, 2, nz_1d)).copy(),
kcat_layb,
np.full((2, 2, nz_1d), 0.14 * 0.01, dtype=np.float64),
0.0010,
0.0010,
dz_1d,
)
planar_h2o2_3d_max_uM = float(np.max(res_pl_h["h_3d"]))
planar_h2o2_rel_pct = 100.0 * abs(planar_h2o2_3d_max_uM - 4.059) / 4.059
_req_iip_0019(planar_h2o2_rel_pct < 1.0, f"Gate 3D-V planar H2O2 error {planar_h2o2_rel_pct:.4f}% >= 1.0%")
# Analytic 1D Robin-standoff BVP
L_half_an = 0.0175
stand_an = 0.0045
s0_an = 2.0e-9
perm_rob = np.full((2, 2, nz_1d), p_krogh_chronic, dtype=np.float64)
res_rob = _solve_3d_oxygen_strict_iip_0019(
perm_rob,
np.zeros_like(perm_rob),
np.full_like(perm_rob, s0_an),
np.zeros_like(perm_rob),
0.0010,
0.0010,
dz_1d,
35.0,
standoff_z_cm=stand_an,
p_ext=p_krogh_chronic,
)
p_ana_1d = 35.0 + s0_an * L_half_an * (stand_an / p_krogh_chronic) + s0_an * (L_half_an**2 - zc_1d**2) / (2.0 * p_krogh_chronic)
robin_rel_err_pct = 100.0 * float(np.max(np.abs(res_rob["p_3d"][0, 0, :] - p_ana_1d) / p_ana_1d))
_req_iip_0019(robin_rel_err_pct < 0.01, f"Gate 3D-V Robin analytic error {robin_rel_err_pct:.5f}% >= 0.01%")
# 64^3 3D spherical Dirichlet-exterior collapse vs Layer-4 spherical closures
n_sph = 64
h_sph = 0.0160 / n_sph
cs_sph = (np.arange(n_sph) + 0.5) * h_sph - 0.0080
Xs, Ys, Zs = np.meshgrid(cs_sph, cs_sph, cs_sph, indexing="ij")
inside_sph = (Xs**2 + Ys**2 + Zs**2) <= (0.0060**2)
perm_s = np.where(inside_sph, p_krogh_islet, 50.0 * p_krogh_islet)
vmax_s = np.where(
inside_sph,
VMAX_ISLET_PURE_MOL_CM3_S * (((4.0 / 3.0) * math.pi * (0.0060**3)) / (float(np.sum(inside_sph)) * (h_sph**3))),
0.0,
)
kp_s = np.where(inside_sph, 0.0, 200.0)
res_ws3d = _solve_3d_oxygen_strict_iip_0019(
perm_s, vmax_s, np.zeros_like(perm_s), kp_s, h_sph, h_sph, h_sph, ref_o2_18h, standoff_z_cm=0.0, p_ext=None
)
sph_3d_core = round(float(np.min(res_ws3d["p_3d"][inside_sph])), 4)
ws_ref = lead_regime["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]
sph_dirichlet_ref = round(float(lead_regime["min_120um_cluster_core_po2_unrounded_mmhg"]), 4)
sph_rel_diff_pct = 100.0 * abs(sph_3d_core - sph_dirichlet_ref) / sph_dirichlet_ref
_req_iip_0019(sph_rel_diff_pct < 0.5, f"Gate 3D-V 64^3 spherical error {sph_rel_diff_pct:.4f}% >= 0.5%")
# 3 Negative controls (live-computed)
d_nc = np.ones((2, 2, 20), dtype=np.float64) * p_krogh_chronic
d_nc[:, :, 9:11] = 1e-4 * p_krogh_chronic
op_harm = PureNumpy3DFVOperator(d_nc, 0.005, 0.005, 0.001, standoff_z_cm=0.0045, d_ext_scalar=p_krogh_chronic)
op_arith = PureNumpy3DFVOperator(
d_nc, 0.005, 0.005, 0.001, standoff_z_cm=0.0045, d_ext_scalar=p_krogh_chronic, use_arithmetic_wrong_control=True
)
rhs_nc_3d = np.zeros_like(d_nc)
rhs_nc_3d[:, :, -1] = op_harm.b_rob[:, :, -1] * 35.0
rhs_nc = rhs_nc_3d.ravel()
u_harm = _pcg_solve_spd_iip_0019(op_harm, np.zeros(d_nc.size), rhs_nc)
u_arith = _pcg_solve_spd_iip_0019(op_arith, np.zeros(d_nc.size), rhs_nc)
nc_arith_vs_harm_rel = float(np.linalg.norm(u_arith - u_harm) / np.linalg.norm(u_harm))
_req_iip_0019(nc_arith_vs_harm_rel > 0.05, "Negative control 1 failed to distinguish arithmetic vs harmonic flux")
# Negative control 2: scaling external collagen resistance erroneously with internal hydrogel diffusivity
op_cap_fixed = PureNumpy3DFVOperator(
np.full((2, 2, 10), 2.0 * p_krogh_chronic), 0.005, 0.005, 0.001, standoff_z_cm=0.0015, d_ext_scalar=p_krogh_chronic / 3.0
)
op_cap_wrong_scaled = PureNumpy3DFVOperator(
np.full((2, 2, 10), 2.0 * p_krogh_chronic), 0.005, 0.005, 0.001, standoff_z_cm=0.0045, d_ext_scalar=None
)
nc_cap_fixed_vs_scaled_rel = float(
abs(op_cap_wrong_scaled.b_rob[0, 0, 0] - op_cap_fixed.b_rob[0, 0, 0]) / op_cap_fixed.b_rob[0, 0, 0]
)
_req_iip_0019(nc_cap_fixed_vs_scaled_rel > 0.25, "Negative control 2 failed to detect wrong capsule permeability scaling")
nc_unconverged_caught = False
try:
_pcg_solve_spd_iip_0019(op_harm, np.zeros(d_nc.size), rhs_nc, maxiter=1, fail_on_maxiter=True)
except RuntimeError:
nc_unconverged_caught = True
_req_iip_0019(nc_unconverged_caught, "Negative control 3 failed to raise RuntimeError on maxiter=1")
# 2. Live ordered 3D unit-cell solves
def _solve_ordered_unit_cell(
load_ieq: float,
diam_um: float,
slab_um: float = 350.0,
lam_um: float = 100.0,
buf_um: float = 0.0,
ocr_mult: float = 1.097,
standoff_phys_um: float = 15.0,
p_ext_val: float = p_krogh_chronic / 3.0,
nx_c: int = 40,
nz_c: int = 70,
shift_half_voxel: bool = False,
) -> Dict[str, Any]:
rad_cm = 0.5 * diam_um * 1e-4
vol_sph = (4.0 / 3.0) * math.pi * (rad_cm**3)
n_face = 0.5 * ((load_ieq * VOL_1_IEQ_CM3) / vol_sph)
side_cm = math.sqrt(1.0 / n_face)
hex_pitch_cm = math.sqrt(2.0 / (math.sqrt(3.0) * n_face))
slab_cm = slab_um * 1e-4
lam_half_cm = 0.5 * lam_um * 1e-4
buf_cm = buf_um * 1e-4
band_inner_z = lam_half_cm + buf_cm
band_outer_z = 0.5 * slab_cm
band_thick_um = (band_outer_z - band_inner_z) * 1e4
_req_iip_0019(band_thick_um >= diam_um, f"Cell band {band_thick_um:.1f} um < cluster diameter {diam_um:.1f} um")
dx_c, dz_c = side_cm / nx_c, slab_cm / nz_c
xs = (np.arange(nx_c) + 0.5) * dx_c - 0.5 * side_cm
zs = (np.arange(nz_c) + 0.5) * dz_c - 0.5 * slab_cm
X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")
x0 = 0.5 * dx_c if shift_half_voxel else 0.0
y0 = 0.5 * dx_c if shift_half_voxel else 0.0
z_mid = 0.5 * (band_inner_z + band_outer_z)
z_c = min(band_outer_z - rad_cm - min(0.0002, 0.5 * (band_outer_z - band_inner_z - 2.0 * rad_cm)), z_mid)
z_c = max(z_c, band_inner_z + rad_cm)
ddx = np.minimum(np.abs(X - x0), side_cm - np.abs(X - x0))
ddy = np.minimum(np.abs(Y - y0), side_cm - np.abs(Y - y0))
r_top = np.sqrt(ddx**2 + ddy**2 + (Z - z_c) ** 2)
r_bot = np.sqrt(ddx**2 + ddy**2 + (Z + z_c) ** 2)
top_sph = r_top <= rad_cm
in_sph = top_sph | (r_bot <= rad_cm)
in_lam = np.abs(Z) <= lam_half_cm
in_buf = (np.abs(Z) > lam_half_cm) & (np.abs(Z) <= band_inner_z)
perm = np.where(in_lam, p_krogh_chronic * (0.42**1.5), p_krogh_chronic)
perm[in_sph] = p_krogh_islet