OpenIslet

scripts/verify_iip0045_cao2_coupled_gate31.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Lot Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 68 KB · 6 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/verify_iip0045_cao2_coupled_gate31.py · SHA-256: 00443954dd735914…

    return {
        "conserved_patient_cao2_mg": m_cao2_mg,
        "rho_cao2_g_cm3": rho_cao2,
        "rho_pdms_g_cm3": rho_pdms,
        "planar_2x20um_barrier_film_volume_200cm2_cm3": round(200.0 * 0.0040, 4),
        "planar_2x20um_barrier_film_volume_333p33cm2_cm3": round((1000.0 / 3.0) * 0.0040, 4),
        "all_conformal_per_bead_cases_physically_unbuildable": all(
            not r["physically_buildable_in_lamina"] for r in rows
        ),
        "cases": rows,
    }


def _import_layer4() -> Any:
    if str(SCRIPT_DIR) not in sys.path:
        sys.path.insert(0, str(SCRIPT_DIR))
    import run_layer4_tissue_and_metabolic_twin as l4  # noqa: PLC0415
    return l4


def reconstruct_interface_plane_h2o2_bpr16(
    h3: np.ndarray,
    zs: np.ndarray,
    z_interface_cm: float,
) -> Dict[str, Any]:
    """
    Reconstruct H2O2 at the exact geometric barrier/tissue interface z = z_interface_cm
    by linear geometric-weight interpolation between the two bracketing cell-center planes
    (equal H2O2 diffusivity across the hydrogel barrier/tissue interface; BPR-16 / DEC-133).
    Also returns the nearest cell-center plane max with its explicit z coordinate so both
    observation sites are transparently reported. Exact for constant and linear fields on
    any aligned mesh.
    """
    zs_arr = np.asarray(zs, dtype=float)
    h_arr = np.asarray(h3, dtype=float)
    if zs_arr.ndim != 1 or h_arr.ndim != 3 or h_arr.shape[2] != zs_arr.shape[0]:
        raise ValueError("h3 must have shape (nx, ny, nz) matching 1D zs")
    if zs_arr.shape[0] < 2:
        raise ValueError("zs must contain at least 2 cell centers")

    # Nearest cell center (legacy behavior, explicitly labeled with its true z coordinate)
    nearest_idx = int(np.argmin(np.abs(zs_arr - z_interface_cm)))
    nearest_z_cm = float(zs_arr[nearest_idx])
    nearest_max = float(np.max(h_arr[:, :, nearest_idx]))

    # Bracketing cell centers for exact interface reconstruction
    hi_candidates = np.where(zs_arr >= z_interface_cm)[0]
    lo_candidates = np.where(zs_arr <= z_interface_cm)[0]
    if len(lo_candidates) == 0 or len(hi_candidates) == 0:
        raise ValueError(f"z_interface_cm={z_interface_cm} outside mesh cell-center span [{zs_arr[0]}, {zs_arr[-1]}]")
    i_lo = int(lo_candidates[-1])
    i_hi = int(hi_candidates[0])
    if i_lo == i_hi:
        w_lo, w_hi = 1.0, 0.0
        h_interface_plane = h_arr[:, :, i_lo]
    else:
        z_lo = float(zs_arr[i_lo])
        z_hi = float(zs_arr[i_hi])
        w_hi = (z_interface_cm - z_lo) / (z_hi - z_lo)
        w_lo = 1.0 - w_hi
        h_interface_plane = w_lo * h_arr[:, :, i_lo] + w_hi * h_arr[:, :, i_hi]

    # First cell center strictly inside tissue (z > z_interface_cm)
    tissue_candidates = np.where(zs_arr > z_interface_cm)[0]
    first_tissue_idx = int(tissue_candidates[0]) if len(tissue_candidates) > 0 else nearest_idx

    return {
        "interface_z_um": round(z_interface_cm * 1e4, 6),
        "interface_h2o2_max_uM": float(np.max(h_interface_plane)),
        "nearest_cell_center_z_um": round(nearest_z_cm * 1e4, 6),
        "nearest_cell_center_h2o2_max_uM": nearest_max,
        "first_tissue_cell_center_z_um": round(float(zs_arr[first_tissue_idx]) * 1e4, 6),
        "first_tissue_cell_center_h2o2_max_uM": float(np.max(h_arr[:, :, first_tissue_idx])),
        "bracketing_cell_centers_z_um": [round(float(zs_arr[i_lo]) * 1e4, 6), round(float(zs_arr[i_hi]) * 1e4, 6)],
        "interpolation_weights": [round(float(w_lo), 6), round(float(w_hi), 6)],
        "materials_both_sides": {
            "inner_side": "planar_P04040_catalase_hydrogel_barrier_abs_z_le_70um",
            "outer_side": "islet_tissue_hydrogel_band_abs_z_gt_70um",
            "equal_h2o2_diffusivity_both_sides": True,
        },
    }


def run_live_3d_fvm_conserved_inventory_coupled_sweeps() -> Dict[str, Any]:
    """Execute live 3D FVM replays conserving 791.5 mg CaO2 across t_1/2 and barrier O2-attenuation."""
    l4 = _import_layer4()
    p_krogh_acute = l4.D_O2_HYDROGEL_CM2_S * l4.ALPHA_BUNSEN_MOL_CM3_MMHG
    p_krogh_islet = l4.D_O2_ISLET_TISSUE_CM2_S * l4.ALPHA_BUNSEN_MOL_CM3_MMHG
    iu_per_cm3_per_sinv = 27000.0 / 18.0

    def _solve_case(
        *,
        t_half_h: float,
        t_eval_h: float,
        cat_ret_override: Optional[float] = None,
        o2_attenuation_factor: float = 1.0,
        vascular_midpoint_horizon_h: float = 36.0,
        slab_um: float = 390.0,
        lam_um: float = 100.0,
        buf_um: float = 20.0,
        load_ieq: float = 1500.0,
        diam_um: float = 80.0,
        lam_iu_200: float = 22680.0,
        buf_iu_200: float = 21600.0,
        nx_c: int = 36,
        dz_um: float = 5.0,
    ) -> 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 * l4.VOL_1_IEQ_CM3) / vol_sph)
        side_cm = math.sqrt(1.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
        nz_c = int(round(slab_um / dz_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")
        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)
        r_top = np.sqrt(X**2 + Y**2 + (Z - z_c) ** 2)
        r_bot = np.sqrt(X**2 + Y**2 + (Z + z_c) ** 2)
        top_sph = r_top <= rad_cm
        bot_sph = r_bot <= rad_cm
        in_sph = top_sph | bot_sph
        in_lam = np.abs(Z) <= lam_half_cm
        in_buf = (np.abs(Z) > lam_half_cm) & (np.abs(Z) <= band_inner_z)

        areal_o2_0_at_68h = 0.45 * (load_ieq * l4.VOL_1_IEQ_CM3) * l4.VMAX_ISLET_PURE_MOL_CM3_S * 1.15
        m_rem = (68.0 / t_half_h) * math.exp(-math.log(2.0) * t_eval_h / t_half_h) * o2_attenuation_factor
        perf_f = (
            float(
                l4.rk4_integrate(
                    lambda t, y: np.array([(0.97 / (1.0 + math.exp(-(t - vascular_midpoint_horizon_h) / 8.0)) - y[0]) / 3.0]),
                    (0.0, t_eval_h),
                    np.array([0.01]),
                    [0.0, t_eval_h],
                    dt_max=0.25,
                )[0, -1]
            )
            if t_eval_h > 0.0
            else 0.01
        )
        k_perf_t = 0.14 * perf_f
        cat_ret_t = cat_ret_override if cat_ret_override is not None else math.exp(-math.log(2.0) * t_eval_h / 168.0)

        r_b = 0.0025  # 50 um wet-sieved bead touching top face of 100 um central lamina
        z_b = lam_half_cm - r_b
        r_bead = np.sqrt(X**2 + Y**2 + (Z - z_b) ** 2)
        in_bead_core = r_bead <= max(r_b - 0.5 * dz_c, 0.4 * r_b)
        in_bead_shell = (r_bead > max(r_b - 0.5 * dz_c, 0.4 * r_b)) & (r_bead <= r_b + 0.65 * dz_c)

        mean_h2o2_uM_s = (2.0 * areal_o2_0_at_68h * m_rem / slab_cm) * 1e9
        src_h = np.zeros_like(X)
        src_h[in_bead_shell] = mean_h2o2_uM_s / float(np.mean(in_bead_shell))
        diff_h = np.where(in_bead_core, 0.0, l4.D_H2O2_HYDROGEL_CM2_S)
        slab_vol_200 = 200.0 * slab_cm
        kcat = np.full_like(X, 0.008)
        lam_avail = in_lam & (~in_bead_core)
        kcat[lam_avail] = ((lam_iu_200 * cat_ret_t) / (slab_vol_200 * iu_per_cm3_per_sinv)) / float(np.mean(lam_avail))
        if buf_um > 0.0 and buf_iu_200 > 0.0:
            kcat[in_buf] = ((buf_iu_200 * cat_ret_t) / (slab_vol_200 * iu_per_cm3_per_sinv)) / float(np.mean(in_buf))
        kp_h = np.where(in_lam | in_buf, 0.0, k_perf_t)
        res_h = l4._solve_3d_h2o2_strict_iip_0019(diff_h, src_h, kcat, kp_h, dx_c, dx_c, dz_c)
        h3 = res_h["h_3d"]
        plane_recon = reconstruct_interface_plane_h2o2_bpr16(h3, zs, band_inner_z)

        src_o2 = 0.5 * res_h["decomp_uM_s"] * 1e-9
        perm_o2 = np.where(in_lam, p_krogh_acute * (0.42**1.5), p_krogh_acute)
        perm_o2[in_bead_core] = p_krogh_acute * 0.25
        perm_o2[in_sph] = p_krogh_islet
        in_gel = (~in_sph) & (~in_lam) & (~in_buf)
        t_phi = (load_ieq * l4.VOL_1_IEQ_CM3) / slab_cm
        vmax = np.zeros_like(X)
        vmax[in_sph] = l4.VMAX_ISLET_PURE_MOL_CM3_S * (t_phi / float(np.mean(in_sph)))
        vmax[in_gel] = (t_phi * l4.VMAX_ISLET_PURE_MOL_CM3_S * 0.15) / float(np.mean(in_gel))
        kp_o2 = np.where(in_gel, k_perf_t, 0.0)
        res_o2 = l4._solve_3d_oxygen_strict_iip_0019(
            perm_o2, vmax, src_o2, kp_o2, dx_c, dx_c, dz_c, 35.0, standoff_z_cm=0.0, p_ext=None
        )
        p3 = res_o2["p_3d"]
        fv_top = l4._compute_exact_fv_interface_stats_iip_0019(p3, perm_o2, top_sph)
        fv_bot = l4._compute_exact_fv_interface_stats_iip_0019(p3, perm_o2, bot_sph)
        worst_face_min = float(min(fv_top["fv_harmonic_face_min_mmhg"], fv_bot["fv_harmonic_face_min_mmhg"]))
        worst_face_mean = float(min(fv_top["fv_harmonic_face_mean_mmhg"], fv_bot["fv_harmonic_face_mean_mmhg"]))
        h2o2_interface_max = plane_recon["interface_h2o2_max_uM"]
        h2o2_cell_center_max = plane_recon["first_tissue_cell_center_h2o2_max_uM"]
        return {
            "t_half_h": t_half_h,
            "t_eval_h": t_eval_h,
            "vascular_midpoint_horizon_h": vascular_midpoint_horizon_h,
            "dz_um": dz_um,
            "catalase_retention_frac": round(cat_ret_t, 6),
            "o2_attenuation_factor": o2_attenuation_factor,
            "islet_plane_observation_site": "barrier_tissue_interface_z70um_linear_reconstructed",
            "islet_plane_observation_coordinate_um": plane_recon["interface_z_um"],
            "islet_plane_h2o2_max_uM": round(h2o2_interface_max, 4),
            "barrier_tissue_interface_z70um_h2o2_max_uM": round(h2o2_interface_max, 4),
            "first_tissue_cell_center_z_um": plane_recon["first_tissue_cell_center_z_um"],
            "first_tissue_cell_center_h2o2_max_uM": round(h2o2_cell_center_max, 4),
            "cluster_surface_h2o2_max_uM": round(float(np.max(h3[in_sph])), 4),
            "global_pore_h2o2_max_uM": round(float(np.max(h3)), 4),
            "worst_face_po2_min_mmhg": round(worst_face_min, 4),
            "worst_face_po2_mean_mmhg": round(worst_face_mean, 4),
            "min_core_po2_mmhg": round(float(np.min(p3[in_sph])), 4),
            "passes_h2o2_tier1_2p5uM": bool(h2o2_interface_max <= 2.5),
            "passes_h2o2_tier2_5p0uM": bool(h2o2_interface_max <= 5.0),
            "passes_first_tissue_cell_h2o2_tier1_2p5uM": bool(h2o2_cell_center_max <= 2.5),
            "passes_first_tissue_cell_h2o2_tier2_5p0uM": bool(h2o2_cell_center_max <= 5.0),
            "passes_po2_worst_face_15mmhg": bool(worst_face_min >= 15.0),
            "h2o2_rel_mass_balance_error": res_h["rel_mass_balance_error"],
            "o2_rel_mass_balance_error": res_o2["rel_mass_balance_error"],
        }

    burst_t0_100pct = [_solve_case(t_half_h=th, t_eval_h=0.0) for th in (4.0, 8.0, 12.0, 18.0, 24.0, 34.0, 68.0, 87.0)]
    burst_t0_50pct = [
        _solve_case(t_half_h=th, t_eval_h=0.0, cat_ret_override=0.50)
        for th in (12.0, 18.0, 24.0, 34.0, 68.0)
    ]
    acute_t18_100pct = [_solve_case(t_half_h=th, t_eval_h=18.0) for th in (4.0, 12.0, 24.0, 34.0, 68.0, 87.0)]
    third_coupling_o2_lag = [
        _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=att)
        for att in (1.0, 0.85, 0.70, 0.50, 0.25, 0.0)
    ]

    # BPR-14: time x vascular timing (36 h vs 60 h) x delivery sensitivity matrix (fixed 791.5 mg inventory)
    bpr14_t50_36_att0p70 = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=0.70, vascular_midpoint_horizon_h=36.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0)
    ]
    bpr14_t50_60_att0p70 = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=0.70, vascular_midpoint_horizon_h=60.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0, 60.0)
    ]
    bpr14_t50_60_att1p00_control = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=1.00, vascular_midpoint_horizon_h=60.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0, 60.0)
    ]
    bpr14_interior_controls = {
        "t_half_64h_att_0p80_t36h_on_60h_branch": _solve_case(
            t_half_h=64.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=60.0
        ),
        "t_half_64h_att_0p80_t36h_on_36h_branch": _solve_case(
            t_half_h=64.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=36.0
        ),