Python API Reference#
High-level NumPy-native interface for computing transport and microstructural
properties on segmented 3D voxel images. All functions listed below are
re-exported at the top level of openimpala (e.g. oi.tortuosity(...))
and operate identically across the compiled AMReX/HYPRE C++ backend (CPU and
CUDA) and the pure-Python SciPy/CuPy solver.
Transport & Phase Analysis#
- openimpala.facade.volume_fraction(data, phase, *, max_grid_size='auto')[source]#
Compute the volume fraction of phase in a 3-D NumPy array, VoxelImage, or file.
- Parameters:
- Return type:
- openimpala.facade.percolation_check(data, phase, direction='x', *, max_grid_size='auto', verbose=0)[source]#
Check whether phase percolates across the domain in direction.
- openimpala.facade.tortuosity(data, phase=None, direction='x', solver='auto', *, voxel_size=None, phase_diffusivities=None, return_field=False, write_plotfile=False, preconditioner='smg', max_grid_size='auto', results_path='.', verbose=0, mlmg_eps=None, mlmg_maxiter=None, mlmg_max_coarsening_level=None)[source]#
Compute steady-state tortuosity and effective diffusivity along direction.
- Parameters:
data (np.ndarray, VoxelImage, or path-like) – 3-D integer array of phase IDs
(Nz, Ny, Nx),VoxelImagehandle, or path to a supported 3-D volume file (TIFF, HDF5, RAW, DAT, NPY, Zarr).phase (int) – Conducting phase ID (required when phase_diffusivities is
None).direction (str or Direction) – Flow direction (
'x','y', or'z').solver (str or SolverType) –
'auto'/'mlmg'(default matrix-free AMReX geometric multigrid), or HYPRE solvers'pcg','flexgmres','gmres','bicgstab','smg','pfmg','jacobi'.voxel_size (float or tuple of 3 floats, optional) – Physical voxel spacing: either a scalar
h(cubic voxels) or(dz, dy, dx)matching NumPy(Nz, Ny, Nx)axis order.phase_diffusivities (Mapping[int, float], optional) – Multi-phase transport map
{phase_id: D_phase}. Phases withD > 0participate in 6-connected transport with harmonic-mean face conductances; unlisted phases or phases withD == 0are insulating.return_field (bool) – If
True, populateresult.solution_fieldwith the solved 3-D potential field(Nz, Ny, Nx)(float64). Defaults toFalseto avoid host memory copies on large grids.write_plotfile (bool) – If
True, write an AMReXHyperCLaw-V1.1plotfile directory under results_path (readable out-of-core viayt.load()and ParaView) and populateresult.plotfile_path.preconditioner (Union[str, 'PrecondType'])
results_path (str)
verbose (int)
mlmg_eps (Optional[float])
mlmg_maxiter (Optional[int])
mlmg_max_coarsening_level (Optional[int])
- Return type:
- openimpala.facade.tortuosity_all(data, phase=None, solver='auto', *, directions=('x', 'y', 'z'), strict=False, voxel_size=None, phase_diffusivities=None, return_field=False, write_plotfile=False, preconditioner='smg', max_grid_size='auto', results_path='.', verbose=0, mlmg_eps=None, mlmg_maxiter=None, mlmg_max_coarsening_level=None)[source]#
Compute steady-state tortuosity across cardinal directions
('x', 'y', 'z').Loads or stages data once, then solves each direction in directions. When
strict=False(default), directions that do not percolate map toNoneinstead of raisingPercolationError.- Parameters:
data (DataInputArg)
phase (Optional[int])
solver (Union[str, 'SolverType'])
directions (Sequence[Union[str, 'Direction']])
strict (bool)
voxel_size (Optional[VoxelSizeArg])
return_field (bool)
write_plotfile (bool)
preconditioner (Union[str, 'PrecondType'])
results_path (str)
verbose (int)
mlmg_eps (Optional[float])
mlmg_maxiter (Optional[int])
mlmg_max_coarsening_level (Optional[int])
- Return type:
dict[str, Optional[TortuosityResult]]
- openimpala.facade.effective_diffusivity(data, phase=None, *, voxel_size=None, phase_diffusivities=None, solver='flexgmres', return_fields=False, write_plotfile=False, max_grid_size='auto', results_path='.', verbose=0)[source]#
Compute the full 3x3 homogenised effective-diffusivity tensor
D_eff.Solves the three periodic homogenisation cell problems in
x,y,zand returnsEffectiveDiffusivityResultwithtensorordered(x, y, z).- Parameters:
- Return type:
Microstructural Characterisation#
- openimpala.facade.specific_surface_area(data, phase_a=0, phase_b=1, *, voxel_size=None, boundary_padding=0, max_grid_size='auto')[source]#
Compute interfacial specific surface area between phase_a and phase_b.
- openimpala.facade.connected_components(data, phase, *, return_labels=False, max_grid_size='auto', verbose=0)[source]#
Label 6-connected components of phase.
- openimpala.facade.particle_size_distribution(data, phase, *, voxel_size=None, max_grid_size='auto', verbose=0)[source]#
Compute equivalent-sphere radii
R = (3V / (4*pi))^(1/3)of 6-connected components.- Parameters:
- Return type:
- openimpala.facade.through_thickness_profile(data, phase, direction='x', *, voxel_size=None, max_grid_size='auto')[source]#
Compute slice-by-slice volume fraction profile of phase along direction.
- Parameters:
- Return type:
Battery Parameterisation (PyBaMM & Faraday BPX)#
- openimpala.facade.to_pybamm_parameters(data, *, electrolyte_phase, solid_phase=None, electrode='negative', direction='x', voxel_size=None, solver='auto')[source]#
Compute an in-memory PyBaMM parameter dictionary directly from a 3-D microstructure.
Keys follow standard PyBaMM DFN / SPM parameter conventions (e.g.
Chen2020,Marquis2019) so the returned dictionary can be passed straight topybamm.ParameterValues(...).update(params, check_already_exists=False).When voxel_size is supplied in metres (or carried by a physical
VoxelImage/ CILImageData/ OME-Zarr store), dimensional[m]keys for through-plane electrode/separator thickness and mean equivalent-sphere particle radius are also populated.
- openimpala.facade.export_bpx_json(data, output_path=None, *, electrolyte_phase, solid_phase=None, electrode='negative', directions=('x', 'y', 'z'), compute_deff_tensor=False, voxel_size=None, solver='auto', sample_id=None, provenance_uri=None)[source]#
Export Faraday BPX & BattINFO-aligned microstructure JSON from a 3-D volume.
Matches the structured
openimpala/units/bpx/provenanceschema emitted by C++ResultsJSON.Hacross both compiled and pure-Python backends. If output_path is provided, writes pretty-printed JSON to disk (on rank 0 under MPI) and returns the dictionary.- Parameters:
data (DataInputArg)
output_path (Optional[Union[str, os.PathLike]])
electrolyte_phase (int)
solid_phase (Optional[int])
electrode (str)
directions (Sequence[Union[str, 'Direction']])
compute_deff_tensor (bool)
voxel_size (Optional[VoxelSizeArg])
solver (Union[str, 'SolverType'])
sample_id (Optional[str])
provenance_uri (Optional[str])
- Return type:
I/O, Segmentation, Cloud Zarr & Plotfiles#
- openimpala.facade.read_image(path, threshold=0.5, *, dark_is_pore=True, pore_value=0, solid_value=1, voxel_size=None, file_format=None, hdf5_dataset='/data', zarr_array_path=None, zarr_level=0, raw_width=0, raw_height=0, raw_depth=0, raw_data_type=None, max_grid_size='auto')[source]#
Read a 3-D image file and threshold it into pore and solid phase IDs.
When dark_is_pore is
True(default X-ray CT contrast), voxels withpixel > thresholdmap to solid_value (default1) and<= thresholdmap to pore_value (default0). Setdark_is_pore=Falsefor inverted (bright-pore) images sopixel > thresholdmaps to pore_value (0).threshold may be a numeric cutoff or
'otsu'to automatically determine the optimal global threshold via Otsu’s between-class variance method. Supports TIFF, HDF5, OME-Zarr (.zarr), RAW, DAT, and NPY volumes across both compiled C++ and pure-Python backends.
- openimpala._io.calculate_otsu_threshold(array, *, nbins=None)[source]#
Compute Otsu’s optimal global threshold maximising between-class variance.
- Parameters:
array (np.ndarray) – Grayscale intensity array of arbitrary shape (2-D or 3-D;
uint8,uint16, integer, or floating-point).nbins (int, optional) – Number of histogram bins. When
None(default), integer volumes whose dynamic rangemax - min <= 65535(including alluint8,int8,uint16, andint16X-ray CT tomograms) use an exact integer histogram with zero quantisation error, while floating-point or wide-range integer arrays use256linearly spaced bins.
- Returns:
float – Optimal scalar threshold
Tsuch thatarray > Tseparates the bright foreground class from the dark background class. Tied maxima of \(\sigma_B^2\) across flat histogram valleys are averaged to return the valley midpoint.- Return type:
- openimpala._io.binarize_otsu(array, *, pore_value=0, solid_value=1, dark_is_pore=True, nbins=None)[source]#
Segment a grayscale volume using Otsu’s method and return
(segmented, threshold).- Parameters:
array (np.ndarray) – Grayscale volume (typically
(Nz, Ny, Nx)).pore_value (int, default 0) – Phase ID assigned to the pore phase.
solid_value (int, default 1) – Phase ID assigned to the solid matrix phase.
dark_is_pore (bool, default True) – When
True(standard X-ray attenuation contrast), dark voxels (intensity <= threshold) map to pore_value and bright voxels (intensity > threshold) map to solid_value. SetFalsefor inverted contrast images where pores are brighter than solid.nbins (int, optional) – Histogram bin count passed to
calculate_otsu_threshold()(Noneselects exact integer bins foruint8/uint16scans).
- Returns:
segmented (np.ndarray) – C-contiguous
int32phase array with the same shape as array.threshold (float) – Computed Otsu threshold value.
- Return type:
- openimpala._io.downsample_volume(array, factor=2, *, mode='majority', tie_break='lowest', voxel_size=None)[source]#
Coarsen a 3-D
(Nz, Ny, Nx)volume by integer block factors.- Parameters:
array (np.ndarray) – 3-D segmented phase array or grayscale tomogram with shape
(Nz, Ny, Nx).factor (int or (int, int, int), default 2) – Isotropic coarsening factor or per-axis
(fz, fy, fx)integer factors. If any axis length is not an exact multiple of its factor, trailing slices are truncated and aUserWarningis emitted.mode ({"majority", "mean", "nearest"}, default "majority") –
"majority"(or"mode"): exact per-block modal phase ID, preserving discrete segmented labels without creating phantom intermediate values. Exact ties between two or more phase IDs in an even-sized block (e.g. 4v4 in a2x2x2block) are broken deterministically according to tie_break (default"lowest", which slightly biases volume fraction upward for phase0)."mean"(or"average"): block arithmetic mean for grayscale volumes prior to thresholding."nearest"(or"stride"): strided subsamplingarray[::fz, ::fy, ::fx].
tie_break ({"lowest", "highest"}, default "lowest") – Deterministic tie-breaking rule for
mode="majority"when two or more labels share the maximum voxel count inside a block:"lowest"selects the smallest phase ID;"highest"selects the largest phase ID.voxel_size (float or (float, float, float), optional) – If supplied, returns
(coarsened_array, (dz * fz, dy * fy, dx * fx)). If omitted, returnscoarsened_arraydirectly.
- Return type:
- openimpala._io.read_zarr_volume(path, *, array_path=None, label_key=None, unit=None, level=0, threshold=None, pore_value=0, solid_value=1, dark_is_pore=True)[source]#
Read a 3-D Zarr array or OME-NGFF (v0.4 / v0.5) multiscale Zarr group.
- Parameters:
path (str or os.PathLike) – Path to the Zarr store directory.
array_path (str, optional) – Explicit sub-array path inside the store (overrides label_key and level).
label_key (str, optional) – Named OME-NGFF label group under
labels/<label_key>(e.g.'phase','phase_lower','phase_upper').unit (str, optional) – Target physical length unit (e.g.
'm'or'um'). When supplied, converts OME-NGFF spatial axis units into unit and raisesUnitCalibrationErrorif spatial axes lack physical length units. Defaults toNone(returns raw OME-NGFF scale values).level (int, default 0) – Multiscale pyramid level index (
0= full resolution).threshold (float or 'otsu', optional) – Optional grayscale binarisation threshold.
pore_value (int) – Output phase IDs when threshold is provided.
solid_value (int) – Output phase IDs when threshold is provided.
dark_is_pore (bool, default True) – Polarity convention when threshold is provided.
- Returns:
tuple of (np.ndarray, tuple of float or None) –
(volume, voxel_size_zyx)wherevoxel_size_zyxis extracted from OME-NGFFcoordinateTransformations(converted to unit when requested).- Return type:
- openimpala._io.write_zarr_volume(path, array, *, voxel_size=(1.0, 1.0, 1.0), chunks=(64, 64, 64), name='volume', unit='micrometer', overwrite=True, zarr_format=2)[source]#
Write a 3-D volume
(Nz, Ny, Nx)to an OME-NGFF chunked Zarr store.Defaults to
zarr_format=2(OME-NGFF v0.4 on Zarr v2) for out-of-the-box compatibility withome-zarr-py, Napari, Fiji MoBIE, Bio-Formats, Neuroglancer, anddask. Passingzarr_format=3onzarr>=3.0writes an OME-NGFF v0.5 store on Zarr v3.
- openimpala._io.write_amrex_plotfile(plotfile_dir, fields, *, voxel_size=(1.0, 1.0, 1.0), time=0.0, step=0)[source]#
Write a 3-D single-level AMReX
HyperCLaw-V1.1plotfile directory.Each field in fields must be a 3-D array ordered
(Nz, Ny, Nx); arrays are transposed to AMReX column-major(Nx, Ny, Nz)little-endian IEEE-754float64FAB format soyt.load()and ParaView read them identically to native C++amrex::WriteSingleLevelPlotfileoutputs.
- openimpala.facade.estimate_memory(shape, num_ranks=1, *, solver='hypre', preconditioner='pfmg', mpi_ranks=None)[source]#
Estimate peak per-rank memory usage (in bytes/MB/GB) for a 3-D transport solve.
Uses empirically calibrated bytes-per-voxel footprints measured on the C++ AMReX/HYPRE multigrid hierarchies across \(64^3\)–\(256^3\) grids:
~310 B/voxelfor matrix-freemlmg,~365 B/voxelforpcg+pfmg,~1030 B/voxelforflexgmres+pfmg, and~1400 B/voxelwithsmg.
- openimpala.facade.build_info()[source]#
Return compile-time + runtime feature flags for the installed wheel.
- Return type:
Sample Datasets (openimpala.datasets)#
Built-in 3-D porous-media benchmark datasets for tutorials and testing.
All dataset loaders return C-contiguous (Nz, Ny, Nx) int32 NumPy arrays
(or openimpala.VoxelImage handles when as_voxel_image=True) and do
not require an active openimpala.Session unless as_voxel_image=True
with the compiled C++ backend. When running from a repository checkout, files
are read directly from data/; in standalone wheel installations, files are
downloaded once over HTTPS, verified against pinned SHA-256 digests, and cached
under $OPENIMPALA_DATA_DIR (default ~/.cache/openimpala).
- openimpala.datasets.fetch_path(filename, *, expected_sha256=None, verify_hash=True, timeout=30.0)[source]#
Resolve filename in the repository
data/folder or verified user cache.- Parameters:
filename (str) – Dataset file name under
data/(e.g.'SampleData_2Phase_stack_3d_1bit.tif').expected_sha256 (str, optional) – Explicit hex SHA-256 digest to enforce. Defaults to the pinned registry digest when filename belongs to
list_datasets().verify_hash (bool, default True) – Verify SHA-256 checksum on cached and newly downloaded files.
timeout (float, default 30.0) – Socket timeout in seconds for HTTPS downloads.
- Returns:
pathlib.Path – Local filesystem path to the dataset file.
- Return type:
- openimpala.datasets.list_datasets()[source]#
Return metadata for all built-in benchmark datasets keyed by canonical name.
- openimpala.datasets.fetch_example(name='two_phase_stack', *, as_voxel_image=False, voxel_size=None, max_grid_size='auto')[source]#
Fetch a named benchmark dataset as an
int32NumPy array orVoxelImage.- Parameters:
name (str, default
'two_phase_stack') – Dataset key or alias (seelist_datasets()).as_voxel_image (bool, default False) – If
True, wrap the volume in anopenimpala.VoxelImage(native AMReXVoxelImagewhen_coreis active, orPureVoxelImagein pure-Python mode).voxel_size (float or 3-sequence of floats, optional) – Physical voxel spacing
hor(dz, dy, dx)when as_voxel_image isTrue.max_grid_size (int or
'auto', default'auto') – AMReX grid block size when as_voxel_image isTrue.
- openimpala.datasets.two_phase_stack()[source]#
Return a
(100, 100, 100)int32isotropic two-phase porous medium.Phase
1is the percolating pore network (\(\varepsilon \approx 0.3983\)); phase0is the solid matrix (\(1 - \varepsilon \approx 0.6017\)).- Return type:
- openimpala.datasets.two_phase_cubic()[source]#
Return a
(64, 64, 64)int32two-phase porous medium.Phase
1is the percolating pore network (\(\varepsilon \approx 0.3993\)); phase0is the solid matrix (\(1 - \varepsilon \approx 0.6007\)).- Return type:
- openimpala.datasets.sphere_pack()[source]#
Return a
(100, 100, 100)int32regular 8-sphere benchmark volume.Phase
0consists of 8 non-overlapping spheres of radius \(R = 15\) voxels (\(\phi_0 \approx 0.1120\)); phase1is the continuous surrounding pore space (\(\varepsilon \approx 0.8880\)).- Return type:
Synthetic Microstructures & ML Datasets (openimpala.synthetic)#
Synthetic 3-D porous-media generators and ML surrogate dataset pipeline.
Provides zero-extra-dependency (NumPy + SciPy) procedural 3-D microstructure generators and a batch dataset builder that pairs 3-D phase volumes with ground- truth transport properties (\(\varepsilon\), Cauchy–Crofton SSA, directional tortuosity \((\tau_x, \tau_y, \tau_z)\), and the full \(3 \times 3\) periodic homogenised diffusivity tensor \(\mathbf{D}_{\mathrm{eff}}\)).
- openimpala.synthetic.gaussian_blobs(shape=(64, 64, 64), porosity=0.5, blobiness=1.0, *, anisotropy=(1.0, 1.0, 1.0), pore_value=0, solid_value=1, periodic=True, seed=None)[source]#
Generate a 3-D two-phase Gaussian random-field (“blobs”) microstructure.
- Parameters:
shape (int or 3-tuple of ints, default
(64, 64, 64)) – Output grid dimensions(Nz, Ny, Nx).porosity (float, default 0.5) – Target volume fraction of pore_value in
[0, 1].blobiness (float or 3-tuple of floats, default 1.0) – Feature frequency factor (smaller values yield larger, coarser pores; larger values yield finer pores).
anisotropy (float or 3-tuple of floats, default
(1.0, 1.0, 1.0)) – Relative stretch factors along(z, y, x)(values> 1elongate features along that axis).pore_value (int, default 0) – Phase ID assigned to the pore space.
solid_value (int, default 1) – Phase ID assigned to the solid matrix.
periodic (bool, default True) – Use periodic wrap-around convolution so opposite domain faces match seamlessly for periodic homogenisation cell problems.
seed (int, optional) – Random seed for deterministic generation.
- Returns:
np.ndarray – C-contiguous
int32array of shape(Nz, Ny, Nx).- Return type:
- openimpala.synthetic.overlapping_spheres(shape=(64, 64, 64), porosity=0.5, radius=6.0, *, pore_value=0, solid_value=1, periodic=True, seed=None)[source]#
Generate a 3-D Boolean-model packing of randomly overlapping solid spheres.
Sphere count is calibrated from the analytical Boolean-model relation \(\varepsilon = \exp(-N_s V_{\mathrm{sphere}} / V_{\mathrm{domain}})\) with iterative top-up so achieved porosity closely matches porosity.
- openimpala.synthetic.multiphase_electrode(shape=(64, 64, 64), pore_fraction=0.35, active_fraction=0.5, binder_fraction=0.15, *, blobiness=1.2, pore_value=0, active_value=1, binder_value=2, periodic=True, seed=None)[source]#
Generate a 3-phase composite battery electrode microstructure.
Produces an active-material backbone (active_value), surface-wetting carbon-binder domain (binder_value) concentrated along active-material interfaces, and electrolyte pore network (pore_value) matching the requested volume fractions.
- openimpala.synthetic.generate_ml_dataset(output_path, n_samples=16, shape=(32, 32, 32), *, generator='blobs', porosity_range=(0.3, 0.7), blobiness_range=(0.8, 2.0), radius_range=(3.0, 7.0), seed=42, compute_deff=True, compute_tortuosity=True, solver='auto', return_volumes=True)[source]#
Generate a labelled 3-D porous-media ML surrogate dataset on disk.
Each sample contains a binary 3-D microstructure (
0= conducting pore,1= insulating solid) alongside ground-truth OpenImpala physics labels: porosity, Cauchy–Crofton specific surface area, directional tortuosities(tau_x, tau_y, tau_z), and the symmetric3x3homogenised effective- diffusivity tensorD_eff.- Supported output formats (auto-detected from output_path suffix):
.npz— compressed NumPy archive (zero optional dependencies).h5/.hdf5— chunked HDF5 archive streamed sample-by-sample (requiresh5py).zarr— chunked Zarr group archive streamed sample-by-sample (requireszarr)
Set
return_volumes=Falsewhen generating large.h5or.zarrdatasets (e.g.10_000+3-D volumes) to stream directly to disk in constantO(Nz * Ny * Nx)host memory.- Parameters:
- Return type:
Result Dataclasses#
All result objects are frozen Python dataclasses that render structured HTML summary tables automatically in Jupyter notebooks and MyST-NB documentation.
- class openimpala.facade.VolumeFractionResult(phase_count, total_count, fraction)[source]#
Result of a volume-fraction calculation.
- class openimpala.facade.PercolationResult(percolates, active_volume_fraction, direction)[source]#
Result of a percolation check.
- class openimpala.facade.TortuosityResult(tortuosity, solver_converged, iterations, residual_norm, flux_in, flux_out, active_volume_fraction, solution_field=None, effective_diffusivity=None, plotfile_path=None)[source]#
Result of a tortuosity / multi-phase steady-state transport calculation.
- Parameters:
- class openimpala.facade.EffectiveDiffusivityResult(tensor, active_volume_fraction, solver_converged, iterations, residuals, corrector_fields=None, plotfile_paths=None)[source]#
Result of a 3-D periodic homogenisation effective-diffusivity tensor calculation.
tensoris a(3, 3)float64NumPy array ordered(x, y, z):tensor[0, 0] = D_xx,tensor[1, 1] = D_yy,tensor[2, 2] = D_zz,tensor[0, 1] = D_xy, etc.- Parameters:
- class openimpala.facade.SpecificSurfaceAreaResult(ssa, ssa_corrected, ssa_voxel, ssa_voxel_corrected, face_count, total_count, face_counts_xyz)[source]#
Result of an interfacial specific surface area calculation.
- class openimpala.facade.ConnectedComponentsResult(num_components, volumes, labels=None)[source]#
Result of 6-connected component labeling.
- class openimpala.facade.ParticleSizeDistributionResult(num_particles, mean_radius, radii, volumes, radii_voxels, volumes_voxels)[source]#
Result of equivalent-sphere particle size distribution analysis.
- class openimpala.facade.ThroughThicknessResult(direction, num_slices, profile, positions)[source]#
Result of a slice-by-slice through-thickness volume fraction profile.
Session Management & Ecosystem Protocol#
- class openimpala.Session(*, verbose=False)[source]#
Ensures AMReX
initialize()/finalize()are called exactly once and in the correct order, even when mpi4py is also in use.- Parameters:
verbose (bool, default False) – When
True(or whenOPENIMPALA_PROFILE=1is set in the environment), enable AMReX startup banners,TinyProfilertiming tables, and Arena memory summaries on session exit. Defaults toFalseso scripts and notebooks stay clean.Usage:: –
import openimpala as oi
- with oi.Session():
vf = oi.volume_fraction(data, phase=0)
- class openimpala.VolumeProtocol(*args, **kwargs)[source]#
Structural protocol for calibrated 3-D voxel volumes (e.g.
basecoat.Volume).When passed into
OpenImpalahigh-level functions withvoxel_size=None,spacing_in("m")is queried to obtain(dz, dy, dx)in SI metres. If the volume is uncalibrated (e.g.unit='voxel'),UnitCalibrationErroris raised unlessvoxel_size=...is supplied explicitly.