1#ifndef MPIPERIODICDELAUNAY_HEADER
2#define MPIPERIODICDELAUNAY_HEADER
27#pragma GCC diagnostic push
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>
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>
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>
46#error "CGAL_NDIM has to be 2 or 3"
49#pragma GCC diagnostic pop
57 namespace TRIANGULATION {
62 typedef CGAL::Exact_predicates_inexact_constructions_kernel
K;
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>;
70 using VbInfo = CGAL::Triangulation_vertex_base_with_info_3<T, Gt, Vb>;
72 using TDS = CGAL::Triangulation_data_structure_3<VbInfo<T>, Cb>;
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>;
78 typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2<K> Gt;
79 using Vb = CGAL::Triangulation_vertex_base_2<Gt>;
81 using VbInfo = CGAL::Triangulation_vertex_base_with_info_2<T, Gt, Vb>;
82 using Fb = CGAL::Periodic_2_triangulation_face_base_2<Gt>;
84 using TDS = CGAL::Triangulation_data_structure_2<VbInfo<T>, Fb>;
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>;
96 inline void sendrecv_bytes(
const void * sendbuf,
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;
108 std::max(nsend, nrecv) <=
size_t(*tag_limit) + 1,
109 "[Delaunay] Chunk tags exceed MPI tag range");
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,
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,
132 &requests[nrecv + k]);
134 MPI_Waitall(
int(requests.size()), requests.data(), MPI_STATUSES_IGNORE);
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);
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++)
155 template <
class U,
class =
void>
156 struct has_set_pos_circ : std::false_type {};
158 struct has_set_pos_circ<
U, std::void_t<decltype(std::declval<U &>().set_pos_circ((const double *)nullptr))>>
162 template <
class U,
class =
void>
163 struct has_set_leak_quantity : std::false_type {};
165 struct has_set_leak_quantity<
U, std::void_t<decltype(std::declval<U &>().set_leak_quantity(0.0))>>
171 return x >= 1.0 ? 0.0 :
x;
184 template <
class VD,
class T>
185 void fiducial_assignment_function([[maybe_unused]] VD * v, [[maybe_unused]] T * p) {}
208 template <
class T,
class VD = VD_FIDUCIAL>
209 class MPIPeriodicDelaunay {
211 using PeriodicDelaunay = PeriodicDelaunayWithInfo<VD>;
212 using Point =
typename PeriodicDelaunay::Point;
213 using Vertex_handle =
typename PeriodicDelaunay::Vertex_handle;
223 double dx_buffer{0.0};
226 std::vector<Vertex_handle> vs{};
227 std::vector<Vertex_handle> vs_boundary{};
231 std::vector<T> p_boundary{};
233 size_t recv_right{0};
236 std::vector<size_t> send_left{};
237 std::vector<size_t> send_right{};
240 static Point make_point(
const F * x) {
242 return Point(
double(x[0]),
double(x[1]));
244 return Point(
double(x[0]),
double(x[1]),
double(x[2]));
249 void select_boundary_particles(T * p,
size_t NumPart) {
254 for (
size_t i = 0;
i < NumPart;
i++) {
257 send_left.push_back(i);
259 send_right.push_back(i);
264 std::vector<T> & get_boundary_particles() {
return p_boundary; }
266 double get_dx_buffer()
const {
return dx_buffer; }
269 PeriodicDelaunay & get_delaunay_triangulation() {
return dt; }
270 const PeriodicDelaunay & get_delaunay_triangulation()
const {
return dt; }
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; }
275 MPIPeriodicDelaunay() =
default;
283 vs_boundary.shrink_to_fit();
285 p_boundary.shrink_to_fit();
287 send_left.shrink_to_fit();
289 send_right.shrink_to_fit();
290 recv_left = recv_right = 0;
295 void for_each_adjacent_vertex(Vertex_handle v, std::vector<Vertex_handle> & work, F &&
f)
const {
298 dt.adjacent_vertices(v, std::back_inserter(work));
299 const bool one_cover =
dt.is_1_cover();
300 for (
auto & w : work) {
302 Vertex_handle
wo = one_cover ?
w :
dt.get_original_vertex(w);
308 auto vc =
dt.adjacent_vertices(v);
312 const bool one_cover =
dt.is_1_cover();
315 Vertex_handle
w = vc;
316 Vertex_handle
wo = one_cover ?
w :
dt.get_original_vertex(w);
319 }
while (++vc != done);
326 void communicate_boundary_particles(T * p,
size_t NumPart, std::vector<T> & p_to_recv) {
328 recv_left = recv_right = 0;
329 select_boundary_particles(p, NumPart);
335 std::cout <<
"[MPIPeriodicDelaunay::communicate_boundary_particles]\n";
341 auto pack = [&](
const std::vector<size_t> &
index, std::vector<char> & buffer) {
344 for (
auto i :
index) {
345 const auto size = FML::PARTICLE::GetSize(p[i]);
353 buffer.resize(
size_t(bytes));
354 char *
b = buffer.data();
355 for (
auto i :
index) {
357 b += FML::PARTICLE::GetSize(p[i]);
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);
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);
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";
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(),
388 buffer_recv_right.data(),
391 detail::sendrecv_bytes(buffer_send_right.data(),
394 buffer_recv_left.data(),
397 buffer_send_left = std::vector<char>();
398 buffer_send_right = std::vector<char>();
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++) {
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");
414 processed += size_t(bytes);
416 assert(processed == buffer.size());
418 unpack(buffer_recv_left, 0, recv_left);
419 unpack(buffer_recv_right, recv_left, recv_right);
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());
433 std::vector<Q>().max_size());
434 std::vector<Q>
result(received.total);
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]];
450 detail::sendrecv_bytes(to_left.data(),
453 recv_right ?
result.data() + recv_left : nullptr,
456 detail::sendrecv_bytes(to_right.data(),
459 recv_left ?
result.data() : nullptr,
469 void make_random_points_outside_domain(
size_t nrandom, std::vector<double> & positions_random)
const {
470 positions_random.clear();
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);
487 std::uniform_real_distribution<double>
uniform(0.0, 1.0);
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++)
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));
500 positions_random.push_back((k / nborder) / double(nborder));
504#ifdef DEBUG_TESSELATION
505 std::cout <<
"Task " <<
FML::ThisTask <<
" made " << nvolume <<
" + 2 x " << nface
506 <<
" guard points in [" <<
x0 <<
" , " <<
x0 + length <<
"]\n";
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>) {
530 assert_mpi(buffer_fraction >= 0.0,
"buffer_fraction must be positive");
531 assert_mpi(random_fraction >= 0.0,
"random_fraction must be positive");
533 random_fraction = buffer_fraction = 0.0;
535 random_fraction = 0.0;
536 buffer_fraction = 0.5;
538 if (buffer_fraction >= 1.0) {
539 buffer_fraction = 1.0 - 1
e-10;
542 assert_mpi(FML::PARTICLE::GetNDIM(T()) == CGAL_NDIM,
"Dimensions do not match");
546 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";
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";
559 std::cout <<
"#=====================================================\n";
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;
572 communicate_boundary_particles(p, NumPart, p_boundary);
573 const size_t nboundary = p_boundary.size();
578 const size_t npoints = NumPart + nboundary + nrandom;
579 std::vector<Point>
points;
580 std::vector<long long int> id;
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);
587 positions_random = std::vector<double>();
588 for (
size_t i = 0;
i < nboundary;
i++) {
590 id.push_back(-(
long long int)(i)-1);
592 for (
size_t i = 0;
i < NumPart;
i++) {
594 id.push_back((
long long int)(i));
597#ifdef DEBUG_TESSELATION
598 std::cout <<
"Task " <<
FML::ThisTask <<
" Tessellation with " << NumPart <<
" (part) + " << nboundary
599 <<
" (boundary) + " << nrandom <<
" (random) = " << npoints <<
" (total)\n";
605 std::vector<size_t>
order(npoints);
606 std::iota(
order.begin(),
order.end(),
size_t(0));
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];
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]);
621 assignment_function(&(
v->info()),
nullptr);
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;
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);
640 CGAL::spatial_sort(
order.begin() + ninserted,
642 SpatialSortTraits(CGAL::make_property_map(
points)));
645 typename PeriodicDelaunay::Cell_handle hint;
647 typename PeriodicDelaunay::Face_handle hint;
649 for (; ninserted < npoints; ninserted++) {
650 const size_t k =
order[ninserted];
651 Vertex_handle
v =
dt.insert(
points[k], hint);
658 print_progress(ninserted);
662 std::cout <<
" Waiting for other tasks to finish" << std::endl;
664#ifdef DEBUG_TESSELATION
665 assert(
dt.is_valid());
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";
677 long long int nbadcells = num_bad_cells();
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";
690 void VoronoiVolume(std::vector<double> & volumes)
const {
691 const size_t npts = vs.size();
692 volumes.resize(npts);
696#pragma omp parallel for reduction(+ : totvol)
698 for (
size_t i = 0;
i < npts;
i++) {
699 const double vol = voronoi_volume(vs[i]);
708 std::cout <<
"[MPIPeriodicDelaunay::VoronoiVolume] Volume missing in the box: "
709 << (1.0 - totvol) * 100 <<
" %\n";
713 double voronoi_volume(Vertex_handle v)
const {
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]);
725 return {
a.x() -
b.x(),
a.y() -
b.y(),
a.z() -
b.z()};
727 thread_local std::vector<Cell_handle> cells;
729 dt.incident_cells(v, std::back_inserter(cells));
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};
740 for (
int k = 0;
k < 3;
k++)
741 cf[k] =
sub(CGAL::circumcenter(pv, q[o[k]], q[o[(k + 1) % 3]]), pv);
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++) {
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;
758 auto fc =
dt.incident_faces(v);
761 double xfirst = 0.0, yfirst = 0.0, xprev = 0.0, yprev = 0.0;
764 typename PeriodicDelaunay::Face_handle
f = fc;
765 const auto ptri =
dt.periodic_triangle(
f);
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();
778 area += xprev *
y - yprev *
x;
782 }
while (++fc != done);
783 area += xprev * yfirst - yprev * xfirst;
784 return 0.5 * std::abs(area);
789 using Cell_handle =
typename PeriodicDelaunay::Cell_handle;
791 using Cell_handle =
typename PeriodicDelaunay::Face_handle;
799 bool cell_is_reliable(Cell_handle c)
const {
801 if (
FML::NTasks == 1 or width + 2.0 * dx_buffer >= 1.0 or not
dt.is_1_cover())
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)
811 const auto pcell =
dt.periodic_tetrahedron(c);
813 const Point cc = CGAL::circumcenter(q0,
dt.point(pcell[1]),
dt.point(pcell[2]),
dt.point(pcell[3]));
815 const auto pcell =
dt.periodic_triangle(c);
817 const Point cc = CGAL::circumcenter(q0,
dt.point(pcell[1]),
dt.point(pcell[2]));
819 const double radius = std::sqrt(CGAL::to_double(CGAL::squared_distance(cc, q0)));
829 long long int num_bad_cells()
const {
830 long long int nbad = 0;
832 for (
auto c =
dt.cells_begin(); c !=
dt.cells_end(); ++c) {
834 for (
auto c =
dt.faces_begin(); c !=
dt.faces_end(); ++c) {
836 bool has_regular =
false;
837 for (
int k = 0;
k <= CGAL_NDIM;
k++) {
838 const double x = c->vertex(k)->point()[0];
841 if (has_regular and not cell_is_reliable(c))
851 enum PointType :
char { REGULAR_POINT, BOUNDARY_POINT, GUARD_POINT };
855 using QuantityType = double;
856 const IDType NoWatershedID = std::numeric_limits<IDType>::max();
857 const QuantityType Infinity = std::numeric_limits<QuantityType>::infinity();
861 struct WatershedLink {
864 double quantity{0.0};
869 inline void reduce_links(std::vector<WatershedLink> & links) {
870 std::sort(links.begin(), links.end(), [](
const WatershedLink & x,
const WatershedLink & y) {
875 return x.quantity < y.quantity;
877 links.erase(std::unique(links.begin(),
879 [](
const WatershedLink & x,
const WatershedLink & y) {
880 return x.a == y.a and x.b == y.b;
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};
919 template <
class T,
class U>
920 void WatershedGeneral(MPIPeriodicDelaunay<T, VertexDataWatershed> & D,
923 std::vector<double> & quantity,
924 std::vector<U> & watershed_groups,
925 std::vector<WatershedLink> * links =
nullptr) {
927 using Delaunay = MPIPeriodicDelaunay<T, VertexDataWatershed>;
928 using Vertex_handle =
typename Delaunay::Vertex_handle;
929 using Point =
typename Delaunay::Point;
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();
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;
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;
955 auto lower = [](Vertex_handle
a, Vertex_handle
b) {
956 const auto qa =
a->info().quantity;
957 const auto qb =
b->info().quantity;
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];
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))
978 parent[
i] = best->info().index;
982 std::vector<size_t> minima;
983 for (
size_t i = 0;
i < NumPart;
i++)
984 if (parent[i] == (
long long int)(i))
986 std::vector<long long int> nminima_per_task(
FML::NTasks, 0);
989 MPI_Allreduce(MPI_IN_PLACE,
990 nminima_per_task.data(),
997 std::vector<FML::COMMUNICATION::Count>(nminima_per_task.begin(), nminima_per_task.end()),
999 long long int id_start = 0;
1001 id_start += nminima_per_task[i];
1002 long long int ntotal_minima_ll = 0;
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);
1009 std::cout <<
"[WatershedGeneral] We found " << ntotal_minima <<
" minimum points\n";
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));
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])
1027 long long int j = (
long long int)(i);
1028 while (j < (
long long int)(NumPart) and label[j] == NoWatershedID and not stuck[j]) {
1032 const bool found = (j >= (
long long int)(NumPart) or not stuck[j]) and label[j] != NoWatershedID;
1033 for (
auto k :
path) {
1040 nassigned +=
path.size();
1048 const int max_iterations = 1000;
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());
1059#ifdef DEBUG_TESSELATION
1061 std::cout <<
"[WatershedGeneral] Labels converged after " << iteration <<
" exchanges\n";
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++) {
1072 if (a == NoWatershedID)
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)
1078 const IDType
b =
label[
w->info().index];
1079 if (b == NoWatershedID or b == a)
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);
1085 local_links.push_back({std::min(a, b), std::max(a, b), link});
1088 if (links and local_links.size() > 4 * ntotal_minima + 1000000)
1089 detail::reduce_links(local_links);
1092 detail::reduce_links(local_links);
1100 detail::reduce_links(*links);
1102 *links = std::move(local_links);
1105 *links = std::move(local_links);
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,
1121 for (
size_t i = 0;
i < NumPart;
i++)
1123 for (
size_t j = 0; j < nboundary; j++)
1124 vs_boundary[j]->
info().WatershedID =
label[NumPart + j];
1127 long long int assigned = 0;
1129 for (
size_t i = 0;
i < NumPart;
i++) {
1130 if (label[i] != NoWatershedID) {
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";
1137 long long int npartotal = (
long long int)(NumPart);
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";
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;
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)
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];
1175 std::vector<Vertex_handle> chosen{vmin};
1176 std::vector<Vertex_handle> candidates = neighbors(vmin);
1178 for (
int n = 0;
n < CGAL_NDIM;
n++) {
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())
1187 if (candidates.empty()) {
1191 Vertex_handle best = candidates[0];
1192 for (
auto & w : candidates)
1195 chosen.push_back(best);
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);
1209 q[j] =
Point(x[0], x[1], x[2]);
1211 q[j] =
Point(x[0], x[1]);
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];
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];
1221 for (
int idim = 0; idim < CGAL_NDIM; idim++)
1222 ok = ok and std::isfinite(cc[idim]);
1224 for (
int idim = 0; idim < CGAL_NDIM; idim++)
1225 circ[idim] = detail::wrap_periodic(pmin[idim] + cc[idim]);
1228 ncircumcenter_failed++;
1233 std::cout <<
"[WatershedGeneral] Warning: could not compute the circumcenter for "
1234 << ncircumcenter_failed <<
" basins, using the position of the minimum for these\n";
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);
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]);
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]);
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);
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));
1274 MPI_Reduce(MPI_IN_PLACE,
1275 watershed_groups.data() + offset,
1282 MPI_Reduce(watershed_groups.data() + offset,
1290 MPI_Op_free(&merge_op);
1291 MPI_Type_free(&group_type);
1297 for (
size_t i = 0;
i < ntotal_minima;
i++) {
1298 watershed_groups[
i].finalize();
1302 watershed_groups.clear();
1303 watershed_groups.shrink_to_fit();
1332 template <
class T,
class U>
1333 void WatershedDensity(T * p,
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) {
1341 static_assert(FML::PARTICLE::has_set_volume<T>(),
1342 "[WatershedDensity] We require the particle to have a set_volume / get_volume method");
1345 if (do_density_maximum)
1346 std::cout <<
"[WatershedDensity] We will locate minima of 1/(voronoi density) of particles\n";
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";
1353 std::function<void(VertexDataWatershed *, T *)> vertex_assignment_function =
1354 [](VertexDataWatershed *
v, T * part) {
v->part_ptr = part ? (
void *)part : nullptr; };
1358 std::cout <<
"[WatershedDensity] Computing tessellation\n";
1359 MPIPeriodicDelaunay<T, VertexDataWatershed>
D;
1360 D.create(p, NumPart, buffer_fraction, random_fraction, vertex_assignment_function);
1364 std::cout <<
"[WatershedDensity] Computing voronoi volumes from tessellation\n";
1365 std::vector<double> volumes;
1366 D.VoronoiVolume(volumes);
1369 for (
size_t i = 0;
i < NumPart;
i++) {
1376 std::vector<double> &
density = volumes;
1378 for (
size_t i = 0;
i < NumPart;
i++) {
1379 if constexpr (FML::PARTICLE::has_get_mass<T>()) {
1382 if (do_density_maximum)
1391 WatershedGeneral<T, U>(D, p, NumPart, density, watershed_groups, links);
const unsigned int random_seed
void info(HaloModel **hmp)
void free(HaloModel **hm)
py::dict cell(const Spatial::CellStatistics &s)
std::vector< Spatial::Point > points(py::handle object, const char *name)
SizeLayout checked_size_layout(const std::vector< Count > &counts, size_t limit=std::numeric_limits< size_t >::max())
size_t checked_bytes(Count count, Count extent, Count limit=std::numeric_limits< size_t >::max())
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.
void require_count(bool valid, const char *message)
bool add_count(Count &sum, Count value, Count limit=std::numeric_limits< Count >::max())
std::unique_ptr< Likelihood > create(const std::string &n, const std::map< std::string, std::string > &o)
const ModelInfo & find(const std::string &name)
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
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
int ThisTask
The MPI task number.
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
void SumOverTasks(T *value)
Inplace sum over tasks of a single value.
double xmin_domain
The local extent of the domain (global domain goes from 0 to 1)
int NTasks
Total number of MPI tasks.
void wrap_periodic(double &x)
Wrap a coordinate (in units of the box) back into [0,1)
double uniform(uint64_t i)
std::mt19937_64 rng(1234)
std::array< double, 3 > Point