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…

    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    *,
    vasc_scale: float,
    native_coarse_face_mmhg: float,
    verified_p_bed: float,
    force_check: bool = False,
    min_exact_scale_ratio: Fraction | None = None,
) -> Dict[str, Any]:
    """
    R14-B1 + R15-B2 + R17-M2 Predeclared 3-grid numerical resolution / error policy (NASA / Roache GCI & ASME V&V-20):
      - Automatically executes the predeclared 3-grid ladder whenever `f_coarse` lies inside the
        route-family near-floor band (`R1 [14.88, 15.25]`, `R2 [14.75, 15.25]`, `R3P [14.70, 15.30] mmHg`)
        or `force_check=True`, with a recorded 2-grid early-stop exception (`grids_run=2`,
        `fine_grid_skipped_already_straddling=True`,
        `mesh_uncertainty_status=TWO_GRID_DIRECT_FLOOR_CROSSING_HOLD`) when
        `force_check=False` and the coarse and medium grids already directly straddle `15.0 mmHg`
        (an irreversible crossing no fine grid can eliminate; pass `force_check=True` for full 3-grid replay).
      - Computes a conservative discretization error interval `[L_num, U_hi]` with safety factor Fs = 1.25:
          * Oscillatory (`(f1 - f2) * (f2 - f3) < 0`): ASME V&V-20 oscillatory half-range
            `U_num = Fs * 0.5 * (f_max - f_min)` centered at `0.5 * (f_min + f_max)`, enclosing `[f_min, f_max]`.
          * Monotone converging (`(f1 - f2) * (f2 - f3) > 0` and `|f1 - f2| < |f2 - f3|`): solves the exact
            observed order `p_obs` on `(r32, r21)`. NEVER clamps `p_obs` upward to `0.5`!
            - Qualified Roache GCI requires `0.5 <= p_obs <= 2.5` (with mild super-convergence `2.0 < p_obs <= 2.5`
              conservatively capped DOWN to formal order `2.0`, widening GCI).
            - Sub-asymptotic slow order (`p_obs < 0.5`), non-positive/unverifiable order, or extreme
              super-convergence (`p_obs > 2.5`) routes fail-closed to `HOLD`
              (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, `interval_valid = False`).
          * Monotone non-shrinking / non-asymptotic: strictly moving AWAY from `15.0 mmHg` applies conservative
            full-spread bounds `Fs * (f_max - f_min)`; direct straddling or accelerating/stalled drift TOWARD
            `15.0 mmHg` routes fail-closed to `HOLD`.
      - Adjudication against immutable `15.0 mmHg` floor:
          * `PASS` iff `interval_valid` and `L_num >= 15.0` and `f_min >= 15.0`
          * `FAIL` iff `interval_valid` and `U_hi < 15.0` and `f_max < 15.0`
          * `HOLD` (`HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR` or
            `HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`) otherwise!
    """
    ladder = _get_nw08_mesh_refinement_ladder(effective_spec)
    c_lvl, c_nx, c_nz = ladder[0]
    m_lvl, m_nx, m_nz = ladder[1]
    f_lvl, f_nx, f_nz = ladder[2]
    fam = str(effective_spec["route_family"])
    lo_delta, hi_delta = NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY.get(
        fam, (-NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG, NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG)
    )
    band_lo_mmhg = CANONICAL_NW08_PO2_FLOOR_MMHG + lo_delta
    band_hi_mmhg = CANONICAL_NW08_PO2_FLOOR_MMHG + hi_delta
    near_floor = bool(band_lo_mmhg <= native_coarse_face_mmhg <= band_hi_mmhg)
    if (not near_floor) and (not force_check):
        decisive_pass = _passes_unrounded_15mmhg_floor(native_coarse_face_mmhg)
        return {
            "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_band_mmhg": [band_lo_mmhg, band_hi_mmhg],
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "triggered_by_near_floor_band": False,
            "executed": False,
            "grids_run": 1,
            "grid_ladder": [
                {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "face_min_mmhg_unrounded": native_coarse_face_mmhg}
            ],
            "predeclared_refinement_grids": [
                [c_nx, c_nx, c_nz],
                [m_nx, m_nx, m_nz],
                [f_nx, f_nx, f_nz],
            ],
            "convergence_regime": "NOT_REQUIRED_FAR_FROM_FLOOR",
            "mesh_uncertainty_status": (
                NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS
                if decisive_pass
                else NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL
            ),
            "observed_order_p_raw": None,
            "apparent_order_p": None,
            "order_qualified": False,
            "interval_valid": False,
            "richardson_extrapolated_mmhg": None,
            "grid_min_mmhg": native_coarse_face_mmhg,
            "grid_max_mmhg": native_coarse_face_mmhg,
            "grid_spread_mmhg": 0.0,
            "fine_grid_face_min_mmhg_unrounded": None,
            "discretization_uncertainty_mmhg": None,
            "conservative_po2_lower_bound_mmhg": None,
            "conservative_po2_upper_bound_mmhg": None,
            "straddles_canonical_15mmhg_floor": False,
            "mesh_convergence_resolved": True,
            "hold_reason_token": None,
            "verdict_from_mesh_policy": "PASS" if decisive_pass else "FAIL",
        }

    f3 = float(native_coarse_face_mmhg)
    f2, _pb2 = _solve_nw08_grid_level_cached(
        openislet_root,
        route_id,
        effective_spec,
        vasc_scale=vasc_scale,
        nx=m_nx,
        nz=m_nz,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    floor_val = CANONICAL_NW08_PO2_FLOOR_MMHG
    # Fast exact early-exit when coarse and medium grids already directly straddle 15.0 mmHg
    # (unless full 3-grid diagnostic replay is explicitly forced via force_check=True):
    # no fine-grid value can eliminate min(f3, f2, f1) < 15.0 <= max(f3, f2, f1)!
    direct_c_to_m_straddle = bool(min(f3, f2) < floor_val <= max(f3, f2))
    if direct_c_to_m_straddle and (not force_check):
        f_min_2 = min(f3, f2)
        f_max_2 = max(f3, f2)
        spread_2 = f_max_2 - f_min_2
        return {
            "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_band_mmhg": [band_lo_mmhg, band_hi_mmhg],
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "triggered_by_near_floor_band": near_floor,
            "executed": True,
            "grids_run": 2,
            "fine_grid_skipped_already_straddling": True,
            "grid_ladder": [
                {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "face_min_mmhg_unrounded": f3},
                {"level": m_lvl, "grid": [m_nx, m_nx, m_nz], "face_min_mmhg_unrounded": f2},
            ],
            "predeclared_refinement_grids": [
                [c_nx, c_nx, c_nz],
                [m_nx, m_nx, m_nz],
                [f_nx, f_nx, f_nz],
            ],
            "convergence_regime": "DIRECT_FLOOR_CROSSING_COARSE_TO_MEDIUM",
            "mesh_uncertainty_status": NW08_MESH_STATUS_TWO_GRID_DIRECT_CROSSING_HOLD,
            "observed_order_p_raw": None,
            "apparent_order_p": None,
            "order_qualified": False,
            "interval_valid": False,
            "richardson_extrapolated_mmhg": None,
            "grid_min_mmhg": f_min_2,
            "grid_max_mmhg": f_max_2,
            "grid_spread_mmhg": spread_2,
            "fine_grid_face_min_mmhg_unrounded": None,
            "discretization_uncertainty_mmhg": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS * spread_2,
            "conservative_po2_lower_bound_mmhg": f_min_2,
            "conservative_po2_upper_bound_mmhg": f_max_2,
            "straddles_canonical_15mmhg_floor": True,
            "mesh_convergence_resolved": False,
            "hold_reason_token": NW08_HOLD_TOKEN_STRADDLES_FLOOR,
            "verdict_from_mesh_policy": "HOLD",
        }

    f1, _pb1 = _solve_nw08_grid_level_cached(
        openislet_root,
        route_id,
        effective_spec,
        vasc_scale=vasc_scale,
        nx=f_nx,
        nz=f_nz,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    return _adjudicate_nw08_three_grid_convergence(
        f3,
        f2,
        f1,
        ladder,
        band_mmhg=[band_lo_mmhg, band_hi_mmhg],
        near_floor=near_floor,
        floor_mmhg=floor_val,
        fs=NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
    )


def dispatch_and_solve_nw08_measured_ocr(
    route_id: str,
    measured_ocr: float,
    uncertainty_se: float,
    *,
    openislet_root: Path | None = None,
    baseline_min_face_mmhg: float | None = None,
    baseline_vasc_ocr_mult: float | None = None,
    p_bed_mmhg: float | None = None,
    local_3d_slope_mmhg_per_pct: float | None = None,
    z_one_sided_95: float | None = None,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
    always_solve_3d: bool = False,
    ocr_uncertainty_model: str | None = None,
    ocr_replicates_n: int | None = None,
    ocr_degrees_of_freedom: int | None = None,
    ocr_uncertainty_provenance: str | None = None,
    measured_ocr_u95_override: float | None = None,
    force_mesh_convergence_check: bool = False,
    _require_explicit_model_for_positive_se: bool = False,
) -> Dict[str, Any]:
    """
    B7 / R03-B2 / R04-B5 / R05-B2 / R14-B1..B3 Live Executable 3D FVM Solver Dispatch Entry Point:
      1. Validates `route_id` against the canonical 8-route NW-08 catalog and validates any
         caller-supplied boundary-pressure (`p_bed_mmhg`) or baseline overrides fail-closed.
      2. Enforces explicit inferential uncertainty provenance whenever `uncertainty_se > 0`
         (exact Student-t critical value `t_{0.95, df}` for `STUDENT_T_ESTIMATED_SE`, scoped
         `KNOWN_SIGMA_NORMAL` with external calibration provenance, or `INDEPENDENT_JUSTIFIED_UPPER_BOUND`;
         rejects bare undeclared positive SE fail-closed; R14-B2).
      3. Carries `p_bed_mmhg` consistently into BOTH the preliminary screen AND the actual
         route-specific 3D FVM solver kwargs (`bed_po2_mmhg`), and computes the exact native
         float64 unrounded baseline directly from the 3D FVM solver at `(eff_p_bed, eff_base_ocr)`
         on every call path (rejecting stale mismatched caller baselines).
      4. Executes every native 3D FVM solve inside an isolated child Python subprocess bound strictly
         to `openislet_root.resolve() / "scripts"` (verifying `Path(mod.__file__).resolve().is_relative_to(resolved_root)`
         for all loaded solver modules and reporting `resolved_solver_module_origins` without mutating
         parent `sys.path`, `sys.modules`, or Layer-4 callbacks; R18-B1 + R18-B2), while retaining the
         process-wide `_FVM_SOLVER_LOCK` for thread-safe root-keyed cache access (R14-B3).
      5. Enforces the predefined 3-grid numerical resolution / error policy (NASA / Roache GCI &
         ASME V&V-20; R14-B1 + R15-B2 + R17-M2): whenever a live solve lies inside the route-family
         near-floor band (`R1 [14.88, 15.25]`, `R2 [14.75, 15.25]`, `R3P [14.70, 15.30] mmHg`; or
         `force_mesh_convergence_check=True`), executes the predeclared 3-grid ladder — with the
         recorded 2-grid early-stop exception (`grids_run=2`,
         `fine_grid_skipped_already_straddling=True`,
         `mesh_uncertainty_status=TWO_GRID_DIRECT_FLOOR_CROSSING_HOLD`) when
         `force_mesh_convergence_check=False` and the coarse and medium grids already directly
         straddle `15.0 mmHg` (`min(f3, f2) < 15.0 <= max(f3, f2)`), since no fine-grid solve can
         remove that irreversible floor crossing (pass `force_mesh_convergence_check=True` to force
         full 3-grid diagnostic replay). Routes any threshold-straddling case to unresolved `HOLD`
         (`HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR`, exit 2) and any slow/non-asymptotic
         order case (`p_obs < 0.5`, non-positive order, `p_obs > 2.5`, or non-asymptotic drift toward
         `15.0 mmHg`) to unresolved `HOLD`
         (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, exit 2,
         `interval_valid=False`) before any release authorization!
    """
    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    catalog = _build_nw08_route_catalog(resolved_root)
    if not isinstance(route_id, str) or route_id not in catalog:
        raise ValueError(f"Unrecognized NW-08 canonical route_id: {route_id!r}; expected one of {sorted(catalog.keys())}")
    spec = catalog[route_id]
    catalog_default_p_bed = float(spec["p_bed_mmhg"])
    catalog_default_p_bed_dec = Decimal(str(catalog_default_p_bed))

    f_measured_ocr, dec_measured_ocr = _parse_nw08_boundary_scalar(
        measured_ocr, "measured_ocr", strictly_positive=True
    )
    f_uncertainty_se, dec_uncertainty_se = _parse_nw08_boundary_scalar(
        uncertainty_se, "uncertainty_se", non_negative=True
    )
    diag_floor, dec_diag_floor = _parse_nw08_boundary_scalar(
        floor_mmhg, "floor_mmhg", strictly_positive=True
    )
    unc_info = _resolve_nw08_ocr_uncertainty_bound(