OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

        raise RuntimeError("Isolated 3D FVM solver subprocess did not return verified solver module origins")

    verified_origins: Dict[str, str] = {}
    verified_relpaths: Dict[str, str] = {}
    for mod_name, origin_str in sorted(raw_origins.items()):
        if not isinstance(mod_name, str) or not isinstance(origin_str, str):
            raise RuntimeError(f"Invalid solver module origin entry: {mod_name!r}: {origin_str!r}")
        origin_path = Path(origin_str).resolve()
        if not origin_path.is_relative_to(resolved_root) or not origin_path.is_relative_to(scripts_dir):
            raise RuntimeError(
                f"Isolated 3D FVM solver module {mod_name!r} resolved outside requested openislet_root: "
                f"{origin_path} not under {resolved_root}"
            )
        verified_origins[mod_name] = str(origin_path)
        verified_relpaths[mod_name] = origin_path.relative_to(resolved_root).as_posix()

    if isinstance(raw_relpaths, dict):
        for mod_name, rel_str in raw_relpaths.items():
            if mod_name in verified_relpaths and rel_str != verified_relpaths[mod_name]:
                raise RuntimeError(f"Solver module relpath mismatch for {mod_name!r}")

    face_min_raw = float.fromhex(str(parsed["face_min_raw_hex"]))
    verified_pb = float.fromhex(str(parsed["verified_p_bed_hex"]))
    d_o2_islet_verified = float.fromhex(str(parsed["d_o2_islet_tissue_cm2_s_hex"]))
    if verified_pb != expected_p_bed:
        raise RuntimeError(
            f"3D FVM solver p_bed mismatch: expected {expected_p_bed!r}, observed {verified_pb!r}"
        )

    res_obj = parsed.get("res_obj")
    if not isinstance(res_obj, dict):
        res_obj = {}
    res_obj["_nw08_isolated_solver_meta"] = {
        "solver_isolation_mode": "ISOLATED_CHILD_SUBPROCESS",
        "resolved_solver_module_paths": verified_origins,
        "resolved_solver_module_relpaths": verified_relpaths,
        "all_solver_module_origins_within_repo_root": True,
        "vascular_operand_audit": parsed.get("vascular_operand_audit"),
        "d_o2_islet_tissue_cm2_s": d_o2_islet_verified,
        "child_pid": int(parsed.get("child_pid") or 0),
        "child_optimize_flag": int(parsed.get("child_optimize_flag") or 0),
    }
    return res_obj, face_min_raw, verified_pb


def _execute_single_3d_fvm_vascular_scaled_solve(
    openislet_root: Path,
    route_spec: Dict[str, Any],
    *,
    vasc_scale: float | None = None,
) -> Tuple[Dict[str, Any], float]:
    """
    Invoke the exact read-only OpenIslet 3D FVM operator for `route_spec` with optional
    vascular-voxel-only OCR scaling and capture the native UNROUNDED float64 face minimum
    directly from `_compute_exact_fv_interface_stats_iip_0019` BEFORE 4-dp display rounding.
    """
    res_obj, face_min_raw, _verified_p_bed = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        route_spec,
        vasc_scale=vasc_scale,
    )
    return res_obj, face_min_raw


def _get_native_unrounded_baseline_mmhg_with_meta(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    eff_base_ocr: float,
) -> Tuple[float, Dict[str, Any]]:
    """
    Compute (with thread-safe root-keyed memoization) the exact native float64 unrounded baseline
    face minimum and verified isolated-subprocess module-origin metadata directly from the route's
    3D FVM operator at the requested boundary pressure (`effective_spec["kwargs"]["bed_po2_mmhg"]`)
    and baseline vascular OCR (R03-B2 + R18-B2).
    Never substitutes a 4-decimal display string as an unrounded baseline!
    """
    eff_p_bed = float(effective_spec["kwargs"]["bed_po2_mmhg"])
    resolved_root_str = str(openislet_root.resolve())
    cache_key = (resolved_root_str, str(route_id), eff_p_bed, float(eff_base_ocr))
    with _FVM_SOLVER_LOCK:
        cached = _NATIVE_BASELINE_MMHG_CACHE.get(cache_key)
        cached_meta = _NATIVE_BASELINE_META_CACHE.get(cache_key)
        if cached is not None and isinstance(cached_meta, dict) and cached_meta.get("resolved_solver_module_paths"):
            return cached, copy.deepcopy(cached_meta)
    shared_ocr = float(effective_spec["baseline_shared_ocr"])
    base_scale: float | None = (
        None if float(eff_base_ocr) == shared_ocr else (float(eff_base_ocr) / shared_ocr)
    )
    res_obj, native_base_mmhg, _pb = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        effective_spec,
        vasc_scale=base_scale,
    )
    iso_meta = copy.deepcopy(res_obj.get("_nw08_isolated_solver_meta") or {})
    with _FVM_SOLVER_LOCK:
        _NATIVE_BASELINE_MMHG_CACHE[cache_key] = native_base_mmhg
        _NATIVE_BASELINE_META_CACHE[cache_key] = iso_meta
    return native_base_mmhg, copy.deepcopy(iso_meta)


def _get_native_unrounded_baseline_mmhg(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    eff_base_ocr: float,
) -> float:
    """
    Compute (with thread-safe memoization) the exact native float64 unrounded baseline
    face minimum directly from the route's 3D FVM operator at the requested boundary
    pressure (`effective_spec["kwargs"]["bed_po2_mmhg"]`) and baseline vascular OCR (R03-B2).
    Never substitutes a 4-decimal display string as an unrounded baseline!
    """
    native_base_mmhg, _meta = _get_native_unrounded_baseline_mmhg_with_meta(
        openislet_root, route_id, effective_spec, eff_base_ocr
    )
    return native_base_mmhg


def _get_nw08_mesh_refinement_ladder(route_spec: Dict[str, Any]) -> Tuple[Tuple[str, int, int], ...]:
    """
    R14-B1 Predeclared 3-grid numerical refinement ladder per canonical NW-08 route family
    (coarse native grid -> medium refined grid -> fine refined grid):
      - R1: (nx0, nz0) -> (nx0+16, round(nz0*(nx0+16)/nx0)) -> (nx0+32, round(nz0*(nx0+32)/nx0))
      - R2: (48, 28) -> (72, 42) -> (96, 56)
      - R3P: (28, 32) -> (42, 48) -> (56, 64)
    """
    fam = str(route_spec["route_family"])
    kw = route_spec["kwargs"]
    if fam == "R1":
        nx0 = int(kw["nx_tot"])
        nz0 = int(kw["nz"])
        return (
            ("coarse", nx0, nz0),
            ("medium", nx0 + 16, int(round(nz0 * (nx0 + 16) / nx0))),
            ("fine", nx0 + 32, int(round(nz0 * (nx0 + 32) / nx0))),
        )
    if fam == "R2":
        nx0 = int(kw.get("nx_override", 48))
        nz0 = int(kw.get("nz_override", 28))
        return (
            ("coarse", nx0, nz0),
            ("medium", int(round(nx0 * 1.5)), int(round(nz0 * 1.5))),
            ("fine", nx0 * 2, nz0 * 2),
        )
    if fam == "R3P":
        nx0 = int(kw.get("nx", 28))
        nz0 = int(kw.get("nz", 32))
        return (
            ("coarse", nx0, nz0),
            ("medium", int(round(nx0 * 1.5)), int(round(nz0 * 1.5))),
            ("fine", nx0 * 2, nz0 * 2),
        )
    raise ValueError(f"Unknown route_family for mesh refinement ladder: {fam!r}")


def _solve_nw08_grid_level_cached(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    *,
    vasc_scale: float,
    nx: int,
    nz: int,
    use_cache: bool = True,
    min_exact_scale_ratio: Fraction | None = None,
) -> Tuple[float, float]:
    """Solve a single refined grid level (nx, nx, nz) with process-wide memoization under `_FVM_SOLVER_LOCK`."""
    eff_p_bed = float(effective_spec["kwargs"]["bed_po2_mmhg"])
    ratio_key = (
        f"{min_exact_scale_ratio.numerator}/{min_exact_scale_ratio.denominator}"
        if min_exact_scale_ratio is not None
        else None
    )
    cache_key = (
        str(openislet_root.resolve()),
        str(route_id),
        eff_p_bed,
        float(vasc_scale),
        int(nx),
        int(nz),
        ratio_key,
    )
    if use_cache:
        with _FVM_SOLVER_LOCK:
            cached = _MESH_REFINEMENT_SOLVE_CACHE.get(cache_key)
            if cached is not None:
                return cached
    refined_spec = copy.deepcopy(effective_spec)
    fam = str(refined_spec["route_family"])
    if fam == "R1":
        refined_spec["kwargs"].update({"nx_tot": int(nx), "nz": int(nz)})
    elif fam == "R2":
        refined_spec["kwargs"].update({"nx_override": int(nx), "nz_override": int(nz)})
    else:
        refined_spec["kwargs"].update({"nx": int(nx), "nz": int(nz)})
    _res, face_raw, verified_pb = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        refined_spec,
        vasc_scale=vasc_scale,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    out = (float(face_raw), float(verified_pb))
    if use_cache:
        with _FVM_SOLVER_LOCK:
            _MESH_REFINEMENT_SOLVE_CACHE[cache_key] = out
    return out


def _adjudicate_nw08_three_grid_convergence(
    f3: float,
    f2: float,
    f1: float,
    ladder: Tuple[Tuple[str, int, int], Tuple[str, int, int], Tuple[str, int, int]],
    *,
    band_mmhg: List[float] | None = None,
    near_floor: bool = True,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
    fs: float = NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
) -> Dict[str, Any]:
    """
    Pure 3-grid numerical convergence adjudication helper (NASA / Roache GCI & ASME V&V-20; R14-B1 + R15-B2).
    NEVER raises observed convergence order `p_obs` UP to `0.5`: any monotone sequence with
    sub-asymptotic slow order (`p_obs < 0.5`), non-positive/unverifiable order, extreme
    super-convergence (`p_obs > 2.5`), or non-asymptotic movement toward `15.0 mmHg` routes
    strictly fail-closed to `HOLD` (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`)
    with `interval_valid = False` and NO claimed clearance bound!
    """
    (c_lvl, c_nx, c_nz), (m_lvl, m_nx, m_nz), (f_lvl, f_nx, f_nz) = ladder
    floor_val = float(floor_mmhg)
    eff_band = list(band_mmhg) if band_mmhg is not None else [
        floor_val - NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG,
        floor_val + NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG,
    ]
    h3 = (float(c_nx) * float(c_nx) * float(c_nz)) ** (-1.0 / 3.0)
    h2 = (float(m_nx) * float(m_nx) * float(m_nz)) ** (-1.0 / 3.0)
    h1 = (float(f_nx) * float(f_nx) * float(f_nz)) ** (-1.0 / 3.0)
    r32 = h3 / h2
    r21 = h2 / h1

    if not (
        math.isfinite(f3)
        and math.isfinite(f2)
        and math.isfinite(f1)
        and math.isfinite(r32)
        and math.isfinite(r21)
        and r32 > 1.0
        and r21 > 1.0
    ):
        return {