OpenIslet

scripts/verify_iip0033_bilayer_and_resp1.py

Deterministic Stage-0 Physics, Multi-Mesh 3D FVM & Respirometry Verifier (IIP-0033 / DEC-112)

script Release v0.8.0 gen-eb955f8266035aba 78 KB · 7 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_iip0033_bilayer_and_resp1.py · SHA-256: 45f1396930f3a6af…

        "ocr_mult": round(ocr_mult, 5),
        "standoff_phys_um": standoff_phys_um,
        "worst_face_mmhg": round(worst_face, 4),
        "worst_core_mmhg": round(worst_core, 4),
        "passes_15_and_5": bool(worst_face >= 15.0 and worst_core >= 5.0),
        "mass_balance_err": _stable_mass_balance_err(res["rel_mass_balance_error"]),
        "mass_balance_bound_lt_1e10": True,
    }


def solve_3d_preperf_microtrack_fvm(
    *,
    label: str,
    r_lumen_um: float,
    tissue_bridge_um: float,
    phi_lumen: float = 0.15,
    cluster_diam_um: float = 65.0,
    bed_po2_mmhg: float = 35.0,
    sleeve_um: float = 0.0,
    sleeve_d_factor: float = 1.0,
    k_perf_wall_s_inv: float = 25.0,
    k_perf_lumen_s_inv: float = 0.0,
    ocr_mult: float = 1.097,
    stromal_frac: float = 0.15,
    gsis_mult: float = 1.0,
    nx_cross: int = 40,
) -> Dict[str, Any]:
    """Exact 3D FVM of periodic parallel cylindrical pre-vascularized micro-tracks."""
    r_lum_cm = r_lumen_um * 1e-4
    r_cl_cm = 0.5 * cluster_diam_um * 1e-4
    v_cl = (4.0 / 3.0) * math.pi * (r_cl_cm ** 3)
    pitch_y_cm = (2.0 * r_lumen_um + tissue_bridge_um) * 1e-4
    h_z_cm = pitch_y_cm

    if r_lumen_um <= 165.0:
        r_off_cm = max(0.0, r_lum_cm - r_cl_cm - 5.0e-4)
        m_ring = 2 if r_lumen_um <= 105.0 else (4 if r_lumen_um <= 130.0 else (6 if r_lumen_um <= 145.0 else 8))
        n_cl_unit = 1 + m_ring
        l_x_cm = (n_cl_unit * v_cl) / (phi_lumen * math.pi * (r_lum_cm ** 2))
        nx_ax = max(28, int(round(nx_cross * (l_x_cm / pitch_y_cm))))
        ny = nx_cross
        nz = nx_cross
    else:
        n_cl_unit = 0
        l_x_cm = 0.0200
        nx_ax = 12
        ny = nx_cross
        nz = nx_cross

    dx = l_x_cm / nx_ax
    dy = pitch_y_cm / ny
    dz = h_z_cm / nz
    xs = (np.arange(nx_ax) + 0.5) * dx
    ys = (np.arange(ny) + 0.5) * dy - 0.5 * pitch_y_cm
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_z_cm
    X, Y, Z = np.meshgrid(xs, ys, zs, indexing="ij")
    R_cyl = np.sqrt(Y ** 2 + Z ** 2)
    dv = dx * dy * dz

    in_lumen = R_cyl <= r_lum_cm
    sleeve_cm = sleeve_um * 1e-4
    in_sleeve = (R_cyl > r_lum_cm) & (R_cyl <= (r_lum_cm + sleeve_cm))
    in_wall = R_cyl > (r_lum_cm + sleeve_cm)

    def pdist_x(a: np.ndarray, c: float) -> np.ndarray:
        d = np.abs(a - c)
        return np.minimum(d, l_x_cm - d)

    d_gel_use = D_GEL_ACUTE if k_perf_lumen_s_inv == 0.0 else D_GEL_CHRON
    k_gel_use = d_gel_use * ALPHA_LOW_SALT
    k_sleeve_use = D_GEL_CHRON * sleeve_d_factor * ALPHA_LOW_SALT

    perm = np.where(in_wall, K_GEL_CHRON, k_gel_use)
    if sleeve_um > 0.0:
        perm[in_sleeve] = k_sleeve_use

    vmax = np.zeros_like(X, dtype=np.float64)
    sphere_masks: List[Tuple[str, np.ndarray]] = []
    in_any_cl = np.zeros_like(X, dtype=bool)

    if n_cl_unit > 0:
        centers = [("center_axis", 0.25 * l_x_cm, 0.0, 0.0)]
        for k in range(m_ring):
            ang = (2.0 * math.pi * k) / m_ring
            centers.append((f"ring_{k}", 0.75 * l_x_cm, r_off_cm * math.cos(ang), r_off_cm * math.sin(ang)))
        for tag, xc, yc, zc in centers:
            msk = (pdist_x(X, xc) ** 2 + (Y - yc) ** 2 + (Z - zc) ** 2) <= (r_cl_cm ** 2)
            assert not np.any(in_any_cl & msk), f"Strict non-overlap violation in {label} ({tag})"
            assert np.all(in_lumen[msk]), f"Sphere protruded outside lumen in {label} ({tag})"
            in_any_cl |= msk
            v_vox = float(np.sum(msk)) * dv
            vmax[msk] = (VMAX_PURE * ocr_mult * gsis_mult) * (v_cl / v_vox)
            sphere_masks.append((tag, msk))
        perm[in_any_cl] = K_ISLET
        in_lumen_fluid = in_lumen & (~in_any_cl)
        vol_lumen_true = math.pi * (r_lum_cm ** 2) * l_x_cm
        total_stroma_rate = (phi_lumen * vol_lumen_true) * (VMAX_PURE * stromal_frac * ocr_mult)
        vmax[in_lumen_fluid] = total_stroma_rate / (float(np.sum(in_lumen_fluid)) * dv)
    else:
        perm[in_lumen] = K_ISLET * phi_lumen + k_gel_use * (1.0 - phi_lumen)
        vmax[in_lumen] = VMAX_PURE * ocr_mult * (gsis_mult + stromal_frac) * phi_lumen

    kp = np.zeros_like(X, dtype=np.float64)
    kp[in_wall] = k_perf_wall_s_inv
    if k_perf_lumen_s_inv > 0.0:
        kp[in_lumen & (~in_any_cl) if n_cl_unit > 0 else in_lumen] = k_perf_lumen_s_inv

    res = l4._solve_3d_oxygen_strict_iip_0019(
        perm, vmax, np.zeros_like(X), kp, dx, dy, dz,
        p_bed=bed_po2_mmhg, standoff_z_cm=15.0e-4, p_ext=K_GEL_CHRON,
    )
    p3 = res["p_3d"]
    if n_cl_unit > 0:
        worst_face = min(
            float(l4._compute_exact_fv_interface_stats_iip_0019(p3, perm, msk)["fv_harmonic_face_min_mmhg"])
            for _, msk in sphere_masks
        )
        core_min = float(np.min(p3[in_any_cl]))
    else:
        worst_face = float(np.min(p3[in_lumen]))
        core_min = worst_face

    return {
        "label": label,
        "r_lumen_um": r_lumen_um,
        "nx_cross": nx_cross,
        "grid_shape": [nx_ax, ny, nz],
        "sleeve_um": sleeve_um,
        "stromal_frac": stromal_frac,
        "worst_face_mmhg": round(worst_face, 4),
        "core_min_mmhg": round(core_min, 4),
        "passes_15_and_5": bool(worst_face >= 15.0 and core_min >= 5.0),
        "mass_balance_err": _stable_mass_balance_err(res["rel_mass_balance_error"]),
        "mass_balance_bound_lt_1e10": True,
    }


def verify_respirometry_contract() -> Dict[str, Any]:
    """Verify Agilent 16.60 / 16.87 / 14.94 / 14.00 / 9.87 uL KRBH caps & Sweet 2008 flow-through."""
    p_5pct = 0.05 * (760.0 - 47.0)       # 35.6500 mmHg
    p_21pct = 0.2095 * (760.0 - 47.0)    # 149.3735 mmHg
    ocr_endo_1p097 = VOL_IEQ * VMAX_PURE * 1.097 * 60.0
    ocr_stroma_15 = 0.15 * ocr_endo_1p097
    ocr_total_1p097 = ocr_endo_1p097 + ocr_stroma_15  # 4.547919e-12 mol/(min*IEQ)
    ocr_whole_pmol = round(ocr_total_1p097 * 1e12, 4) # 4.5479 pmol/(min*IEQ)

    regime_specs = [
        ("agilent_fluxpak_16p60uL_krbh_1p27", 16.60, ALPHA_KRBH, "Agilent FluxPak 103518-100 published 16.60 uL + KRBH"),
        ("agilent_brochure_16p87uL_krbh_1p27", 16.87, ALPHA_KRBH, "Agilent brochure 5991-8657EN p.9 published 16.87 uL (101122-100) + KRBH"),
        ("governing_minus10pct_14p94uL_krbh_1p27", 14.94, ALPHA_KRBH, "Conservative -10% margin off 16.60 uL (14.94 uL) + KRBH — 9/16 IEQ (+0.61 mmHg 16-IEQ air-FCCP margin)"),
        ("screen_displaced_14p00uL_krbh_1p27", 14.00, ALPHA_KRBH, "Screen-displaced 14.00 uL sensitivity + KRBH — 9/15 IEQ"),
        ("agilent_xf24_faq_9p87uL_krbh_1p27", 9.87, ALPHA_KRBH, "Agilent XF24 support FAQ 9.87 uL volume + KRBH — 6/10 IEQ (9/16 IEQ predicts 20.96/105.84 mmHg FAIL)"),
        ("obsolete_v7_22p70uL_lowsalt_1p34", 22.70, ALPHA_LOW_SALT, "OBSOLETE Gerencser 2009 V7 22.70 uL (mouse-liver mitochondria n=4) + 1.34e-9 comparator (false-pass 25.56/121.34 mmHg)"),
        ("obsolete_v7_22p70uL_purewater_1p39", 22.70, ALPHA_PURE_WATER_37C, "OBSOLETE Gerencser 2009 V7 22.70 uL + 1.39e-9 pure water comparator (false-pass 25.92/122.35 mmHg)"),
    ]
    static_regimes: Dict[str, Any] = {}
    for key, vol_uL, alpha, desc in regime_specs:
        cap = compute_static_xfe24_101122_100_cap_iip0033(
            volume_uL=vol_uL,
            alpha_mol_cm3_mmhg=alpha,
            ocr_whole_prep_pmol_min_ieq=ocr_whole_pmol,
            read_min=3.0,
        )
        dp_exact = (ocr_whole_pmol * 1e-12 * 3.0) / ((vol_uL * 1e-3) * alpha)
        static_regimes[key] = {
            "description": desc,
            "volume_uL": vol_uL,
            "alpha_mol_cm3_mmhg": alpha,
            "dp_basal_3min_mmhg_per_ieq": cap["dp_basal_3min_mmhg_per_ieq"],
            "max_ieq_5pct_basal_ge25": cap["max_ieq_5pct_basal_ge25"],
            "max_ieq_5pct_gsis_1p5x_ge25": cap["max_ieq_5pct_gsis_1p5x_ge25"],
            "max_ieq_21pct_fccp_2p5x_ge120": cap["max_ieq_21pct_fccp_2p5x_ge120"],
            "pred_9_ieq_5pct_gsis1p5_mmhg": round(p_5pct - 9.0 * 1.5 * dp_exact, 2),
            "pred_16_ieq_21pct_fccp2p5_mmhg": round(p_21pct - 16.0 * 2.5 * dp_exact, 2),
            "pred_15_ieq_5pct_gsis1p5_mmhg": round(p_5pct - 15.0 * 1.5 * dp_exact, 2),
            "pred_25_ieq_21pct_fccp2p5_mmhg": round(p_21pct - 25.0 * 2.5 * dp_exact, 2),
        }

    # Exact assertions locking all published Agilent hardware specifications
    assert static_regimes["governing_minus10pct_14p94uL_krbh_1p27"]["max_ieq_5pct_gsis_1p5x_ge25"] == 9
    assert static_regimes["governing_minus10pct_14p94uL_krbh_1p27"]["max_ieq_21pct_fccp_2p5x_ge120"] == 16
    assert abs(static_regimes["governing_minus10pct_14p94uL_krbh_1p27"]["pred_16_ieq_21pct_fccp2p5_mmhg"] - 120.61) <= 0.01
    assert static_regimes["screen_displaced_14p00uL_krbh_1p27"]["max_ieq_21pct_fccp_2p5x_ge120"] == 15
    assert static_regimes["agilent_xf24_faq_9p87uL_krbh_1p27"]["max_ieq_5pct_gsis_1p5x_ge25"] == 6
    assert static_regimes["agilent_xf24_faq_9p87uL_krbh_1p27"]["max_ieq_21pct_fccp_2p5x_ge120"] == 10
    assert static_regimes["agilent_xf24_faq_9p87uL_krbh_1p27"]["pred_9_ieq_5pct_gsis1p5_mmhg"] == 20.96
    assert static_regimes["agilent_xf24_faq_9p87uL_krbh_1p27"]["pred_16_ieq_21pct_fccp2p5_mmhg"] == 105.84

    # Primary flow-through perifusion modeled on Sweet 2008 methodological precedent
    ft_lead = compute_sweet2008_flow_through_po2_out_iip0033(
        n_ieq=200.0, flow_uL_min=200.0, alpha_mol_cm3_mmhg=ALPHA_KRBH, ocr_whole_prep_pmol_min_ieq=ocr_whole_pmol
    )
    assert ft_lead["p_out_5pct_basal_1p0x_mmhg"] == 32.07
    assert ft_lead["p_out_5pct_gsis_1p5x_mmhg"] == 30.28
    assert ft_lead["p_out_5pct_gsis_2p0x_mmhg"] == 28.49
    assert ft_lead["p_out_5pct_fccp_2p5x_mmhg"] == 26.70
    assert ft_lead["all_4_states_ge_25mmhg"] is True and ft_lead["passes_primary_spec"] is True

    return {
        "capture_screen_pore_size_um": 125.0,
        "requires_calibrated_volume_and_cluster_retention_for_static_caps": True,
        "sweet2008_methodological_precedent_note": (
            "Sweet et al. (2008 PMID:18021279; 750 handpicked islets, glucose/carbachol) establishes the flow-through "
            "differential-OCR methodological precedent; 200 IEQ @ 200 uL/min in 5% O2 KRBH and outlet values "
            "(32.07/30.28/28.49/26.70 mmHg) are modeled Stage-0 assumptions and predictions."
        ),
        "static_xfe24_101122_100_regimes": static_regimes,
        "flow_through_primary_lead_200ieq_200uLmin_krbh": ft_lead,
    }


def verify_fixed_pitch_bilayer_and_holds(meshes: Sequence[Tuple[int, int, int, int]]) -> Dict[str, Any]:
    """Run fixed-pitch 2x2 mixed-lot 65 um bilayer 3D FVM across meshes and prove all HOLD cases fail."""
    d_comp_68 = (2.0 * (65.0 ** 3) - (68.0 ** 3)) ** (1.0 / 3.0)
    d_comp_70 = (2.0 * (65.0 ** 3) - (70.0 ** 3)) ** (1.0 / 3.0)
    fixed_pitch_um = math.sqrt(1.0 / (0.5 * 1500.0 * VOL_IEQ / ((4.0 / 3.0) * math.pi * (32.5e-4 ** 3)))) * 1e4
    assert abs(fixed_pitch_um - 104.1604) < 1e-4

    # Verify GY-027 monolayer fixed-pitch vs re-derived 75 um packing gap
    mono_p65_um = math.sqrt(1.0 / (1500.0 * VOL_IEQ / ((4.0 / 3.0) * math.pi * (32.5e-4 ** 3)))) * 1e4
    mono_p75_um = math.sqrt(1.0 / (1500.0 * VOL_IEQ / ((4.0 / 3.0) * math.pi * (37.5e-4 ** 3)))) * 1e4
    gy027_packing_check = {
        "mono_65um_pitch_um": round(mono_p65_um, 4),
        "mono_65um_ordered_gap_um": round(mono_p65_um - 65.0, 2),
        "mono_75um_under_fixed_65um_pitch_gap_um": round(mono_p65_um - 75.0, 2),
        "mono_75um_rederived_pitch_um": round(mono_p75_um, 4),
        "mono_75um_rederived_gap_um": round(mono_p75_um - 75.0, 2),
    }
    assert gy027_packing_check["mono_75um_under_fixed_65um_pitch_gap_um"] == -1.35
    assert gy027_packing_check["mono_75um_rederived_gap_um"] == 16.29

    pass_runs: List[Dict[str, Any]] = []
    hold_runs: List[Dict[str, Any]] = []
    avascular_runs: List[Dict[str, Any]] = []

    for nx_t, nz_dz, nz_160, nz_r1 in meshes:
        r_z30 = solve_design_z_supercell_fixed_pitch(
            label=f"PASS_R2_140Stag_Chr30_NoFBR_kperf0p1358_p95_68_2xAdj_nx{nx_t}",
            top_diams_um=[68.0, 65.0, 65.0, d_comp_68],
            bot_diams_um=[68.0, 65.0, 65.0, d_comp_68],
            slab_h_um=140.0, z_c_um=27.5, staggered=True,
            bed_po2_mmhg=30.0, standoff_um=15.0, standoff_d_factor=1.0,
            d_gel_cm2_s=D_GEL_CHRON, k_perf_s_inv=K_PERF_CHRON, nx_tot=nx_t, nz=nz_dz,
        )
        assert r_z30["passes_15_and_5"]
        pass_runs.append(r_z30)

        r_z35 = solve_design_z_supercell_fixed_pitch(
            label=f"PASS_R2_140Stag_Chr35_15FBR3x_kperf0p1358_p95_68_2xAdj_nx{nx_t}",
            top_diams_um=[68.0, 65.0, 65.0, d_comp_68],