openimpala 4.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openimpala/__init__.py ADDED
@@ -0,0 +1,111 @@
1
+ """OpenImpala — Python bindings for transport-property computation on 3-D voxel images.
2
+
3
+ Two layers are provided:
4
+
5
+ * **Low-level (power-user) API** — ``openimpala.core``
6
+ Direct pybind11 wrappers around C++ classes; operates via ``VoxelImage`` handles.
7
+
8
+ * **High-level (general) API** — module-level functions
9
+ NumPy-native helpers that set up AMReX objects automatically.
10
+
11
+ Quick-start::
12
+
13
+ import openimpala as oi
14
+ import numpy as np
15
+
16
+ data = np.random.choice([0, 1], size=(32, 32, 32)).astype(np.int32)
17
+
18
+ with oi.Session():
19
+ vf = oi.volume_fraction(data, phase=0)
20
+ print(f"Volume fraction: {vf.fraction:.4f}")
21
+ """
22
+
23
+ import importlib
24
+
25
+ from importlib.metadata import version, PackageNotFoundError
26
+
27
+ try:
28
+ __version__ = version("openimpala")
29
+ except PackageNotFoundError:
30
+ try:
31
+ __version__ = version("openimpala-cuda")
32
+ except PackageNotFoundError:
33
+ __version__ = "unknown"
34
+
35
+ # Session context manager (pure Python — always available)
36
+ from .session import Session
37
+
38
+ # Custom exceptions (pure Python — always available)
39
+ from .exceptions import (
40
+ OpenImpalaError,
41
+ ConvergenceError,
42
+ PercolationError,
43
+ )
44
+
45
+
46
+ def _load_core():
47
+ """Load the _core C extension.
48
+
49
+ Repeated calls are cheap — Python caches the import.
50
+ """
51
+ return importlib.import_module("openimpala._core")
52
+
53
+
54
+ def __getattr__(name):
55
+ """Lazy-load C extension symbols on first access.
56
+
57
+ This allows ``from openimpala.cli import _build_parser`` and other
58
+ pure-Python imports to succeed without loading the compiled backend.
59
+ """
60
+ # Symbols that live in the _core C extension
61
+ _CORE_ATTRS = {
62
+ "core", "_core", "VoxelImage", "Direction", "CellType", "RawDataType",
63
+ "SolverType", "EffDiffSolverType", "PhysicsType",
64
+ }
65
+ # Symbols that live in the facade module
66
+ _FACADE_ATTRS = {
67
+ "volume_fraction", "percolation_check", "tortuosity", "estimate_memory",
68
+ "read_image",
69
+ }
70
+
71
+ if name in _CORE_ATTRS:
72
+ try:
73
+ _core = _load_core()
74
+ except ImportError:
75
+ raise AttributeError(
76
+ f"'openimpala.{name}' requires the compiled C++ backend (_core). "
77
+ f"In pure-Python mode, use the high-level API: "
78
+ f"openimpala.volume_fraction(), tortuosity(), etc."
79
+ )
80
+ if name in ("core", "_core"):
81
+ return _core
82
+ return getattr(_core, name)
83
+
84
+ if name in _FACADE_ATTRS:
85
+ from . import facade
86
+ return getattr(facade, name)
87
+
88
+ raise AttributeError(f"module 'openimpala' has no attribute {name!r}")
89
+
90
+
91
+ # Explicitly define the public API for IDEs and static analysis
92
+ __all__ = [
93
+ "__version__",
94
+ "core",
95
+ "VoxelImage",
96
+ "Direction",
97
+ "CellType",
98
+ "RawDataType",
99
+ "SolverType",
100
+ "EffDiffSolverType",
101
+ "PhysicsType",
102
+ "Session",
103
+ "OpenImpalaError",
104
+ "ConvergenceError",
105
+ "PercolationError",
106
+ "volume_fraction",
107
+ "percolation_check",
108
+ "tortuosity",
109
+ "estimate_memory",
110
+ "read_image",
111
+ ]
openimpala/_solver.py ADDED
@@ -0,0 +1,465 @@
1
+ """Pure-Python tortuosity solver using sparse matrices (SciPy / CuPy).
2
+
3
+ This module provides a drop-in replacement for the C++ HYPRE-based solver,
4
+ enabling ``pip install openimpala`` to work without any compiled extensions.
5
+ GPU acceleration is available automatically when CuPy is installed.
6
+
7
+ The algorithm matches the C++ implementation exactly:
8
+ 1. Flood-fill percolation check (6-connected BFS)
9
+ 2. 7-point stencil Laplacian with harmonic-mean face coefficients
10
+ 3. Dirichlet BCs at inlet/outlet, zero-flux Neumann on sides
11
+ 4. Sparse CG solve (CuPy on GPU, SciPy on CPU)
12
+ 5. Flux integration for D_eff, then tau = active_vf / D_eff
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import numpy as np
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Backend detection: prefer CuPy (GPU), fall back to SciPy (CPU)
21
+ # ---------------------------------------------------------------------------
22
+
23
+ _USE_CUPY = False
24
+ try:
25
+ import cupy as cp
26
+ import cupyx.scipy.sparse as cusp
27
+ import cupyx.scipy.sparse.linalg as cusp_linalg
28
+
29
+ # Verify a GPU is actually available
30
+ cp.cuda.runtime.getDeviceCount()
31
+ _USE_CUPY = True
32
+ except Exception:
33
+ cp = None
34
+
35
+ import scipy.sparse as sp
36
+ import scipy.sparse.linalg as sp_linalg
37
+ import scipy.ndimage as ndimage
38
+
39
+
40
+ def _xp():
41
+ """Return the active array module (cupy or numpy)."""
42
+ return cp if _USE_CUPY else np
43
+
44
+
45
+ def backend_name() -> str:
46
+ """Return a human-readable name for the active compute backend."""
47
+ if _USE_CUPY:
48
+ dev = cp.cuda.runtime.getDeviceProperties(cp.cuda.runtime.getDevice())
49
+ name = dev["name"].decode() if isinstance(dev["name"], bytes) else dev["name"]
50
+ return f"CuPy (GPU: {name})"
51
+ return "SciPy (CPU)"
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Volume fraction
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def volume_fraction(data: np.ndarray, phase: int = 0) -> tuple[int, int, float]:
59
+ """Return (phase_count, total_count, fraction) for *phase*."""
60
+ mask = data == phase
61
+ pc = int(np.count_nonzero(mask))
62
+ tc = int(data.size)
63
+ return pc, tc, pc / tc if tc > 0 else 0.0
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Percolation check (6-connected flood fill)
68
+ # ---------------------------------------------------------------------------
69
+
70
+ def percolation_check(
71
+ data: np.ndarray,
72
+ phase: int = 0,
73
+ direction: int = 0,
74
+ ) -> tuple[bool, float, np.ndarray]:
75
+ """Check if *phase* percolates in *direction* (0=x, 1=y, 2=z).
76
+
77
+ Returns (percolates, active_vf, active_mask).
78
+ The active_mask marks cells reachable from BOTH inlet and outlet.
79
+ """
80
+ phase_mask = data == phase
81
+
82
+ # Label connected components using 6-connectivity (faces only)
83
+ struct = ndimage.generate_binary_structure(3, 1) # 6-connected
84
+ labels, num_features = ndimage.label(phase_mask, structure=struct)
85
+
86
+ if num_features == 0:
87
+ return False, 0.0, np.zeros_like(data, dtype=np.int32)
88
+
89
+ # Find labels touching inlet face (first slice along direction)
90
+ # and outlet face (last slice along direction)
91
+ inlet_slice = [slice(None)] * 3
92
+ inlet_slice[direction] = 0
93
+ outlet_slice = [slice(None)] * 3
94
+ outlet_slice[direction] = data.shape[direction] - 1
95
+
96
+ inlet_labels = set(labels[tuple(inlet_slice)].ravel()) - {0}
97
+ outlet_labels = set(labels[tuple(outlet_slice)].ravel()) - {0}
98
+
99
+ # Active labels are those touching both inlet and outlet
100
+ active_labels = inlet_labels & outlet_labels
101
+
102
+ if not active_labels:
103
+ return False, 0.0, np.zeros_like(data, dtype=np.int32)
104
+
105
+ # Build active mask
106
+ active_mask = np.isin(labels, list(active_labels)).astype(np.int32)
107
+ active_vf = float(np.count_nonzero(active_mask)) / float(data.size)
108
+
109
+ return True, active_vf, active_mask
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Sparse matrix assembly (7-point stencil, harmonic-mean face coefficients)
114
+ # ---------------------------------------------------------------------------
115
+
116
+ def _build_laplacian(
117
+ active_mask: np.ndarray,
118
+ diff_coeff: np.ndarray,
119
+ direction: int,
120
+ dx: tuple[float, float, float],
121
+ vlo: float = 0.0,
122
+ vhi: float = 1.0,
123
+ ):
124
+ """Assemble the sparse linear system Ax = b.
125
+
126
+ Parameters
127
+ ----------
128
+ active_mask : (Nz, Ny, Nx) int32 — 1 for active cells, 0 for inactive
129
+ diff_coeff : (Nz, Ny, Nx) float — diffusion coefficient per cell
130
+ direction : 0=x, 1=y, 2=z flow direction
131
+ dx : grid spacing (dz, dy, dx) matching array axis order
132
+ vlo, vhi : Dirichlet BC values at inlet/outlet
133
+
134
+ Returns
135
+ -------
136
+ A : sparse CSR matrix (N x N)
137
+ b : RHS vector (N,)
138
+ """
139
+ shape = active_mask.shape # (Nz, Ny, Nx)
140
+ N = int(np.prod(shape))
141
+
142
+ # Flat index helper
143
+ def flat(i, j, k):
144
+ return i * shape[1] * shape[2] + j * shape[2] + k
145
+
146
+ # Pre-flatten arrays for fast indexing
147
+ mask_flat = active_mask.ravel()
148
+ diff_flat = diff_coeff.ravel()
149
+
150
+ # Strides for each axis in the flattened array
151
+ strides = [shape[1] * shape[2], shape[2], 1]
152
+
153
+ # Inverse squared grid spacing for each axis
154
+ dxinv2 = [1.0 / (dx[d] * dx[d]) for d in range(3)]
155
+
156
+ # Neighbor offsets: (axis, delta, stride)
157
+ neighbors = []
158
+ for axis in range(3):
159
+ neighbors.append((axis, -1, -strides[axis]))
160
+ neighbors.append((axis, +1, +strides[axis]))
161
+
162
+ # Build COO data
163
+ rows = []
164
+ cols = []
165
+ vals = []
166
+ rhs = np.zeros(N, dtype=np.float64)
167
+
168
+ # Vectorized assembly using NumPy
169
+ indices = np.arange(N)
170
+ i3d = np.unravel_index(indices, shape) # (iz, iy, ix) arrays
171
+
172
+ # For each cell: if inactive, diagonal=1, rhs=0
173
+ # If active but on Dirichlet boundary: diagonal=1, rhs=bc_value
174
+ # If active interior: build 7-point stencil
175
+
176
+ is_active = mask_flat == 1
177
+
178
+ # Identify Dirichlet boundary cells (inlet/outlet faces)
179
+ is_inlet = np.zeros(N, dtype=bool)
180
+ is_outlet = np.zeros(N, dtype=bool)
181
+ is_inlet[is_active] = i3d[direction][is_active] == 0
182
+ is_outlet[is_active] = i3d[direction][is_active] == shape[direction] - 1
183
+
184
+ is_dirichlet = is_inlet | is_outlet
185
+ is_interior = is_active & ~is_dirichlet
186
+
187
+ # --- Inactive cells: A_ii = 1, rhs = 0 ---
188
+ inactive_idx = indices[~is_active]
189
+ rows.append(inactive_idx)
190
+ cols.append(inactive_idx)
191
+ vals.append(np.ones(len(inactive_idx)))
192
+
193
+ # --- Dirichlet cells: A_ii = 1, rhs = bc_value ---
194
+ dirichlet_idx = indices[is_dirichlet]
195
+ rows.append(dirichlet_idx)
196
+ cols.append(dirichlet_idx)
197
+ vals.append(np.ones(len(dirichlet_idx)))
198
+ rhs[is_inlet] = vlo
199
+ rhs[is_outlet] = vhi
200
+
201
+ # --- Interior active cells: 7-point stencil ---
202
+ interior_idx = indices[is_interior]
203
+ if len(interior_idx) > 0:
204
+ diag = np.zeros(len(interior_idx), dtype=np.float64)
205
+ D_center = diff_flat[interior_idx]
206
+
207
+ for axis, delta, stride in neighbors:
208
+ nbr_idx = interior_idx + stride
209
+ coord = i3d[axis][interior_idx] + delta
210
+
211
+ # Check bounds
212
+ in_bounds = (coord >= 0) & (coord < shape[axis])
213
+
214
+ # For out-of-bounds neighbors (domain boundary), zero-flux Neumann
215
+ # means we simply don't add a coupling term.
216
+ valid = in_bounds.copy()
217
+ valid_nbr = nbr_idx[valid]
218
+
219
+ # Check neighbor is active
220
+ nbr_active = np.zeros(len(interior_idx), dtype=bool)
221
+ nbr_active[valid] = mask_flat[valid_nbr] == 1
222
+
223
+ # Compute harmonic mean face coefficient for valid+active neighbors
224
+ coupled = nbr_active
225
+ coupled_idx = interior_idx[coupled]
226
+ coupled_nbr = interior_idx[coupled] + stride
227
+ D_c = D_center[coupled]
228
+ D_n = diff_flat[coupled_nbr]
229
+
230
+ denom = D_c + D_n
231
+ # Harmonic mean: 2*D_c*D_n / (D_c + D_n), zero if denom==0
232
+ D_face = np.where(denom > 0, 2.0 * D_c * D_n / denom, 0.0)
233
+
234
+ coeff = -D_face * dxinv2[axis]
235
+
236
+ rows.append(coupled_idx)
237
+ cols.append(coupled_nbr)
238
+ vals.append(coeff)
239
+
240
+ # Accumulate diagonal (negative of off-diagonal sum)
241
+ diag[coupled] -= coeff
242
+
243
+ rows.append(interior_idx)
244
+ cols.append(interior_idx)
245
+ vals.append(diag)
246
+
247
+ # Assemble sparse matrix
248
+ all_rows = np.concatenate(rows)
249
+ all_cols = np.concatenate(cols)
250
+ all_vals = np.concatenate(vals)
251
+
252
+ A = sp.coo_matrix((all_vals, (all_rows, all_cols)), shape=(N, N)).tocsr()
253
+
254
+ return A, rhs
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # Flux computation
259
+ # ---------------------------------------------------------------------------
260
+
261
+ def _compute_flux(
262
+ solution: np.ndarray,
263
+ active_mask: np.ndarray,
264
+ diff_coeff: np.ndarray,
265
+ direction: int,
266
+ dx: tuple[float, float, float],
267
+ ) -> tuple[float, float, float]:
268
+ """Compute inlet flux, outlet flux, and D_eff from the solved potential.
269
+
270
+ Returns (flux_in, flux_out, D_eff).
271
+ """
272
+ shape = active_mask.shape # (Nz, Ny, Nx)
273
+ sol = solution.reshape(shape)
274
+
275
+ # Cross-sectional area perpendicular to flow direction
276
+ perp_axes = [a for a in range(3) if a != direction]
277
+ cross_area = dx[perp_axes[0]] * dx[perp_axes[1]]
278
+
279
+ # Domain length in flow direction
280
+ L = shape[direction] * dx[direction]
281
+
282
+ # --- Compute flux through each interior plane perpendicular to flow ---
283
+ # For plane between cell i and i+1:
284
+ # flux = sum over plane of: -D_face * (phi[i+1] - phi[i]) / dx * cell_area
285
+ n_planes = shape[direction] - 1
286
+ plane_fluxes = np.zeros(n_planes)
287
+
288
+ for p in range(n_planes):
289
+ # Build slices for left and right cells
290
+ left_sl = [slice(None)] * 3
291
+ left_sl[direction] = p
292
+ right_sl = [slice(None)] * 3
293
+ right_sl[direction] = p + 1
294
+
295
+ left_sl = tuple(left_sl)
296
+ right_sl = tuple(right_sl)
297
+
298
+ mask_l = active_mask[left_sl]
299
+ mask_r = active_mask[right_sl]
300
+ both_active = (mask_l == 1) & (mask_r == 1)
301
+
302
+ if not np.any(both_active):
303
+ continue
304
+
305
+ D_l = diff_coeff[left_sl][both_active]
306
+ D_r = diff_coeff[right_sl][both_active]
307
+ denom = D_l + D_r
308
+ D_face = np.where(denom > 0, 2.0 * D_l * D_r / denom, 0.0)
309
+
310
+ grad = (sol[right_sl][both_active] - sol[left_sl][both_active]) / dx[direction]
311
+ plane_fluxes[p] = np.sum(-D_face * grad * cross_area)
312
+
313
+ # Flux in = first plane, flux out = last plane
314
+ flux_in = plane_fluxes[0]
315
+ flux_out = plane_fluxes[-1]
316
+
317
+ # Average flux magnitude from all interior planes
318
+ nonzero_planes = plane_fluxes[plane_fluxes != 0.0]
319
+ if len(nonzero_planes) > 0:
320
+ avg_flux = float(np.mean(np.abs(nonzero_planes)))
321
+ else:
322
+ avg_flux = 0.5 * (abs(flux_in) + abs(flux_out))
323
+
324
+ # Total cross-section area of the domain
325
+ total_cross_area = 1.0
326
+ for a in perp_axes:
327
+ total_cross_area *= shape[a] * dx[a]
328
+
329
+ # Imposed gradient
330
+ vlo, vhi = 0.0, 1.0
331
+ grad_imposed = abs(vhi - vlo) / L
332
+
333
+ # D_eff = avg_flux / (A_total * grad_imposed)
334
+ if total_cross_area * grad_imposed > 0:
335
+ D_eff = avg_flux / (total_cross_area * grad_imposed)
336
+ else:
337
+ D_eff = 0.0
338
+
339
+ return float(flux_in), float(flux_out), float(D_eff)
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Main solver entry point
344
+ # ---------------------------------------------------------------------------
345
+
346
+ def solve_tortuosity(
347
+ data: np.ndarray,
348
+ phase: int = 0,
349
+ direction: int = 0,
350
+ tol: float = 1e-9,
351
+ maxiter: int = 2000,
352
+ ) -> dict:
353
+ """Compute tortuosity of *phase* in *direction*.
354
+
355
+ Parameters
356
+ ----------
357
+ data : (Nz, Ny, Nx) int32 array of phase IDs
358
+ phase : target phase ID
359
+ direction : 0=x, 1=y, 2=z (axis index in the NumPy array)
360
+ tol : solver tolerance
361
+ maxiter : max solver iterations
362
+
363
+ Returns
364
+ -------
365
+ dict with keys: tortuosity, solver_converged, iterations, residual_norm,
366
+ flux_in, flux_out, active_volume_fraction, backend
367
+ """
368
+ data = np.ascontiguousarray(data, dtype=np.int32)
369
+ if data.ndim != 3:
370
+ raise ValueError(f"Expected 3-D array, got shape {data.shape}")
371
+
372
+ shape = data.shape # (Nz, Ny, Nx)
373
+
374
+ # --- Percolation check ---
375
+ percolates, active_vf, active_mask = percolation_check(data, phase, direction)
376
+ if not percolates:
377
+ from .exceptions import PercolationError
378
+ dir_names = {0: "x", 1: "y", 2: "z"}
379
+ raise PercolationError(
380
+ f"Phase {phase} does not percolate in the {dir_names[direction]} direction. "
381
+ f"The solver cannot converge when the conducting phase is "
382
+ f"disconnected between the inlet and outlet faces."
383
+ )
384
+
385
+ # --- Build diffusion coefficient field ---
386
+ # All active cells get D=1.0, inactive get D=0.0
387
+ diff_coeff = np.where(active_mask == 1, 1.0, 0.0)
388
+
389
+ # --- Grid spacing (uniform unit grid) ---
390
+ dx = (1.0, 1.0, 1.0)
391
+
392
+ # --- Assemble sparse system ---
393
+ A_sp, rhs = _build_laplacian(active_mask, diff_coeff, direction, dx)
394
+
395
+ # --- Initial guess: linear gradient in flow direction ---
396
+ x0 = np.zeros(A_sp.shape[0], dtype=np.float64)
397
+ coords = np.arange(shape[direction], dtype=np.float64)
398
+ grad_init = coords / max(shape[direction] - 1, 1)
399
+
400
+ # Broadcast linear gradient to 3D then flatten
401
+ bcast_shape = [1, 1, 1]
402
+ bcast_shape[direction] = shape[direction]
403
+ tile_shape = list(shape)
404
+ tile_shape[direction] = 1
405
+ x0_3d = np.tile(grad_init.reshape(bcast_shape), tile_shape)
406
+ x0 = x0_3d.ravel()
407
+ # Zero out inactive cells
408
+ x0[active_mask.ravel() == 0] = 0.0
409
+
410
+ # --- Solve ---
411
+ if _USE_CUPY:
412
+ A_gpu = cusp.csr_matrix(A_sp)
413
+ rhs_gpu = cp.asarray(rhs)
414
+ x0_gpu = cp.asarray(x0)
415
+
416
+ # CuPy CG solve
417
+ solution_gpu, info = cusp_linalg.cg(A_gpu, rhs_gpu, x0=x0_gpu,
418
+ tol=tol, maxiter=maxiter)
419
+ solution = cp.asnumpy(solution_gpu)
420
+ converged = info == 0
421
+ # CuPy doesn't return iteration count directly; estimate from info
422
+ iterations = maxiter if not converged else -1 # unknown exact count
423
+ # Compute residual
424
+ res = cp.asnumpy(rhs_gpu - A_gpu @ solution_gpu)
425
+ residual_norm = float(np.linalg.norm(res) / max(np.linalg.norm(rhs), 1e-30))
426
+ else:
427
+ # SciPy CG solve with callback to count iterations
428
+ iter_count = [0]
429
+
430
+ def _callback(xk):
431
+ iter_count[0] += 1
432
+
433
+ # scipy >= 1.12 renamed tol → rtol; older versions use tol.
434
+ try:
435
+ solution, info = sp_linalg.cg(A_sp, rhs, x0=x0, rtol=tol,
436
+ maxiter=maxiter, callback=_callback)
437
+ except TypeError:
438
+ solution, info = sp_linalg.cg(A_sp, rhs, x0=x0, tol=tol,
439
+ maxiter=maxiter, callback=_callback)
440
+ converged = info == 0
441
+ iterations = iter_count[0]
442
+ res = rhs - A_sp @ solution
443
+ residual_norm = float(np.linalg.norm(res) / max(np.linalg.norm(rhs), 1e-30))
444
+
445
+ # --- Compute flux and D_eff ---
446
+ flux_in, flux_out, D_eff = _compute_flux(
447
+ solution, active_mask, diff_coeff, direction, dx,
448
+ )
449
+
450
+ # --- Tortuosity: tau = active_vf / D_eff ---
451
+ if D_eff > 0:
452
+ tau = active_vf / D_eff
453
+ else:
454
+ tau = float("inf")
455
+
456
+ return {
457
+ "tortuosity": tau,
458
+ "solver_converged": converged,
459
+ "iterations": iterations,
460
+ "residual_norm": residual_norm,
461
+ "flux_in": flux_in,
462
+ "flux_out": flux_out,
463
+ "active_volume_fraction": active_vf,
464
+ "backend": backend_name(),
465
+ }