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:
  • data (DataInputArg)

  • phase (int)

  • max_grid_size (Union[int, str])

Return type:

VolumeFractionResult

openimpala.facade.percolation_check(data, phase, direction='x', *, max_grid_size='auto', verbose=0)[source]#

Check whether phase percolates across the domain in direction.

Parameters:
  • data (DataInputArg)

  • phase (int)

  • direction (Union[str, 'Direction'])

  • max_grid_size (Union[int, str])

  • verbose (int)

Return type:

PercolationResult

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), VoxelImage handle, 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 with D > 0 participate in 6-connected transport with harmonic-mean face conductances; unlisted phases or phases with D == 0 are insulating.

  • return_field (bool) – If True, populate result.solution_field with the solved 3-D potential field (Nz, Ny, Nx) (float64). Defaults to False to avoid host memory copies on large grids.

  • write_plotfile (bool) – If True, write an AMReX HyperCLaw-V1.1 plotfile directory under results_path (readable out-of-core via yt.load() and ParaView) and populate result.plotfile_path.

  • preconditioner (Union[str, 'PrecondType'])

  • max_grid_size (Union[int, str])

  • results_path (str)

  • verbose (int)

  • mlmg_eps (Optional[float])

  • mlmg_maxiter (Optional[int])

  • mlmg_max_coarsening_level (Optional[int])

Return type:

TortuosityResult

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 to None instead of raising PercolationError.

Parameters:
  • data (DataInputArg)

  • phase (Optional[int])

  • solver (Union[str, 'SolverType'])

  • directions (Sequence[Union[str, 'Direction']])

  • strict (bool)

  • voxel_size (Optional[VoxelSizeArg])

  • phase_diffusivities (Optional[Mapping[int, float]])

  • return_field (bool)

  • write_plotfile (bool)

  • preconditioner (Union[str, 'PrecondType'])

  • max_grid_size (Union[int, str])

  • 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, z and returns EffectiveDiffusivityResult with tensor ordered (x, y, z).

Parameters:
  • data (DataInputArg)

  • phase (Optional[int])

  • voxel_size (Optional[VoxelSizeArg])

  • phase_diffusivities (Optional[Mapping[int, float]])

  • solver (Union[str, 'SolverType'])

  • return_fields (bool)

  • write_plotfile (bool)

  • max_grid_size (Union[int, str])

  • results_path (str)

  • verbose (int)

Return type:

EffectiveDiffusivityResult

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.

Parameters:
  • data (DataInputArg)

  • phase_a (int)

  • phase_b (int)

  • voxel_size (Optional[VoxelSizeArg])

  • boundary_padding (int)

  • max_grid_size (Union[int, str])

Return type:

SpecificSurfaceAreaResult

openimpala.facade.connected_components(data, phase, *, return_labels=False, max_grid_size='auto', verbose=0)[source]#

Label 6-connected components of phase.

Parameters:
  • data (DataInputArg)

  • phase (int)

  • return_labels (bool)

  • max_grid_size (Union[int, str])

  • verbose (int)

Return type:

ConnectedComponentsResult

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:
  • data (DataInputArg)

  • phase (int)

  • voxel_size (Optional[VoxelSizeArg])

  • max_grid_size (Union[int, str])

  • verbose (int)

Return type:

ParticleSizeDistributionResult

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:
  • data (DataInputArg)

  • phase (int)

  • direction (Union[str, 'Direction'])

  • voxel_size (Optional[VoxelSizeArg])

  • max_grid_size (Union[int, str])

Return type:

ThroughThicknessResult

openimpala.facade.rev_study(data, sizes, phase=None, *, num_samples=3, voxel_size=None, solver='flexgmres', csv_path=None, max_grid_size='auto', verbose=0)[source]#

Run a Representative Elementary Volume (REV) convergence study.

Parameters:
  • data (DataInputArg)

  • sizes (Sequence[int])

  • phase (Optional[int])

  • num_samples (int)

  • voxel_size (Optional[VoxelSizeArg])

  • solver (Union[str, 'SolverType'])

  • csv_path (Optional[str])

  • max_grid_size (Union[int, str])

  • verbose (int)

Return type:

REVStudyResult

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 to pybamm.ParameterValues(...).update(params, check_already_exists=False).

When voxel_size is supplied in metres (or carried by a physical VoxelImage / CIL ImageData / OME-Zarr store), dimensional [m] keys for through-plane electrode/separator thickness and mean equivalent-sphere particle radius are also populated.

Parameters:
  • data (DataInputArg)

  • electrolyte_phase (int)

  • solid_phase (Optional[int])

  • electrode (str)

  • direction (Union[str, 'Direction'])

  • voxel_size (Optional[VoxelSizeArg])

  • solver (Union[str, 'SolverType'])

Return type:

dict[str, float]

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 / provenance schema emitted by C++ ResultsJSON.H across 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:

dict[str, Any]

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 with pixel > threshold map to solid_value (default 1) and <= threshold map to pore_value (default 0). Set dark_is_pore=False for inverted (bright-pore) images so pixel > threshold maps 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.

Parameters:
Return type:

tuple

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 range max - min <= 65535 (including all uint8, int8, uint16, and int16 X-ray CT tomograms) use an exact integer histogram with zero quantisation error, while floating-point or wide-range integer arrays use 256 linearly spaced bins.

Returns:

float – Optimal scalar threshold T such that array > T separates 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:

float

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. Set False for inverted contrast images where pores are brighter than solid.

  • nbins (int, optional) – Histogram bin count passed to calculate_otsu_threshold() (None selects exact integer bins for uint8/uint16 scans).

Returns:

  • segmented (np.ndarray) – C-contiguous int32 phase array with the same shape as array.

  • threshold (float) – Computed Otsu threshold value.

Return type:

tuple[ndarray, float]

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 a UserWarning is 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 a 2x2x2 block) are broken deterministically according to tie_break (default "lowest", which slightly biases volume fraction upward for phase 0).

    • "mean" (or "average"): block arithmetic mean for grayscale volumes prior to thresholding.

    • "nearest" (or "stride"): strided subsampling array[::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, returns coarsened_array directly.

Return type:

ndarray | tuple[ndarray, tuple[float, float, float]]

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 raises UnitCalibrationError if spatial axes lack physical length units. Defaults to None (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) where voxel_size_zyx is extracted from OME-NGFF coordinateTransformations (converted to unit when requested).

Return type:

tuple[ndarray, tuple[float, float, float] | None]

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 with ome-zarr-py, Napari, Fiji MoBIE, Bio-Formats, Neuroglancer, and dask. Passing zarr_format=3 on zarr>=3.0 writes an OME-NGFF v0.5 store on Zarr v3.

Parameters:
Return type:

Path

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.1 plotfile 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-754 float64 FAB format so yt.load() and ParaView read them identically to native C++ amrex::WriteSingleLevelPlotfile outputs.

Parameters:
Return type:

Path

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/voxel for matrix-free mlmg, ~365 B/voxel for pcg+pfmg, ~1030 B/voxel for flexgmres+pfmg, and ~1400 B/voxel with smg.

Parameters:
Return type:

dict

openimpala.facade.build_info()[source]#

Return compile-time + runtime feature flags for the installed wheel.

Return type:

dict

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:

Path

openimpala.datasets.list_datasets()[source]#

Return metadata for all built-in benchmark datasets keyed by canonical name.

Return type:

dict[str, dict[str, Any]]

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 int32 NumPy array or VoxelImage.

Parameters:
  • name (str, default 'two_phase_stack') – Dataset key or alias (see list_datasets()).

  • as_voxel_image (bool, default False) – If True, wrap the volume in an openimpala.VoxelImage (native AMReX VoxelImage when _core is active, or PureVoxelImage in pure-Python mode).

  • voxel_size (float or 3-sequence of floats, optional) – Physical voxel spacing h or (dz, dy, dx) when as_voxel_image is True.

  • max_grid_size (int or 'auto', default 'auto') – AMReX grid block size when as_voxel_image is True.

openimpala.datasets.two_phase_stack()[source]#

Return a (100, 100, 100) int32 isotropic two-phase porous medium.

Phase 1 is the percolating pore network (\(\varepsilon \approx 0.3983\)); phase 0 is the solid matrix (\(1 - \varepsilon \approx 0.6017\)).

Return type:

ndarray

openimpala.datasets.two_phase_cubic()[source]#

Return a (64, 64, 64) int32 two-phase porous medium.

Phase 1 is the percolating pore network (\(\varepsilon \approx 0.3993\)); phase 0 is the solid matrix (\(1 - \varepsilon \approx 0.6007\)).

Return type:

ndarray

openimpala.datasets.sphere_pack()[source]#

Return a (100, 100, 100) int32 regular 8-sphere benchmark volume.

Phase 0 consists of 8 non-overlapping spheres of radius \(R = 15\) voxels (\(\phi_0 \approx 0.1120\)); phase 1 is the continuous surrounding pore space (\(\varepsilon \approx 0.8880\)).

Return type:

ndarray

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 > 1 elongate 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 int32 array of shape (Nz, Ny, Nx).

Return type:

ndarray

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.

Parameters:
Return type:

ndarray

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.

Parameters:
Return type:

ndarray

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 symmetric 3x3 homogenised effective- diffusivity tensor D_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 (requires h5py)

  • .zarr — chunked Zarr group archive streamed sample-by-sample (requires zarr)

Set return_volumes=False when generating large .h5 or .zarr datasets (e.g. 10_000+ 3-D volumes) to stream directly to disk in constant O(Nz * Ny * Nx) host memory.

Parameters:
Return type:

dict[str, Any]

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.

Parameters:
class openimpala.facade.PercolationResult(percolates, active_volume_fraction, direction)[source]#

Result of a percolation check.

Parameters:
  • percolates (bool)

  • active_volume_fraction (float)

  • direction (str)

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:
  • tortuosity (float)

  • solver_converged (bool)

  • iterations (int)

  • residual_norm (float)

  • flux_in (float)

  • flux_out (float)

  • active_volume_fraction (float)

  • solution_field (ndarray | None)

  • effective_diffusivity (float | None)

  • plotfile_path (str | None)

property macmullin_number: float#

MacMullin number N_M = tau / eps_active = (D_eff / D_0)^(-1).

property bruggeman_exponent: float | None#

Fitted Bruggeman exponent b defined by D_eff / D_0 = eps_active ** b.

Returns None when active_volume_fraction is not strictly in (0, 1) or when D_eff <= 0.

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.

tensor is a (3, 3) float64 NumPy 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:
property D_eff: ndarray#

Alias for tensor (the symmetric (3, 3) effective diffusivity tensor).

property diagonal: tuple[float, float, float]#

Principal diagonal entries (D_xx, D_yy, D_zz).

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.

Parameters:
class openimpala.facade.ConnectedComponentsResult(num_components, volumes, labels=None)[source]#

Result of 6-connected component labeling.

Parameters:
class openimpala.facade.ParticleSizeDistributionResult(num_particles, mean_radius, radii, volumes, radii_voxels, volumes_voxels)[source]#

Result of equivalent-sphere particle size distribution analysis.

Parameters:
class openimpala.facade.ThroughThicknessResult(direction, num_slices, profile, positions)[source]#

Result of a slice-by-slice through-thickness volume fraction profile.

Parameters:
class openimpala.facade.REVStudyResult(sizes, samples, mean_diagonal, std_diagonal, csv_path=None)[source]#

Result of a Representative Elementary Volume (REV) convergence study.

Parameters:

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 when OPENIMPALA_PROFILE=1 is set in the environment), enable AMReX startup banners, TinyProfiler timing tables, and Arena memory summaries on session exit. Defaults to False so scripts and notebooks stay clean.

  • Usage:: –

    import openimpala as oi

    with oi.Session():

    vf = oi.volume_fraction(data, phase=0)

classmethod ensure_active()[source]#

Lazily start a process-level session if not already inside with Session():.

Return type:

None

class openimpala.VolumeProtocol(*args, **kwargs)[source]#

Structural protocol for calibrated 3-D voxel volumes (e.g. basecoat.Volume).

When passed into OpenImpala high-level functions with voxel_size=None, spacing_in("m") is queried to obtain (dz, dy, dx) in SI metres. If the volume is uncalibrated (e.g. unit='voxel'), UnitCalibrationError is raised unless voxel_size=... is supplied explicitly.

property data: ndarray#

Underlying NumPy array ordered (Nz, Ny, Nx).

property shape: Tuple[int, ...]#

Array dimensions.

property dtype: dtype#

Array element data type.

property ndim: int#

Number of array dimensions.

spacing_in(unit)[source]#

Return per-axis physical voxel spacing converted to unit (e.g. 'm').

Parameters:

unit (str)

Return type:

Tuple[float, …]

Exceptions#

class openimpala.OpenImpalaError[source]#

Base exception for all OpenImpala errors.

class openimpala.ConvergenceError[source]#

Raised when a linear solver fails to converge.

class openimpala.PercolationError[source]#

Raised when the target phase does not percolate across the domain.

class openimpala.UnitCalibrationError[source]#

Raised when a VolumeProtocol or OME-Zarr input lacks physical length calibration.