OpenIslet

scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py

OpenIslet Wave-6 Round-14 Prospective Candidate W6-C2 (Staged Slot IIP-0047 -> Provisional

script Release v0.8.0 gen-eb955f8266035aba 466 KB · 37 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_iip0056_route4_omentum_and_exvivo_rest.py · SHA-256: 25e12d578ba80b55…

    phi_tot = (loading_ieq_cm2 * vol_ieq) / h_cm
    vmax[in_gel] = (phi_tot * c["vmax_islet_pure_mol_cm3_s"] * c["stromal_ocr_fraction"] * ocr_mult) / float(np.mean(in_gel))
    perm = np.where(in_any, d_islet * alpha_use, d_gel * alpha_use)
    p_ext = c["d_o2_gel_chronic_cm2_s"] * (0.5 if fibrin_um > 0.0 else 1.0) * alpha_use

    res = solve_3d_mm_oxygen_fvm(
        perm, vmax, np.zeros_like(X), dx, dx, dz,
        p_bed=0.5 * (pb_bot + pb_top), km_o2=c["km_o2_mmhg"], alpha_o2=alpha_use,
        p_bed_bot=pb_bot, p_bed_top=pb_top,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=p_ext, p_ext_top=p_ext, top_adiabatic=top_adiabatic,
    )
    p3 = res["p_3d"]
    wf = min(compute_exact_fv_interface_stats(p3, perm, m)["fv_harmonic_face_min_mmhg"] for m in masks)
    wc = min(float(np.min(p3[m])) for m in masks)
    anoxic_frac = float(np.mean(p3[in_any] < 0.5))
    return {
        "site": site_name,
        "grid": [nx, nx, nz],
        "loading_ieq_cm2": loading_ieq_cm2,
        "pitch_um": round(pitch_cm * 1e4, 2),
        "h_um": h_um,
        "z_c_um": round(z_c_used_um, 3),
        "wall_clearance_um": round(wall_clearance_um, 3),
        "min_cross_plane_center_dist_um": round(min_dist * 1e4, 2),
        "ocr_mult": round(ocr_mult, 4),
        "bed_po2_mmhg": round(0.5 * (pb_bot + pb_top), 2),
        "bed_po2_bot_mmhg": pb_bot,
        "bed_po2_top_mmhg": pb_top,
        "fibrin_um": fibrin_um,
        "d_matrix_cm2_s": d_gel,
        "alpha_o2_mol_cm3_mmhg": alpha_use,
        "top_adiabatic": top_adiabatic,
        "worst_face_mmhg": round(wf, 4),
        "worst_core_mmhg": round(wc, 4),
        "anoxic_islet_frac_lt_0p5mmHg": round(anoxic_frac, 4),
        "passes_15_and_5": bool(wf >= 15.0 and wc >= 5.0),
        "o2_rel_mass_balance_error": _fmt_sci_float(res["rel_mass_balance_error"]),
        "o2_post_rel_residual": _fmt_sci_float(res["post_rel_residual"]),
    }


def analyze_3grid_convergence(
    vals: Sequence[float],
    uniform_ratio: float,
    raw_mbes: Sequence[float],
) -> Dict[str, Any]:
    """Honest equal-ratio 3-mesh convergence diagnostic without negative-order clamping."""
    require_cond(len(vals) == 3 and len(raw_mbes) == 3, "Expected exactly 3 mesh levels")
    require_cond(uniform_ratio > 1.0, f"Invalid uniform refinement ratio: {uniform_ratio}")
    f3, f2, f1 = float(vals[0]), float(vals[1]), float(vals[2])
    e32 = f2 - f3
    e21 = f1 - f2
    v_min, v_max = min(f3, f2, f1), max(f3, f2, f1)
    spread = v_max - v_min
    half_range = 0.5 * spread
    base = {
        "uniform_refinement_ratio_xyz": round(uniform_ratio, 4),
        "coarse_medium_fine_mmhg": [round(f3, 4), round(f2, 4), round(f1, 4)],
        "raw_grid_min_max_mmhg": [round(v_min, 4), round(v_max, 4)],
        "max_spread_mmhg": round(spread, 4),
        "raw_o2_rel_mass_balance_errors": [_fmt_sci_float(x) for x in raw_mbes],
    }
    if abs(e21) < 1e-12 and abs(e32) < 1e-12:
        return {
            **base,
            "convergence_type": "EXACT_ZERO_SPREAD",
            "asymptotic_order_resolved": True,
            "observed_order_p": None,
            "conservative_bracket_covering_all_grids_mmhg": [round(f1, 4), round(f1, 4)],
        }
    if e21 * e32 <= 0.0:
        return {
            **base,
            "convergence_type": "OSCILLATORY_STAIRCASE_BOUND",
            "asymptotic_order_resolved": False,
            "observed_order_p": None,
            "asme_half_range_uncertainty_mmhg": round(half_range, 4),
            "conservative_bracket_covering_all_grids_mmhg": [round(v_min - half_range, 4), round(v_max + half_range, 4)],
            "diagnostic_note": "Voxelized spherical interface shifts discontinuously across Cartesian refinement; oscillatory half-range bracket reported.",
        }
    p_obs = math.log(abs(e32 / e21)) / math.log(uniform_ratio)
    if p_obs <= 0.0:
        return {
            **base,
            "convergence_type": "MONOTONE_NON_ASYMPTOTIC_UNRESOLVED_ORDER",
            "asymptotic_order_resolved": False,
            "observed_order_p": round(p_obs, 3),
            "asme_half_range_uncertainty_mmhg": round(half_range, 4),
            "conservative_bracket_covering_all_grids_mmhg": [round(v_min - half_range, 4), round(v_max + half_range, 4)],
            "diagnostic_note": "Observed order is non-positive (not clamped); grid sequence is outside asymptotic regime due to discrete sphere voxelization.",
        }
    p_gci = min(2.0, p_obs)
    gci_fine = 1.25 * abs(e21) / max((uniform_ratio ** p_gci) - 1.0, 1e-6)
    lo = min(v_min, f1 - gci_fine)
    hi = max(v_max, f1 + gci_fine)
    return {
        **base,
        "convergence_type": "MONOTONE_ASYMPTOTIC",
        "asymptotic_order_resolved": True,
        "observed_order_p": round(p_obs, 3),
        "gci_order_used": round(p_gci, 3),
        "gci_fine_mmhg": round(gci_fine, 4),
        "conservative_bracket_covering_all_grids_mmhg": [round(lo, 4), round(hi, 4)],
    }


# =============================================================================
# 4. 3D Crank-Nicolson FVM Insulin Shut-Off t50 (With Exact Transient Mass Balance)
# =============================================================================
def compute_3d_fvm_insulin_shutoff_t50(
    *,
    h_um: float,
    pitch_um: float,
    cluster_diam_um: float,
    bilayer: bool,
    fibrin_um: float,
    fibrin_d_factor: float,
    d_ins_matrix_cm2_s: float,
    d_ins_islet_cm2_s: float,
    t50_intrinsic_min: float,
    top_adiabatic: bool = False,
    z_c_um: float | None = None,
    nx: int = 18,
    nz: int = 24,
    dt_s: float = 2.0,
) -> Dict[str, Any]:
    r_cm = 0.5 * cluster_diam_um * 1e-4
    pitch_cm = pitch_um * 1e-4
    h_cm = h_um * 1e-4
    dx = pitch_cm / nx
    dz = h_cm / nz
    xs = (np.arange(nx) + 0.5) * dx
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_cm
    X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")

    def pdist(a: np.ndarray, ctr: float) -> np.ndarray:
        d = np.abs(a - ctr)
        return np.minimum(d, pitch_cm - d)

    in_cl = np.zeros_like(X, dtype=bool)
    if bilayer:
        margin = 15.0e-4 if h_um >= 170.0 else 5.0e-4
        z_c = (0.5 * h_cm - r_cm - margin) if z_c_um is None else (float(z_c_um) * 1e-4)
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, +z_c), (0.0, 0.0, -z_c)]
    else:
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, 0.0)]
    for cx, cy, cz in centers:
        in_cl |= (pdist(X, cx) ** 2 + pdist(Y, cy) ** 2 + (Z - cz) ** 2) <= (r_cm ** 2)

    d_field = np.where(in_cl, d_ins_islet_cm2_s, d_ins_matrix_cm2_s)
    d_ext = d_ins_matrix_cm2_s * (fibrin_d_factor if fibrin_um > 0.0 else 1.0)
    op = Standalone3DFVOperator(
        d_field, dx, dx, dz,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=d_ext, p_ext_top=d_ext, top_adiabatic=top_adiabatic,
    )
    b_rob = op.b_rob.ravel()
    src = np.where(in_cl, 1.0 / max(float(np.sum(in_cl)), 1.0), 0.0).ravel()

    c_vec = pcg_solve_spd(op, np.zeros_like(src), src, rtol=1e-13, maxiter=2500)
    j0 = float(np.sum(b_rob * c_vec))
    s0 = float(np.sum(src))
    ss_mbe = abs(j0 - s0) / max(abs(s0), 1e-30)
    require_cond(ss_mbe < 1e-10, f"Transient insulin steady-state mass-balance violation: {ss_mbe:.3e}")

    k_int = math.log(2.0) / (t50_intrinsic_min * 60.0)
    inv_2_dt = 2.0 / dt_s
    extra_cn = np.full_like(src, inv_2_dt)

    m0 = float(np.sum(c_vec))
    s_cum = 0.0
    j_cum = 0.0
    max_step_mbe = 0.0
    t_prev = 0.0
    f_prev = 1.0
    t50_s = None
    for step in range(1, 240):
        t_cur = step * dt_s
        s_avg_2 = src * (math.exp(-k_int * t_prev) + math.exp(-k_int * t_cur))
        rhs = inv_2_dt * c_vec + op.apply_A(c_vec) + s_avg_2
        c_next = pcg_solve_spd(op, extra_cn, rhs, rtol=1e-12, maxiter=1500)

        dm_step = float(np.sum(c_next - c_vec))
        s_step = 0.5 * dt_s * float(np.sum(s_avg_2))
        j_step = 0.5 * dt_s * float(np.sum(b_rob * (c_vec + c_next)))
        step_mbe = abs(dm_step + j_step - s_step) / max(abs(dm_step), abs(j_step), abs(s_step), 1e-30)
        max_step_mbe = max(max_step_mbe, step_mbe)
        s_cum += s_step
        j_cum += j_step
        c_vec = c_next

        f_cur = float(np.sum(b_rob * c_vec)) / j0
        if f_cur <= 0.5:
            frac = (f_prev - 0.5) / max(f_prev - f_cur, 1e-15)
            t50_s = t_prev + frac * dt_s
            break
        t_prev = t_cur
        f_prev = f_cur

    require_cond(t50_s is not None, "3D FVM insulin shut-off failed to cross 50%")
    m_end = float(np.sum(c_vec))
    cum_mbe = abs((m_end - m0) + j_cum - s_cum) / max(abs(m0), abs(j_cum), abs(s_cum), 1e-30)
    require_cond(max_step_mbe < 1e-10 and cum_mbe < 1e-10, f"Transient insulin CN mass-balance violation: step={max_step_mbe:.3e}, cum={cum_mbe:.3e}")

    t50_min = float(t50_s) / 60.0
    return {
        "h_um": h_um,
        "pitch_um": round(pitch_um, 2),
        "fibrin_um": fibrin_um,
        "bilayer": bilayer,
        "top_adiabatic": top_adiabatic,
        "grid": [nx, nx, nz],
        "t50_3d_fvm_min": round(t50_min, 4),
        "margin_below_3min_s": round((3.0 - t50_min) * 60.0, 2),
        "passes_lt_3p0_min": bool(t50_min < 3.0),
        "ss_rel_mass_balance_error": _fmt_sci_float(ss_mbe),
        "max_step_rel_mass_balance_error": _fmt_sci_float(max_step_mbe),
        "cumulative_rel_mass_balance_error": _fmt_sci_float(cum_mbe),
    }


# =============================================================================
# 5. Exact Crank Diazoxide Washout (GY-014 Kill), Systemic PK, & Decoupled Retrieval Audit
# =============================================================================
def _sphere_washout_times(radius_cm: float, d_cm2_s: float, n_modes: int = 200) -> Dict[str, float]:
    def rem(t: float) -> float:
        s = 0.0
        pref = (math.pi ** 2) * d_cm2_s * t / (radius_cm ** 2)
        for n in range(1, n_modes + 1):
            e = pref * n * n
            if e > 700.0:
                break
            s += math.exp(-e) / (n * n)
        return (6.0 / (math.pi ** 2)) * s

    out: Dict[str, float] = {}
    for label, target in [("t50_s", 0.50), ("t90_s", 0.10), ("t99_s", 0.01)]:
        lo, hi = 0.0, 1e6
        for _ in range(80):
            mid = 0.5 * (lo + hi)
            if rem(mid) > target:
                lo = mid
            else:
                hi = mid
        out[label] = round(0.5 * (lo + hi), 5)
    return out


def _slab_washout_times(half_thickness_cm: float, d_cm2_s: float, n_modes: int = 200) -> Dict[str, float]: