FML
Loading...
Searching...
No Matches
PeriodicDelaunay.h
Go to the documentation of this file.
1#ifndef MPIPERIODICDELAUNAY_HEADER
2#define MPIPERIODICDELAUNAY_HEADER
3
5#include <algorithm>
6#include <array>
7#include <cassert>
8#include <climits>
9#include <cmath>
10#include <functional>
11#include <limits>
12#include <numeric>
13#include <random>
14#include <type_traits>
15#include <vector>
16
17#include <FML/Global/Global.h>
21
22#ifndef CGAL_NDIM
23#define CGAL_NDIM 3
24#endif
25
26// save diagnostic state
27#pragma GCC diagnostic push
28// turn off the specific warning
29#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
30#pragma GCC diagnostic ignored "-Wconversion"
31#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
32#include <CGAL/Kernel/global_functions.h>
33#include <CGAL/property_map.h>
34#include <CGAL/spatial_sort.h>
35#if CGAL_NDIM == 3
36#include <CGAL/Periodic_3_Delaunay_triangulation_3.h>
37#include <CGAL/Periodic_3_Delaunay_triangulation_traits_3.h>
38#include <CGAL/Spatial_sort_traits_adapter_3.h>
39#include <CGAL/Triangulation_vertex_base_with_info_3.h>
40#elif CGAL_NDIM == 2
41#include <CGAL/Periodic_2_Delaunay_triangulation_2.h>
42#include <CGAL/Periodic_2_Delaunay_triangulation_traits_2.h>
43#include <CGAL/Spatial_sort_traits_adapter_2.h>
44#include <CGAL/Triangulation_vertex_base_with_info_2.h>
45#else
46#error "CGAL_NDIM has to be 2 or 3"
47#endif
48// turn the warnings back on
49#pragma GCC diagnostic pop
50
51namespace FML {
52
53 //========================================================================================
54 /// This namespace deals with performing triangulations (Delaunay and Voronoi)
55 //========================================================================================
56
57 namespace TRIANGULATION {
58
59 //========================================================================================
60 // CGAL aliases
61 //========================================================================================
62 typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
63#if CGAL_NDIM == 3
64 typedef CGAL::Periodic_3_Delaunay_triangulation_traits_3<K> Gt;
65 using VbDS = CGAL::Periodic_3_triangulation_ds_vertex_base_3<>;
66 using Vb = CGAL::Triangulation_vertex_base_3<Gt, VbDS>;
67 using CbDS = CGAL::Periodic_3_triangulation_ds_cell_base_3<>;
68 using Cb = CGAL::Triangulation_cell_base_3<Gt, CbDS>;
69 template <class T>
70 using VbInfo = CGAL::Triangulation_vertex_base_with_info_3<T, Gt, Vb>;
71 template <class T>
72 using TDS = CGAL::Triangulation_data_structure_3<VbInfo<T>, Cb>;
73 template <class T>
74 using PeriodicDelaunayWithInfo = CGAL::Periodic_3_Delaunay_triangulation_3<Gt, TDS<T>>;
75 using VD_FIDUCIAL = CGAL::Periodic_3_triangulation_ds_vertex_base_3<>;
76 using SpatialSortTraits = CGAL::Spatial_sort_traits_adapter_3<K, CGAL::Pointer_property_map<K::Point_3>::type>;
77#elif CGAL_NDIM == 2
78 typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2<K> Gt;
79 using Vb = CGAL::Triangulation_vertex_base_2<Gt>;
80 template <class T>
81 using VbInfo = CGAL::Triangulation_vertex_base_with_info_2<T, Gt, Vb>;
82 using Fb = CGAL::Periodic_2_triangulation_face_base_2<Gt>;
83 template <class T>
84 using TDS = CGAL::Triangulation_data_structure_2<VbInfo<T>, Fb>;
85 template <class T>
86 using PeriodicDelaunayWithInfo = CGAL::Periodic_2_Delaunay_triangulation_2<Gt, TDS<T>>;
87 using VD_FIDUCIAL = CGAL::Periodic_2_triangulation_vertex_base_2<Gt>;
88 using SpatialSortTraits = CGAL::Spatial_sort_traits_adapter_2<K, CGAL::Pointer_property_map<K::Point_2>::type>;
89#endif
90 //========================================================================================
91
92 namespace detail {
93#ifdef USE_MPI
94 /// Send sendbytes bytes to dest and receive recvbytes bytes from source. Messages are split
95 /// into chunks so that we never pass a count larger than INT_MAX to MPI
96 inline void sendrecv_bytes(const void * sendbuf,
97 size_t sendbytes,
98 int dest,
99 void * recvbuf,
100 size_t recvbytes,
101 int source) {
102 const size_t chunk = size_t(1) << 30;
103 const size_t nsend = sendbytes / chunk + (sendbytes % chunk != 0);
104 const size_t nrecv = recvbytes / chunk + (recvbytes % chunk != 0);
105 int *tag_limit = nullptr, present = 0;
106 MPI_Comm_get_attr(FML::communicator, MPI_TAG_UB, &tag_limit, &present);
107 FML::COMMUNICATION::require_count(present && tag_limit &&
108 std::max(nsend, nrecv) <= size_t(*tag_limit) + 1,
109 "[Delaunay] Chunk tags exceed MPI tag range");
110 const auto layout = FML::COMMUNICATION::checked_size_layout(
112 std::min(size_t(INT_MAX), std::vector<MPI_Request>().max_size()));
113 std::vector<MPI_Request> requests(layout.total);
114 for (size_t k = 0; k < nrecv; k++) {
115 const size_t bytes = std::min(chunk, recvbytes - k * chunk);
116 MPI_Irecv(static_cast<char *>(recvbuf) + k * chunk,
117 int(bytes),
118 MPI_BYTE,
119 source,
120 int(k),
122 &requests[k]);
123 }
124 for (size_t k = 0; k < nsend; k++) {
125 const size_t bytes = std::min(chunk, sendbytes - k * chunk);
126 MPI_Isend(const_cast<char *>(static_cast<const char *>(sendbuf)) + k * chunk,
127 int(bytes),
128 MPI_BYTE,
129 dest,
130 int(k),
132 &requests[nrecv + k]);
133 }
134 MPI_Waitall(int(requests.size()), requests.data(), MPI_STATUSES_IGNORE);
135 }
136
137 /// Send one value to dest and receive one value from source
138 template <class Q>
139 void sendrecv_value(const Q & send, int dest, Q & recv, int source) {
140 static_assert(std::is_trivially_copyable_v<Q>);
141 sendrecv_bytes(&send, sizeof(Q), dest, &recv, sizeof(Q), source);
142 }
143
144 /// MPI reduction operation that merges watershed groups
145 template <class U>
146 void merge_groups_op(void * in, void * inout, int * len, MPI_Datatype *) {
147 U * a = static_cast<U *>(in);
148 U * b = static_cast<U *>(inout);
149 for (int k = 0; k < *len; k++)
150 b[k].merge(a[k]);
151 }
152#endif
153
154 /// Does the watershed group class have a set_pos_circ(const double *) method
155 template <class U, class = void>
156 struct has_set_pos_circ : std::false_type {};
157 template <class U>
158 struct has_set_pos_circ<U, std::void_t<decltype(std::declval<U &>().set_pos_circ((const double *)nullptr))>>
159 : std::true_type {};
160
161 /// Does the watershed group class have a set_leak_quantity(double) method
162 template <class U, class = void>
163 struct has_set_leak_quantity : std::false_type {};
164 template <class U>
165 struct has_set_leak_quantity<U, std::void_t<decltype(std::declval<U &>().set_leak_quantity(0.0))>>
166 : std::true_type {};
167
168 /// Map x into [0,1)
169 inline double wrap_periodic(double x) {
170 x -= std::floor(x);
171 return x >= 1.0 ? 0.0 : x;
172 }
173 } // namespace detail
174
175 /// Fiducial assignment function for when we have info at vertices
176 /// (the fiducial choice is no info)
177 ///
178 /// @tparam VD The vertex base
179 /// @tparam The particle class
180 ///
181 /// @param[in] v Pointer to the vertex
182 /// @param[in] p Pointer to the particle
183 ///
184 template <class VD, class T>
185 void fiducial_assignment_function([[maybe_unused]] VD * v, [[maybe_unused]] T * p) {}
186
187 //====================================================================
188 ///
189 /// Create a Periodic Delaunay triangulation with particles spread
190 /// across tasks (slabs in x). We communicate a buffer of particles to the left
191 /// and right of the current task and create a periodic tessellation
192 /// with the regular particles, the boundary particles and a set of
193 /// guard particles in the rest of the box (without them the triangulation
194 /// of a slab never becomes 1-sheeted, which makes it much slower). In the end
195 /// we have the tessellation with a vertex handle to each of the regular particles
196 /// and each of the boundary particles.
197 ///
198 /// Templated on a vertex class and when creating the user can
199 /// supply a function that assigns data to the vertices
200 ///
201 /// Only available in 2D and 3D. Use define CGAL_NDIM to choose this
202 /// at compiletime
203 ///
204 /// The local particles are assumed to be inside the local domain [xmin_domain, xmax_domain)
205 ///
206 //====================================================================
207
208 template <class T, class VD = VD_FIDUCIAL>
209 class MPIPeriodicDelaunay {
210 public:
211 using PeriodicDelaunay = PeriodicDelaunayWithInfo<VD>;
212 using Point = typename PeriodicDelaunay::Point;
213 using Vertex_handle = typename PeriodicDelaunay::Vertex_handle;
214
215 private:
216 // Seed for the random numbers we use (guard points and the initial random insertion order)
217 static constexpr unsigned int random_seed = 1234;
218
219 // The CGAL tessellation structure
220 PeriodicDelaunay dt;
221
222 // The size of the buffer
223 double dx_buffer{0.0};
224
225 // Vertex handles to the regular and the boundary particles
226 std::vector<Vertex_handle> vs{};
227 std::vector<Vertex_handle> vs_boundary{};
228
229 // The boundary particles we got from the neighbor tasks
230 // The first recv_left came from the left task and the rest from the right task
231 std::vector<T> p_boundary{};
232 size_t recv_left{0};
233 size_t recv_right{0};
234
235 // Index of the local particles we sent to the left and right task
236 std::vector<size_t> send_left{};
237 std::vector<size_t> send_right{};
238
239 template <class F>
240 static Point make_point(const F * x) {
241#if CGAL_NDIM == 2
242 return Point(double(x[0]), double(x[1]));
243#elif CGAL_NDIM == 3
244 return Point(double(x[0]), double(x[1]), double(x[2]));
245#endif
246 }
247
248 /// Select which of the local particles are inside the buffer of the neighbor tasks
249 void select_boundary_particles(T * p, size_t NumPart) {
250 send_left.clear();
251 send_right.clear();
252 if (FML::NTasks == 1)
253 return;
254 for (size_t i = 0; i < NumPart; i++) {
255 const double x = double(FML::PARTICLE::GetPos(p[i])[0]);
256 if (x < FML::xmin_domain + dx_buffer)
257 send_left.push_back(i);
258 if (x > FML::xmax_domain - dx_buffer)
259 send_right.push_back(i);
260 }
261 }
262
263 public:
264 std::vector<T> & get_boundary_particles() { return p_boundary; }
265
266 double get_dx_buffer() const { return dx_buffer; }
267
268 /// Return the CGAL triangulation we have created
269 PeriodicDelaunay & get_delaunay_triangulation() { return dt; }
270 const PeriodicDelaunay & get_delaunay_triangulation() const { return dt; }
271
272 const std::vector<Vertex_handle> & get_vertex_handles_regular() const { return vs; }
273 const std::vector<Vertex_handle> & get_vertex_handles_boundary() const { return vs_boundary; }
274
275 MPIPeriodicDelaunay() = default;
276
277 /// Free all memory associated with this class
278 void free() {
279 dt.clear();
280 vs.clear();
281 vs.shrink_to_fit();
282 vs_boundary.clear();
283 vs_boundary.shrink_to_fit();
284 p_boundary.clear();
285 p_boundary.shrink_to_fit();
286 send_left.clear();
287 send_left.shrink_to_fit();
288 send_right.clear();
289 send_right.shrink_to_fit();
290 recv_left = recv_right = 0;
291 }
292
293 /// Call f(w) for all vertices w adjacent to v
294 template <class F>
295 void for_each_adjacent_vertex(Vertex_handle v, std::vector<Vertex_handle> & work, F && f) const {
296#if CGAL_NDIM == 3
297 work.clear();
298 dt.adjacent_vertices(v, std::back_inserter(work));
299 const bool one_cover = dt.is_1_cover();
300 for (auto & w : work) {
301 // If the triangulation is not 1-sheeted the neighbors can be virtual copies
302 Vertex_handle wo = one_cover ? w : dt.get_original_vertex(w);
303 if (wo != v)
304 f(wo);
305 }
306#elif CGAL_NDIM == 2
307 (void)work;
308 auto vc = dt.adjacent_vertices(v);
309 auto done = vc;
310 if (vc == nullptr)
311 return;
312 const bool one_cover = dt.is_1_cover();
313 do {
314 // If the triangulation is not 1-sheeted the neighbors can be virtual copies
315 Vertex_handle w = vc;
316 Vertex_handle wo = one_cover ? w : dt.get_original_vertex(w);
317 if (wo != v)
318 f(wo);
319 } while (++vc != done);
320#endif
321 }
322
323 /// Communicate the full particle data of the particles that are inside the buffer of the neighbor tasks
324 /// The particles we receive are stored in p_to_recv: first the ones from the left task then the ones from
325 /// the right task
326 void communicate_boundary_particles(T * p, size_t NumPart, std::vector<T> & p_to_recv) {
327 p_to_recv.clear();
328 recv_left = recv_right = 0;
329 select_boundary_particles(p, NumPart);
330#ifdef USE_MPI
331 if (FML::NTasks == 1)
332 return;
333
334 if (FML::ThisTask == 0)
335 std::cout << "[MPIPeriodicDelaunay::communicate_boundary_particles]\n";
336
337 const int LeftTask = (FML::ThisTask - 1 + FML::NTasks) % FML::NTasks;
338 const int RightTask = (FML::ThisTask + 1) % FML::NTasks;
339
340 // Pack particles to send
341 auto pack = [&](const std::vector<size_t> & index, std::vector<char> & buffer) {
343 bool valid = true;
344 for (auto i : index) {
345 const auto size = FML::PARTICLE::GetSize(p[i]);
346 valid &= size > 0;
347 if (size > 0)
348 valid &= FML::COMMUNICATION::add_count(bytes,
350 buffer.max_size());
351 }
352 FML::COMMUNICATION::require_count(valid, "[Delaunay] Serialized byte count overflow");
353 buffer.resize(size_t(bytes));
354 char * b = buffer.data();
355 for (auto i : index) {
357 b += FML::PARTICLE::GetSize(p[i]);
358 }
359 };
360 std::vector<char> buffer_send_left;
361 std::vector<char> buffer_send_right;
362 pack(send_left, buffer_send_left);
363 pack(send_right, buffer_send_right);
364
365 // Communicate how many particles and bytes to send
366 const size_t count_left = send_left.size();
367 const size_t count_right = send_right.size();
368 const size_t bytes_send_left = buffer_send_left.size();
369 const size_t bytes_send_right = buffer_send_right.size();
370 size_t bytes_recv_left = 0;
371 size_t bytes_recv_right = 0;
372 detail::sendrecv_value(count_left, LeftTask, recv_right, RightTask);
373 detail::sendrecv_value(count_right, RightTask, recv_left, LeftTask);
374 detail::sendrecv_value(bytes_send_left, LeftTask, bytes_recv_right, RightTask);
375 detail::sendrecv_value(bytes_send_right, RightTask, bytes_recv_left, LeftTask);
376
377#ifdef DEBUG_TESSELATION
378 std::cout << "Task " << FML::ThisTask << " will send " << count_left << " + " << count_right
379 << " and receive " << recv_left << " + " << recv_right << " boundary particles\n";
380#endif
381
382 // Communicate the particles
383 std::vector<char> buffer_recv_left(bytes_recv_left);
384 std::vector<char> buffer_recv_right(bytes_recv_right);
385 detail::sendrecv_bytes(buffer_send_left.data(),
386 bytes_send_left,
387 LeftTask,
388 buffer_recv_right.data(),
389 bytes_recv_right,
390 RightTask);
391 detail::sendrecv_bytes(buffer_send_right.data(),
392 bytes_send_right,
393 RightTask,
394 buffer_recv_left.data(),
395 bytes_recv_left,
396 LeftTask);
397 buffer_send_left = std::vector<char>();
398 buffer_send_right = std::vector<char>();
399
400 // Unpack
401 const auto received = FML::COMMUNICATION::checked_size_layout(
403 p_to_recv.max_size());
404 p_to_recv.resize(received.total);
405 auto unpack = [&](const std::vector<char> & buffer, size_t offset, size_t count) {
406 const char * b = buffer.data();
407 size_t processed = 0;
408 for (size_t i = 0; i < count; i++) {
409 FML::PARTICLE::AssignFromBuffer(p_to_recv[offset + i], const_cast<char *>(b));
410 const auto bytes = FML::PARTICLE::GetSize(p_to_recv[offset + i]);
411 assert_mpi(bytes > 0 && size_t(bytes) <= buffer.size() - processed,
412 "[Delaunay] Invalid deserialized particle byte count");
413 b += size_t(bytes);
414 processed += size_t(bytes);
415 }
416 assert(processed == buffer.size());
417 };
418 unpack(buffer_recv_left, 0, recv_left);
419 unpack(buffer_recv_right, recv_left, recv_right);
420#endif
421 }
422
423 /// Communicate a value for each local particle (values[i] belongs to particle i) and
424 /// return the values for the boundary particles in the same order as the boundary particles
425 /// (i.e. result[j] belongs to get_boundary_particles()[j] and get_vertex_handles_boundary()[j]).
426 /// Requires create to have been called.
427 template <class Q>
428 std::vector<Q> communicate_boundary_values(const std::vector<Q> & values) const {
429 static_assert(std::is_trivially_copyable_v<Q>, "Can only communicate trivially copyable types");
430 assert(values.size() == vs.size());
431 const auto received = FML::COMMUNICATION::checked_size_layout(
433 std::vector<Q>().max_size());
434 std::vector<Q> result(received.total);
435#ifdef USE_MPI
436 if (FML::NTasks == 1)
437 return result;
438 const int LeftTask = (FML::ThisTask - 1 + FML::NTasks) % FML::NTasks;
439 const int RightTask = (FML::ThisTask + 1) % FML::NTasks;
440 std::vector<Q> to_left(send_left.size());
441 std::vector<Q> to_right(send_right.size());
442 for (size_t k = 0; k < send_left.size(); k++)
443 to_left[k] = values[send_left[k]];
444 for (size_t k = 0; k < send_right.size(); k++)
445 to_right[k] = values[send_right[k]];
446 const size_t sl = FML::COMMUNICATION::checked_bytes(to_left.size(), sizeof(Q));
447 const size_t sr = FML::COMMUNICATION::checked_bytes(to_right.size(), sizeof(Q));
448 const size_t rl = FML::COMMUNICATION::checked_bytes(recv_left, sizeof(Q));
449 const size_t rr = FML::COMMUNICATION::checked_bytes(recv_right, sizeof(Q));
450 detail::sendrecv_bytes(to_left.data(),
451 sl,
452 LeftTask,
453 recv_right ? result.data() + recv_left : nullptr,
454 rr,
455 RightTask);
456 detail::sendrecv_bytes(to_right.data(),
457 sr,
458 RightTask,
459 recv_left ? result.data() : nullptr,
460 rl,
461 LeftTask);
462#endif
463 return result;
464 }
465
466 /// Generate guard points in the part of the box not covered by the local domain plus buffer.
467 /// We put a regular grid of points on the two edges of the covered region and the rest uniformly
468 /// in the uncovered region. They are only there to speed up the tessellation.
469 void make_random_points_outside_domain(size_t nrandom, std::vector<double> & positions_random) const {
470 positions_random.clear();
471 if (FML::NTasks == 1 or nrandom == 0)
472 return;
473
474 // The uncovered region is [x0, x0 + length] (periodic)
475 const double x0 = FML::xmax_domain + dx_buffer;
476 const double length = 1.0 - (FML::xmax_domain - FML::xmin_domain) - 2.0 * dx_buffer;
477 if (length <= 0.0)
478 return;
479
480 // ~10% of the points on the two edges
481 const int nborder = std::max(1, int(std::pow(nrandom / 10.0, 1.0 / (CGAL_NDIM - 1.0))));
482 const size_t nface = CGAL_NDIM == 2 ? size_t(nborder) : size_t(nborder) * size_t(nborder);
483 const size_t nvolume = nrandom > 2 * nface ? nrandom - 2 * nface : 0;
484 positions_random.reserve((nvolume + 2 * nface) * CGAL_NDIM);
485
486 std::mt19937_64 rng(random_seed + FML::ThisTask);
487 std::uniform_real_distribution<double> uniform(0.0, 1.0);
488
489 for (size_t i = 0; i < nvolume; i++) {
490 positions_random.push_back(detail::wrap_periodic(x0 + length * uniform(rng)));
491 for (int idim = 1; idim < CGAL_NDIM; idim++)
492 positions_random.push_back(uniform(rng));
493 }
494
495 for (const double xface : {x0, x0 + length}) {
496 for (size_t k = 0; k < nface; k++) {
497 positions_random.push_back(detail::wrap_periodic(xface));
498 positions_random.push_back((k % nborder) / double(nborder));
499 if (CGAL_NDIM == 3)
500 positions_random.push_back((k / nborder) / double(nborder));
501 }
502 }
503
504#ifdef DEBUG_TESSELATION
505 std::cout << "Task " << FML::ThisTask << " made " << nvolume << " + 2 x " << nface
506 << " guard points in [" << x0 << " , " << x0 + length << "]\n";
507#endif
508 }
509
510 /// Create the tessellation and check that it is good
511 ///
512 /// @param[in] p Pointer to the particles
513 /// @param[in] NumPart Number of local particles
514 /// @param[in] buffer_fraction Optional: what fraction of the neighboring domain(s) we include when making
515 /// the tessellation.
516 /// @param[in] random_fraction Optional: how many guard points we add (as a fraction of NumPart) outside of
517 /// the domain plus buffer (just to speed up the calculation)
518 /// @param[in] assignment_function Optional: function to tell what data to store at the vertices. Called
519 /// with a nullptr for the guard points
520 ///
521 void create(T * p,
522 size_t NumPart,
523 double buffer_fraction = 0.25,
524 double random_fraction = 0.3,
525 std::function<void(VD *, T * p)> assignment_function = fiducial_assignment_function<VD, T>) {
526
527 free();
528 if (FML::NTasks == 1 and NumPart == 0)
529 return;
530 assert_mpi(buffer_fraction >= 0.0, "buffer_fraction must be positive");
531 assert_mpi(random_fraction >= 0.0, "random_fraction must be positive");
532 if (FML::NTasks == 1)
533 random_fraction = buffer_fraction = 0.0;
534 if (buffer_fraction >= 0.5 and FML::NTasks == 2) {
535 random_fraction = 0.0;
536 buffer_fraction = 0.5;
537 }
538 if (buffer_fraction >= 1.0) {
539 buffer_fraction = 1.0 - 1e-10;
540 }
541
542 assert_mpi(FML::PARTICLE::GetNDIM(T()) == CGAL_NDIM, "Dimensions do not match");
543
544 if (FML::ThisTask == 0) {
545 std::cout << "\n";
546 std::cout << "#=====================================================\n";
547 std::cout << "#\n";
548 std::cout << "# ________ .__ \n";
549 std::cout << "# \\______ \\ ____ | | _____ ____ ____ ___.__. \n";
550 std::cout << "# | | \\_/ __ \\| | \\__ \\ / \\_/ __ < | |\n";
551 std::cout << "# | ` \\ ___/| |__/ __ \\| | \\ ___/\\___ | \n";
552 std::cout << "# /_______ /\\___ >____(____ /___| /\\___ > ____| \n";
553 std::cout << "# \\/ \\/ \\/ \\/ \\/\\/ \n";
554 std::cout << "#\n";
555 std::cout << "# Creating periodic Delaunay tessellation on " << NumPart << " parts\n";
556 std::cout << "# Buffer fraction: " << buffer_fraction << "\n";
557 std::cout << "# Random fraction: " << random_fraction << "\n";
558 std::cout << "#\n";
559 std::cout << "#=====================================================\n";
560 std::cout << "\n";
561 }
562
563 // The buffersize we communicate particles from neighbor tasks
564 dx_buffer = buffer_fraction * (FML::xmax_domain - FML::xmin_domain);
565
566 // Guard points
567 std::vector<double> positions_random;
568 make_random_points_outside_domain(size_t(NumPart * random_fraction), positions_random);
569 const size_t nrandom = positions_random.size() / CGAL_NDIM;
570
571 // Boundary particles
572 communicate_boundary_particles(p, NumPart, p_boundary);
573 const size_t nboundary = p_boundary.size();
574
575 // Total point set. The id tells us what type of point it is:
576 // id >= 0: regular point with index id, -nboundary <= id < 0: boundary point with index -id-1 and
577 // LLONG_MIN: guard point
578 const size_t npoints = NumPart + nboundary + nrandom;
579 std::vector<Point> points;
580 std::vector<long long int> id;
581 points.reserve(npoints);
582 id.reserve(npoints);
583 for (size_t i = 0; i < nrandom; i++) {
584 points.push_back(make_point(&positions_random[CGAL_NDIM * i]));
585 id.push_back(LLONG_MIN);
586 }
587 positions_random = std::vector<double>();
588 for (size_t i = 0; i < nboundary; i++) {
589 points.push_back(make_point(FML::PARTICLE::GetPos(p_boundary[i])));
590 id.push_back(-(long long int)(i)-1);
591 }
592 for (size_t i = 0; i < NumPart; i++) {
593 points.push_back(make_point(FML::PARTICLE::GetPos(p[i])));
594 id.push_back((long long int)(i));
595 }
596
597#ifdef DEBUG_TESSELATION
598 std::cout << "Task " << FML::ThisTask << " Tessellation with " << NumPart << " (part) + " << nboundary
599 << " (boundary) + " << nrandom << " (random) = " << npoints << " (total)\n";
600#endif
601
602 // Insertion order: random until the triangulation is 1-sheeted (this happens quickly and
603 // inserting in random order makes this happen fast) and then the rest along a space filling
604 // curve using the last inserted vertex as the starting point for locating the next one
605 std::vector<size_t> order(npoints);
606 std::iota(order.begin(), order.end(), size_t(0));
607 std::mt19937_64 rng(random_seed + 1000 + FML::ThisTask);
608 std::shuffle(order.begin(), order.end(), rng);
609
610 vs.assign(NumPart, Vertex_handle());
611 vs_boundary.assign(nboundary, Vertex_handle());
612 auto assign_vertex = [&](Vertex_handle v, size_t k) {
613 const long long int i = id[k];
614 if (i >= 0) {
615 vs[i] = v;
616 assignment_function(&(v->info()), &p[i]);
617 } else if (i > LLONG_MIN) {
618 vs_boundary[-i - 1] = v;
619 assignment_function(&(v->info()), &p_boundary[-i - 1]);
620 } else {
621 assignment_function(&(v->info()), nullptr);
622 }
623 };
624
625 if (FML::ThisTask == 0)
626 std::cout << "[MPIPeriodicDelaunay::create] Tessellating: 0% " << std::flush;
627 auto print_progress = [&](size_t i) {
628 if (FML::ThisTask == 0 and ((i * 10) / npoints != ((i + 1) * 10) / npoints))
629 std::cout << ((i + 1) * 10) / npoints * 10 << "% " << std::flush;
630 };
631
632 size_t ninserted = 0;
633 while (ninserted < npoints and not dt.is_1_cover()) {
634 const size_t k = order[ninserted];
635 assign_vertex(dt.insert(points[k]), k);
636 print_progress(ninserted);
637 ninserted++;
638 }
639
640 CGAL::spatial_sort(order.begin() + ninserted,
641 order.end(),
642 SpatialSortTraits(CGAL::make_property_map(points)));
643
644#if CGAL_NDIM == 3
645 typename PeriodicDelaunay::Cell_handle hint;
646#elif CGAL_NDIM == 2
647 typename PeriodicDelaunay::Face_handle hint;
648#endif
649 for (; ninserted < npoints; ninserted++) {
650 const size_t k = order[ninserted];
651 Vertex_handle v = dt.insert(points[k], hint);
652 assign_vertex(v, k);
653#if CGAL_NDIM == 3
654 hint = v->cell();
655#elif CGAL_NDIM == 2
656 hint = v->face();
657#endif
658 print_progress(ninserted);
659 }
660
661 if (FML::ThisTask == 0)
662 std::cout << " Waiting for other tasks to finish" << std::endl;
663
664#ifdef DEBUG_TESSELATION
665 assert(dt.is_valid());
666#endif
667 if (not dt.is_1_cover())
668 std::cout << "[MPIPeriodicDelaunay::create] Warning task " << FML::ThisTask
669 << ": the triangulation is not 1-sheeted (too few points / no guard points) which makes "
670 "it much slower and we cannot check if the buffer is large enough. Use "
671 "random_fraction > 0\n";
672 if (dt.number_of_vertices() != npoints)
673 std::cout << "[MPIPeriodicDelaunay::create] Warning task " << FML::ThisTask
674 << " has fewer vertices: " << dt.number_of_vertices() << " than points " << npoints
675 << " (duplicate points)\n";
676
677 long long int nbadcells = num_bad_cells();
678 FML::SumOverTasks(&nbadcells);
679 if (FML::ThisTask == 0 and nbadcells > 0)
680 std::cout << "[MPIPeriodicDelaunay::create] Warning: " << nbadcells
681 << " cells around the local particles might not be correct as they extend "
682 "outside of the buffer. Increase buffer_fraction\n";
683 }
684
685 /// Computes the voronoi volumes (area in 2D) for the regular points which we have stored vertex handles for
686 ///
687 /// @param[out] volumes List of volumes. The ith entry corresponds to the ith particle used to create the
688 /// tessellation
689 ///
690 void VoronoiVolume(std::vector<double> & volumes) const {
691 const size_t npts = vs.size();
692 volumes.resize(npts);
693
694 double totvol = 0.0;
695#ifdef USE_OMP
696#pragma omp parallel for reduction(+ : totvol)
697#endif
698 for (size_t i = 0; i < npts; i++) {
699 const double vol = voronoi_volume(vs[i]);
700 volumes[i] = vol;
701 totvol += vol;
702 }
703
704 // Communicate over tasks
705 FML::SumOverTasks(&totvol);
706
707 if (FML::ThisTask == 0)
708 std::cout << "[MPIPeriodicDelaunay::VoronoiVolume] Volume missing in the box: "
709 << (1.0 - totvol) * 100 << " %\n";
710 }
711
712 /// The volume (area in 2D) of the Voronoi cell of a vertex
713 double voronoi_volume(Vertex_handle v) const {
714#if CGAL_NDIM == 3
715 // The part of the Voronoi cell of v inside a Delaunay cell (v,a,b,c) is the union of the
716 // 6 tetrahedra (v, midpoint(v,w), circumcenter(v,w,x), circumcenter(v,a,b,c)) for w != x in {a,b,c}.
717 // Summing their signed volumes over all cells incident to v gives the volume of the Voronoi cell
718 // (also when the circumcenters are outside the cells). Coordinates are relative to v
719 using Vec = std::array<double, 3>;
720 auto det = [](const Vec & a, const Vec & b, const Vec & c) {
721 return a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) +
722 a[2] * (b[0] * c[1] - b[1] * c[0]);
723 };
724 auto sub = [](const Point & a, const Point & b) -> Vec {
725 return {a.x() - b.x(), a.y() - b.y(), a.z() - b.z()};
726 };
727 thread_local std::vector<Cell_handle> cells;
728 cells.clear();
729 dt.incident_cells(v, std::back_inserter(cells));
730 double volume = 0.0;
731 for (auto & cell : cells) {
732 const auto ptet = dt.periodic_tetrahedron(cell);
733 const Point q[4] = {dt.point(ptet[0]), dt.point(ptet[1]), dt.point(ptet[2]), dt.point(ptet[3])};
734 const int iv = cell->index(v);
735 const Point & pv = q[iv];
736 const Vec cc = sub(CGAL::circumcenter(q[0], q[1], q[2], q[3]), pv);
737 const int o[3] = {(iv + 1) % 4, (iv + 2) % 4, (iv + 3) % 4};
738 // Face circumcenters for the faces (v, o[k], o[k+1])
739 Vec cf[3];
740 for (int k = 0; k < 3; k++)
741 cf[k] = sub(CGAL::circumcenter(pv, q[o[k]], q[o[(k + 1) % 3]]), pv);
742 Vec r[3];
743 for (int k = 0; k < 3; k++)
744 r[k] = sub(q[o[k]], pv);
745 const double sign = det(r[0], r[1], r[2]) > 0.0 ? 1.0 : -1.0;
746 for (int k = 0; k < 3; k++) {
747 // Face (v, o[k], o[k+1]) with the two edges (v, o[k]) and (v, o[k+1])
748 const int k1 = (k + 1) % 3;
749 const Vec m0 = {0.5 * r[k][0], 0.5 * r[k][1], 0.5 * r[k][2]};
750 const Vec m1 = {0.5 * r[k1][0], 0.5 * r[k1][1], 0.5 * r[k1][2]};
751 volume += sign * (det(m0, cf[k], cc) - det(m1, cf[k], cc)) / 6.0;
752 }
753 }
754 return volume;
755#elif CGAL_NDIM == 2
756 // The Voronoi cell is the polygon formed by the circumcenters of the incident faces
757 // (which come in counterclockwise order). We compute the coordinates relative to v
758 auto fc = dt.incident_faces(v);
759 auto done = fc;
760 double area = 0.0;
761 double xfirst = 0.0, yfirst = 0.0, xprev = 0.0, yprev = 0.0;
762 bool first = true;
763 do {
764 typename PeriodicDelaunay::Face_handle f = fc;
765 const auto ptri = dt.periodic_triangle(f);
766 const Point a = dt.point(ptri[0]);
767 const Point b = dt.point(ptri[1]);
768 const Point c = dt.point(ptri[2]);
769 const Point cc = CGAL::circumcenter(a, b, c);
770 const Point pv = dt.point(ptri[f->index(v)]);
771 const double x = cc.x() - pv.x();
772 const double y = cc.y() - pv.y();
773 if (first) {
774 xfirst = x;
775 yfirst = y;
776 first = false;
777 } else {
778 area += xprev * y - yprev * x;
779 }
780 xprev = x;
781 yprev = y;
782 } while (++fc != done);
783 area += xprev * yfirst - yprev * xfirst;
784 return 0.5 * std::abs(area);
785#endif
786 }
787
788#if CGAL_NDIM == 3
789 using Cell_handle = typename PeriodicDelaunay::Cell_handle;
790#elif CGAL_NDIM == 2
791 using Cell_handle = typename PeriodicDelaunay::Face_handle;
792#endif
793
794 /// Check if we can trust a cell (tetrahedron in 3D, triangle in 2D): it is exactly the same as in a
795 /// tessellation of the full box if it has no guard points as vertices and its circumsphere is inside the
796 /// region covered by the domain plus buffer (so no particle we do not have can be inside it). Guard points
797 /// are identified by their position. Always true when the buffer covers the whole box. For triangulations
798 /// that are not 1-sheeted we cannot check this and return true.
799 bool cell_is_reliable(Cell_handle c) const {
800 const double width = FML::xmax_domain - FML::xmin_domain;
801 if (FML::NTasks == 1 or width + 2.0 * dx_buffer >= 1.0 or not dt.is_1_cover())
802 return true;
803 const double xhigh = FML::xmax_domain + dx_buffer;
804 const double length_guard = 1.0 - width - 2.0 * dx_buffer;
805 for (int k = 0; k <= CGAL_NDIM; k++) {
806 const double x = c->vertex(k)->point()[0];
807 if (detail::wrap_periodic(x - xhigh) <= length_guard * (1.0 + 1e-10) + 1e-14)
808 return false;
809 }
810#if CGAL_NDIM == 3
811 const auto pcell = dt.periodic_tetrahedron(c);
812 const Point q0 = dt.point(pcell[0]);
813 const Point cc = CGAL::circumcenter(q0, dt.point(pcell[1]), dt.point(pcell[2]), dt.point(pcell[3]));
814#elif CGAL_NDIM == 2
815 const auto pcell = dt.periodic_triangle(c);
816 const Point q0 = dt.point(pcell[0]);
817 const Point cc = CGAL::circumcenter(q0, dt.point(pcell[1]), dt.point(pcell[2]));
818#endif
819 const double radius = std::sqrt(CGAL::to_double(CGAL::squared_distance(cc, q0)));
820 double x = cc[0];
821 x -= std::round(x - 0.5 * (FML::xmin_domain + FML::xmax_domain));
822 return x - radius >= FML::xmin_domain - dx_buffer and x + radius <= xhigh;
823 }
824
825 /// Count the number of cells (tetrahedra in 3D, triangles in 2D) that have at least one regular particle as
826 /// a vertex and that are not reliable (see cell_is_reliable). If this is zero then the Voronoi cells of all
827 /// the regular particles are exactly the same as if we had tessellated the full box.
828 /// Regular points are identified by their position.
829 long long int num_bad_cells() const {
830 long long int nbad = 0;
831#if CGAL_NDIM == 3
832 for (auto c = dt.cells_begin(); c != dt.cells_end(); ++c) {
833#elif CGAL_NDIM == 2
834 for (auto c = dt.faces_begin(); c != dt.faces_end(); ++c) {
835#endif
836 bool has_regular = false;
837 for (int k = 0; k <= CGAL_NDIM; k++) {
838 const double x = c->vertex(k)->point()[0];
839 has_regular = has_regular or (x >= FML::xmin_domain and x < FML::xmax_domain);
840 }
841 if (has_regular and not cell_is_reliable(c))
842 nbad++;
843 }
844 return nbad;
845 }
846 };
847
848 //===============================================================================
849 // Keep track of which type of point we are adding
850 //===============================================================================
851 enum PointType : char { REGULAR_POINT, BOUNDARY_POINT, GUARD_POINT };
852
853 // Type definitions
854 using IDType = int;
855 using QuantityType = double;
856 const IDType NoWatershedID = std::numeric_limits<IDType>::max();
857 const QuantityType Infinity = std::numeric_limits<QuantityType>::infinity();
858
859 /// A link between two watershed basins: the lowest quantity at which they connect. For a pair of neighboring
860 /// particles in the two basins the link has the larger of the two quantities
861 struct WatershedLink {
862 long long int a{0};
863 long long int b{0};
864 double quantity{0.0};
865 };
866
867 namespace detail {
868 /// Keep only the lowest link for each pair (a < b)
869 inline void reduce_links(std::vector<WatershedLink> & links) {
870 std::sort(links.begin(), links.end(), [](const WatershedLink & x, const WatershedLink & y) {
871 if (x.a != y.a)
872 return x.a < y.a;
873 if (x.b != y.b)
874 return x.b < y.b;
875 return x.quantity < y.quantity;
876 });
877 links.erase(std::unique(links.begin(),
878 links.end(),
879 [](const WatershedLink & x, const WatershedLink & y) {
880 return x.a == y.a and x.b == y.b;
881 }),
882 links.end());
883 }
884 } // namespace detail
885
886 /// The vertex base for the CGAL tessellation needed for the Watershed algorithm.
887 struct VertexDataWatershed {
888 void * part_ptr{nullptr};
889 QuantityType quantity{Infinity};
890 long long int index{-1};
891 IDType WatershedID{NoWatershedID};
892 char point_type{GUARD_POINT};
893 };
894
895 //===============================================================================
896 /// In this method we take a tessellation, assign [quantity] to vertices
897 /// and walk the tessellation assigning the particles to Watershed basins:
898 /// every particle is linked to the neighbor with the smallest quantity (steepest descent)
899 /// and a basin is all the particles that end up at the same local minimum.
900 /// Ties are broken using the positions, so the result does not depend on the number of tasks.
901 /// When quantity is the density or inverse density of the particle then we get a Void or Cluster finder
902 ///
903 /// If the buffer is too small the results will not be perfect, we give warnings
904 /// when this is the case (instead of just throwing) as some times this is fine.
905 ///
906 /// @tparam T The particle class
907 /// @tparam U The watershed binning class
908 ///
909 /// @param[in] D MPIPeriodicDelaunay tessellation (already created).
910 /// @param[in] p Pointer to the particles.
911 /// @param[in] NumPart Number of local particles.
912 /// @param[in] quantity Vector with the quantity to watershed on (e.g. the density of the particles).
913 /// quantity[i] corresponds to the quantity for particle i.
914 /// @param[out] watershed_groups The result of the watershed: a list of watershed groups (only on task 0).
915 /// @param[out] links Optional: the links between the basins (index into watershed_groups), only on task 0.
916 ///
917 //===============================================================================
918
919 template <class T, class U>
920 void WatershedGeneral(MPIPeriodicDelaunay<T, VertexDataWatershed> & D,
921 T * p,
922 size_t NumPart,
923 std::vector<double> & quantity,
924 std::vector<U> & watershed_groups,
925 std::vector<WatershedLink> * links = nullptr) {
926
927 using Delaunay = MPIPeriodicDelaunay<T, VertexDataWatershed>;
928 using Vertex_handle = typename Delaunay::Vertex_handle;
929 using Point = typename Delaunay::Point;
930
931 assert_mpi(quantity.size() == NumPart, "[WatershedGeneral] quantity must have size NumPart");
932 const auto & vs = D.get_vertex_handles_regular();
933 const auto & vs_boundary = D.get_vertex_handles_boundary();
934 assert_mpi(vs.size() == NumPart, "[WatershedGeneral] The tessellation was not made with these particles");
935 const size_t nboundary = vs_boundary.size();
936
937 // Assign quantity to the regular and boundary vertices
938 for (size_t i = 0; i < NumPart; i++) {
939 auto & info = vs[i]->info();
940 info.quantity = quantity[i];
941 info.point_type = REGULAR_POINT;
942 info.index = (long long int)(i);
943 info.WatershedID = NoWatershedID;
944 }
945 const std::vector<double> quantity_boundary = D.communicate_boundary_values(quantity);
946 for (size_t j = 0; j < nboundary; j++) {
947 auto & info = vs_boundary[j]->info();
948 info.quantity = quantity_boundary[j];
949 info.point_type = BOUNDARY_POINT;
950 info.index = (long long int)(NumPart + j);
951 info.WatershedID = NoWatershedID;
952 }
953
954 // Ordering of the vertices: by quantity and then by position to break ties
955 auto lower = [](Vertex_handle a, Vertex_handle b) {
956 const auto qa = a->info().quantity;
957 const auto qb = b->info().quantity;
958 if (qa != qb)
959 return qa < qb;
960 const auto & pa = a->point();
961 const auto & pb = b->point();
962 for (int idim = 0; idim < CGAL_NDIM; idim++)
963 if (pa[idim] != pb[idim])
964 return pa[idim] < pb[idim];
965 return false;
966 };
967
968 // For each regular particle find the neighbor with the lowest quantity (the particle
969 // itself if its a local minimum). Index i < NumPart is a regular particle, i >= NumPart a boundary particle
970 std::vector<long long int> parent(NumPart);
971 std::vector<Vertex_handle> work;
972 for (size_t i = 0; i < NumPart; i++) {
973 Vertex_handle best = vs[i];
974 D.for_each_adjacent_vertex(vs[i], work, [&](Vertex_handle w) {
975 if (w->info().point_type != GUARD_POINT and lower(w, best))
976 best = w;
977 });
978 parent[i] = best->info().index;
979 }
980
981 // Find the minima and give them an ID that is unique across tasks
982 std::vector<size_t> minima;
983 for (size_t i = 0; i < NumPart; i++)
984 if (parent[i] == (long long int)(i))
985 minima.push_back(i);
986 std::vector<long long int> nminima_per_task(FML::NTasks, 0);
987 nminima_per_task[FML::ThisTask] = (long long int)(minima.size());
988#ifdef USE_MPI
989 MPI_Allreduce(MPI_IN_PLACE,
990 nminima_per_task.data(),
992 MPI_LONG_LONG,
993 MPI_SUM,
995#endif
997 std::vector<FML::COMMUNICATION::Count>(nminima_per_task.begin(), nminima_per_task.end()),
998 size_t(LLONG_MAX));
999 long long int id_start = 0;
1000 for (int i = 0; i < FML::ThisTask; i++)
1001 id_start += nminima_per_task[i];
1002 long long int ntotal_minima_ll = 0;
1003 for (int i = 0; i < FML::NTasks; i++)
1004 ntotal_minima_ll += nminima_per_task[i];
1005 assert_mpi(ntotal_minima_ll < (long long int)(NoWatershedID), "[WatershedGeneral] Too many minima");
1006 const size_t ntotal_minima = size_t(ntotal_minima_ll);
1007
1008 if (FML::ThisTask == 0)
1009 std::cout << "[WatershedGeneral] We found " << ntotal_minima << " minimum points\n";
1010
1011 // Labels for the regular and boundary particles
1012 std::vector<IDType> label(NumPart + nboundary, NoWatershedID);
1013 for (size_t k = 0; k < minima.size(); k++)
1014 label[minima[k]] = IDType(id_start + (long long int)(k));
1015
1016 // Follow the parent links until we reach a particle with a label. If we end up at a boundary
1017 // particle we don't have the label for yet we have to wait until we get it from the neighbor task
1018 std::vector<char> stuck;
1019 std::vector<long long int> path;
1020 auto assign_labels = [&]() -> size_t {
1021 stuck.assign(NumPart, 0);
1022 size_t nassigned = 0;
1023 for (size_t i = 0; i < NumPart; i++) {
1024 if (label[i] != NoWatershedID or stuck[i])
1025 continue;
1026 path.clear();
1027 long long int j = (long long int)(i);
1028 while (j < (long long int)(NumPart) and label[j] == NoWatershedID and not stuck[j]) {
1029 path.push_back(j);
1030 j = parent[j];
1031 }
1032 const bool found = (j >= (long long int)(NumPart) or not stuck[j]) and label[j] != NoWatershedID;
1033 for (auto k : path) {
1034 if (found)
1035 label[k] = label[j];
1036 else
1037 stuck[k] = 1;
1038 }
1039 if (found)
1040 nassigned += path.size();
1041 }
1042 return nassigned;
1043 };
1044 assign_labels();
1045
1046 // Exchange labels of the boundary particles with the neighbor tasks until no more particles get assigned
1047 if (FML::NTasks > 1) {
1048 const int max_iterations = 1000;
1049 int iteration = 0;
1050 for (; iteration < max_iterations; iteration++) {
1051 const std::vector<IDType> label_regular(label.begin(), label.begin() + NumPart);
1052 const std::vector<IDType> label_boundary = D.communicate_boundary_values(label_regular);
1053 std::copy(label_boundary.begin(), label_boundary.end(), label.begin() + NumPart);
1054 long long int nassigned = (long long int)(assign_labels());
1055 FML::SumOverTasks(&nassigned);
1056 if (nassigned == 0)
1057 break;
1058 }
1059#ifdef DEBUG_TESSELATION
1060 if (FML::ThisTask == 0)
1061 std::cout << "[WatershedGeneral] Labels converged after " << iteration << " exchanges\n";
1062#endif
1063 }
1064
1065 // The leak quantity of each basin (as in ZOBOV): the lowest quantity at which the basin links to a
1066 // neighboring basin. A link between two neighboring particles in different basins has the larger
1067 // of the two quantities. Pairs that cross tasks are seen by the task that owns one of the particles
1068 std::vector<double> leak_quantity(ntotal_minima, std::numeric_limits<double>::infinity());
1069 std::vector<WatershedLink> local_links;
1070 for (size_t i = 0; i < NumPart; i++) {
1071 const IDType a = label[i];
1072 if (a == NoWatershedID)
1073 continue;
1074 const double qi = vs[i]->info().quantity;
1075 D.for_each_adjacent_vertex(vs[i], work, [&](Vertex_handle w) {
1076 if (w->info().point_type == GUARD_POINT)
1077 return;
1078 const IDType b = label[w->info().index];
1079 if (b == NoWatershedID or b == a)
1080 return;
1081 const double link = std::max(qi, double(w->info().quantity));
1082 leak_quantity[a] = std::min(leak_quantity[a], link);
1083 leak_quantity[b] = std::min(leak_quantity[b], link);
1084 if (links)
1085 local_links.push_back({std::min(a, b), std::max(a, b), link});
1086 });
1087 // Keep only the lowest link for each pair of basins now and then to save memory
1088 if (links and local_links.size() > 4 * ntotal_minima + 1000000)
1089 detail::reduce_links(local_links);
1090 }
1091 if (links) {
1092 detail::reduce_links(local_links);
1093 // Gather on task 0 (where the groups are)
1094 links->clear();
1095#ifdef USE_MPI
1096 if (FML::NTasks > 1) {
1097 *links = FML::COMMUNICATION::gather_records_checked(local_links);
1098
1099 if (FML::ThisTask == 0)
1100 detail::reduce_links(*links);
1101 } else {
1102 *links = std::move(local_links);
1103 }
1104#else
1105 *links = std::move(local_links);
1106#endif
1107 }
1108#ifdef USE_MPI
1109 for (size_t offset = 0; offset < leak_quantity.size(); offset += (size_t(1) << 28)) {
1110 const int count = int(std::min(size_t(1) << 28, leak_quantity.size() - offset));
1111 MPI_Allreduce(MPI_IN_PLACE,
1112 leak_quantity.data() + offset,
1113 count,
1114 MPI_DOUBLE,
1115 MPI_MIN,
1117 }
1118#endif
1119
1120 // Store the labels in the tessellation
1121 for (size_t i = 0; i < NumPart; i++)
1122 vs[i]->info().WatershedID = label[i];
1123 for (size_t j = 0; j < nboundary; j++)
1124 vs_boundary[j]->info().WatershedID = label[NumPart + j];
1125
1126 // Count how many regular particles we have assigned
1127 long long int assigned = 0;
1128 int nwarnings = 0;
1129 for (size_t i = 0; i < NumPart; i++) {
1130 if (label[i] != NoWatershedID) {
1131 assigned++;
1132 } else if (nwarnings++ < 10) {
1133 std::cout << "[WatershedGeneral] Warning: on task " << FML::ThisTask << " particle " << i
1134 << " pos: " << vs[i]->point() << " has not been assigned!\n";
1135 }
1136 }
1137 long long int npartotal = (long long int)(NumPart);
1138 FML::SumOverTasks(&assigned);
1139 FML::SumOverTasks(&npartotal);
1140 if (FML::ThisTask == 0) {
1141 std::cout << "[WatershedGeneral] Total particles assigned " << assigned << " / " << npartotal << "\n";
1142 if (assigned < npartotal) {
1143 std::cout << "[WatershedGeneral] Warning we have not managed to assign all particles to their "
1144 "respective minima, cannot guarantee the results are perfect\n";
1145 }
1146 }
1147
1148 // The position of the minima and the circumcenter of the minimum and its NDIM lowest-quantity mutually
1149 // adjacent neighbors (as in Revolver, Nadathur et al.): the first neighbor is the neighbor of the minimum
1150 // with the lowest quantity, the second the one with the lowest quantity among the common neighbors of
1151 // the minimum and the first neighbor, etc. In 3D this is the center of an empty sphere in the basin.
1152 // If we can't find such neighbors (or they are degenerate) we use the minimum. Make sure all tasks have
1153 // this
1154 std::vector<double> pos_minima(ntotal_minima * CGAL_NDIM, 0.0);
1155 std::vector<double> pos_circumcenter(ntotal_minima * CGAL_NDIM, 0.0);
1156 long long int ncircumcenter_failed = 0;
1157 {
1158 auto neighbors = [&](Vertex_handle v) {
1159 std::vector<Vertex_handle> result;
1160 D.for_each_adjacent_vertex(v, work, [&](Vertex_handle w) {
1161 if (w->info().point_type != GUARD_POINT)
1162 result.push_back(w);
1163 });
1164 return result;
1165 };
1166 for (size_t k = 0; k < minima.size(); k++) {
1167 const Vertex_handle vmin = vs[minima[k]];
1168 const auto & pmin = vmin->point();
1169 double * pos = &pos_minima[(size_t(id_start) + k) * CGAL_NDIM];
1170 double * circ = &pos_circumcenter[(size_t(id_start) + k) * CGAL_NDIM];
1171 for (int idim = 0; idim < CGAL_NDIM; idim++)
1172 circ[idim] = pos[idim] = pmin[idim];
1173
1174 // Pick the neighbors
1175 std::vector<Vertex_handle> chosen{vmin};
1176 std::vector<Vertex_handle> candidates = neighbors(vmin);
1177 bool ok = true;
1178 for (int n = 0; n < CGAL_NDIM; n++) {
1179 if (n > 0) {
1180 const auto nbor = neighbors(chosen.back());
1181 std::vector<Vertex_handle> common;
1182 for (auto & w : candidates)
1183 if (std::find(nbor.begin(), nbor.end(), w) != nbor.end())
1184 common.push_back(w);
1185 candidates = common;
1186 }
1187 if (candidates.empty()) {
1188 ok = false;
1189 break;
1190 }
1191 Vertex_handle best = candidates[0];
1192 for (auto & w : candidates)
1193 if (lower(w, best))
1194 best = w;
1195 chosen.push_back(best);
1196 }
1197
1198 // The circumcenter (positions relative to the minimum so that it works across the boundary)
1199 if (ok) {
1200 Point q[CGAL_NDIM + 1];
1201 for (int j = 0; j <= CGAL_NDIM; j++) {
1202 double x[CGAL_NDIM];
1203 for (int idim = 0; idim < CGAL_NDIM; idim++) {
1204 double dx = chosen[j]->point()[idim] - pmin[idim];
1205 dx -= std::round(dx);
1206 x[idim] = dx;
1207 }
1208#if CGAL_NDIM == 3
1209 q[j] = Point(x[0], x[1], x[2]);
1210#elif CGAL_NDIM == 2
1211 q[j] = Point(x[0], x[1]);
1212#endif
1213 }
1214#if CGAL_NDIM == 3
1215 ok = not CGAL::coplanar(q[0], q[1], q[2], q[3]);
1216 const Point cc = ok ? CGAL::circumcenter(q[0], q[1], q[2], q[3]) : q[0];
1217#elif CGAL_NDIM == 2
1218 ok = not CGAL::collinear(q[0], q[1], q[2]);
1219 const Point cc = ok ? CGAL::circumcenter(q[0], q[1], q[2]) : q[0];
1220#endif
1221 for (int idim = 0; idim < CGAL_NDIM; idim++)
1222 ok = ok and std::isfinite(cc[idim]);
1223 if (ok)
1224 for (int idim = 0; idim < CGAL_NDIM; idim++)
1225 circ[idim] = detail::wrap_periodic(pmin[idim] + cc[idim]);
1226 }
1227 if (not ok)
1228 ncircumcenter_failed++;
1229 }
1230 }
1231 FML::SumOverTasks(&ncircumcenter_failed);
1232 if (FML::ThisTask == 0 and ncircumcenter_failed > 0)
1233 std::cout << "[WatershedGeneral] Warning: could not compute the circumcenter for "
1234 << ncircumcenter_failed << " basins, using the position of the minimum for these\n";
1235#ifdef USE_MPI
1236 for (auto * vec : {&pos_minima, &pos_circumcenter}) {
1237 for (size_t offset = 0; offset < vec->size(); offset += (size_t(1) << 28)) {
1238 const int count = int(std::min(size_t(1) << 28, vec->size() - offset));
1239 MPI_Allreduce(MPI_IN_PLACE, vec->data() + offset, count, MPI_DOUBLE, MPI_SUM, FML::communicator);
1240 }
1241 }
1242#endif
1243
1244 // Make the groups and bin up the particles
1245 watershed_groups.resize(ntotal_minima);
1246 for (size_t k = 0; k < ntotal_minima; k++) {
1247 watershed_groups[k].init(&pos_minima[k * CGAL_NDIM]);
1248 if constexpr (detail::has_set_pos_circ<U>::value)
1249 watershed_groups[k].set_pos_circ(&pos_circumcenter[k * CGAL_NDIM]);
1250 if constexpr (detail::has_set_leak_quantity<U>::value)
1251 watershed_groups[k].set_leak_quantity(leak_quantity[k]);
1252 }
1253 pos_circumcenter = std::vector<double>();
1254 pos_minima = std::vector<double>();
1255 for (size_t i = 0; i < NumPart; i++)
1256 if (label[i] != NoWatershedID)
1257 watershed_groups[label[i]].add_particle(&p[i], quantity[i]);
1258
1259 // Merge the groups from all tasks on task 0
1260 // NB: assumes U is a simple type so that we can send it as bytes
1261#ifdef USE_MPI
1262 if (FML::NTasks > 1) {
1263 static_assert(std::is_trivially_copyable_v<U>, "The watershed group class must be trivially copyable");
1264 static_assert(sizeof(U) <= size_t(INT_MAX), "Watershed MPI record extent exceeds int");
1265 MPI_Datatype group_type;
1266 MPI_Type_contiguous(int(sizeof(U)), MPI_BYTE, &group_type);
1267 MPI_Type_commit(&group_type);
1268 MPI_Op merge_op;
1269 MPI_Op_create(&detail::merge_groups_op<U>, 1, &merge_op);
1270 const size_t chunk = size_t(1) << 20;
1271 for (size_t offset = 0; offset < ntotal_minima; offset += chunk) {
1272 const int count = int(std::min(chunk, ntotal_minima - offset));
1273 if (FML::ThisTask == 0)
1274 MPI_Reduce(MPI_IN_PLACE,
1275 watershed_groups.data() + offset,
1276 count,
1277 group_type,
1278 merge_op,
1279 0,
1281 else
1282 MPI_Reduce(watershed_groups.data() + offset,
1283 nullptr,
1284 count,
1285 group_type,
1286 merge_op,
1287 0,
1289 }
1290 MPI_Op_free(&merge_op);
1291 MPI_Type_free(&group_type);
1292 }
1293#endif
1294
1295 // Finalize the binning
1296 if (FML::ThisTask == 0) {
1297 for (size_t i = 0; i < ntotal_minima; i++) {
1298 watershed_groups[i].finalize();
1299 }
1300 } else {
1301 // We only keep the data on task 0 so clear the rest to avoid any confusion
1302 watershed_groups.clear();
1303 watershed_groups.shrink_to_fit();
1304 }
1305
1306 // TODO: second step of ZOBOV, merging the basins (zones) into voids. Compile up the links between
1307 // neighboring basins (from the Delaunay links between particles in different basins), communicate
1308 // these to task 0, sort the basins by their minimum quantity and merge them
1309 }
1310
1311 //==========================================================================================
1312 /// In this method we perform a tessellation, compute voronoi volumes and
1313 /// assign density to each cell mass_of_part/volume and then we locate the density minima (or maxima)
1314 /// and walk the tessellation assigning the particles to Watershed basins
1315 /// If density_maximum = true then we assign 1/density to the particles and run the same algorithm so
1316 /// we locate density peaks instead of density minima. The method sets the volume of each particle and
1317 /// the particle must have a set_volume method.
1318 ///
1319 /// @tparam T The particle class
1320 /// @tparam U The watershed binning class
1321 ///
1322 /// @param[in] p Pointer to the particles
1323 /// @param[in] NumPart Number of local particles.
1324 /// @param[out] watershed_groups The result of the watershed: a list of watershed groups.
1325 /// @param[in] buffer_fraction Optional. How big part of the neighbor domain do we include as the buffer.
1326 /// @param[in] random_fraction Optional. How many (as fraction of the normal particles) random particles do we
1327 /// add (this is to help speed up the tesslation).
1328 /// @param[in] do_density_maximum Optional. Watershed based on the density (false) or 1/density (true).
1329 ///
1330 //==========================================================================================
1331
1332 template <class T, class U>
1333 void WatershedDensity(T * p,
1334 size_t NumPart,
1335 std::vector<U> & watershed_groups,
1336 double buffer_fraction = 0.30,
1337 double random_fraction = 0.5,
1338 bool do_density_maximum = false,
1339 std::vector<WatershedLink> * links = nullptr) {
1340
1341 static_assert(FML::PARTICLE::has_set_volume<T>(),
1342 "[WatershedDensity] We require the particle to have a set_volume / get_volume method");
1343
1344 if (FML::ThisTask == 0) {
1345 if (do_density_maximum)
1346 std::cout << "[WatershedDensity] We will locate minima of 1/(voronoi density) of particles\n";
1347 else
1348 std::cout << "[WatershedDensity] We will locate minima of the voronoi density of particles\n";
1349 std::cout << "[WatershedDensity] Buffer fraction " << buffer_fraction << " of neighbor domains\n";
1350 }
1351
1352 // Vertex assignment function
1353 std::function<void(VertexDataWatershed *, T *)> vertex_assignment_function =
1354 [](VertexDataWatershed * v, T * part) { v->part_ptr = part ? (void *)part : nullptr; };
1355
1356 // Create tessellation
1357 if (FML::ThisTask == 0)
1358 std::cout << "[WatershedDensity] Computing tessellation\n";
1359 MPIPeriodicDelaunay<T, VertexDataWatershed> D;
1360 D.create(p, NumPart, buffer_fraction, random_fraction, vertex_assignment_function);
1361
1362 // Compute Voronoi volumes
1363 if (FML::ThisTask == 0)
1364 std::cout << "[WatershedDensity] Computing voronoi volumes from tessellation\n";
1365 std::vector<double> volumes;
1366 D.VoronoiVolume(volumes);
1367
1368 // Set the volume to the particles
1369 for (size_t i = 0; i < NumPart; i++) {
1370 FML::PARTICLE::SetVolume(p[i], volumes[i]);
1371 }
1372
1373 // Convert volumes to mass density
1374 // If you want to tessellated based on an other property then this is all we
1375 // need to change
1376 std::vector<double> & density = volumes;
1377 double mass = 1.0;
1378 for (size_t i = 0; i < NumPart; i++) {
1379 if constexpr (FML::PARTICLE::has_get_mass<T>()) {
1380 mass = FML::PARTICLE::GetMass(p[i]);
1381 }
1382 if (do_density_maximum)
1383 // To find clusters use 1/density as the quantity to watershed
1384 density[i] = volumes[i] / mass;
1385 else
1386 // To find voids use density as watershed quantity
1387 density[i] = mass / volumes[i];
1388 }
1389
1390 // Run general algorithm
1391 WatershedGeneral<T, U>(D, p, NumPart, density, watershed_groups, links);
1392 }
1393
1394 } // namespace TRIANGULATION
1395} // namespace FML
1396
1397#endif
double f
Definition Minimizer.cpp:28
const unsigned int random_seed
Definition Main.cpp:47
void info(HaloModel **hmp)
Definition Wrapper.cpp:88
void free(HaloModel **hm)
Definition Wrapper.cpp:34
py::dict cell(const Spatial::CellStatistics &s)
Definition bindings.cpp:92
std::vector< Spatial::Point > points(py::handle object, const char *name)
Definition bindings.cpp:23
SizeLayout checked_size_layout(const std::vector< Count > &counts, size_t limit=std::numeric_limits< size_t >::max())
Definition MPICounts.h:43
unsigned long long Count
Definition MPICounts.h:12
size_t checked_bytes(Count count, Count extent, Count limit=std::numeric_limits< size_t >::max())
Definition MPICounts.h:33
std::vector< T > gather_records_checked(const std::vector< T > &local, bool replicate=false, int root=0, Count limit=INT_MAX)
Checked legacy Gatherv/Allgatherv for homogeneous trivially copyable records.
Definition MPICounts.h:96
void require_count(bool valid, const char *message)
Definition MPICounts.h:27
bool add_count(Count &sum, Count value, Count limit=std::numeric_limits< Count >::max())
Definition MPICounts.h:15
std::unique_ptr< Likelihood > create(const std::string &n, const std::map< std::string, std::string > &o)
const ModelInfo & find(const std::string &name)
Definition Model.cpp:351
get_vel constexpr double * GetPos(...)
void AssignFromBuffer(T &t, char *buffer)
constexpr void SetVolume(...)
void AppendToBuffer(T &t, char *buffer)
set_mass constexpr double GetMass(Args &... args)
FML_UNITS_INLINE constexpr double density
Definition Units.h:49
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
int ThisTask
The MPI task number.
Definition Global.cpp:39
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
Definition Global.cpp:26
void SumOverTasks(T *value)
Inplace sum over tasks of a single value.
Definition Global.h:229
double xmin_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:49
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
void wrap_periodic(double &x)
Wrap a coordinate (in units of the box) back into [0,1)
Definition ExternalIC.h:123
double uniform(uint64_t i)
std::mt19937_64 rng(1234)
std::array< double, 3 > Point