pnm 1.0.3
peclet.pnm — pore-network extraction from SDF geometry (Kokkos)
Loading...
Searching...
No Matches
pnm_bindings.cpp
Go to the documentation of this file.
1
30#include <nanobind/nanobind.h>
31#include <nanobind/ndarray.h>
32#include <nanobind/stl/optional.h> // optional openness arrays, optional shape_zyx
33#include <nanobind/stl/string.h>
34#include <nanobind/stl/vector.h> // list[Pore] and the z-y-x triples
35
36#include <array>
37#include <cstddef>
38#include <cstdint>
39#include <cstdio>
40#include <cstdlib>
41#include <Kokkos_Core.hpp>
42#include <optional>
43#include <type_traits>
44#include <utility>
45#include <vector>
46
47#include "peclet/core/python/kokkos_teardown.hpp"
48#include "peclet/core/python/ndarray_interop.hpp"
49#include "pore_extraction.hpp"
50#include "sdf_reader.h"
51
52#ifdef PECLET_PNM_MPI
53#include <mpi.h>
54
56#endif
57
58namespace nb = nanobind;
59using pnm::Pore;
60
61#include "pnm_bindings_checks.hpp" // input validation of the entry points (ValueError)
62namespace chk = pnm::binding_checks;
63
64#ifdef PECLET_PNM_MPI
65// Ensure MPI_Init has been called (mirrors the flow/dem idiom); safe to call repeatedly. If WE
66// initialized MPI (no mpi4py in the driver), also finalize it at exit so mpirun sees a clean
67// shutdown; when mpi4py did the init, its own atexit hook finalizes.
68static void ensure_mpi_init() {
69 int inited = 0;
70 MPI_Initialized(&inited);
71 if (!inited) {
72 int argc = 0;
73 char** argv = nullptr;
74 MPI_Init(&argc, &argv);
75 std::atexit([]() {
76 int fin = 0;
77 MPI_Finalized(&fin);
78 if (!fin)
79 MPI_Finalize();
80 });
81 }
82}
83#endif
84
85// C-order (Nz,Ny,Nx) float SDF -> flat x-fastest vector + res = (Nx,Ny,Nz).
86static std::vector<float> to_sdf(nb::ndarray<float, nb::c_contig> a, std::array<int, 3>& res) {
87 if (a.ndim() != 3)
88 throw std::runtime_error("SDF array must be 3D (Nz,Ny,Nx)");
89 res = {(int)a.shape(2), (int)a.shape(1), (int)a.shape(0)};
90 return peclet::core::python::ndarray_to_vector<float>(nb::ndarray<>(a));
91}
92
93// C-order (Nz,Ny,Nx) double field -> flat x-fastest vector, shape-checked against the SDF's res.
94static std::vector<double> to_field(nb::ndarray<double, nb::c_contig> a,
95 const std::array<int, 3>& res, const char* name) {
96 if (a.ndim() != 3 || (int)a.shape(2) != res[0] || (int)a.shape(1) != res[1] ||
97 (int)a.shape(0) != res[2])
98 throw std::runtime_error(std::string(name) + " must be (Nz,Ny,Nx) matching the SDF");
99 return peclet::core::python::ndarray_to_vector<double>(nb::ndarray<>(a));
100}
101
102// ---- outputs: host vectors moved into capsule-owned NumPy arrays (no element-wise boxing) ----
103
104// Flat x-fastest labels of an (Nx,Ny,Nz) grid -> int32 (Nz,Ny,Nx) C-order array over the SAME
105// memory (an (Nz,Ny,Nx) C-order buffer is x-fastest, so this is a re-shape, not a transpose).
106static nb::ndarray<nb::numpy, int> labels_to_ndarray(std::vector<int>&& seg,
107 const std::array<int, 3>& res) {
108 const std::size_t nx = res[0], ny = res[1], nz = res[2];
109 if (seg.size() != nx * ny * nz)
110 throw std::runtime_error("internal: segmentation size does not match the grid");
111 return peclet::core::python::vector_to_ndarray<int>(std::move(seg), {nz, ny, nx},
112 {std::int64_t(ny * nx), std::int64_t(nx), 1});
113}
114
115// Label pairs -> (M,2) int32 array over the pair vector's own storage.
116static nb::ndarray<nb::numpy, int> pairs_to_ndarray(std::vector<std::pair<int, int>>&& v) {
117 using P = std::pair<int, int>;
118 static_assert(sizeof(P) == 2 * sizeof(int) && std::is_standard_layout_v<P>,
119 "std::pair<int,int> must be two adjacent ints to alias it as an (M,2) array");
120 const std::size_t m = v.size();
121 auto* held = new std::vector<P>(std::move(v));
122 nb::capsule owner(held, [](void* p) noexcept { delete static_cast<std::vector<P>*>(p); });
123 return nb::ndarray<nb::numpy, int>(reinterpret_cast<int*>(held->data()), {m, 2}, owner, {2, 1},
124 nb::dtype<int>(), nb::device::cpu::value, 0);
125}
126
127// Per-pore / per-throat scalars -> 1-D float64 array.
128static nb::ndarray<nb::numpy, double> doubles_to_ndarray(std::vector<double>&& v) {
129 const std::size_t n = v.size();
130 return peclet::core::python::vector_to_ndarray<double>(std::move(v), {n}, {1});
131}
132
133// Flat z-y-x-interleaved triples -> (count,3) float64 array over the vector's own storage.
134static nb::ndarray<nb::numpy, double> triples_to_ndarray(std::vector<double>&& v) {
135 const std::size_t m = v.size() / 3;
136 return peclet::core::python::vector_to_ndarray<double>(std::move(v), {m, 3}, {3, 1});
137}
138
139// The network-flow result as the documented dict (pores: list[Pore]; everything else ndarray).
140static nb::dict network_flow_dict(pnm::NetworkFlow&& net) {
141 nb::dict d;
142 d["pores"] = net.pores;
143 d["pore_pressure"] = doubles_to_ndarray(std::move(net.pore_pressure));
144 d["pore_residual"] = doubles_to_ndarray(std::move(net.pore_residual));
145 d["throats"] = pairs_to_ndarray(std::move(net.throats));
146 d["throat_flow"] = doubles_to_ndarray(std::move(net.throat_flow));
147 d["throat_area"] = doubles_to_ndarray(std::move(net.throat_area));
148 d["throat_dp"] = doubles_to_ndarray(std::move(net.throat_dp));
149 d["throat_momentum_flux_zyx"] = triples_to_ndarray(std::move(net.throat_momentum_flux_zyx));
150 d["throat_kinetic_energy_flux"] = doubles_to_ndarray(std::move(net.throat_kinetic_energy_flux));
151 d["throat_pressure_work_flux"] = doubles_to_ndarray(std::move(net.throat_pressure_work_flux));
152 d["throat_normal_zyx"] = triples_to_ndarray(std::move(net.throat_normal_zyx));
153 d["throat_centroid_zyx"] = triples_to_ndarray(std::move(net.throat_centroid_zyx));
154 d["throat_dp_mean"] = doubles_to_ndarray(std::move(net.throat_dp_mean));
155 d["pore_volume"] = doubles_to_ndarray(std::move(net.pore_volume));
156 d["pore_mean_pressure"] = doubles_to_ndarray(std::move(net.pore_mean_pressure));
157 d["pore_mean_kinetic_energy"] = doubles_to_ndarray(std::move(net.pore_mean_kinetic_energy));
158 d["pore_mean_velocity_zyx"] = triples_to_ndarray(std::move(net.pore_mean_velocity_zyx));
159 d["pore_volume_centroid_zyx"] = triples_to_ndarray(std::move(net.pore_volume_centroid_zyx));
160 return d;
161}
162
163// Common docstring tail of extract_network_flow / extract_network_flow_mpi (nanobind keeps the
164// doc POINTER, so the assembled strings below are function-local statics).
165static constexpr const char* kNetworkFlowDictDoc =
166 "\n\nReturns a dict: 'pores' (list[Pore], ordered by label: pores[k] is label k+1), "
167 "'pore_pressure' and 'pore_residual' (float64 (N,)), 'throats' ((M,2) int32 label pairs "
168 "a < b, per PATCH), 'throat_flow', 'throat_area' and 'throat_dp' (float64 (M,)).\n\n"
169 "Momentum/volume extension (per unit density; a throat is oriented throats[t,0] -> "
170 "throats[t,1] as throat_flow; every *_zyx array is (count,3) float64 with columns z, y, x): "
171 "'throat_momentum_flux_zyx' (M,3) = sum over the patch faces of o*A*u_vec*(u.n), u_vec the "
172 "face-centre velocity (normal = the MAC face value, each tangential component the mean of "
173 "the 4 nearest staggered values); 'throat_kinetic_energy_flux' (M,) = sum o*A*|u_vec|^2/2*"
174 "(u.n); 'throat_pressure_work_flux' (M,) = sum o*A*p_f*(u.n), p_f the mean of the two "
175 "adjacent cell pressures (periodic part); 'throat_normal_zyx' (M,3) = sum o*A*n / sum o*A "
176 "(oriented, NOT normalised: |n| < 1 "
177 "on a curved patch); 'throat_centroid_zyx' (M,3), open-area weighted, in the periodic image "
178 "nearest pore throats[t,0]'s peak voxel (not wrapped into the box); 'throat_dp_mean' (M,) = "
179 "throat_dp evaluated with pore_mean_pressure at the volume centroids. Per pore, over the "
180 "fluid cells (sdf > 0) of its watershed segment: 'pore_volume' (N,), 'pore_mean_pressure' "
181 "(N,) (periodic part of p, as pore_pressure), 'pore_mean_kinetic_energy' (N,) = mean "
182 "|u_c|^2/2 and 'pore_mean_velocity_zyx' (N,3) with u_c the cell-centred velocity (mean of "
183 "the cell's two faces per component), 'pore_volume_centroid_zyx' (N,3) in the image of the "
184 "pore's peak voxel.\n\n"
185 "PRECONDITION (cross-repo, not checkable here): the openness arrays must be the face "
186 "openness the velocity field was projected with. For peclet.flow's cut-cell IBM that means "
187 "the solid was set with set_solid(..., cutcell_pressure=True) — without it every openness "
188 "flow reports is 0, so every throat_flow and throat_area comes back 0; for the ghost-cell "
189 "IBM (set_ghost_projection) pass get_ox_proj()/get_oy_proj()/get_oz_proj() instead.";
190
191NB_MODULE(_pnm, m) {
192 m.attr("__doc__") =
193 "pnm — pore-network extraction from SDF geometry (Kokkos).\n\n"
194 "Arrays are (Nz,Ny,Nx) C-order and every describing triple is z-y-x with a `_zyx` suffix. "
195 "Precision: the SDF is float32 and the geometry kernels compute in float32; origin_zyx / "
196 "spacing_zyx are doubles narrowed to float32 (pore centres and radii are float32 in the "
197 "input "
198 "unit system); the network-flow MAC fields (u, v, w, p, ox, oy, oz) are float64 and their "
199 "sums are double. SDF sign: negative inside the solid, positive in the pore space.";
200 // Kokkos init + the release-then-finalize atexit hook + finalize() + execution_space: the
201 // suite-wide teardown pattern (peclet/core/python/kokkos_teardown.hpp). pnm's functions hold no
202 // Kokkos state between calls and return host-vector-backed arrays, so its registry stays empty;
203 // the atexit Kokkos::finalize is still REQUIRED on CUDA (else cudaErrorCudartUnloading at exit).
204 peclet::core::python::install(m);
205
206 // VTI reader (pure C++; sdf_reader.cpp). Returns (sdf_3d[nz,ny,nx], origin_zyx, spacing_zyx).
207 nb::class_<SDFReader>(m, "SDFReader",
208 "VTI (VTK ImageData) reader for a signed-distance-field volume. Stateless: "
209 "the class exists only to hold read_vti as a static method, not to be "
210 "instantiated — call SDFReader.read_vti(filename) directly.")
211 .def_static(
212 "read_vti",
213 [](const std::string& filename) {
214 auto* data = new SDFData(SDFReader::read_vti(filename));
215 std::size_t shape[3]{(std::size_t)data->resolution[2], (std::size_t)data->resolution[1],
216 (std::size_t)data->resolution[0]};
217 std::vector<double> org{data->origin[2], data->origin[1], data->origin[0]};
218 std::vector<double> spc{data->spacing[2], data->spacing[1], data->spacing[0]};
219 // C-contiguous (nz,ny,nx) float array referencing the reader's buffer; the capsule
220 // keeps the SDFData alive for exactly as long as Python holds the array.
221 nb::capsule owner(data, [](void* p) noexcept { delete static_cast<SDFData*>(p); });
222 nb::ndarray<nb::numpy, float> sdf_3d(data->sdf_values.data(), 3, shape, owner);
223 return nb::make_tuple(sdf_3d, org, spc);
224 },
225 "Reads a VTI (VTK ImageData) SDF volume. Returns the tuple (sdf, origin_zyx, "
226 "spacing_zyx), in that order: sdf a float32 (Nz,Ny,Nx) C-order array over the "
227 "reader's buffer (no copy), origin_zyx and spacing_zyx the z-y-x lists of the grid "
228 "origin and cell size (float64).");
229
230 nb::class_<Pore>(m, "Pore",
231 "One detected pore: a strict local maximum of the SDF over its 26-neighbourhood "
232 "(periodic in all three directions). The centre is the peak voxel's position "
233 "plus a squared-SDF-weighted sub-voxel offset over the 3x3x3 stencil, in the "
234 "unit system of origin_zyx / spacing_zyx; the radius is the SDF value at the "
235 "peak, i.e. the physical inscribed-sphere radius. All fields are float32. "
236 "The centre is exposed as three self-named scalars x, y, z (not a triple), so "
237 "no axis order is implied and no _zyx suffix applies — the documented "
238 "exception to NAMING.md 1.7.")
239 .def(nb::init<>())
240 .def("__init__", &chk::initPore, nb::arg("x"), nb::arg("y"), nb::arg("z"), nb::arg("radius"))
241 .def_rw("x", &Pore::x, "Centre x coordinate (physical units of origin_zyx / spacing_zyx).")
242 .def_rw("y", &Pore::y, "Centre y coordinate (physical units of origin_zyx / spacing_zyx).")
243 .def_rw("z", &Pore::z, "Centre z coordinate (physical units of origin_zyx / spacing_zyx).")
244 .def_rw("radius", &Pore::radius,
245 "Inscribed-sphere radius = the SDF value at the peak voxel (physical units).")
246 .def("__repr__", [](const Pore& p) {
247 char buf[128];
248 std::snprintf(buf, sizeof buf, "Pore(x=%g, y=%g, z=%g, radius=%g)", (double)p.x,
249 (double)p.y, (double)p.z, (double)p.radius);
250 return std::string(buf);
251 });
252
253 m.def(
254 "extract_pores",
255 [](nb::ndarray<float, nb::c_contig> sdf, std::vector<double> origin_zyx,
256 std::vector<double> spacing_zyx) {
257 chk::grid("extract_pores", origin_zyx, spacing_zyx);
258 std::array<int, 3> res;
259 auto v = to_sdf(sdf, res);
260 std::array<float, 3> org{(float)origin_zyx[2], (float)origin_zyx[1], (float)origin_zyx[0]};
261 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
262 (float)spacing_zyx[0]};
263 return pnm::extract_pores_k(v, res, org, spc);
264 },
265 nb::arg("sdf"), nb::arg("origin_zyx"), nb::arg("spacing_zyx"),
266 "Pore detection: every voxel with sdf > 0 that is a strict local maximum of the SDF over its "
267 "26 neighbours (periodic wrap in x, y, z; ties broken towards the higher flat index) becomes "
268 "a Pore. sdf is a float32 (Nz,Ny,Nx) C-order array; origin_zyx / spacing_zyx are the grid's "
269 "z-y-x origin and cell size (narrowed to float32). Returns the list of Pore(x, y, z, radius) "
270 "in the input unit system, in device-completion order (NOT sorted; sort by (z, y, x) for a "
271 "reproducible order). Capped at 1e6 pores.");
272
273 m.def(
274 "segment_volume",
275 [](nb::ndarray<float, nb::c_contig> sdf, std::vector<double> spacing_zyx) {
276 chk::spacingZyx("segment_volume", spacing_zyx);
277 std::array<int, 3> res;
278 auto v = to_sdf(sdf, res);
279 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
280 (float)spacing_zyx[0]};
281 return labels_to_ndarray(pnm::segment_volume_k(v, res, spc), res);
282 },
283 nb::arg("sdf"), nb::arg("spacing_zyx"),
284 "Marker-controlled watershed segmentation of the SDF grid. Returns an int32 (Nz,Ny,Nx) "
285 "C-order label array (sdf.shape; the same memory as the kernels' flat x-fastest label "
286 "vector — no copy, no reshape needed): pore voxels (sdf > 0) carry the "
287 "id of the pore basin they belong to, 1, 2, ... in first-encounter (flat-index) order of the "
288 "basin peaks — the same peaks extract_pores finds — assigned by a gradient-ascent path to "
289 "the local SDF maximum; solid voxels (sdf <= 0) carry the NEGATIVE id -1, -2, ... of their "
290 "connected solid grain (26-connected components of the deep solid, sdf < -1.5 * min "
291 "spacing, flooded outwards by a Jacobi min-label sweep), and 0 marks solid debris no grain "
292 "reached. Periodic in all three directions. spacing_zyx (the cell size per axis, in the "
293 "SDF's length units) only sets the deep-solid marker threshold.");
294
295 m.def(
296 "extract_topology",
297 [](nb::ndarray<const int, nb::c_contig> segmentation,
298 std::optional<std::vector<int>> shape_zyx) {
299 chk::topologyShape(shape_zyx);
300 std::array<int, 3> res;
301 if (segmentation.ndim() == 3) {
302 res = {(int)segmentation.shape(2), (int)segmentation.shape(1),
303 (int)segmentation.shape(0)};
304 if (shape_zyx && (shape_zyx->size() != 3 || (*shape_zyx)[0] != res[2] ||
305 (*shape_zyx)[1] != res[1] || (*shape_zyx)[2] != res[0]))
306 throw std::runtime_error("shape_zyx does not match the (Nz,Ny,Nx) segmentation");
307 } else if (segmentation.ndim() == 1) {
308 if (!shape_zyx)
309 throw std::runtime_error("a flat segmentation needs shape_zyx = (Nz, Ny, Nx)");
310 if (shape_zyx->size() != 3)
311 throw std::runtime_error("shape_zyx must be (Nz, Ny, Nx)");
312 res = {(*shape_zyx)[2], (*shape_zyx)[1], (*shape_zyx)[0]};
313 if (segmentation.size() != std::size_t(res[0]) * res[1] * res[2])
314 throw std::runtime_error("segmentation length does not match shape_zyx");
315 } else {
316 throw std::runtime_error("segmentation must be (Nz,Ny,Nx) or flat");
317 }
318 return pairs_to_ndarray(
319 pnm::extract_topology_k(segmentation.data(), segmentation.size(), res));
320 },
321 nb::arg("segmentation"), nb::arg("shape_zyx") = nb::none(),
322 "Label adjacency of a segment_volume result: the sorted, unique (a, b) pairs with a < b of "
323 "labels that share a voxel face (+x, +y, +z, periodic wrap), as an (M,2) int32 array. "
324 "segmentation is the int32 (Nz,Ny,Nx) array segment_volume returned (read in place, no "
325 "copy); a flat x-fastest label vector is accepted too, then shape_zyx = (Nz, Ny, Nx) of "
326 "the grid it was made on (= sdf.shape) is required. Rows with a label <= 0 are pore-solid "
327 "(or grain-grain / debris) contacts; the pore-to-pore throats are the rows with both "
328 "labels > 0. One row per label pair (a per-PATCH throat list, which can repeat a pair, is "
329 "what extract_network_flow returns).");
330
331 // Fused pipeline (F1): SDF uploaded once, segmentation device-resident across all three stages.
332 m.def(
333 "extract_pore_network",
334 [](nb::ndarray<float, nb::c_contig> sdf, std::vector<double> origin_zyx,
335 std::vector<double> spacing_zyx) {
336 chk::grid("extract_pore_network", origin_zyx, spacing_zyx);
337 std::array<int, 3> res;
338 auto v = to_sdf(sdf, res);
339 std::array<float, 3> org{(float)origin_zyx[2], (float)origin_zyx[1], (float)origin_zyx[0]};
340 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
341 (float)spacing_zyx[0]};
342 pnm::PoreNetwork net = pnm::extract_pore_network_k(v, res, org, spc);
343 return nb::make_tuple(net.pores, labels_to_ndarray(std::move(net.seg), res),
344 pairs_to_ndarray(std::move(net.connections)));
345 },
346 nb::arg("sdf"), nb::arg("origin_zyx"), nb::arg("spacing_zyx"),
347 "Fused extraction (SDF uploaded once, segmentation device-resident across stages): returns "
348 "the tuple (pores, segmentation, connections), in that order, each element exactly what "
349 "extract_pores, segment_volume and extract_topology return (list[Pore]; int32 (Nz,Ny,Nx) "
350 "array; (M,2) int32 array).\n\n"
351 "UNITS: everything is in the system `origin_zyx` / `spacing_zyx` and the SDF are stated in "
352 "(the VTI's own, straight from SDFReader.read_vti) — pore centres are physical coordinates "
353 "and a pore radius is the physical inscribed radius, not a voxel count. Pass "
354 "spacing_zyx = [1,1,1] and origin_zyx = [0,0,0] to work in voxels. Measured on "
355 "flow/data/packing_ring.vti: doubling the spacing, the origin and the SDF together leaves "
356 "the pore count (7199) and the throat-connection count (53020) unchanged and doubles every "
357 "radius BITWISE. One sub-voxel caveat: the centre's intra-cell offset is guarded by an "
358 "absolute `sw > 1e-6` on a squared-distance weight sum, so a near-degenerate peak's centre "
359 "can shift by a fraction of a cell (measured up to 0.37 cells) under a change of unit "
360 "system. Radii, counts and topology are unaffected.");
361
362 // Network flow: throat flow rates + pore-center pressures from a peclet.flow MAC field (the
363 // method transferred from the Voronoi PNM). Pass flow's fields transposed to (Nz,Ny,Nx):
364 // u = s.get_uf().T etc. (zero-copy view of the [x,y,z] Fortran array).
365 static const std::string kNetworkFlowDoc =
366 std::string(
367 "Pore-network FLOW data from a MAC field on the same grid as the SDF: segments the SDF, "
368 "then returns per-pore-label centers/pressures (trilinear p at the basin peak, periodic) "
369 "and per-throat flow rates (sum of openness-weighted MAC face fluxes o*u*A over the "
370 "label-interface faces; positive from the lower to the higher label). All arrays are "
371 "(Nz,Ny,Nx) C-order on the SDF grid: pass flow's fields as get_uf().T, get_p().T, "
372 "get_ox().T, ... u(i,j,k) is the -x face velocity of cell (i,j,k) (flow's MAC layout); "
373 "omit ox/oy/oz for a fully open grid. grad_p_zyx adds the macroscopic gradient along "
374 "the min-image pore-to-pore vector to throat_dp (= P_i - P_j, drives flow i->j when "
375 "positive). pore_residual is the signed flux sum over each pore's whole boundary — "
376 "~solver tolerance when u is flow's projected divergence-free field. Throats are "
377 "PER-PATCH (a connected patch of interface faces): two disjoint interfaces between the "
378 "same two pores are separate parallel throats, so the throat list can repeat a label "
379 "pair.") +
381 m.def(
382 "extract_network_flow",
383 [](nb::ndarray<float, nb::c_contig> sdf, std::vector<double> origin_zyx,
384 std::vector<double> spacing_zyx, nb::ndarray<double, nb::c_contig> u,
385 nb::ndarray<double, nb::c_contig> v, nb::ndarray<double, nb::c_contig> w,
386 nb::ndarray<double, nb::c_contig> p, std::optional<nb::ndarray<double, nb::c_contig>> ox,
387 std::optional<nb::ndarray<double, nb::c_contig>> oy,
388 std::optional<nb::ndarray<double, nb::c_contig>> oz, std::vector<double> grad_p_zyx) {
389 std::array<int, 3> res;
390 auto sv = to_sdf(sdf, res);
391 if ((bool)ox != (bool)oy || (bool)ox != (bool)oz)
392 throw std::runtime_error("pass all three openness arrays (ox,oy,oz) or none");
393 std::array<float, 3> org{(float)origin_zyx[2], (float)origin_zyx[1], (float)origin_zyx[0]};
394 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
395 (float)spacing_zyx[0]};
396 std::array<double, 3> gp{grad_p_zyx[2], grad_p_zyx[1], grad_p_zyx[0]};
398 sv, res, org, spc, to_field(u, res, "u"), to_field(v, res, "v"), to_field(w, res, "w"),
399 to_field(p, res, "p"), ox ? to_field(*ox, res, "ox") : std::vector<double>{},
400 oy ? to_field(*oy, res, "oy") : std::vector<double>{},
401 oz ? to_field(*oz, res, "oz") : std::vector<double>{}, gp);
402 return network_flow_dict(std::move(net));
403 },
404 nb::arg("sdf"), nb::arg("origin_zyx"), nb::arg("spacing_zyx"), nb::arg("u"), nb::arg("v"),
405 nb::arg("w"), nb::arg("p"), nb::arg("ox") = nb::none(), nb::arg("oy") = nb::none(),
406 nb::arg("oz") = nb::none(), nb::arg("grad_p_zyx") = std::vector<double>{0.0, 0.0, 0.0},
407 kNetworkFlowDoc.c_str());
408
409#ifdef PECLET_PNM_MPI
410 // Distributed path (built with -DPECLET_PNM_MPI=ON): the SDF is decomposed over ranks by the
411 // shared core ORB (same deterministic partition as flow/dem). Query this rank's block with
412 // mpi_block, pass the LOCAL block's SDF to extract_pore_network_mpi. Bit-exact to single-rank.
413 // Rank / size queries are mpi4py's job (MPI.COMM_WORLD.rank / .size), not this module's.
414 m.def(
415 "mpi_block",
416 [](std::vector<int> global_shape_zyx) {
417 ensure_mpi_init();
418 if (global_shape_zyx.size() != 3)
419 throw std::runtime_error("global_shape_zyx must be (Nz, Ny, Nx)");
420 chk::globalShapeZyx("mpi_block", global_shape_zyx, /*sized=*/true);
421 std::array<int, 3> gd{global_shape_zyx[2], global_shape_zyx[1], global_shape_zyx[0]};
422 std::array<int, 3> o{}, s{};
423 pnm::mpi_block_of(gd, MPI_COMM_WORLD, o, s);
424 return nb::make_tuple(nb::make_tuple(o[2], o[1], o[0]), nb::make_tuple(s[2], s[1], s[0]));
425 },
426 nb::arg("global_shape_zyx"),
427 "This rank's ORB block of the global (Nz,Ny,Nx) grid (collective; MPI_Init is called if "
428 "needed): returns the tuple (offset_zyx, shape_zyx), in that order — two int 3-tuples, the "
429 "block's first VOXEL index per axis and its voxel count per axis. offset_zyx is an integer "
430 "grid offset, NOT the physical origin_zyx the extraction functions take (that stays the "
431 "global grid's). Slice the global SDF as sdf[oz:oz+sz, oy:oy+sy, ox:ox+sx] and pass the "
432 "block to extract_pore_network_mpi / extract_network_flow_mpi.");
433 m.def(
434 "extract_pore_network_mpi",
435 [](nb::ndarray<float, nb::c_contig> sdf_local, std::vector<int> global_shape_zyx,
436 std::vector<double> origin_zyx, std::vector<double> spacing_zyx) {
437 chk::globalShapeZyx("extract_pore_network_mpi", global_shape_zyx, /*sized=*/false);
438 chk::grid("extract_pore_network_mpi", origin_zyx, spacing_zyx);
439 ensure_mpi_init();
440 std::array<int, 3> res;
441 auto v = to_sdf(sdf_local, res);
442 std::array<int, 3> gd{global_shape_zyx[2], global_shape_zyx[1], global_shape_zyx[0]};
443 std::array<int, 3> bo{}, bs{};
444 pnm::mpi_block_of(gd, MPI_COMM_WORLD, bo, bs);
445 if (res != bs)
446 throw std::runtime_error("sdf_local shape does not match this rank's mpi_block");
447 std::array<float, 3> org{(float)origin_zyx[2], (float)origin_zyx[1], (float)origin_zyx[0]};
448 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
449 (float)spacing_zyx[0]};
450 auto net = pnm::extract_pore_network_mpi(v, gd, org, spc, MPI_COMM_WORLD);
451 return nb::make_tuple(net.pores, labels_to_ndarray(std::move(net.seg), res),
452 pairs_to_ndarray(std::move(net.connections)));
453 },
454 nb::arg("sdf_local"), nb::arg("global_shape_zyx"), nb::arg("origin_zyx"),
455 nb::arg("spacing_zyx"),
456 "Distributed fused extraction (collective over MPI_COMM_WORLD). sdf_local is this rank's "
457 "ORB block (Nz,Ny,Nx C-order, from mpi_block); origin_zyx / spacing_zyx are the GLOBAL "
458 "grid's, in the SDF's length units (as for extract_pore_network). Returns the tuple "
459 "(pores, segmentation, connections), in that order: the pores "
460 "whose peak this rank owns (list[Pore]), this rank's block of the segmentation (int32 "
461 "array of sdf_local.shape, global label ids), and the GLOBAL connection list ((M,2) int32, "
462 "identical on every rank). Bit-exact to the single-rank extract_pore_network on the "
463 "gathered grid.");
464 static const std::string kNetworkFlowMpiDoc =
465 std::string(
466 "Distributed network-flow extraction (collective over MPI_COMM_WORLD): all arrays are "
467 "this rank's ORB block (Nz,Ny,Nx C-order, from mpi_block; MAC fields from a distributed "
468 "peclet.flow run on the SAME BlockDecomposer). Returns the same dict as "
469 "extract_network_flow, GLOBAL and identical on every rank.") +
471 m.def(
472 "extract_network_flow_mpi",
473 [](nb::ndarray<float, nb::c_contig> sdf_local, std::vector<int> global_shape_zyx,
474 std::vector<double> origin_zyx, std::vector<double> spacing_zyx,
475 nb::ndarray<double, nb::c_contig> u, nb::ndarray<double, nb::c_contig> v,
476 nb::ndarray<double, nb::c_contig> w, nb::ndarray<double, nb::c_contig> p,
477 std::optional<nb::ndarray<double, nb::c_contig>> ox,
478 std::optional<nb::ndarray<double, nb::c_contig>> oy,
479 std::optional<nb::ndarray<double, nb::c_contig>> oz, std::vector<double> grad_p_zyx) {
480 ensure_mpi_init();
481 std::array<int, 3> res;
482 auto sv = to_sdf(sdf_local, res);
483 std::array<int, 3> gd{global_shape_zyx[2], global_shape_zyx[1], global_shape_zyx[0]};
484 std::array<int, 3> bo{}, bs{};
485 pnm::mpi_block_of(gd, MPI_COMM_WORLD, bo, bs);
486 if (res != bs)
487 throw std::runtime_error("sdf_local shape does not match this rank's mpi_block");
488 if ((bool)ox != (bool)oy || (bool)ox != (bool)oz)
489 throw std::runtime_error("pass all three openness arrays (ox,oy,oz) or none");
490 std::array<float, 3> org{(float)origin_zyx[2], (float)origin_zyx[1], (float)origin_zyx[0]};
491 std::array<float, 3> spc{(float)spacing_zyx[2], (float)spacing_zyx[1],
492 (float)spacing_zyx[0]};
493 std::array<double, 3> gp{grad_p_zyx[2], grad_p_zyx[1], grad_p_zyx[0]};
495 sv, gd, org, spc, to_field(u, res, "u"), to_field(v, res, "v"), to_field(w, res, "w"),
496 to_field(p, res, "p"), ox ? to_field(*ox, res, "ox") : std::vector<double>{},
497 oy ? to_field(*oy, res, "oy") : std::vector<double>{},
498 oz ? to_field(*oz, res, "oz") : std::vector<double>{}, gp, MPI_COMM_WORLD);
499 return network_flow_dict(std::move(net));
500 },
501 nb::arg("sdf_local"), nb::arg("global_shape_zyx"), nb::arg("origin_zyx"),
502 nb::arg("spacing_zyx"), nb::arg("u"), nb::arg("v"), nb::arg("w"), nb::arg("p"),
503 nb::arg("ox") = nb::none(), nb::arg("oy") = nb::none(), nb::arg("oz") = nb::none(),
504 nb::arg("grad_p_zyx") = std::vector<double>{0.0, 0.0, 0.0}, kNetworkFlowMpiDoc.c_str());
505#endif
506}
static SDFData read_vti(const std::string &filename)
void grid(const char *who, const std::vector< double > &origin, const std::vector< double > &spacing)
origin_zyx + spacing_zyx of extract_pores / extract_pore_network(_mpi).
void topologyShape(const std::optional< std::vector< int > > &shape)
extract_topology's shape_zyx, when given as three values: voxel counts >= 0 whose product fits in std...
void spacingZyx(const char *who, const std::vector< double > &spacing)
spacing_zyx: the grid's cell size per axis, three values > 0 (length units).
void globalShapeZyx(const char *who, const std::vector< int > &shape, bool sized)
The global grid of the ORB decomposition: at least one voxel per axis.
void initPore(Pore *p, float x, float y, float z, float radius)
Pore(x, y, z, radius): a finite centre and a finite radius >= 0 (Pore() is all zeros).
NetworkFlow extract_network_flow_k(const std::vector< float > &sdf_h, std::array< int, 3 > resolution, std::array< float, 3 > origin, std::array< float, 3 > spacing, const std::vector< double > &u_h, const std::vector< double > &v_h, const std::vector< double > &w_h, const std::vector< double > &p_h, const std::vector< double > &ox_h, const std::vector< double > &oy_h, const std::vector< double > &oz_h, std::array< double, 3 > grad_p)
MpiPoreNetwork extract_pore_network_mpi(const std::vector< float > &sdf_local, std::array< int, 3 > gdims, std::array< float, 3 > origin, std::array< float, 3 > spacing, MPI_Comm comm)
Distributed fused extraction.
std::vector< int > segment_volume_k(const std::vector< float > &sdf_h, std::array< int, 3 > resolution, std::array< float, 3 > spacing)
std::vector< Pore > extract_pores_k(const std::vector< float > &sdf_h, std::array< int, 3 > resolution, std::array< float, 3 > origin, std::array< float, 3 > spacing)
NetworkFlow extract_network_flow_mpi(const std::vector< float > &sdf_local, std::array< int, 3 > gdims, std::array< float, 3 > origin, std::array< float, 3 > spacing, const std::vector< double > &u_h, const std::vector< double > &v_h, const std::vector< double > &w_h, const std::vector< double > &p_h, const std::vector< double > &ox_h, const std::vector< double > &oy_h, const std::vector< double > &oz_h, std::array< double, 3 > grad_p, MPI_Comm comm)
std::vector< std::pair< int, int > > extract_topology_k(const int *seg_h, std::size_t n, std::array< int, 3 > resolution)
void mpi_block_of(std::array< int, 3 > gdims, MPI_Comm comm, std::array< int, 3 > &offset, std::array< int, 3 > &size)
This rank's ORB block of the global grid (deterministic; same partition as flow/dem): offset = the bl...
PoreNetwork extract_pore_network_k(const std::vector< float > &sdf_h, std::array< int, 3 > resolution, std::array< float, 3 > origin, std::array< float, 3 > spacing)
NB_MODULE(_pnm, m)
static std::vector< float > to_sdf(nb::ndarray< float, nb::c_contig > a, std::array< int, 3 > &res)
static std::vector< double > to_field(nb::ndarray< double, nb::c_contig > a, const std::array< int, 3 > &res, const char *name)
static nb::ndarray< nb::numpy, int > pairs_to_ndarray(std::vector< std::pair< int, int > > &&v)
static nb::dict network_flow_dict(pnm::NetworkFlow &&net)
static nb::ndarray< nb::numpy, int > labels_to_ndarray(std::vector< int > &&seg, const std::array< int, 3 > &res)
static nb::ndarray< nb::numpy, double > doubles_to_ndarray(std::vector< double > &&v)
static constexpr const char * kNetworkFlowDictDoc
static nb::ndarray< nb::numpy, double > triples_to_ndarray(std::vector< double > &&v)
Input validation of the peclet.pnm Python binding (src/pnm_bindings.cpp only).
peclet.pnm — portable (Kokkos) single-rank pore-network extraction from an SDF.
peclet.pnm — distributed (MPI) pore-network extraction on the core block decomposition.
Reader for SDF / VTI geometry (interface).
float y
float z
float radius
float x
The full pore network from one extraction: pores, the per-voxel segmentation (flat),...