peclet.voro 1.0.4
Device-native moving-particle Voronoi dynamics
Loading...
Searching...
No Matches
voro_bindings_tess.hpp
Go to the documentation of this file.
1
10#ifndef PECLET_VORO_BINDINGS_TESS_HPP
11#define PECLET_VORO_BINDINGS_TESS_HPP
12
24
25namespace peclet::voro::pybind {
26
27// --------------------------------------------------------------------------------------------------
28// Tessellation: the bare moving-point (power-)Voronoi tessellator, optionally SDF-clipped.
29// The engine is chosen at build() from what was set: {Voronoi, Power} x {no geometry, SdfScene}.
30// --------------------------------------------------------------------------------------------------
31template <bool W, class S>
32using MT =
34using MtVariant =
35 std::variant<MT<false, NoSdfT>, MT<true, NoSdfT>, MT<false, SceneT>, MT<true, SceneT>>;
36
37inline nb::dict repairStatsDict(const peclet::voro::RepairStats& st) {
38 nb::dict d;
39 d["flagged"] = st.pass1Raw; // cells the certificate flagged
40 d["pass1"] = st.pass1; // cells gathered in Pass 1
41 d["pass2"] = st.pass2; // cells gathered in Pass 2
42 d["rebuilt"] =
43 (st.route == peclet::voro::RepairStats::kRebuildGate); // gate routed to a full rebuild
44 d["fell_back"] = st.fellBack; // verify failed -> cold rebuild
45 d["extra"] = st.extra; // cells gathered across the verify extra-passes
46 d["surgical"] = st.surgical; // Pass-1 cells repaired surgically (no grid gather)
47 d["verify_passes"] = st.verifyPasses; // number of verify iterations run
48 d["wall_flagged"] = st.wallFlagged; // cells flagged by the SDF boundary watch
49 return d;
50}
51
52class Tess : public peclet::core::python::Releasable {
53 public:
54 Tess() = default;
55
56 void set_domain(std::array<real_t, 3> extent, std::array<real_t, 3> origin,
57 std::array<bool, 3> periodic) {
58 checkDomain("Tessellation", extent, origin, periodic);
59 L_ = extent;
60 }
61 std::array<real_t, 3> extent() const { return L_; }
62 void set_tolerance(real_t frac) {
63 if (!(frac > real_t(0)))
64 throw std::invalid_argument("voro: set_tolerance(frac) needs frac > 0.");
65 tolFrac_ = frac;
66 }
67 void set_geometry(nb::ndarray<int, nb::c_contig> node_ints,
68 nb::ndarray<real_t, nb::c_contig> node_reals, int root, real_t grad_h) {
69 scene_ = makeSceneHolder(node_ints, node_reals, root, grad_h);
70 }
71 void clear_geometry() { scene_.clear(); }
72 void set_wall_mode(const std::string& mode, real_t skin_frac) {
73 wallExact_ = parseWallMode(mode);
74 if (skin_frac < real_t(0))
75 throw std::invalid_argument("voro: set_wall_mode(skin_frac=...) needs skin_frac >= 0.");
76 wallSkinFrac_ = skin_frac;
77 }
78 void set_weights(nb::ndarray<real_t, nb::c_contig> w) {
79 if (w.ndim() != 1)
80 throw std::runtime_error("set_weights(): expected an (N,) array");
81 wHost_ = flatten1(w);
82 weighted_ = true;
83 wDirty_ = true;
84 }
86 wHost_.clear();
87 weighted_ = false;
88 wDirty_ = false;
89 }
90
91 // diagnostics: ablation switches of the repair (both certificates are complete; the gate is the
92 // "never slower than a cold build" guard) and the validity counts of the last cold build.
93 void set_local_certificate(bool on) { localCert_ = on; }
94 void set_gate(bool on) { useGate_ = on; }
95 void set_profile(bool on) {
96 profile_ = on;
97 std::visit([&](auto& mt) { mt.profile = on; }, mt_);
98 }
99 nb::dict build_report() {
100 auto r = std::visit([](auto& mt) { return mt.report(); }, mt_);
101 nb::dict d;
102 d["buried"] = r.buried;
103 d["reach_exceeded"] = r.reachExceeded;
104 d["empty"] = r.empty;
105 d["overflow"] = r.overflow;
106 d["incomplete"] = r.incomplete;
107 d["degenerate"] = r.degenerate;
108 d["over_buffer_rebuilds"] = r.overBufferRebuilds;
109 return d;
110 }
111
112 // Cold build: (re)allocate the resident tessellation for N points and build it from scratch.
113 void build(nb::ndarray<real_t, nb::c_contig> a, bool strict) {
114 std::vector<real_t> p = flatten3(a);
115 N_ = static_cast<int>(p.size() / 3);
116 if (N_ <= 0)
117 throw std::runtime_error("voro: build() needs at least one point");
118 const double boxVol = static_cast<double>(L_[0]) * L_[1] * L_[2];
119 const real_t spacing = static_cast<real_t>(std::cbrt(boxVol / N_));
120 if (weighted_ && static_cast<int>(wHost_.size()) != N_)
121 throw std::runtime_error("build(): weights (N,) must match the particle count");
122 pos_ = peclet::core::toDevice<real_t>(p, "pos");
123 if (weighted_) {
124 weight_ = peclet::core::toDevice<real_t>(wHost_, "w");
125 wDirty_ = false;
126 }
127 if (!weighted_ && !scene_.set)
128 mt_.template emplace<MT<false, NoSdfT>>();
129 else if (weighted_ && !scene_.set)
130 mt_.template emplace<MT<true, NoSdfT>>();
131 else if (!weighted_)
132 mt_.template emplace<MT<false, SceneT>>();
133 else
134 mt_.template emplace<MT<true, SceneT>>();
135 std::visit(
136 [&](auto& mt) {
137 using T = std::decay_t<decltype(mt)>;
138 mt.localCert = localCert_;
139 mt.useGate = useGate_;
140 mt.profile = profile_;
141 if constexpr (T::kHasSdf) {
142 mt.sdf = scene_.scene;
143 mt.wallExact = wallExact_;
144 mt.wallSkin = wallSkinFrac_ * spacing;
145 }
146 if constexpr (std::is_same_v<typename T::PlanePolicy, peclet::voro::Power>)
147 mt.setWeights(weight_);
148 mt.alloc(N_, L_.data(), tolFrac_ * spacing, real_t(defaults::kSkin) * spacing,
149 defaults::kSearchWindow, N_);
150 mt.rebuild(pos_);
151 },
152 mt_);
153 auto r = std::visit([](auto& mt) { return mt.report(); }, mt_);
154 // Empty power cells (`buried`) are exact results, not validity failures: counted in the
155 // report only.
156 if (r.reachExceeded > 0 || r.overflow > 0) {
157 const std::string msg =
158 "peclet.voro: the tessellation is not a guaranteed-exact partition: " +
159 std::to_string(r.reachExceeded) + " cell(s) with a search reach beyond half the box " +
160 "(min-image invalid), " + std::to_string(r.overflow) +
161 " overflowed cell(s). See diagnostics.build_report().";
162 if (strict)
163 throw std::runtime_error(msg);
164 nb::module_::import_("warnings").attr("warn")(msg);
165 }
166 }
167
168 // Incremental repair: update the resident tessellation to new positions (same N) without a full
169 // rebuild. Returns the per-step work stats.
170 nb::dict step(nb::ndarray<real_t, nb::c_contig> a) {
171 if (N_ == 0)
172 throw std::runtime_error(
173 "voro: Tessellation.step() before build() — call build(positions) first.");
174 std::vector<real_t> p = flatten3(a);
175 if (static_cast<int>(p.size() / 3) != N_)
176 throw std::runtime_error(
177 "voro: step(positions) got " + std::to_string(p.size() / 3) + " points but build() had " +
178 std::to_string(N_) +
179 " — the count is fixed by build(); call build() again to change it.");
180 pos_ = peclet::core::toDevice<real_t>(p, "pos");
181 if (weighted_ && wDirty_) { // weights changed since the last build/step: refresh in place
182 if (static_cast<int>(wHost_.size()) != N_)
183 throw std::runtime_error("step(): weights (N,) must match the particle count");
184 Kokkos::deep_copy(
185 weight_, Kokkos::View<const real_t*, Kokkos::HostSpace>(wHost_.data(), wHost_.size()));
186 wDirty_ = false;
187 }
188 auto st = std::visit([&](auto& mt) { return mt.step(pos_); }, mt_);
189 return repairStatsDict(st);
190 }
191
192 nb::ndarray<nb::numpy, real_t> get_volumes() {
193 const std::size_t N = static_cast<std::size_t>(N_);
194 DView vol = std::visit([](auto& mt) { return mt.vol; }, mt_);
195 auto v = Kokkos::subview(vol, Kokkos::make_pair(std::size_t(0), N));
196 return peclet::core::python::vector_to_ndarray(peclet::core::toVector(v), {N}, {1});
197 }
198
199 // Per-cell Voronoi neighbour (= face) count, recomputed from the resident topology store.
200 nb::ndarray<nb::numpy, int> get_neighbor_counts() {
201 using Cell =
203 const int N = N_;
204 Kokkos::View<int*, peclet::core::MemSpace> cnt("nbr", N);
205 auto st = std::visit([](auto& mt) { return mt.store; }, mt_);
206 auto C = cnt;
207 const real_t Lx = L_[0], Ly = L_[1], Lz = L_[2];
208 Kokkos::parallel_for(
209 "peclet.voro.nbrcount", Kokkos::RangePolicy<peclet::core::ExecSpace>(0, N),
210 KOKKOS_LAMBDA(int i) {
211 Cell c;
212 st.load(i, c, Lx, Ly, Lz);
213 C(i) = c.countFaces();
214 });
215 return peclet::core::python::vector_to_ndarray(peclet::core::toVector(cnt),
216 {static_cast<std::size_t>(N)}, {1});
217 }
218
219 // Rung A3: energies + forces of the RESIDENT tessellation (after build/step) on the published
220 // view — interfacial Σσ(t_i,t_j)A, wetting Σσ_s(t_i)A_wall, volume Σe_i(V_i) via a
221 // caller-supplied e'(V_i) — routed to the seed positions (and power weights). No rebuild:
222 // reevalPublish over the store with the facet-edge area-Jacobian CSR.
223 nb::dict energy_forces(nb::ndarray<int, nb::c_contig> types,
224 nb::ndarray<real_t, nb::c_contig> tension,
225 std::optional<nb::ndarray<real_t, nb::c_contig>> sigma_wall,
226 std::optional<nb::ndarray<real_t, nb::c_contig>> dEdV, real_t lloyd,
227 real_t facet_tension) {
228 if (N_ == 0)
229 throw std::runtime_error(
230 "voro: Tessellation.energy_forces() before build() — call build(positions) first.");
231 const int N = N_;
232 if ((int)types.shape(0) != N)
233 throw std::runtime_error("energy_forces(): types must be (N,)");
234 int nT = 0;
235 for (int i = 0; i < N; ++i)
236 nT = std::max(nT, types.data()[i] + 1);
237 if ((int)tension.size() != nT * nT)
238 throw std::runtime_error(
239 "energy_forces(): tension must be (nTypes, nTypes) with nTypes = max(types)+1");
240 Kokkos::View<int*, Mem> dtype("en.type", N);
241 Kokkos::deep_copy(dtype, Kokkos::View<const int*, Kokkos::HostSpace>(types.data(), N));
242 DView dten("en.tension", (size_t)nT * nT);
243 Kokkos::deep_copy(
244 dten, Kokkos::View<const real_t*, Kokkos::HostSpace>(tension.data(), (size_t)nT * nT));
245 DView dsw, dde;
246 if (sigma_wall) {
247 if ((int)sigma_wall->size() != nT)
248 throw std::runtime_error("energy_forces(): sigma_wall must be (nTypes,)");
249 dsw = DView("en.sw", nT);
250 Kokkos::deep_copy(dsw,
251 Kokkos::View<const real_t*, Kokkos::HostSpace>(sigma_wall->data(), nT));
252 }
253 if (dEdV) {
254 if ((int)dEdV->size() != N)
255 throw std::runtime_error("energy_forces(): dEdV must be (N,)");
256 dde = DView("en.dEdV", N);
257 Kokkos::deep_copy(dde, Kokkos::View<const real_t*, Kokkos::HostSpace>(dEdV->data(), N));
258 }
259 DView force("en.force", 3 * (size_t)N), forceW("en.forceW", weighted_ ? N : 0);
260 Kokkos::deep_copy(force, real_t(0));
261 if (weighted_)
262 Kokkos::deep_copy(forceW, real_t(0));
263 real_t eIf = 0, eWall = 0, eLloyd = 0, eTen = 0;
264 const real_t Larr[3] = {L_[0], L_[1], L_[2]};
265 std::visit(
266 [&](auto& mt) {
267 using T = std::decay_t<decltype(mt)>;
268 using Policy = typename T::PlanePolicy;
269 auto view = peclet::voro::reevalPublish<real_t, defaults::kMaxPlanes,
270 defaults::kMaxTriangles, Policy>(
271 mt.store, pos_, mt.vol, N, Larr, mt.wall, mt.xRef, /*withAreaGrad=*/true,
272 /*withMoments=*/lloyd != 0, weight_);
273 if (lloyd != 0)
274 eLloyd = peclet::voro::energy::lloydEnergyForce<real_t>(view, pos_, lloyd, force);
275 if (facet_tension != 0)
276 eTen = peclet::voro::energy::facetTensionEnergyForce<real_t, Policy>(
277 view, facet_tension, pos_, weight_, L_[0], force, forceW, mt.sdf);
278 eIf = peclet::voro::energy::interfaceEnergyForce<real_t, Policy>(
279 view, dtype, dten, nT, pos_, weight_, L_[0], force, forceW, mt.sdf);
280 if (dsw.extent(0) > 0)
281 eWall = peclet::voro::energy::wallEnergyForce<real_t, Policy>(
282 view, dtype, dsw, mt.sdf, pos_, weight_, L_[0], force, forceW);
283 if (dde.extent(0) > 0)
284 peclet::voro::energy::volumeGradientForce<real_t, Policy>(view, dde, pos_, weight_,
285 L_[0], force, forceW, mt.sdf);
286 },
287 mt_);
288 nb::dict d;
289 d["interface_energy"] = eIf;
290 d["wall_energy"] = eWall;
291 d["lloyd_energy"] = eLloyd;
292 d["tension_energy"] = eTen;
293 d["force"] = peclet::core::python::vector_to_ndarray(
294 peclet::core::toVector(force), {static_cast<std::size_t>(N), std::size_t(3)}, {3, 1});
295 if (weighted_)
296 d["force_w"] = peclet::core::python::vector_to_ndarray(peclet::core::toVector(forceW),
297 {static_cast<std::size_t>(N)}, {1});
298 return d;
299 }
300
301 // The face mesh of the resident tessellation (track C): reevalPublish over the store, then the
302 // reciprocal map and the owner/neighbour face records (fv/mesh.hpp). Used by FlowSolver.
304
305 // Per-cell number of resident SDF wall planes (0 everywhere without geometry).
306 nb::ndarray<nb::numpy, int> get_wall_counts() {
307 const std::size_t N = static_cast<std::size_t>(N_);
308 std::vector<int> v = std::visit(
309 [&](auto& mt) {
310 using T = std::decay_t<decltype(mt)>;
311 if constexpr (T::kHasSdf)
312 return peclet::core::toVector(mt.wall.cnt);
313 else
314 return std::vector<int>(N, 0);
315 },
316 mt_);
317 return peclet::core::python::vector_to_ndarray(std::move(v), {N}, {1});
318 }
319
320 int num_particles() const { return N_; }
321
322 // Drop every Kokkos View (teardown registry: runs before Kokkos::finalize at shutdown).
323 void release() noexcept override {
324 mt_.template emplace<MT<false, NoSdfT>>();
325 pos_ = DView{};
326 weight_ = DView{};
327 scene_.clear();
328 N_ = 0;
329 }
330
331 private:
332 std::array<real_t, 3> L_{1, 1, 1};
333 real_t tolFrac_ = defaults::kCertificateTolerance;
334 bool localCert_ = true, useGate_ = true, profile_ = false;
335 bool wallExact_ = true;
336 real_t wallSkinFrac_ = defaults::kWallSkin;
337 bool weighted_ = false, wDirty_ = false;
338 std::vector<real_t> wHost_;
339 int N_ = 0;
340 DView pos_, weight_;
341 SceneHolder scene_;
342 MtVariant mt_;
343};
344
345// The diagnostics tier of Tessellation: a view onto the owner (no state of its own).
348};
349} // namespace peclet::voro::pybind
350
351#endif // PECLET_VORO_BINDINGS_TESS_HPP
Definition voro_bindings_tess.hpp:52
std::array< real_t, 3 > extent() const
Definition voro_bindings_tess.hpp:61
nb::dict build_report()
Definition voro_bindings_tess.hpp:99
nb::ndarray< nb::numpy, real_t > get_volumes()
Definition voro_bindings_tess.hpp:192
void release() noexcept override
Definition voro_bindings_tess.hpp:323
void set_geometry(nb::ndarray< int, nb::c_contig > node_ints, nb::ndarray< real_t, nb::c_contig > node_reals, int root, real_t grad_h)
Definition voro_bindings_tess.hpp:67
nb::ndarray< nb::numpy, int > get_neighbor_counts()
Definition voro_bindings_tess.hpp:200
void set_tolerance(real_t frac)
Definition voro_bindings_tess.hpp:62
void set_gate(bool on)
Definition voro_bindings_tess.hpp:94
nb::dict energy_forces(nb::ndarray< int, nb::c_contig > types, nb::ndarray< real_t, nb::c_contig > tension, std::optional< nb::ndarray< real_t, nb::c_contig > > sigma_wall, std::optional< nb::ndarray< real_t, nb::c_contig > > dEdV, real_t lloyd, real_t facet_tension)
Definition voro_bindings_tess.hpp:223
nb::dict step(nb::ndarray< real_t, nb::c_contig > a)
Definition voro_bindings_tess.hpp:170
void set_local_certificate(bool on)
Definition voro_bindings_tess.hpp:93
void set_weights(nb::ndarray< real_t, nb::c_contig > w)
Definition voro_bindings_tess.hpp:78
void clear_weights()
Definition voro_bindings_tess.hpp:85
void clear_geometry()
Definition voro_bindings_tess.hpp:71
nb::ndarray< nb::numpy, int > get_wall_counts()
Definition voro_bindings_tess.hpp:306
void set_wall_mode(const std::string &mode, real_t skin_frac)
Definition voro_bindings_tess.hpp:72
void set_domain(std::array< real_t, 3 > extent, std::array< real_t, 3 > origin, std::array< bool, 3 > periodic)
Definition voro_bindings_tess.hpp:56
peclet::voro::fv::FaceMesh< real_t > face_mesh()
Definition voro_tessellation.cpp:8
void set_profile(bool on)
Definition voro_bindings_tess.hpp:95
void build(nb::ndarray< real_t, nb::c_contig > a, bool strict)
Definition voro_bindings_tess.hpp:113
int num_particles() const
Definition voro_bindings_tess.hpp:320
Rung A3: interfacial (surface-tension) energy between cells of different species on the published vie...
Track B, rung B1: the CENTROIDAL (Lloyd / CVT) energy on the published view.
Track C, rung C1 (Voronoi methods plan): the FACE mesh of a published tessellation — one record per g...
constexpr double kWallSkin
Definition voro_bindings_common.hpp:70
Definition voro_bindings_common.hpp:45
void checkDomain(const char *cls, std::array< real_t, 3 > extent, std::array< real_t, 3 > origin, std::array< bool, 3 > periodic)
Definition voro_bindings_common.hpp:195
nb::dict repairStatsDict(const peclet::voro::RepairStats &st)
Definition voro_bindings_tess.hpp:37
std::vector< real_t > flatten1(nb::ndarray< real_t, nb::c_contig > a)
Definition voro_bindings_common.hpp:114
std::vector< real_t > flatten3(nb::ndarray< real_t, nb::c_contig > a)
Definition voro_bindings_common.hpp:106
bool parseWallMode(const std::string &mode)
Definition voro_bindings_common.hpp:216
std::variant< MT< false, NoSdfT >, MT< true, NoSdfT >, MT< false, SceneT >, MT< true, SceneT > > MtVariant
Definition voro_bindings_tess.hpp:35
SceneHolder makeSceneHolder(nb::ndarray< int, nb::c_contig > node_ints, nb::ndarray< real_t, nb::c_contig > node_reals, int root, real_t grad_h)
Definition voro_bindings_common.hpp:152
TessellationView< Real > reevalPublish(const TopologyStore< MAXP, MAXT > &store, const Kokkos::View< Real *, peclet::core::MemSpace > &pos, const Kokkos::View< Real *, peclet::core::MemSpace > &vol, int N, const Real L[3], WallStore< Real > wall={}, Kokkos::View< Real *, peclet::core::MemSpace > xRef={}, bool withAreaGrad=false, bool withMoments=false, Kokkos::View< Real *, peclet::core::MemSpace > weight={})
Definition reeval_tessellation.hpp:55
Definition convex_cell.hpp:140
Definition repair.hpp:91
Per-step repair telemetry.
Definition repair.hpp:61
int wallFlagged
cells flagged by the SDF boundary watch (0 without an SDF)
Definition repair.hpp:70
int extra
cells gathered across the verify extra-passes
Definition repair.hpp:67
int pass1
cells gathered in Pass 1 (flagged ∪ partners ∪ skin-movers, after dilation)
Definition repair.hpp:64
int surgical
Pass-1 cells repaired surgically (Phase 4, no grid gather)
Definition repair.hpp:68
int pass2
cells gathered in Pass 2 (new face-neighbours of the movers)
Definition repair.hpp:66
bool fellBack
true if the cold-build fallback was triggered (repair did not close)
Definition repair.hpp:73
Route route
Definition repair.hpp:72
int pass1Raw
flagged count BEFORE dilation (the gate signal: pass1Raw/nProc = churn)
Definition repair.hpp:65
@ kRebuildGate
Definition repair.hpp:63
int verifyPasses
number of verify iterations run
Definition repair.hpp:69
Definition mesh.hpp:33
SceneT scene
Definition voro_bindings_common.hpp:141
void clear()
Definition voro_bindings_common.hpp:143
bool set
Definition voro_bindings_common.hpp:142
Definition voro_bindings_tess.hpp:346
Tess * t
Definition voro_bindings_tess.hpp:347
Track B, rung B1: uniform facet tension E = σ Σ_faces A_f (every interior face once) — the "roundness...
Rung A3: per-cell volume energies e_i(V_i) on the published view — target volume, log-barrier and the...
Internal helpers shared by the translation units of the peclet.voro nanobind module.
Kokkos::View< real_t *, peclet::core::MemSpace > DView
Definition voro_bindings_common.hpp:39
double real_t
Definition voro_bindings_common.hpp:38
The ONE seed-foot SDF wall chain (Voronoi methods plan, rung A3) + the wall interfacial energy on the...