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…

            scale_f > 1.0
            and Fraction(scale_f) >= req_ratio
            and Fraction(eff_ocr_f) >= Fraction(u95_d)
        )

    r17_t5_r2_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_det0, d_r17_sub_ulp_t5, Decimal("1.097"))
    r17_ks_r2_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_det0, d_r17_sub_ulp_ks, Decimal("1.097"))
    r17_t5_r1_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_r1_det0, d_r17_sub_ulp_r1_t5, Decimal("1.2067"))

    r17_m1_scope_ok = all(
        (
            d_obj.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and d_obj.get("physical_qualification_complete") is False
            and d_obj.get("solver_isolation_mode") == "ISOLATED_CHILD_SUBPROCESS"
            and d_obj.get("all_solver_module_origins_within_repo_root") is True
        )
        for d_obj in (
            d_r17_fast_det0,
            d_r17_live_det0,
            d_r17_sub_ulp_t5,
            d_r17_sub_ulp_ks,
            d_r17_live_r1_det0,
            d_r17_sub_ulp_r1_t5,
        )
    )
    ok_31 = bool(
        d_r17_fast_det0["solver_executed"] is False
        and d_r17_fast_det0["native_solver_vasc_scale_float64"] == 1.0
        and d_r17_live_det0["solver_executed"] is True
        and d_r17_live_det0["native_solver_vasc_scale_float64"] == 1.0
        and d_r17_sub_ulp_t5["solver_executed"] is True
        and d_r17_sub_ulp_ks["solver_executed"] is True
        and d_r17_sub_ulp_r1_t5["solver_executed"] is True
        and r17_t5_r2_solver_ok
        and r17_ks_r2_solver_ok
        and r17_t5_r1_solver_ok
        and r17_m1_scope_ok
    )
    tests.append({
        "test": "r17_b2_m1_sub_ulp_positive_se_upward_native_solver_scale_and_direct_qualification_scope",
        "det0_fast_path_scale": d_r17_fast_det0["native_solver_vasc_scale_float64"],
        "det0_live_3d_scale": d_r17_live_det0["native_solver_vasc_scale_float64"],
        "sub_ulp_t5_r2_scale_float64": d_r17_sub_ulp_t5["native_solver_vasc_scale_float64"],
        "sub_ulp_t5_r2_effective_ocr_float64": d_r17_sub_ulp_t5["native_solver_effective_vascular_ocr_float64"],
        "sub_ulp_t5_r2_solver_operand_strictly_up": r17_t5_r2_solver_ok,
        "sub_ulp_ks_r2_solver_operand_strictly_up": r17_ks_r2_solver_ok,
        "sub_ulp_t5_r1_1p2067_solver_operand_strictly_up": r17_t5_r1_solver_ok,
        "direct_dispatch_qualification_scope_present_all_paths": r17_m1_scope_ok,
        "passed": ok_31,
    })

    # 32. R18-B1: Concurrent raw native Layer-4 isolation (WITHOUT acquiring `_FVM_SOLVER_LOCK`):
    #     unchanged native R2 call (~24.0468 mmHg) agrees bit-for-bit before, during, and after
    #     a simultaneous modified NW-08 call (R2_DZ40, bed=40, base=5.0, meas=10.0 -> ~13.1032 mmHg)!
    tests.append(_run_r18_b1_concurrent_raw_native_isolation_test(openislet_root))

    # 33. R18-B2: Sequential cross-root isolation (`copy_A` then `copy_B` across R2, R3P, and R1):
    #     `resolved_solver_module_origins` points strictly inside `copy_A` on call 1 and strictly
    #     inside `copy_B` on call 2, rejecting symlink escape outside `repo_root` with zero host path leaks!
    tests.append(_run_r18_b2_cross_root_sequential_isolation_test(openislet_root))

    passed_n = sum(1 for t in tests if t["passed"])
    return {
        "executed": True,
        "total_tests": len(tests),
        "passed_tests": passed_n,
        "all_passed": passed_n == len(tests),
        "tests": tests,
    }


def _run_true_3d_fvm_vascular_voxel_replays(
    openislet_root: Path,
    r1_rows: List[Dict[str, Any]],
) -> Dict[str, Any]:
    """
    Replay ALL 8 live Route 1 / Route 2 / Route 3P 3D FVM baselines AND exact vascular-voxel-only
    stress solves (m_vasc = 1.3164 = 1.097 * 1.20, plus matched +20% above 1.2067 = 1.44804 on
    R1_390_stress so linear vs 3D are compared on IDENTICAL perturbations!) using OpenIslet's
    read-only 3D FVM operators inside isolated child Python subprocesses bound strictly to
    `openislet_root`. Captures native UNROUNDED float64 face minima directly from
    _compute_exact_fv_interface_stats_iip_0019 BEFORE route 4-dp display serialization!
    """
    nominal = 1.097
    m_vasc_target = nominal * 1.20  # 1.3164
    catalog = _build_nw08_route_catalog(openislet_root)
    replays: Dict[str, Any] = {}
    diffusivity_verified: float | None = None

    for label in (
        "R1_390_nominal",
        "R1_350_stress",
        "R1_390_stress",
        "R2_DZ40",
        "R3P_35",
        "R3P_30",
        "R3P_30_KRBH",
        "R3P_35_VPIO120",
    ):
        spec = catalog[label]
        current_vasc_ocr = float(spec["baseline_shared_ocr"])
        p_bed = float(spec["p_bed_mmhg"])
        operator_name = str(spec["operator_name"])
        base_res, base_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
            openislet_root, spec, vasc_scale=None
        )
        base_iso_meta = (
            copy.deepcopy(base_res.get("_nw08_isolated_solver_meta") or {})
            if isinstance(base_res, dict)
            else {}
        )
        if diffusivity_verified is None and isinstance(base_iso_meta.get("d_o2_islet_tissue_cm2_s"), float):
            diffusivity_verified = float(base_iso_meta["d_o2_islet_tissue_cm2_s"])
        cache_key = (str(openislet_root.resolve()), str(label), float(p_bed), float(current_vasc_ocr))
        with _FVM_SOLVER_LOCK:
            _NATIVE_BASELINE_MMHG_CACHE[cache_key] = base_raw_mmhg
            if base_iso_meta:
                _NATIVE_BASELINE_META_CACHE[cache_key] = base_iso_meta
        _stress_res, stress_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
            openislet_root, spec, vasc_scale=(m_vasc_target / current_vasc_ocr)
        )
        delta_vasc_pct = ((m_vasc_target / current_vasc_ocr) - 1.0) * 100.0
        drop_mmhg = base_raw_mmhg - stress_raw_mmhg
        slope_mmhg_per_pct = drop_mmhg / delta_vasc_pct if delta_vasc_pct > 0 else 0.0
        extrap_breach_pct = ((base_raw_mmhg - 15.0) / slope_mmhg_per_pct) if (base_raw_mmhg > 15.0 and slope_mmhg_per_pct > 0) else 0.0
        entry: Dict[str, Any] = {
            "route_operator": operator_name,
            "p_bed_mmhg": p_bed,
            "baseline_shared_ocr": round(current_vasc_ocr, 4),
            "target_vascular_voxel_ocr": round(m_vasc_target, 4),
            "vascular_ocr_increment_pct_above_baseline_operator": round(delta_vasc_pct, 2),
            "baseline_3d_fvm_face_min_unrounded_mmhg": base_raw_mmhg,
            "vasc_1p3164_3d_fvm_face_min_unrounded_mmhg": stress_raw_mmhg,
            "baseline_3d_fvm_face_min_mmhg": round(base_raw_mmhg, 4),
            "vasc_1p3164_3d_fvm_face_min_mmhg": round(stress_raw_mmhg, 4),
            "delta_3d_fvm_mmhg": round(stress_raw_mmhg - base_raw_mmhg, 4),
            "local_3d_slope_mmhg_per_pct": round(slope_mmhg_per_pct, 6),
            "passes_15mmhg_at_baseline_unrounded": _passes_unrounded_15mmhg_floor(base_raw_mmhg, 15.0),
            "passes_15mmhg_at_vasc_1p3164_3d_fvm_unrounded": _passes_unrounded_15mmhg_floor(stress_raw_mmhg, 15.0),
            "two_point_linear_extrapolated_breach_pct_not_exact_3d_threshold": (
                round(extrap_breach_pct, 2) if _passes_unrounded_15mmhg_floor(base_raw_mmhg, 15.0) else 0.0
            ),
        }
        if label == "R1_390_stress":
            _s20_res, stress_plus20_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
                openislet_root, spec, vasc_scale=1.20
            )
            entry["matched_plus20pct_above_1p2067_vasc_ocr"] = round(current_vasc_ocr * 1.20, 5)
            entry["matched_plus20pct_3d_fvm_face_min_unrounded_mmhg"] = stress_plus20_raw_mmhg
            entry["matched_plus20pct_3d_fvm_face_min_mmhg"] = round(stress_plus20_raw_mmhg, 4)
            entry["passes_15mmhg_at_matched_plus20pct_3d_fvm_unrounded"] = _passes_unrounded_15mmhg_floor(stress_plus20_raw_mmhg, 15.0)
        replays[label] = entry

    if diffusivity_verified is None:
        raise RuntimeError("Isolated 3D FVM replay failed to verify D_O2_ISLET_TISSUE_CM2_S")

    return {
        "executed": True,
        "unrounded_native_floor_comparison_enforced": True,
        "diffusivity_cm2_s_verified": diffusivity_verified,
        "two_point_extrapolation_caveat": (
            "Reported `two_point_linear_extrapolated_breach_pct_not_exact_3d_threshold` values are "
            "two-point local-slope linear extrapolations from baseline and m_vasc=1.3164 solves, NOT exact "
            "nonlinear 3D FVM thresholds (direct nonlinear 3D solves at R2 +659.39% and R3P35 +327.38% "
            "remain above 15.0 mmHg at 15.11128 and 15.03710 mmHg respectively)."
        ),
        "note_r1_shared_ocr_operator": (
            "In live verify_iip0033_bilayer_and_resp1.py, both R1_350_stress ('PurePlus10OCR') and "
            "R1_390_stress ('CoupledPlus10OCR') invoke the same shared 1.2067x OCR multiplier for both "
            "islet and gel voxels; scaling only vascular voxels from 1.2067 to 1.3164 is +9.09% above "
            "1.2067x (+20.0% above 1.097x), whereas +20.0% above 1.2067x is m_vasc = 1.44804. On the "
            "native 80x80x78 grid for R1_390_stress at +9.09% (1.3164), face pO2 is 15.0741 mmHg, "
            "but predeclared 3-grid refinement (80x80x78 -> 96x96x94 -> 112x112x109: 15.0741 -> "
            "14.9753 -> 15.0638 mmHg; conservative ASME V&V-20 interval [14.9629, 15.0864] mmHg) "
            "straddles 15.0 mmHg and therefore routes to unresolved HOLD "
            "(HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR) rather than decisive PASS. At +20.0% "
            "(1.44804), all three grids (14.8489, 14.7492, 14.8373 mmHg; interval [14.7367, 14.8614]) "
            "remain strictly < 15.0 mmHg (decisive FAIL). R3P_35_VPIO120 at +20.0% (1.3164) clears "
            "15.0 mmHg across all three predeclared grids (15.1005, 15.1059, 15.3084 mmHg; lower bound "
            "15.0485 >= 15.0 mmHg -> decisive PASS)."
        ),
        "replays": replays,
    }


def run_nw08_calibration_and_layer4_margin_audit(
    openislet_root: Path,
    *,
    run_3d_fvm: bool = True,
) -> Dict[str, Any]:
    """
    NW-08 multi-lineage calibration & true 3D FVM vascular-voxel oxygen audit:
      - Reads exact live IIP-0033, Layer-4 Design Z, and IIP-0034 baselines
      - Executes true 3D FVM vascular-voxel (m_vasc = 1.3164) solves across all 8 geometries
        comparing strictly on native UNROUNDED float64 face minima >= 15.0 mmHg, plus matched
        +20% (1.44804) on R1 390 Coupled so linear vs 3D are compared on identical perturbations
      - Provides executable evaluate_nw08_measured_ocr_trigger(...) & unit tests
      - Labels all breach percentages honestly as two-point linear extrapolations (not exact 3D thresholds)
      - Explicitly source-types every calibration row and distinguishes Layer-4 1.000x basal (2.312 fmol/min/cell)
        from 1.097x stimulated (2.536 / ~2.54 fmol/min/cell).
    """
    vmax_islet_mol_cm3_s = 3.4e-8
    vol_1_ieq_cm3 = (4.0 / 3.0) * math.pi * ((75.0e-4) ** 3)
    alpha_bunsen_nominal = 1.34e-9
    d_o2_islet = 1.3e-5             # Exact live Layer-4 D_O2_ISLET_TISSUE_CM2_S (run_layer4:306)
    d_o2_gel_chronic = 1.50e-5
    diploid_dna_pg_per_cell = 6.67
    cells_per_ieq_standard_diploid = 10.4 / (diploid_dna_pg_per_cell * 1e-3)

    l4_pure_ieq_pmol_min = vmax_islet_mol_cm3_s * vol_1_ieq_cm3 * 60.0 * 1e12  # 3.604978
    l4_whole_1p00_pmol_min = l4_pure_ieq_pmol_min * 1.15                       # 4.145724
    l4_whole_1p097_pmol_min = l4_whole_1p00_pmol_min * 1.097                   # 4.547860
    l4_pure_1p00_fmol_min_cell = (l4_pure_ieq_pmol_min * 1000.0) / cells_per_ieq_standard_diploid        # 2.3120
    l4_pure_1p097_fmol_min_cell = (l4_pure_ieq_pmol_min * 1.097 * 1000.0) / cells_per_ieq_standard_diploid  # 2.5363

    papas_human_id_pmol_min_ieq = 110.0 * 10.4e-3  # 1.144 pmol/(min*IEQ)
    papas_human_ii_pmol_min_ieq = 115.0 * 10.4e-3  # 1.196 pmol/(min*IEQ)

    d33 = strict_json_load_file(openislet_root / "data/extracted/iip0033_bilayer_and_respirometry_verification_v0.8.0.json", preserve_boundary_decimals=False)
    d34 = strict_json_load_file(openislet_root / "data/extracted/iip0034_planar_and_portfolio_verification_v0.8.0.json", preserve_boundary_decimals=False)
    l4 = strict_json_load_file(openislet_root / "data/extracted/layer4_tissue_and_metabolic_twin_atlas.json", preserve_boundary_decimals=False)

    r1_rows = d33["fixed_pitch_bilayer_and_holds"]["pass_runs_multimesh"]

    def _find_iip33(lbl: str) -> float:
        for r in r1_rows:
            if r["label"] == lbl:
                return float(r["worst_face_mmhg"])
        raise ValueError(f"Missing live IIP-0033 baseline {lbl}")

    def _find_iip34(lbl: str) -> float:
        for r in d34["planar_3d_fvm_oxygen_envelopes"]:
            if r["label"] == lbl:
                return float(r["worst_face_mmhg"])
        raise ValueError(f"Missing live IIP-0034 baseline {lbl}")

    r1_390_nom_live = _find_iip33("PASS_R1_390_Staggered_Nominal1p097_p95_68_2xAdj_nx80")
    r2_dz_40_live = float(
        l4["part_a_336h_spatial_reaction_diffusion_pouch_pde"]
        ["lineage_partitioned_metabolic_rest_and_m101_exclusion_audit"]
        ["design_z_140um_parameterized_acute_chronic_and_pfc_matrix"]
        ["cases"]["Chronic_40mmHg_1p097xOCR_ChronicGel"]["fv_harmonic_face_min_mmhg"]
    )
    r3p_h180_35_live = _find_iip34("Hybrid333_H180_Day0_Clean_65um_PASS")
    r3p_h180_30_nom_live = _find_iip34("Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_PASS")
    r3p_h180_30_krbh_live = float(
        d34["planar_30mmhg_buffer_solubility_sensitivity"]["hybrid333_h180_bed30_clean_phys_buffer"]["worst_face_mmhg"]
    )
    r3p_h180_35_vpio120_live = _find_iip34("Hybrid333_H180_Day0_Avascular_VPIO120_Clean_PASS")
    r1_350_p10_live = _find_iip33("PASS_R1_350_Staggered_PurePlus10OCR_15umStandoff_max68_t7p95_66p95_1x68_nx80")