Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -37,22 +37,25 @@ 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
uv pip install --python .venv/bin/python -e ".[dev]" cmake
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
23 changes: 23 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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`).
205 changes: 205 additions & 0 deletions ECOSYSTEM.md

Large diffs are not rendered by default.

11 changes: 10 additions & 1 deletion porousdiff/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
162 changes: 162 additions & 0 deletions porousdiff/io.py
Original file line number Diff line number Diff line change
@@ -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
12 changes: 9 additions & 3 deletions porousdiff/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}")
Expand All @@ -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
35 changes: 35 additions & 0 deletions porousdiff_workflows/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
File renamed without changes.
Loading
Loading