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…

    checked_repo = False
    repo_refs_verified = False

    if repo_root is not None:
        p43 = repo_root / "scripts" / "verify_iip0043_wholegraft_gate0v_and_calibration.py"
        pl4 = repo_root / "scripts" / "run_layer4_tissue_and_metabolic_twin.py"
        p34 = repo_root / "scripts" / "verify_iip0034_planar_and_portfolio.py"
        j34 = repo_root / "data" / "extracted" / "iip0034_planar_and_portfolio_verification_v0.8.0.json"
        for p in (p43, pl4, p34, j34):
            require_cond(p.is_file(), f"Missing required OpenIslet read-only file: {p}")

        src43 = p43.read_text(encoding="utf-8")
        srcl4 = pl4.read_text(encoding="utf-8")
        src34 = p34.read_text(encoding="utf-8")

        def _parse_float(txt: str, pat: str, label: str) -> float:
            m = re.search(pat, txt)
            require_cond(m is not None, f"Failed to parse {label} from OpenIslet source")
            return float(m.group(1))

        require_cond(abs(_parse_float(src43, r"vmax_islet_mol_cm3_s\s*=\s*([0-9.eE+-]+)", "vmax") - c["vmax_islet_pure_mol_cm3_s"]) < 1e-18, "vmax mismatch")
        require_cond(abs(_parse_float(src43, r"alpha_bunsen_nominal\s*=\s*([0-9.eE+-]+)", "alpha_nom") - c["alpha_o2_nominal_mol_cm3_mmhg"]) < 1e-18, "alpha_nom mismatch")
        require_cond(abs(_parse_float(src43, r"d_o2_islet\s*=\s*([0-9.eE+-]+)", "d_islet") - c["d_o2_islet_cm2_s"]) < 1e-18, "d_islet mismatch")
        require_cond(abs(_parse_float(src43, r"d_o2_gel_chronic\s*=\s*([0-9.eE+-]+)", "d_gel_chron") - c["d_o2_gel_chronic_cm2_s"]) < 1e-18, "d_gel_chron mismatch")
        require_cond(abs(_parse_float(src43, r"CANONICAL_NW08_PO2_FLOOR_MMHG:\s*float\s*=\s*([0-9.eE+-]+)", "po2_floor") - c["po2_gsis_face_floor_mmhg"]) < 1e-12, "po2_floor mismatch")
        require_cond(abs(_parse_float(srcl4, r"KM_O2_MMHG\s*=\s*([0-9.eE+-]+)", "km") - c["km_o2_mmhg"]) < 1e-12, "km mismatch")
        require_cond(abs(_parse_float(srcl4, r"D_O2_HYDROGEL_CM2_S\s*=\s*([0-9.eE+-]+)", "d_gel_acute") - c["d_o2_gel_acute_cm2_s"]) < 1e-12, "d_gel_acute mismatch")
        require_cond(abs(_parse_float(src34, r"ALPHA_PHYS_BUFFER\s*=\s*([0-9.eE+-]+)", "alpha_krbh") - c["alpha_o2_krbh_mol_cm3_mmhg"]) < 1e-18, "alpha_krbh mismatch")
        require_cond(abs(_parse_float(src34, r"d_ins_cm2_s\s*=\s*([0-9.eE+-]+)", "d_ins") - c["d_insulin_hydrogel_cm2_s"]) < 1e-18, "d_ins mismatch")
        require_cond(abs(_parse_float(src34, r"t50_intrinsic_min\s*=\s*([0-9.eE+-]+)", "t50_int") - c["insulin_intrinsic_t50_min"]) < 1e-12, "t50_int mismatch")

        d34 = load_strict_json_text(j34.read_text(encoding="utf-8"), j34.name)
        ref_map = {r["label"]: float(r["worst_face_mmhg"]) for r in d34["planar_3d_fvm_oxygen_envelopes"]}
        require_cond(abs(ref_map["Hybrid333_H180_Day0_Clean_65um_PASS"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_PASS"]) < 1e-4, "IIP-0034 clean ref mismatch")
        require_cond(abs(ref_map["Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL"]) < 1e-4, "IIP-0034 10um ref mismatch")
        require_cond(abs(ref_map["Hybrid333_H180_Day0_15umFibrin_0p5D_65um"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_15umFibrin_0p5D_65um"]) < 1e-4, "IIP-0034 15um ref mismatch")
        krbh_val = float(d34["planar_30mmhg_buffer_solubility_sensitivity"]["hybrid333_h180_bed30_clean_phys_buffer"]["worst_face_mmhg"])
        require_cond(abs(krbh_val - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_Alpha1p27e9_FACE_FAIL"]) < 1e-4, "IIP-0034 KRBH ref mismatch")
        checked_repo = True
        repo_refs_verified = True

    return {
        **c,
        "repo_constants_cross_verified": checked_repo,
        "repo_iip0034_refs_cross_verified": repo_refs_verified,
    }


# =============================================================================
# 2. Standalone 3D Finite-Volume Reaction-Diffusion Solver (Pure NumPy)
# =============================================================================
def _harm_mean(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    s = a + b
    return np.where(s > 0.0, 2.0 * a * b / np.where(s > 0.0, s, 1.0), 0.0)


class Standalone3DFVOperator:
    """
    Matrix-free 3D finite-volume operator:
      - Periodic in X and Y
      - Independent Robin or adiabatic (no-flux) Z-boundaries at bottom (k=0) and top (k=nz-1)
      - Exact harmonic-mean face conductivities across all interior faces.
    """

    def __init__(
        self,
        perm_field: np.ndarray,
        dx: float,
        dy: float,
        dz: float,
        *,
        standoff_bot_cm: float = 0.0,
        standoff_top_cm: float = 0.0,
        p_ext_bot: float | None = None,
        p_ext_top: float | None = None,
        top_adiabatic: bool = False,
    ) -> None:
        self.shape = perm_field.shape
        self.dx = float(dx)
        self.dy = float(dy)
        self.dz = float(dz)

        self.gx = _harm_mean(perm_field, np.roll(perm_field, -1, axis=0)) / (dx * dx)
        self.gx_m = np.roll(self.gx, 1, axis=0)
        self.gy = _harm_mean(perm_field, np.roll(perm_field, -1, axis=1)) / (dy * dy)
        self.gy_m = np.roll(self.gy, 1, axis=1)
        self.gz = _harm_mean(perm_field[:, :, :-1], perm_field[:, :, 1:]) / (dz * dz) if perm_field.shape[2] > 1 else None

        self.b_rob_bot = np.zeros_like(perm_field, dtype=np.float64)
        self.b_rob_top = np.zeros_like(perm_field, dtype=np.float64)
        self.neg_diag = self.gx + self.gx_m + self.gy + self.gy_m
        if self.gz is not None:
            self.neg_diag[:, :, :-1] += self.gz
            self.neg_diag[:, :, 1:] += self.gz

        df_b = perm_field[:, :, 0]
        de_b = df_b if p_ext_bot is None else np.full_like(df_b, float(p_ext_bot))
        r_b = (0.5 * dz) / np.maximum(df_b, 1e-30) + standoff_bot_cm / np.maximum(de_b, 1e-30)
        gf_b = 1.0 / (dz * r_b)
        self.neg_diag[:, :, 0] += gf_b
        self.b_rob_bot[:, :, 0] += gf_b

        if not top_adiabatic:
            df_t = perm_field[:, :, -1]
            de_t = df_t if p_ext_top is None else np.full_like(df_t, float(p_ext_top))
            r_t = (0.5 * dz) / np.maximum(df_t, 1e-30) + standoff_top_cm / np.maximum(de_t, 1e-30)
            gf_t = 1.0 / (dz * r_t)
            self.neg_diag[:, :, -1] += gf_t
            self.b_rob_top[:, :, -1] += gf_t

        self.b_rob = self.b_rob_bot + self.b_rob_top

    def apply_A(self, u: np.ndarray) -> np.ndarray:
        u3 = u.reshape(self.shape)
        out = -self.neg_diag * u3
        out[:-1, :, :] += self.gx[:-1, :, :] * u3[1:, :, :]
        out[-1, :, :] += self.gx[-1, :, :] * u3[0, :, :]
        out[1:, :, :] += self.gx_m[1:, :, :] * u3[:-1, :, :]
        out[0, :, :] += self.gx_m[0, :, :] * u3[-1, :, :]
        out[:, :-1, :] += self.gy[:, :-1, :] * u3[:, 1:, :]
        out[:, -1, :] += self.gy[:, -1, :] * u3[:, 0, :]
        out[:, 1:, :] += self.gy_m[:, 1:, :] * u3[:, :-1, :]
        out[:, 0, :] += self.gy_m[:, 0, :] * u3[:, -1, :]
        if self.gz is not None:
            out[:, :, :-1] += self.gz * u3[:, :, 1:]
            out[:, :, 1:] += self.gz * u3[:, :, :-1]
        return out.ravel()


def pcg_solve_spd(
    op: Standalone3DFVOperator,
    extra_diag: np.ndarray,
    rhs: np.ndarray,
    *,
    rtol: float = 1e-13,
    maxiter: int = 2500,
) -> np.ndarray:
    rhs_norm = float(np.linalg.norm(rhs))
    if rhs_norm <= 1e-30:
        return np.zeros_like(rhs)
    diag_tot = op.neg_diag.ravel() + extra_diag
    op_scale = max(float(np.max(diag_tot)), 1e-30)
    inv_op_scale = 1.0 / op_scale
    m_inv = op_scale / np.maximum(diag_tot, 1e-30)
    r = rhs / rhs_norm
    x = np.zeros_like(r)
    z = m_inv * r
    p_dir = z.copy()
    rz_old = float(np.dot(r, z))
    for _ in range(maxiter):
        ap = ((-op.apply_A(p_dir)) + extra_diag * p_dir) * inv_op_scale
        denom = float(np.dot(p_dir, ap))
        if denom <= 1e-300:
            break
        alpha = rz_old / denom
        x += alpha * p_dir
        r -= alpha * ap
        if float(np.linalg.norm(r)) <= rtol:
            return x * (rhs_norm * inv_op_scale)
        z = m_inv * r
        rz_new = float(np.dot(r, z))
        beta = rz_new / max(rz_old, 1e-300)
        p_dir = z + beta * p_dir
        rz_old = rz_new
    require_cond(float(np.linalg.norm(r)) <= 1e-9, f"PCG failed to converge: rel_res={float(np.linalg.norm(r)):.3e}")
    return x * (rhs_norm * inv_op_scale)


def solve_3d_mm_oxygen_fvm(
    perm: np.ndarray,
    vmax: np.ndarray,
    kp: np.ndarray,
    dx: float,
    dy: float,
    dz: float,
    *,
    p_bed: float,
    km_o2: float,
    alpha_o2: float,
    p_bed_bot: float | None = None,
    p_bed_top: float | None = None,
    standoff_bot_cm: float = 0.0,
    standoff_top_cm: float = 0.0,
    p_ext_bot: float | None = None,
    p_ext_top: float | None = None,
    top_adiabatic: bool = False,
    max_newton_iter: int = 65,
    tol_rel: float = 1e-13,
) -> Dict[str, Any]:
    op = Standalone3DFVOperator(
        perm, dx, dy, dz,
        standoff_bot_cm=standoff_bot_cm,
        standoff_top_cm=standoff_top_cm,
        p_ext_bot=p_ext_bot,
        p_ext_top=p_ext_top,
        top_adiabatic=top_adiabatic,
    )
    pb_b = float(p_bed if p_bed_bot is None else p_bed_bot)
    pb_t = float(p_bed if p_bed_top is None else p_bed_top)
    b_rhs = (op.b_rob_bot * pb_b + op.b_rob_top * pb_t).ravel()
    v_f = vmax.ravel()
    k_f = (kp * alpha_o2).ravel()
    scale = max(float(np.max(v_f)), float(np.max(b_rhs)), 1e-12)

    p = np.full(perm.size, 0.5 * (pb_b + pb_t), dtype=np.float64)
    converged = False
    iters = 0
    for it in range(1, max_newton_iter + 1):
        iters = it
        mm = p / (km_o2 + p)
        dmm = km_o2 / ((km_o2 + p) ** 2)
        f = op.apply_A(p) + b_rhs - v_f * mm + k_f * (p_bed - p)
        if float(np.max(np.abs(f))) / scale <= tol_rel and it >= 2:
            converged = True
            break
        dp = pcg_solve_spd(op, v_f * dmm + k_f, f, rtol=1e-13, maxiter=2500)
        p_cand = p + dp
        if np.any(p_cand < 0.0):
            p = np.where(p_cand > 0.1 * p, p_cand, 0.1 * p)
        else:
            p = p_cand

    mm_fin = p / (km_o2 + p)
    ap_fin = op.apply_A(p)
    f_post = ap_fin + b_rhs - v_f * mm_fin + k_f * (p_bed - p)
    post_rel = float(np.max(np.abs(f_post))) / scale
    require_cond(converged or post_rel <= 1e-9, f"3D FVM Newton non-convergence: {post_rel:.3e}")

    dv = dx * dy * dz
    bnd_in = float(np.sum((ap_fin + b_rhs) * dv))
    perf_in = float(np.sum(k_f * (p_bed - p) * dv))
    sink = float(np.sum(v_f * mm_fin * dv))
    mbe = abs(bnd_in + perf_in - sink) / max(abs(bnd_in), abs(perf_in), abs(sink), 1e-30)
    require_cond(mbe < 1e-10, f"Global flux mass-balance violation: {mbe:.3e}")

    return {
        "p_3d": p.reshape(perm.shape),
        "newton_iterations": iters,
        "post_rel_residual": post_rel,
        "rel_mass_balance_error": mbe,
    }


def compute_exact_fv_interface_stats(p3: np.ndarray, perm: np.ndarray, mask: np.ndarray) -> Dict[str, float]:
    face_vals: List[np.ndarray] = []
    for axis in (0, 1):
        for shift in (-1, 1):
            nbr_mask = np.roll(mask, shift, axis=axis)
            bnd = mask & (~nbr_mask)
            if np.any(bnd):