diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3312712..2efaa5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: - name: Syntax, Slurm & End-to-End Pytest Suite (Python ${{ matrix.python-version }}) + name: Syntax, Layer Lint, Slurm & End-to-End Pytest Suite (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest timeout-minutes: 20 env: @@ -37,7 +37,7 @@ jobs: cache-dependency-glob: "pyproject.toml" python-version: ${{ matrix.python-version }} - - name: Install CPU PyTorch, PorousDiff, and pure-Python OpenImpala v4.6 + - name: Install CPU PyTorch, PorousDiff, basecoat, and pure-Python OpenImpala v5.1 run: | uv venv --clear .venv uv pip install --python .venv/bin/python torch --index-url https://download.pytorch.org/whl/cpu @@ -45,14 +45,17 @@ jobs: SKBUILD_CMAKE_DEFINE="OPENIMPALA_PURE_PYTHON=ON" SKBUILD_WHEEL_PLATLIB="false" \ uv pip install --python .venv/bin/python "git+https://github.com/BASE-Laboratory/OpenImpala.git" - - name: Validate Python syntax across package, scripts, and tests - run: .venv/bin/python -m compileall -q porousdiff scripts tests + - name: Validate Python syntax across packages, scripts, and tests + run: .venv/bin/python -m compileall -q porousdiff porousdiff_workflows scripts tests + + - name: Check Layer 2 architectural import boundaries + run: .venv/bin/python -m basecoat.layers - name: Run Ruff static lint checks - run: .venv/bin/ruff check porousdiff scripts tests + run: .venv/bin/ruff check porousdiff porousdiff_workflows scripts tests - name: Validate Slurm batch script syntax run: bash -n slurm/*.slurm - - name: Run unit, OpenImpala PDE, conditioning convergence, and 5-stage end-to-end CLI pipeline tests + - name: Run unit, basecoat OME-Zarr, OpenImpala v5.1 PDE, and 5-stage end-to-end CLI pipeline tests run: .venv/bin/pytest -v diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1a9b41d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,23 @@ +# Agent & Contributor Guidelines (`PorousDiff`) + +Read [ECOSYSTEM.md](./ECOSYSTEM.md) before adding a module, dependency, file reader, or dataset constant. The master copy of `ECOSYSTEM.md` lives in `BASE-Laboratory/basecoat`. + +## Branch Governance + +- **`main`:** Preserved untouched as MSc student Asif Ali's original archive (`0546679`). **Never merge into or overwrite `main` without James Le Houx's explicit instruction.** +- **`feature/paper-ready-conditional`:** Active `v0.5+` mainline maintained by James Le Houx. Open feature pull requests against `--base feature/paper-ready-conditional`. + +## Ecosystem Layer + +- **Repository:** `BASE-Laboratory/PorousDiff` +- **Core package (`porousdiff/`):** **Layer 2 — Image & generative tools** (`BSD-3-Clause`). + - **Allowed ecosystem dependencies:** `basecoat` (Layer 1) **only**. + - **Banned imports inside `porousdiff/` (enforced by `python -m basecoat.layers` via `[tool.basecoat.layers]`):** `multimodal_benchmark`, `xct_research`, `openimpala`, `sms`, `openlsrx`, `x_fuse`, `braggtrack`, `porousdiff_workflows`, `zarr`, `numcodecs`. +- **Coupled workflow package (`porousdiff_workflows/` & `scripts/evaluation/`):** **Layer 4 — Coupled benchmark & beamline workflow** inside this repository, orchestrating `porousdiff` (Layer 2) + `basecoat` (Layer 1) + `OpenImpala v5.1` (Layer 3) + DLS K11 DIAD XRD clamping-pressure (`sigma*`) optimisation. + +## Ownership Boundaries + +- **`porousdiff/` owns:** Conditional 3D DDPM/DDIM models with FiLM continuous load/stress conditioning (`porousdiff/models.py`, `porousdiff/losses.py`), Lagrangian slab DDIM virtual compression (`porousdiff/virtual_compression.py`), morphological baselines (`porousdiff/baselines.py`), and 3D Cauchy–Crofton / chord / Euler / geodesic morphology (`porousdiff/metrics.py`). +- **Delegates to `basecoat` (`v0.2`):** Calibrated `Volume` / `VolumeSet` / `AxisSpec` (`unit="um"`), OME-Zarr v0.4 phase-labelled export and reading (`porousdiff.io.export_volume_ome_zarr`, `porousdiff.io.load_volume_array`), and TIFF reading/writing (`basecoat.read_tiff`, `basecoat.write_tiff`). +- **`porousdiff_workflows/` owns:** Coupled `OpenImpala v5.1` continuum PDE transport (`VolumeProtocol` with calibrated SI `spacing_in("m")`), K11 DIAD XRD correlation (`porousdiff_workflows/transport_and_xrd.py`), and series-resistance / Newman ASR clamping optimisation (`porousdiff_workflows/optimization.py`). +- **Deprecated for `v0.6` removal (retained in `v0.5.x` for manuscript reproducibility):** `export_openimpala_tiff` (superseded by `porousdiff.io.export_volume_ome_zarr` consumed natively by `OpenImpala v5.1` and `SMS`) and campaign material tables in `porousdiff/data.py` (`MATERIAL_TO_ID`). diff --git a/ECOSYSTEM.md b/ECOSYSTEM.md new file mode 100644 index 0000000..115f25b --- /dev/null +++ b/ECOSYSTEM.md @@ -0,0 +1,205 @@ +# BASE Lab image-based modelling ecosystem + +Nov 20, 2026 · @James + +## Purpose + +This document sets where every piece of BASE Lab software lives, what it may depend on, and how the pieces exchange data. It is written for coding agents and group members working in any BASE Lab repository. Read it before adding a module, a dependency, a loader, or a dataset constant anywhere. + +Status: draft v0.3, written 20 November 2026 from an audit of `MultimodalBenchmark` (`feat/benchmark-v2`), `OpenImpala` (`v5.0.0`), `OpenLSR-X`, `X-FUSE`, `BraggTrack`, `PorousDiff`, and `structural_mechanics_solver` (`feat/modernize-tests-python`). New repositories need James's approval. + +How agents should use it: + +- Treat sections marked as rules as binding. If a task would break one, stop and ask rather than working around it. +- Use the decision procedure ("Where does this code go?") to place new code. If two placements look equally valid, ask. +- Items under **Open decisions** are not settled. Do not implement against them without confirmation. +- **Single source of truth:** The canonical copy of this file lives in `BASE-Laboratory/basecoat/ECOSYSTEM.md`. Do not copy the full text into other repositories (copies drift). Each downstream repository carries a short pointer and layer declaration in its `CLAUDE.md` / `AGENTS.md`. + +--- + +## Layers and the dependency rule + +The ecosystem has four layers, and imports only ever point down. A tool never imports another tool, a solver never imports a tool or another solver, and nothing imports a workflow. + +```mermaid +flowchart TD + L4["Layer 4: Workflows, Benchmarks & Beamline Loops
(MultimodalBenchmark, XCT-Research, PyBaMM / TESA couplings)"] + L2["Layer 2: Perception & Image Tools
(OpenLSR-X, X-FUSE, BraggTrack, PorousDiff)"] + L3["Layer 3: Physics Solvers
(OpenImpala, structural_mechanics_solver)"] + L1["Layer 1: Core Plumbing
(basecoat)"] + + L4 --> L2 + L4 --> L3 + L4 --> L1 + L2 --> L1 + L3 -.->|"VolumeProtocol (planned) or optional extra"| L1 +``` + +Workflows may import anything below them. Tools and solvers depend only on `basecoat` (or duck-type its `VolumeProtocol` without importing `basecoat`), and pass volumes to each other as contract files or in-memory `Volume` objects orchestrated by Layer 4. + +1. **Layer 1 — Core (`basecoat`):** Shared plumbing that passes the two-consumer admission rule. In `v0.1`: `Volume`, `VolumeSet`, `AxisSpec`, `LazyVolume`, `VolumeProtocol`, OME-Zarr v0.4 (image + labels), HDF5 / TIFF / raw I/O, `AffineTransform3D` + `SimilarityTransform3D` + resampling, and SHA-256 fetching. Facility readers, uncertainty sidecars, filters, HDF5 solver staging, and the config-driven layer linter enter `basecoat` only as their second consumer migrates. +2. **Layer 2 — Perception and image tools:** Methods that turn detector or image volumes into reconstructed volumes, phase segmentations/uncertainties, or tracked feature graphs. `OpenLSR-X`, `X-FUSE`, `BraggTrack`, `PorousDiff`. +3. **Layer 3 — Physics solvers:** Methods that turn a labelled or fractional volume into fields and effective properties. `OpenImpala` (transport), `structural_mechanics_solver` / `SMS` (mechanics). +4. **Layer 4 — Workflows, benchmarks, and services:** Code tied to a dataset, an experiment, a coupled pipeline, or user-facing cataloguing/visualisation. `MultimodalBenchmark`, `XCT-Research` (DIAD trigger), `DFXM-Topographic-Origins`, `datalab-app-xrayct`, `OperandoCellLibrary`, `BatteryExplorer`, and external `PyBaMM` / `TESA` couplings. + +### Dependency rules (binding) + +- **Layer 2** packages may depend on `basecoat`, and on nothing else in the BASE Lab ecosystem. +- **Layer 3** solvers keep standalone installability where needed (`pip install openimpala` requires zero BASE Lab packages). Planned integration (`OpenImpala v5.1`, `SMS` modernisation branch) accepts any object satisfying `VolumeProtocol` at the Python boundary without requiring `basecoat` at runtime (with an optional `openimpala[basecoat]` extra for `.ome.zarr` path convenience). Solvers never import Layer 2 tools or other Layer 3 solvers. +- **Layer 4** workflows may depend on anything in Layers 1–3. +- **No lateral imports:** Tools and solvers exchange data through files that follow the data contract or through `Volume` objects passed by a Layer 4 caller, never by importing each other. A helper such as `export_for_openimpala` inside another tool is a sign this rule was broken. +- **Nothing depends on Layer 4:** No Layer 1, 2, or 3 package may import or list `multimodal-benchmark`, `xct-research`, or any other Layer 4 repo as a dependency. +- **`basecoat` stays light:** Required dependencies of `basecoat` are strictly `numpy`, `scipy`, `h5py`, `tifffile`, `zarr` (`>=2.16,<3`), and `numcodecs`. `torch`, `scikit-image`, `dask`, `ome-zarr`, `Pillow`, `mpi4py`, `AMReX`, `SimpleITK`, and `rosettasciio` are never required by `basecoat`; `SimpleITK` and `rosettasciio` may appear only behind optional extras. + +--- + +## Repo registry + +Each repo owns one job. The "Must not contain" column lists what agents should migrate out when touching a repo, never add to. New repositories need James's approval. + +| Repo | Layer | Owns | Must not contain | Maintainer | Status | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **`basecoat`** | 1 Core | `v0.1`: `Volume`, `VolumeSet`, `AxisSpec`, `LazyVolume`, `VolumeProtocol`; OME-Zarr v0.4 (image + labels), HDF5, TIFF, raw I/O; `AffineTransform3D`, `SimilarityTransform3D` & resampling; SHA-256 fetch/cache. *Planned on 2nd consumer:* facility readers, sidecars, artefact filters, HDF5 staging, layer linter | Dataset constants, scan IDs, method/model code, heavy required dependencies, downstream repo names | James | Building `v0.1.0` | +| **`OpenImpala`** | 3 Solver | AMReX/HYPRE transport solves; effective diffusivity, tortuosity, SSA, volume fraction, percolation; solver-native C++ readers in `src/io`; Python facade; PyBaMM & BPX helpers. *Planned (`v5.1` branch):* `VolumeProtocol` & optional `.ome.zarr` input | Dataset loaders, ML code, `basecoat` runtime import in core `openimpala` | James | `v5.0.0` released Nov 2026, JOSS paper. Public API changes need James | +| **`structural_mechanics_solver` (`SMS`)** | 3 Solver | Voxel finite-volume linear elasticity (Fortran, MPI); effective modulus; strain/displacement fields; Python bindings. *Planned:* `VolumeProtocol` / contract `.ome.zarr` reader at Python boundary | XCT preprocessing, TESA-specific code, dataset constants | Peter Soar (to confirm) | Modernising on `feat/modernize-tests-python` | +| **`OpenLSR-X`** | 2 Tool | Super-resolution models, training, inference, SR-specific losses and metrics | Zn-13X constants (`data/zn13x.py`, `zn13x_certified_regions.yaml`), generic readers, registration, `export_for_openimpala` | James | Strong beta, *npj* manuscript in prep | +| **`X-FUSE`** | 2 Tool | Correlative fusion models, conformal uncertainty, fusion heads | Zn-13X & DIAD loaders, the $47.5^\circ$ offset, de-ringing/cupping code, generic readers, `export_for_openimpala` | James | `v1.0` candidate (licence to be settled before lifting any code) | +| **`BraggTrack`** | 2 Tool | Bragg spot segmentation, multi-frame tracking, lineage, DFXM triggers, `ImageD11` / `NXprocess` export | Dataset constants, generic readers once `basecoat` facility readers land | James | `v0.5`, JOSS submission | +| **`PorousDiff`** | 2 Tool (+ Layer 4 `porousdiff_workflows`) | Conditional 3D diffusion & Lagrangian slab DDIM virtual compression (`porousdiff`); coupled `OpenImpala` + K11 DIAD XRD clamping optimisation lives in `porousdiff_workflows` | `openimpala` imports inside `porousdiff/`, raw uncalibrated TIFF solver hand-offs | James (`feature/paper-ready-conditional`); `main` preserved for Asif (MSc archive) | Active `v0.5` on `feature/paper-ready-conditional` (PR #1) | +| **`MultimodalBenchmark`** | 4 Workflow | Zn-13X manifest & errata, fitted transforms, ruby metrology, splits, task specs, evaluator, tool adapters, derived release packaging, the benchmark paper | Model implementations; generic I/O & transforms once switched to `basecoat` | James | `v2` on `feat/benchmark-v2` (first `basecoat` consumer) | +| **`XCT-Research`** | 4 Workflow | DIAD image-subtraction trigger and replay harness | Reusable tools (graduate to Layer 2 once proven and approved) | Mizanur | Scaffold | +| **`DFXM-Topographic-Origins`** | 4 Workflow | Paper notebooks & FEA scripts for NMC811 single-crystal DFXM study | Reusable tracking code (lives in `BraggTrack`) | James | Published preprint archive | +| **`datalab-app-xrayct`**, **`OperandoCellLibrary`**, **`BatteryExplorer`** | 4 Service | FAIR NeXus cataloguing; sample-environment registry; 4D operando dashboard | — | James | Maintained as needed | +| **`TESA`** | External | Peter and Matt's coupled models | — | Peter, Matt | Consumes and produces data through the contract | + +--- + +## The data contract + +The contract is deliberately light. It has four invariants that **always** hold, and a table of defaults you can depart from when the work needs it. Where you depart, say so in the code, metadata, or README. + +### Always + +1. **Say what you've got.** A `Volume` holds **one** array plus its `AxisSpec` tuple (`name`, `kind`, `unit`, `scale`, `offset`), stating its physical unit (`"um"`, `"m"`, etc.) or explicitly stating `"voxel"` when uncalibrated. Labelled volumes carry an integer-to-meaning map. Co-registered layers (an image plus named label masks, and later uncertainty/probability arrays) travel in a `VolumeSet`, not as extra array attributes stuffed onto `Volume`. +2. **Convert in one named place.** Changes between voxel and physical units, between axis orders, or between label schemes happen in an explicit function or method (`vol.spacing_in("m")`, `tx.to_sitk()`), never by guessing or by nominal magnification ratios. Calling `spacing_in("m")` on an uncalibrated `"voxel"` volume raises an error explaining how to supply spacing. +3. **Transforms say which way they go.** Every stored or in-memory transform records `from_space`, `to_space`, `unit` (`"um"` or `"voxel"`), and `axis_order`. +4. **Don't load what you don't need.** Readers support region reads (`open_volume` $\rightarrow$ `LazyVolume.read_region`). `LazyVolume` never silently materialises a full multi-GB dataset into RAM. + +### Defaults + +| Topic | Default | Fine to depart when | +| :--- | :--- | :--- | +| **Units** | `"voxel"` within one uncalibrated grid; **`"um"` (micrometres)** when two grids meet (registration, resampling between resolutions, cross-beamline comparison) or in shared `.ome.zarr` files | A tool or solver's natural unit differs (`OpenImpala`'s solver takes metres; `BraggTrack` uses `deg` and `angstrom`). Convert at its boundary | +| **Grid coordinate convention** | **Cell-centre at index `0`:** `AxisSpec.offset` is the physical coordinate of the **centre** of voxel `0`, so voxel `i` has its centre at `offset + i * scale` (matching SimpleITK `Origin` and `napari` `translate`). Coarsening by factor `k` shifts the coarse level's index-`0` centre to `offset + 0.5 * (k - 1) * scale` | A staggered finite-volume solver needs face or node coordinates; record `centering="face_x" \| "node"` | +| **Axis order** | `(z, y, x)` for 3D NumPy and OME-Zarr; `(y, x)` for 2D slices | A Fortran or C++ solver works in `(x, y, z)`. It documents how direction names map to axes and uses zero-copy views (`arr.T`) rather than copying large arrays | +| **Bit depth** | Highest available for quantitative work (`float32` reconstructions, `uint16`/`uint32` raw counts). Never compare volumes windowed or rescaled independently | Previews, figures, quick registration checks (mark as preview) | +| **Labels and masks** | Integer labels with a documented meaning; downsampled label pyramid levels use the **mode** (most common label, smallest ID on ties), never the mean | Fractional masks (e.g. `SMS` solid fraction), when documented | +| **Transforms** | Pullback affine/similarity convention (**maps fixed / output points $\rightarrow$ moving / input points**), matching `SimpleITK.ResampleImageFilter` and `scipy.ndimage.affine_transform` | Forward point kinematics (`t -> t+1` trajectories); store `from_space` and `to_space` explicitly | +| **Files** | OME-Zarr v0.4 for archive and sharing; chunked HDF5 for multi-node MPI solver input (`OpenImpala`'s C++ readers); TIFF for small standalone volumes | A consumer or online loop needs another format or in-memory `Volume` handoff | +| **Chunking & compression** | Typically `64`–`256` voxels per side (e.g. `128³`) with lossless `Blosc` (`zstd`, bitshuffle), chosen to suit the access pattern | Slice-wise access, uncompressed fast scratch, or MPI domain decomposition needs otherwise | +| **Field outputs** | State where values sit (`cell` centres, `face`, or `node`). Exchange cell-centred fields by default | A consumer needs native staggered fields (`SMS` displacements) | +| **Provenance** | Record source, `basecoat` version, git SHA, data precision, and processing steps on outputs that feed reported results | Scratch work, exploration | + +--- + +## Where does this code go? + +Work through these questions in order and **stop at the first yes**: + +1. **Does it mention a specific sample, scan ID, DOI, beamline visit, or fitted value?** + It goes in the Layer 4 workflow repo for that dataset or experiment (`Zn-13X` $\rightarrow$ `MultimodalBenchmark`; the DIAD loop $\rightarrow$ `XCT-Research`). This includes fitted transforms, scan tables, motor offsets such as the $47.5^\circ$ correction, and frozen preprocessing parameters. +2. **Does it couple two or more tools or solvers, or run an experiment end to end?** + Layer 4: a workflow repo. +3. **Is it a physics solve on a labelled or fractional volume?** + The solver for that physics. Transport goes in `OpenImpala`, elasticity in `SMS`. A new physics with no home goes on the **Open decisions** list, not into a new repo. +4. **Is it the method a tool exists for (a model, a loss, a fusion head, a tracker)?** + That tool. +5. **Is it plumbing (reading, writing, resampling, fetching, generic filtering)?** + Check the **`basecoat` admission rule** below. If it passes, it goes in `basecoat`. If not, it stays private inside the one repo that needs it, with a leading underscore (`_helper.py`), until a second consumer needs it. + +### `basecoat` admission rule (the two-consumer rule) + +Code enters `basecoat` **only if all five hold**: +- **Two consumers:** At least two tools, solvers, or workflows need it now (one consumer keeps it private with an underscore prefix until the second consumer migrates). +- **Zero dataset constants:** No scan IDs, Zenodo record numbers, or sample-specific thresholds. +- **Not a tool's method:** No learned models, training loops, or solver-specific PDE kernels. +- **Light dependencies:** Required dependencies stay within `numpy`, `scipy`, `h5py`, `tifffile`, `zarr` (`<3`), and `numcodecs`. Anything heavier sits behind an optional extra. +- **Clear licence & credit:** Source code being lifted has a compatible BSD-3-Clause licence (do **not** lift code from `X-FUSE` until its licence is settled) and credits original authors in `CITATION.cff` and module docstrings. + +`basecoat` keeps an explicit `__all__` guarded by a contract test and follows semantic versioning. Public API changes need James's approval. + +--- + +## Hard rules for agents + +These rules come from failures found in the November 2026 audit. Breaking one needs James's explicit approval in the task. + +### Structure +- **Follow the two-consumer rule rather than copying across repos.** Do not copy a module from one repo into another. If a second repo now needs an existing private helper (and its licence is settled), extract it cleanly into `basecoat` with tests and author credit; otherwise ask first. +- **Do not put dataset constants in a tool or solver.** When you find one, list it for migration rather than editing around it. +- **Do not import one tool or solver from another, and do not add a dependency on any Layer 4 repo.** When the layer linter lands, each repo declares its own layer and banned imports in `[tool.basecoat.layers]` inside its `pyproject.toml` (`basecoat` never hardcodes downstream package names). +- **Do not change `OpenImpala`'s public Python API or C++ interfaces without James.** + +### Honesty of outputs +- **Every command, CLI subcommand, or function named in a script, config, README, or paper must exist.** Run it, or at least `--help`, before committing. +- **Every reference in a `.bib` file needs a DOI or arXiv ID that you have opened.** No `"and others"` author lists in place of real authors. +- **Results files state what data they were computed on** (`8-bit preview`, `32-bit float`, `synthetic`). Placeholders are marked as `"pending"`, never filled with plausible numbers. +- **Physics, geometry, and filter code needs analytical or reference tests** (a known closed-form solution, a symmetry, cell-centre invariance, or MPI-rank invariance following `SMS` and `OpenImpala`). Filter tests assert edge sharpness and chemistry retention *first* with conservative artefact suppression as a floor—never aggressive variance-drop targets that strip real signal. +- **Report honestly at the end of every session:** state what was run, what passed, and what was not tested. Never write example outputs or benchmark numbers that were not produced by an actual run. James checks all validation outputs before they are reported. + +### Versions and releases +- Pin direct ecosystem dependencies with an upper bound (`basecoat>=0.1,<0.2`, `openimpala>=5.0,<6.0`). +- Each repo names one maintainer in its `README.md`. +- Commit messages describe what changed in plain words. One logical change per commit. + +--- + +## Known duplication and staged migration + +The audit found the same job done in up to four places, with copies already disagreeing (`OpenLSR-X`'s Zn-13X file gives Rung 1's ratio as `1.6023×` vs `MultimodalBenchmark`'s `1.6039×`). Migration happens **one repository per PR**, only after `basecoat v0.1` is built and tested standalone. + +| Capability | Where it is now | Target home & timing | +| :--- | :--- | :--- | +| **Generic volume I/O & OME-Zarr (image + labels)** | `OpenImpala` `_io.py`, `OpenLSR-X` `load_volume_any`, `X-FUSE` `io.py`, `MultimodalBenchmark` `io.py` & `write_ome_zarr_v04` | **`basecoat v0.1`** (`OpenImpala` keeps its C++ readers & standalone pure-Python fallback) | +| **3D similarity/affine transforms & resampling** | `MultimodalBenchmark` `registration/i13_ladder.py`, `OpenLSR-X` `data/zn13x.py`, `X-FUSE` `registration.py` | **`basecoat v0.1`** (verified empirically against `MultimodalBenchmark`'s `SimpleITK` resampler) | +| **Download, cache & SHA-256 checksum** | `OpenImpala` `datasets.py`, `OpenLSR-X` (two copies), `X-FUSE` `datasets.py` | **`basecoat v0.1`** | +| **Hand-off to `OpenImpala`** | `export_for_openimpala` in `OpenLSR-X` and `X-FUSE` | **Deleted as each tool migrates.** `OpenImpala v5.1` branch adds `VolumeProtocol` / optional `.ome.zarr` support | +| **Savu, NeXus, DAWN, BLISS & Rigaku readers** | `MultimodalBenchmark` `io.py`, `X-FUSE` `loaders.py`, `OpenLSR-X` `extract_aligned_slab_from_h5`, `BraggTrack` `io/` | **`basecoat` (`v0.2+`)**, added as the second consumer migrates (after `X-FUSE` licence is settled if any `X-FUSE` code is referenced) | +| **Ring removal & cupping detrend** | `MultimodalBenchmark` `preprocessing/artifact_cleanup.py`, `X-FUSE` `loaders.py` | **Algorithm in `basecoat` (`v0.2+`)** when second consumer migrates; frozen parameters stay in `MultimodalBenchmark` | +| **Probability, uncertainty & conformal sidecars** | `OpenLSR-X` (`sigma_ortho`), `X-FUSE` (`VolumetricUncertaintyReport`) | **`basecoat.VolumeSet` extension (`v0.2+`)** when `OpenLSR-X` and `X-FUSE` migrate | +| **Zn-13X scan tables, DOIs, fitted transforms, $47.5^\circ$ offset** | `MultimodalBenchmark`, `OpenLSR-X` `data/zn13x.py` & `zn13x_certified_regions.yaml`, `X-FUSE` `datasets.py` & `loaders.py` | **`MultimodalBenchmark` only** | +| **Benchmark adapters for `OpenLSR-X` & `X-FUSE`** | `MultimodalBenchmark` `baselines/integrations/` | **Rewritten in `MultimodalBenchmark`** against each tool's real CLI/API | + +### Migration sequence + +1. **Session 1 (`basecoat v0.1.0` standalone):** Build and test `basecoat` on its own. Do **not** touch `OpenImpala`, `OpenLSR-X`, `X-FUSE`, `MultimodalBenchmark`, or `SMS` in the same session. +2. **First consumer (`MultimodalBenchmark` branch):** Switch `MultimodalBenchmark`'s volume I/O, OME-Zarr writer, and 7-DOF resampling onto `basecoat`. **Gate:** Stage 0 and T2/T4 numbers in its results JSON files must reproduce within stated numerical tolerance. +3. **Solver boundary PRs (separate branches, one repo at a time):** + - `OpenImpala` (`v5.1` feature branch, requires James's sign-off): accept `VolumeProtocol` with `OpenImpala`'s own unit-error exception (no `basecoat` runtime import). + - `SMS` (`feat/modernize-tests-python` follow-up): accept contract OME-Zarr / `VolumeProtocol` at its Python boundary so `MultimodalBenchmark` can score stiffness alongside tortuosity. +4. **Layer 2 tool cleanups (one repo per PR, existing test suites staying green):** Switch `OpenLSR-X`, `X-FUSE`, `PorousDiff` (`feature/paper-ready-conditional`, preserving `main` for Asif), and `BraggTrack` (`fix/v0.5.1-events-bugs-and-joss`) onto `basecoat` (`v0.2`), deprecating bespoke `OpenImpala` deck/TIFF hand-offs in favour of calibrated `.ome.zarr` / `VolumeProtocol` and isolating coupled `PorousDiff` + `OpenImpala` clamping workflows into `porousdiff_workflows/`. + +--- + +## Physics solvers + +Transport and mechanics stay in separate solvers for now and couple through contract files. In-memory coupling is a Horizon 3 decision. + +- **`OpenImpala`** owns transport physics: diffusion, tortuosity, effective conductivity, and later impedance. Its scope grows only by James's decision. +- **`SMS`** owns linear elasticity. It is the validated reference implementation for mechanics, with analytical and MPI-invariance tests. Its link to `TESA` is through the data contract. +- **Coupling now** is one-way and file-based. Both solvers take the same labelled OME-Zarr volume (once their `VolumeProtocol` / `.ome.zarr` boundary branches land) and write fields on the same grid. The first joint use is in `MultimodalBenchmark`, scoring whether image processing steps alter stiffness as well as tortuosity. +- **In-memory chemo-mechanics later (Horizon 3):** Diffusion-induced swelling stress on one grid would require an elasticity operator built on AMReX inside `OpenImpala`, using `SMS` as its test oracle. Agents must not start this before James and Peter settle it. +- **Benchmark before porting:** Compare `SMS`'s finite-volume solver, an AMReX multigrid operator, and FFT-based homogenisation (Moulinec–Suquet / rotated-stencil type, e.g. `AMITEX_FFTP`) on identical porous volumes—including zero-stiffness void phase ($E_{\text{pore}} = 0$)—for speed and agreement. + +--- + +## Open decisions + +Agents do not implement against these until they are settled here. + +- [x] **Licence of `X-FUSE` *(Settled 20 Nov 2026)*:** `X-FUSE` remains under `MIT` (preserving third-party MIT attributions); `X-FUSE` consumes `basecoat` (`BSD-3-Clause`), and zero code from `X-FUSE` is lifted into `basecoat`. +- [ ] **Long-term maintenance of `basecoat`:** James initially; decide whether an RSE post is costed into the next major grant to own it. +- [ ] **Maintainer of `SMS`:** Peter, James, or shared. +- [x] **`SMS` Python boundary conventions *(Settled 20 Nov 2026)*:** Zero runtime `basecoat` dependency; accepts `VolumeProtocol` / `VolumeSet` and OME-Zarr v0.4 (`(z, y, x)` transposed zero-copy to Fortran `(x, y, z)`), converts `spacing_in("m")` to isotropic SI `dx` in metres (`UnitCalibrationError` if uncalibrated), and returns cell-centred `(nx, ny, nz)` fields in `SolveResult`. +- [ ] **Horizon 3 elasticity path:** Whether elasticity enters `OpenImpala` on AMReX after the `SMS` vs AMReX vs FFT solver comparison. +- [ ] **`TESA` exchange format:** Whether `TESA`'s fields sit on regular Cartesian grids that fit the OME-Zarr contract directly. diff --git a/porousdiff/__init__.py b/porousdiff/__init__.py index 2c70d4b..db27d51 100644 --- a/porousdiff/__init__.py +++ b/porousdiff/__init__.py @@ -1,3 +1,12 @@ """PorousDiff: Multi-electrode, multi-phase conditional 3D diffusion for compressed porous electrodes.""" -__version__ = "0.5.1" +from porousdiff.io import export_volume_ome_zarr, load_volume_array, to_basecoat_volume + +__version__ = "0.5.2" + +__all__ = [ + "__version__", + "export_volume_ome_zarr", + "load_volume_array", + "to_basecoat_volume", +] diff --git a/porousdiff/io.py b/porousdiff/io.py new file mode 100644 index 0000000..48d557b --- /dev/null +++ b/porousdiff/io.py @@ -0,0 +1,162 @@ +"""Layer 2 volume I/O bridges delegating calibrated OME-Zarr v0.4 and TIFF storage to `basecoat`.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Mapping, Sequence + +import basecoat +from basecoat import UnitConversionError, Volume, VolumeSet +import numpy as np + +DEFAULT_BINARY_LABELS: dict[int, str] = { + 0: "pore", + 1: "solid", +} + +DEFAULT_MULTIPHASE_LABELS: dict[int, str] = { + 0: "pore", + 1: "carbon", + 2: "coating", +} + + +def to_basecoat_volume( + volume: np.ndarray | Volume, + *, + voxel_size_um: float | Sequence[float] = 1.0, + preserve_multiphase: bool = False, + pore_label: int = 0, + solid_label: int = 1, + label_map: Mapping[int, str] | None = None, + metadata: Mapping[str, Any] | None = None, +) -> Volume: + """Wrap a 3D `(Z, Y, X)` microstructure array into a calibrated `basecoat.Volume` (`unit='um'`). + + Satisfies `OpenImpala v5.1+` and `SMS` `VolumeProtocol` (`spacing_in('m')`), eliminating + uncalibrated raw-array unit mismatches at solver boundaries. + """ + arr = np.asarray(volume.data) if isinstance(volume, Volume) else np.asarray(volume) + if arr.ndim != 3: + raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {arr.shape}") + + if preserve_multiphase: + mapped = np.clip(arr, 0, 255).astype(np.uint8) + resolved_labels = dict(label_map) if label_map is not None else dict(DEFAULT_MULTIPHASE_LABELS) + else: + mapped = np.where(arr > 0, solid_label, pore_label).astype(np.uint8) + resolved_labels = ( + dict(label_map) + if label_map is not None + else {int(pore_label): "pore", int(solid_label): "solid"} + ) + + if isinstance(voxel_size_um, (int, float, np.floating, np.integer)): + vox = float(voxel_size_um) + if vox <= 0.0 or not np.isfinite(vox): + raise ValueError(f"voxel_size_um must be positive and finite, got {voxel_size_um!r}") + spacing: float | Sequence[float] = vox + else: + vals = tuple(float(v) for v in voxel_size_um) + if len(vals) != 3 or any(v <= 0.0 or not np.isfinite(v) for v in vals): + raise ValueError( + f"voxel_size_um sequence must have 3 positive finite values (dz, dy, dx), got {voxel_size_um!r}" + ) + spacing = vals + + prov = {"producer": "porousdiff", **(dict(metadata) if metadata else {})} + return Volume.from_array( + mapped, + voxel_size_um=spacing, + label_names=resolved_labels, + provenance=prov, + ) + + +def export_volume_ome_zarr( + volume: np.ndarray | Volume, + store_path: str | Path, + *, + voxel_size_um: float | Sequence[float] = 1.0, + preserve_multiphase: bool = False, + pore_label: int = 0, + solid_label: int = 1, + label_map: Mapping[int, str] | None = None, + multiscale_levels: int = 2, + chunks: tuple[int, int, int] = (64, 64, 64), + metadata: Mapping[str, Any] | None = None, + overwrite: bool = True, +) -> Path: + """Export a calibrated OME-Zarr v0.4 store (`unit='um'`, mode-downsampled `labels/phase`). + + Replaces bespoke `export_openimpala_tiff` hand-offs: both `OpenImpala v5.1+` and `SMS` + consume the resulting `.ome.zarr` store directly with calibrated SI spacing. + """ + phase_vol = to_basecoat_volume( + volume, + voxel_size_um=voxel_size_um, + preserve_multiphase=preserve_multiphase, + pore_label=pore_label, + solid_label=solid_label, + label_map=label_map, + metadata=metadata, + ) + image_vol = Volume( + data=phase_vol.data.astype(np.float32), + axes=phase_vol.axes, + provenance=phase_vol.provenance, + ) + vset = VolumeSet(image=image_vol, labels={"phase": phase_vol}) + out = Path(store_path) + out.parent.mkdir(parents=True, exist_ok=True) + return basecoat.write_ome_zarr( + vset, + out, + multiscale_levels=int(multiscale_levels), + chunks=chunks, + overwrite=overwrite, + ) + + +def load_volume_array( + path: str | Path, + *, + label_key: str = "phase", +) -> tuple[np.ndarray, float | None]: + """Load a 3D `(Z, Y, X)` `uint8` microstructure volume and optional calibrated `voxel_size_um`. + + Supports `.ome.zarr` / `.zarr` (selecting `labels[label_key]` when present), `.tif` / `.tiff`, + `.h5` / `.hdf5` / `.nxs` via `basecoat`, and `.npy`. + """ + p = Path(path) + name_low = p.name.lower() + + if name_low.endswith(".npy"): + arr = np.load(p, allow_pickle=False) + if arr.ndim == 4: + arr = arr[0] + if arr.ndim != 3: + raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {arr.shape}") + return np.asarray(arr, dtype=np.uint8), None + + if name_low.endswith((".ome.zarr", ".zarr")): + vset = basecoat.read_ome_zarr(p, level=0, as_set=True) + vol = vset.labels[label_key] if label_key in vset.labels else vset.image + else: + loaded_any = basecoat.read_volume(p) + vol = loaded_any.image if isinstance(loaded_any, VolumeSet) else loaded_any + + arr = np.asarray(vol.data) + if arr.ndim == 4: + arr = arr[0] + if arr.ndim != 3: + raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {arr.shape}") + + vox_um: float | None = None + try: + sp_um = vol.spacing_in("um") + vox_um = float(np.mean(sp_um)) + except UnitConversionError: + vox_um = None + + return np.asarray(arr, dtype=np.uint8), vox_um diff --git a/porousdiff/metrics.py b/porousdiff/metrics.py index 0c0a3bf..c0ca400 100644 --- a/porousdiff/metrics.py +++ b/porousdiff/metrics.py @@ -7,7 +7,6 @@ from typing import Mapping, Sequence import numpy as np -import tifffile from scipy.ndimage import distance_transform_edt, label from scipy.sparse import coo_matrix from scipy.sparse.csgraph import dijkstra @@ -565,7 +564,14 @@ def export_openimpala_tiff( solid_label: int = 1, preserve_multiphase: bool = False, ) -> Path: - """Export a 3D multi-page `uint8` TIFF stack formatted for OpenImpala transport solvers.""" + """Export a 3D multi-page `uint8` TIFF stack formatted for OpenImpala transport solvers. + + .. deprecated:: 0.5.2 + Prefer :func:`porousdiff.io.export_volume_ome_zarr`, which writes calibrated OME-Zarr v0.4 + stores (`unit='um'`, `labels/phase`) consumed directly by `OpenImpala v5.1+` and `SMS`. + """ + import basecoat + vol = np.asarray(volume) if vol.ndim != 3: raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {vol.shape}") @@ -575,5 +581,5 @@ def export_openimpala_tiff( mapped = np.where(vol > 0, solid_label, pore_label).astype(np.uint8) output_path = Path(output_path) output_path.parent.mkdir(parents=True, exist_ok=True) - tifffile.imwrite(output_path, mapped) + basecoat.write_volume( basecoat.Volume.from_array(mapped), output_path ) return output_path diff --git a/porousdiff_workflows/__init__.py b/porousdiff_workflows/__init__.py new file mode 100644 index 0000000..eb6855d --- /dev/null +++ b/porousdiff_workflows/__init__.py @@ -0,0 +1,35 @@ +"""Layer 4 coupled evaluation workflows: PorousDiff + basecoat + OpenImpala v5.1 + K11 DIAD XRD.""" + +from porousdiff_workflows.optimization import ( + NEWMAN_REGIMES, + compute_transport_and_fom_record, + evaluate_newman_asr_curve, + load_openimpala_lookup, + load_openimpala_records, +) +from porousdiff_workflows.transport_and_xrd import ( + compute_openimpala_volume_transport, + correlate_xrd_with_microstructure, + generate_openimpala_job_suite, + has_openimpala_python, + parse_openimpala_results, + run_openimpala_python_suite, + run_openimpala_rev_convergence, + write_openimpala_ini, +) + +__all__ = [ + "NEWMAN_REGIMES", + "compute_openimpala_volume_transport", + "compute_transport_and_fom_record", + "correlate_xrd_with_microstructure", + "evaluate_newman_asr_curve", + "generate_openimpala_job_suite", + "has_openimpala_python", + "load_openimpala_lookup", + "load_openimpala_records", + "parse_openimpala_results", + "run_openimpala_python_suite", + "run_openimpala_rev_convergence", + "write_openimpala_ini", +] diff --git a/porousdiff/optimization.py b/porousdiff_workflows/optimization.py similarity index 100% rename from porousdiff/optimization.py rename to porousdiff_workflows/optimization.py diff --git a/porousdiff/transport_and_xrd.py b/porousdiff_workflows/transport_and_xrd.py similarity index 90% rename from porousdiff/transport_and_xrd.py rename to porousdiff_workflows/transport_and_xrd.py index 2f61962..1f9cbc7 100644 --- a/porousdiff/transport_and_xrd.py +++ b/porousdiff_workflows/transport_and_xrd.py @@ -13,9 +13,10 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np -import tifffile from scipy.stats import pearsonr, spearmanr +from porousdiff.io import load_volume_array, to_basecoat_volume + def write_openimpala_ini( ini_path: Path, @@ -270,6 +271,7 @@ def _solve_openimpala_phase_transport( oi.Session.ensure_active() vol = np.asarray(volume, dtype=np.uint8) vox = max(float(voxel_size_um), 1e-6) + vol_bc = to_basecoat_volume(vol, voxel_size_um=vox, preserve_multiphase=True) if phase_diffusivities is not None: active_labels = [int(k) for k, v in phase_diffusivities.items() if float(v) > 0.0] @@ -279,10 +281,9 @@ def _solve_openimpala_phase_transport( try: res_all = oi.tortuosity_all( - vol, + vol_bc, phase=int(phase), strict=False, - voxel_size=vox, phase_diffusivities=phase_diffusivities, ) except oi.OpenImpalaError: @@ -309,9 +310,8 @@ def _solve_openimpala_phase_transport( if compute_homogenized_tensor: try: eff_res = oi.effective_diffusivity( - vol, + vol_bc, phase=int(phase), - voxel_size=vox, phase_diffusivities=phase_diffusivities, ) ten = np.asarray(eff_res.tensor, dtype=np.float64) @@ -340,7 +340,12 @@ def compute_openimpala_volume_transport( coating_rel_conductivity: float = 0.05, compute_homogenized_tensor: bool = False, ) -> dict[str, object]: - """Run in-process OpenImpala v4.6 PDE transport & interfacial characterization on a 3D `(Z, Y, X)` volume.""" + """Run in-process OpenImpala v5.1+ PDE transport & interfacial characterization on a 3D `(Z, Y, X)` volume. + + Passes calibrated `basecoat.Volume` (`unit='um'`) to OpenImpala via `VolumeProtocol`, so + OpenImpala computes SSA in true SI `m^-1` (`spacing_in('m')`), which is reported both in + SI `m^-1` (`*_m_inv`) and converted (`* 1e-6`) to `um^-1` for `PorousDiff`'s `1/um` metrics. + """ import openimpala as oi oi.Session.ensure_active() @@ -351,6 +356,8 @@ def compute_openimpala_volume_transport( n_ph = int(num_phases) if num_phases is not None else (3 if int(np.max(vol)) >= 2 else 2) vol_bin = (vol > 0).astype(np.uint8) + vol_bin_bc = to_basecoat_volume(vol_bin, voxel_size_um=vox, preserve_multiphase=False) + vol_mp_bc = to_basecoat_volume(vol, voxel_size_um=vox, preserve_multiphase=True) phases_out: dict[str, dict[str, float]] = {} phases_out["pore_ionic"] = _solve_openimpala_phase_transport( @@ -381,27 +388,36 @@ def compute_openimpala_volume_transport( compute_homogenized_tensor=compute_homogenized_tensor, ) - ssa_bin = oi.specific_surface_area(vol_bin, phase_a=0, phase_b=1, voxel_size=vox) + m_inv_to_um_inv = 1e-6 + ssa_bin = oi.specific_surface_area(vol_bin_bc, phase_a=0, phase_b=1) interfacial: dict[str, float] = { - "ssa_total_raw": float(ssa_bin.ssa), - "ssa_total_cc": float(ssa_bin.ssa_corrected), + "ssa_total_raw_m_inv": float(ssa_bin.ssa), + "ssa_total_cc_m_inv": float(ssa_bin.ssa_corrected), + "ssa_total_raw": float(ssa_bin.ssa) * m_inv_to_um_inv, + "ssa_total_cc": float(ssa_bin.ssa_corrected) * m_inv_to_um_inv, } if n_ph == 3: - ssa_pc = oi.specific_surface_area(vol, phase_a=0, phase_b=2, voxel_size=vox) - ssa_pcarb = oi.specific_surface_area(vol, phase_a=0, phase_b=1, voxel_size=vox) - ssa_cc = oi.specific_surface_area(vol, phase_a=1, phase_b=2, voxel_size=vox) + ssa_pc = oi.specific_surface_area(vol_mp_bc, phase_a=0, phase_b=2) + ssa_pcarb = oi.specific_surface_area(vol_mp_bc, phase_a=0, phase_b=1) + ssa_cc = oi.specific_surface_area(vol_mp_bc, phase_a=1, phase_b=2) interfacial.update( { - "ssa_pore_coating_raw": float(ssa_pc.ssa), - "ssa_pore_coating_cc": float(ssa_pc.ssa_corrected), - "ssa_pore_carbon_raw": float(ssa_pcarb.ssa), - "ssa_pore_carbon_cc": float(ssa_pcarb.ssa_corrected), - "ssa_carbon_coating_raw": float(ssa_cc.ssa), - "ssa_carbon_coating_cc": float(ssa_cc.ssa_corrected), + "ssa_pore_coating_raw_m_inv": float(ssa_pc.ssa), + "ssa_pore_coating_cc_m_inv": float(ssa_pc.ssa_corrected), + "ssa_pore_carbon_raw_m_inv": float(ssa_pcarb.ssa), + "ssa_pore_carbon_cc_m_inv": float(ssa_pcarb.ssa_corrected), + "ssa_carbon_coating_raw_m_inv": float(ssa_cc.ssa), + "ssa_carbon_coating_cc_m_inv": float(ssa_cc.ssa_corrected), + "ssa_pore_coating_raw": float(ssa_pc.ssa) * m_inv_to_um_inv, + "ssa_pore_coating_cc": float(ssa_pc.ssa_corrected) * m_inv_to_um_inv, + "ssa_pore_carbon_raw": float(ssa_pcarb.ssa) * m_inv_to_um_inv, + "ssa_pore_carbon_cc": float(ssa_pcarb.ssa_corrected) * m_inv_to_um_inv, + "ssa_carbon_coating_raw": float(ssa_cc.ssa) * m_inv_to_um_inv, + "ssa_carbon_coating_cc": float(ssa_cc.ssa_corrected) * m_inv_to_um_inv, } ) - prof_z = oi.through_thickness_profile(vol_bin, phase=1, direction="z", voxel_size=vox) + prof_z = oi.through_thickness_profile(vol_bin_bc, phase=1, direction="z") prof_arr = np.asarray(prof_z.profile, dtype=np.float64) lookup_summary: dict[str, float] = { @@ -436,7 +452,7 @@ def run_openimpala_python_suite( coating_rel_conductivity: float = 0.05, compute_homogenized_tensor: bool = False, ) -> list[dict[str, object]]: - """Execute OpenImpala v4.6 PDE transport directly in-process across Real, Baselines & PorousDiff. + """Execute OpenImpala v5.1+ PDE transport directly in-process across Real, Baselines & PorousDiff. Writes per-job JSON artifacts under `suite_dir / 'outputs'`, `openimpala_jobs.json`, and `out_csv` (`openimpala_transport_parity.csv`) directly consumable by `load_openimpala_lookup`. @@ -455,17 +471,26 @@ def run_openimpala_python_suite( beamline = str(entry.get("beamline", "primary")) load_val = float(entry.get("load_value", 0.0)) # type: ignore[arg-type] n_ph = int(entry.get("num_phases", 2)) # type: ignore[arg-type] - vox = float(entry.get("voxel_size_um", 1.0)) # type: ignore[arg-type] + explicit_vox = entry.get("voxel_size_um") if "volume" in entry and entry["volume"] is not None: vol = np.asarray(entry["volume"], dtype=np.uint8) + vox = float(explicit_vox) if explicit_vox is not None else 1.0 # type: ignore[arg-type] stem = str(entry.get("stem", f"vol_{idx:03d}")) - tiff_str = str(entry.get("tiff_path", "")) + tiff_str = str(entry.get("tiff_path", entry.get("zarr_path", ""))) else: - tiff_path = Path(str(entry["tiff_path"])) - vol = np.asarray(tifffile.imread(tiff_path), dtype=np.uint8) - stem = tiff_path.stem - tiff_str = str(tiff_path.resolve()) + src_key = "zarr_path" if "zarr_path" in entry and entry["zarr_path"] else "tiff_path" + src_path = Path(str(entry[src_key])) + vol, loaded_vox = load_volume_array(src_path) + vox = ( + float(explicit_vox) # type: ignore[arg-type] + if explicit_vox is not None + else (loaded_vox if loaded_vox is not None else 1.0) + ) + stem = src_path.name.removesuffix(".ome.zarr").removesuffix(".zarr") + if src_path.suffix.lower() in (".tif", ".tiff", ".npy", ".h5", ".hdf5", ".nxs"): + stem = src_path.stem + tiff_str = str(src_path.resolve()) vol_res = compute_openimpala_volume_transport( vol, @@ -542,6 +567,7 @@ def run_openimpala_rev_convergence( raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {vol.shape}") min_dim = int(min(vol.shape)) vox = max(float(voxel_size_um), 1e-6) + vol_bc = to_basecoat_volume(vol, voxel_size_um=vox, preserve_multiphase=True) if sizes is None: cand_sizes = sorted({max(8, min_dim // 2), max(8, (3 * min_dim) // 4), min_dim}) @@ -557,11 +583,10 @@ def run_openimpala_rev_convergence( size_rows: list[dict[str, float]] = [] try: rev_res = oi.rev_study( - vol, + vol_bc, sizes=cand_sizes, num_samples=max(1, int(num_samples)), phase=int(phase), - voxel_size=vox, csv_path=csv_path_str, ) for sz in rev_res.sizes: @@ -617,7 +642,9 @@ def run_openimpala_rev_convergence( writer.writerows(size_rows) prof = oi.through_thickness_profile( - (vol > 0).astype(np.uint8), phase=1, direction="z", voxel_size=vox + to_basecoat_volume((vol > 0).astype(np.uint8), voxel_size_um=vox, preserve_multiphase=False), + phase=1, + direction="z", ) prof_arr = np.asarray(prof.profile, dtype=np.float64) largest_cov = float(size_rows[-1]["cov_d_zz"]) if size_rows else float("nan") diff --git a/pyproject.toml b/pyproject.toml index 95023d1..b975e28 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,12 +4,13 @@ build-backend = "setuptools.build_meta" [project] name = "porousdiff" -version = "0.5.1" +version = "0.5.2" description = "Conditional 3D Diffusion Surrogate Modelling for Compressed Porous Battery Electrodes" readme = "README.md" license = { file = "LICENSE" } requires-python = ">=3.10" dependencies = [ + "basecoat @ git+https://github.com/BASE-Laboratory/basecoat.git@v0.2.0", "numpy>=1.24", "scipy>=1.10", "scikit-image>=0.21", @@ -30,7 +31,23 @@ transport = [ ] [tool.setuptools.packages.find] -include = ["porousdiff*"] +include = ["porousdiff", "porousdiff.*", "porousdiff_workflows", "porousdiff_workflows.*"] + +[tool.basecoat.layers] +layer = 2 +source_dirs = ["porousdiff"] +banned_imports = [ + "multimodal_benchmark", + "xct_research", + "openimpala", + "sms", + "openlsrx", + "x_fuse", + "braggtrack", + "porousdiff_workflows", + "zarr", + "numcodecs", +] [tool.pytest.ini_options] testpaths = ["tests"] @@ -44,4 +61,3 @@ target-version = "py310" [tool.ruff.lint] select = ["E", "F", "W"] ignore = ["E501", "E402"] - diff --git a/scripts/evaluation/evaluate_beamtime_multiplier.py b/scripts/evaluation/evaluate_beamtime_multiplier.py index 938a8f5..1ee8f96 100755 --- a/scripts/evaluation/evaluate_beamtime_multiplier.py +++ b/scripts/evaluation/evaluate_beamtime_multiplier.py @@ -62,7 +62,7 @@ infer_use_ordinal_material_channel, ) from porousdiff.preprocessing import infer_material_name, parse_load_value -from porousdiff.transport_and_xrd import ( +from porousdiff_workflows.transport_and_xrd import ( correlate_xrd_with_microstructure, generate_openimpala_job_suite, has_openimpala_python, diff --git a/scripts/evaluation/optimize_clamping_pressure.py b/scripts/evaluation/optimize_clamping_pressure.py index b2fa5b0..a630e8b 100644 --- a/scripts/evaluation/optimize_clamping_pressure.py +++ b/scripts/evaluation/optimize_clamping_pressure.py @@ -50,13 +50,13 @@ build_noise_scheduler, infer_use_ordinal_material_channel, ) -from porousdiff.optimization import ( +from porousdiff_workflows.optimization import ( compute_transport_and_fom_record, find_optimal_clamping_pressure, load_openimpala_records, ) from porousdiff.preprocessing import infer_material_name, parse_load_value -from porousdiff.transport_and_xrd import ( +from porousdiff_workflows.transport_and_xrd import ( compute_openimpala_volume_transport, has_openimpala_python, ) diff --git a/scripts/evaluation/parse_openimpala_suite.py b/scripts/evaluation/parse_openimpala_suite.py index 9295af7..c134e05 100755 --- a/scripts/evaluation/parse_openimpala_suite.py +++ b/scripts/evaluation/parse_openimpala_suite.py @@ -15,7 +15,7 @@ if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) -from porousdiff.transport_and_xrd import parse_openimpala_results +from porousdiff_workflows.transport_and_xrd import parse_openimpala_results def main() -> None: diff --git a/scripts/evaluation/sample_carbon_conditional_96.py b/scripts/evaluation/sample_carbon_conditional_96.py index 58dec94..236dc67 100644 --- a/scripts/evaluation/sample_carbon_conditional_96.py +++ b/scripts/evaluation/sample_carbon_conditional_96.py @@ -47,7 +47,7 @@ infer_use_ordinal_material_channel, ) from porousdiff.preprocessing import infer_material_name, parse_load_value -from porousdiff.transport_and_xrd import ( +from porousdiff_workflows.transport_and_xrd import ( has_openimpala_python, run_openimpala_rev_convergence, ) diff --git a/scripts/evaluation/virtual_compress_scan.py b/scripts/evaluation/virtual_compress_scan.py index bf788ab..974d8c0 100644 --- a/scripts/evaluation/virtual_compress_scan.py +++ b/scripts/evaluation/virtual_compress_scan.py @@ -21,7 +21,6 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np -import tifffile import torch REPO_ROOT = Path(__file__).resolve().parents[2] @@ -29,6 +28,7 @@ sys.path.insert(0, str(REPO_ROOT)) from porousdiff.data import default_project_root, resolve_material_id +from porousdiff.io import export_volume_ome_zarr, load_volume_array from porousdiff.metrics import ( evaluate_multiphase_physics, evaluate_volume_physics, @@ -50,19 +50,8 @@ PHASE_CMAP = ListedColormap(["#0b0e14", "#38bdf8", "#facc15"]) -def _load_input_volume(path: Path) -> np.ndarray: - ext = path.suffix.lower() - if ext == ".npy": - arr = np.load(path) - elif ext in (".tif", ".tiff"): - arr = tifffile.imread(path) - else: - raise ValueError(f"Unsupported input volume format {path}; expected .npy or .tif/.tiff") - if arr.ndim == 4: - arr = arr[0] - if arr.ndim != 3: - raise ValueError(f"Expected 3D volume (Z, Y, X), got shape {arr.shape}") - return arr.astype(np.uint8) +def _load_input_volume(path: Path) -> tuple[np.ndarray, float | None]: + return load_volume_array(path) def _save_virtual_panel( @@ -138,6 +127,7 @@ def main() -> None: parser.add_argument("--refine-strength", type=float, default=0.35) parser.add_argument("--guidance-scale", type=float, default=1.5) parser.add_argument("--export-openimpala", action="store_true") + parser.add_argument("--export-ome-zarr", action="store_true") parser.add_argument("--allow-cpu", action="store_true") args = parser.parse_args() @@ -161,13 +151,19 @@ def main() -> None: if not ckpt_path.is_file(): raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}") + source_vol, loaded_vox_um = _load_input_volume(args.input) + saved = torch.load(ckpt_path, map_location="cpu", weights_only=False) cfg = saved["config"] patch_size = int(cfg.get("patch_size", 96)) num_phases = int(cfg.get("num_phases", 2)) num_materials = int(cfg.get("num_materials", 1)) ref_vox = float(cfg.get("ref_voxel_size_um", 1.0)) - vox_um = args.voxel_size_um if args.voxel_size_um > 0 else ref_vox + vox_um = ( + args.voxel_size_um + if args.voxel_size_um > 0 + else (loaded_vox_um if loaded_vox_um is not None else ref_vox) + ) unit_label = "kPa" if bool(cfg.get("use_stress_kpa", False)) else "mV/V" model = ContinuousLoadConditionedUNet( @@ -200,7 +196,6 @@ def main() -> None: prediction_type=str(cfg["prediction_type"]), ) - source_vol = _load_input_volume(args.input) target_loads = [float(x.strip()) for x in args.target_loads.split(",") if x.strip()] extrap = check_load_extrapolation( [float(args.source_load), *target_loads], @@ -328,6 +323,19 @@ def main() -> None: out_dir / "openimpala" / f"virtual_{args.material}_{tag}.tif", preserve_multiphase=(num_phases == 3), ) + if args.export_ome_zarr: + export_volume_ome_zarr( + vol, + out_dir / "ome_zarr" / f"virtual_{args.material}_{tag}.ome.zarr", + voxel_size_um=vox_um, + preserve_multiphase=(num_phases == 3), + metadata={ + "material": args.material, + "load_value": float(lv), + "load_unit": unit_label, + "mode": args.mode, + }, + ) phys = eval_fn(vol, voxel_size=vox_um) fid = compute_virtual_compression_fidelity( source_vol, vol, same_load_reconstructions=same_load_vol diff --git a/tests/test_basecoat_layer2_migration.py b/tests/test_basecoat_layer2_migration.py new file mode 100644 index 0000000..cfd217a --- /dev/null +++ b/tests/test_basecoat_layer2_migration.py @@ -0,0 +1,112 @@ +"""Tests for PorousDiff Layer 2 `basecoat` boundary, OME-Zarr export, and OpenImpala v5.1 SI hand-off.""" + +from __future__ import annotations + +from pathlib import Path + +import basecoat +from basecoat.layers import check_layer_imports +import numpy as np +import openimpala as oi +import pytest + +from porousdiff import export_volume_ome_zarr, load_volume_array, to_basecoat_volume +from porousdiff.metrics import CAUCHY_CROFTON_3D_FACTOR, evaluate_multiphase_physics +from porousdiff_workflows.transport_and_xrd import ( + compute_openimpala_volume_transport, + run_openimpala_python_suite, +) + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def test_porousdiff_layer2_import_boundary() -> None: + """`porousdiff/` must contain zero imports of Layer 3/4 packages (`openimpala`, `porousdiff_workflows`, etc.).""" + violations = check_layer_imports(REPO_ROOT) + assert violations == [] + + +def test_basecoat_ome_zarr_multiphase_roundtrip_and_mode_downsampling(tmp_path: Path) -> None: + """Exporting a 3-phase `{0: pore, 1: carbon, 2: coating}` volume preserves labels, spacing, and mode pyramid.""" + vol = np.zeros((16, 16, 16), dtype=np.uint8) + vol[:, 4:12, 4:12] = 2 # coating shell + vol[:, 6:10, 6:10] = 1 # carbon core + + store_path = tmp_path / "electrode_3phase.ome.zarr" + out = export_volume_ome_zarr( + vol, + store_path, + voxel_size_um=0.65, + preserve_multiphase=True, + multiscale_levels=2, + metadata={"material": "tio2_anode", "stress_kpa": 45.0}, + ) + assert out == store_path and store_path.is_dir() + + vset = basecoat.read_ome_zarr(store_path, level=0, as_set=True) + assert isinstance(vset, basecoat.VolumeSet) + assert "phase" in vset.labels + phase_vol = vset.labels["phase"] + assert np.array_equal(phase_vol.data, vol) + assert phase_vol.spacing_in("um") == pytest.approx((0.65, 0.65, 0.65)) + assert phase_vol.spacing_in("m") == pytest.approx((0.65e-6, 0.65e-6, 0.65e-6)) + assert phase_vol.label_names == {0: "pore", 1: "carbon", 2: "coating"} + + # Pyramid level 1 uses block-mode (pure integer labels {0, 1, 2}, never fractional averages) + vset_l1 = basecoat.read_ome_zarr(store_path, level=1, as_set=True) + assert isinstance(vset_l1, basecoat.VolumeSet) + assert set(np.unique(vset_l1.labels["phase"].data)).issubset({0, 1, 2}) + + loaded_arr, loaded_vox = load_volume_array(store_path) + assert np.array_equal(loaded_arr, vol) + assert loaded_vox == pytest.approx(0.65) + + +def test_direct_openimpala_v51_handoff_and_si_ssa_calibration(tmp_path: Path) -> None: + """Both in-memory `to_basecoat_volume` and `.ome.zarr` stores pass calibrated SI metres to OpenImpala v5.1.""" + oi.Session.ensure_active() + + vol = np.zeros((20, 20, 20), dtype=np.uint8) + vol[:, 5:15, 5:15] = 2 + vol[:, 7:13, 7:13] = 1 + vox_um = 0.8 + + bc_vol = to_basecoat_volume(vol, voxel_size_um=vox_um, preserve_multiphase=True) + store_path = export_volume_ome_zarr(vol, tmp_path / "cyl.ome.zarr", voxel_size_um=vox_um, preserve_multiphase=True) + + # 1. Direct OpenImpala v5.1 tortuosity on both VolumeProtocol and .ome.zarr store + res_mem = oi.tortuosity(bc_vol, phase=0, direction="z") + res_zarr = oi.tortuosity(store_path, phase=0, direction="z") + assert res_mem.effective_diffusivity == pytest.approx(res_zarr.effective_diffusivity, rel=1e-6) + assert res_mem.tortuosity == pytest.approx(res_zarr.tortuosity, rel=1e-6) + + # 2. SI SSA calibration: OpenImpala returns m^-1 = 1e6 * PorousDiff's um^-1 + mp_um = evaluate_multiphase_physics(vol, voxel_size=vox_um) + oi_res = compute_openimpala_volume_transport(vol, voxel_size_um=vox_um, num_phases=3) + interfacial = oi_res["interfacial"] # type: ignore[index] + + assert float(interfacial["ssa_pore_coating_cc"]) == pytest.approx( + mp_um["ssa_pore_coating"] * CAUCHY_CROFTON_3D_FACTOR, rel=1e-5 + ) + assert float(interfacial["ssa_pore_coating_cc_m_inv"]) == pytest.approx( + float(interfacial["ssa_pore_coating_cc"]) * 1e6, rel=1e-5 + ) + + # 3. Suite runner consumes `.ome.zarr` entries directly without intermediate TIFFs + suite_dir = tmp_path / "zarr_suite" + rows = run_openimpala_python_suite( + [ + { + "method": "porousdiff", + "state": "tio2_45kpa", + "material": "tio2_anode", + "load_value": 45.0, + "zarr_path": store_path, + "num_phases": 3, + } + ], + suite_dir=suite_dir, + out_csv=suite_dir / "parity.csv", + ) + assert len(rows) == 4 + assert (suite_dir / "parity.csv").is_file() diff --git a/tests/test_beamtime_multiplier.py b/tests/test_beamtime_multiplier.py index ad07b09..fdbbe33 100644 --- a/tests/test_beamtime_multiplier.py +++ b/tests/test_beamtime_multiplier.py @@ -583,7 +583,7 @@ def test_nested_discovery_group_calibration_append_and_resume(tmp_path: Path) -> def test_openimpala_suite_and_diad_xrd_correlation(tmp_path: Path) -> None: """Verify OpenImpala output ingestion CLI and K11 DIAD XRD correlation analysis.""" from porousdiff.metrics import export_openimpala_tiff - from porousdiff.transport_and_xrd import ( + from porousdiff_workflows.transport_and_xrd import ( correlate_xrd_with_microstructure, generate_openimpala_job_suite, ) diff --git a/tests/test_next_level_novelty.py b/tests/test_next_level_novelty.py index d82f75a..2118236 100644 --- a/tests/test_next_level_novelty.py +++ b/tests/test_next_level_novelty.py @@ -26,12 +26,12 @@ ) from porousdiff.metrics import evaluate_multiphase_physics, summarize_metric_records from porousdiff.models import ContinuousLoadConditionedUNet, build_noise_scheduler -from porousdiff.optimization import ( +from porousdiff_workflows.optimization import ( compute_transport_and_fom_record, find_optimal_clamping_pressure, load_openimpala_lookup, ) -from porousdiff.transport_and_xrd import correlate_xrd_with_microstructure +from porousdiff_workflows.transport_and_xrd import correlate_xrd_with_microstructure from porousdiff.virtual_compression import generate_tiled_3d, virtual_compress_volumes REPO_ROOT = Path(__file__).resolve().parents[1] @@ -735,7 +735,7 @@ def test_newman_asr_dimensional_sweet_spot_and_regime_sensitivity() -> None: def test_mixed_unit_manifest_guard_and_openimpala_template_and_tile_symmetry(tmp_path: Path) -> None: import pytest - from porousdiff.transport_and_xrd import generate_openimpala_job_suite + from porousdiff_workflows.transport_and_xrd import generate_openimpala_job_suite from porousdiff.virtual_compression import _compute_tile_starts from scripts.training.train_carbon_conditional_96 import load_manifest_specs diff --git a/tests/test_openimpala_and_roadmap.py b/tests/test_openimpala_and_roadmap.py index 243f2fb..4861cf9 100644 --- a/tests/test_openimpala_and_roadmap.py +++ b/tests/test_openimpala_and_roadmap.py @@ -24,11 +24,11 @@ specific_surface_area, ) from porousdiff.models import ContinuousLoadConditionedUNet, build_noise_scheduler -from porousdiff.optimization import ( +from porousdiff_workflows.optimization import ( compute_transport_and_fom_record, find_optimal_clamping_pressure, ) -from porousdiff.transport_and_xrd import ( +from porousdiff_workflows.transport_and_xrd import ( compute_openimpala_volume_transport, has_openimpala_python, run_openimpala_rev_convergence, @@ -651,7 +651,7 @@ def test_redteam_zero_heldout_porosity_leakage_in_lagrangian_slab(tmp_path: Path def test_redteam_per_realization_openimpala_bootstrap_and_static_asr(tmp_path: Path) -> None: """Verify load_openimpala_records preserves per-patch variance and static-cell Newman ASR has zero pump penalty.""" import csv - from porousdiff.optimization import NEWMAN_REGIMES, load_openimpala_records + from porousdiff_workflows.optimization import NEWMAN_REGIMES, load_openimpala_records # 1. Static Swagelok/coin/pouch primary regimes have zero convective pumping penalty for reg_key in ("kinetics_limited", "balanced", "mass_transport_limited"):