FML
Loading...
Searching...
No Matches
FoF.h
Go to the documentation of this file.
1#ifndef FOF_HEADER
2#define FOF_HEADER
4#include <FML/Global/Global.h>
7#include <algorithm>
8#include <array>
9#include <cassert>
10#include <cmath>
11#include <iostream>
12#include <iterator>
13#include <limits>
14#include <map>
15#include <vector>
16
17namespace FML {
18
19 //========================================================================================
20 /// This namespace deals how to link together particles in groups
21 //========================================================================================
22 namespace FOF {
23
24 /// If a particle belongs to no FoF group it is given this FoF ID
25 const constexpr size_t no_FoF_ID = std::numeric_limits<size_t>::max();
26
27 /// Type of particle for book-keeping
29
30 /// The maximum grid we are allowed to use to bin the particle to
31 /// This is just to have a memory limit in what the algorithm is
32 /// allowed to allocate. This value is used if user do not provide it.
33 inline int FoF_Ngrid_max = 1024;
34
36 /// Records timings of the FoF search
38
39 /// The number of groups found in the last call to FriendsOfFriends (summed over tasks) that reach the edge of
40 /// the buffer of particles copied from the neighbor tasks. These might be cut off (and then also found as a
41 /// second, partial group on the neighbor task): increase the buffer if this is not zero
43
44 //========================================================================================
45 /// Locate friends of friends groups and bin what you want over these groups.
46 ///
47 /// @tparam T The particle class
48 /// @tparam NDIM The number of dimensions
49 /// @tparam FoFHaloClass The FoF group class, determined what to be binned up over the FoF group. It needs the
50 /// members of FoFHalo used here: a constructor from the (size_t) id, the members id and np, add(particle,
51 /// periodic), finalize(periodic) and get_pos() (the center, used to decide which task keeps the group).
52 /// A class derived from FoFHalo (with using FoFHalo::FoFHalo;) works.
53 ///
54 /// @param[in] part Pointer to particles. If the particle has a set_fofid then we will also store the FoFID in
55 /// the particles. NB: the particles are sorted (by their y-coordinate) in place.
56 /// @param[in] NumPart Number of local particles
57 /// @param[in] linking_length The distance in units of mean particle separation (in [0,1)) required to have a
58 /// link between two particles. Typical value is 0.2.
59 /// @param[in] nmin_FoF_group Minimum number of particles in a FoF group to store it. Typical value is 20.
60 /// @param[in] periodic Is the box periodic?
61 /// @param[in] Buffersize_over_Boxsize The buffer we communicate on both sides of the domain in units of the
62 /// boxsize. Typical value for N-body simulations is (3 Mpc/h) / boxsize.
63 /// @param[out] LocalFoFGroups The results: list of FoF groups.
64 /// @param[in] Ngrid (Optional) The maximum gridsize we use to bin the particles to in order to speed up the
65 /// calculation. The default FoF_Ngrid_max is set in the header. Larger value means more memory needed. The
66 /// grid used has at most about one cell per particle (the result does not depend on the grid).
67 ///
68 //========================================================================================
69 template <class T, int NDIM, class FoFHaloClass>
70 void FriendsOfFriends(T * part,
71 size_t NumPart,
72 double linking_length,
73 int nmin_FoF_group,
74 bool periodic,
75 double Buffersize_over_Boxsize,
76 std::vector<FoFHaloClass> & LocalFoFGroups,
77 int Ngrid = FoF_Ngrid_max);
78
79 //=========================================================================
80 /// A gridcell in a grid used for speeding up the linking of particles
81 /// The ID of the particles is their position in the particle list
82 //=========================================================================
83 class FoFCell {
84 public:
85 /// Number of particles in the cell
86 int np{0};
87 /// Number of boundary particles in the cell
89 /// List of indices of particles that are in the cell
90 size_t * ParticleIndex;
91 /// List of indices of particles that are in the cell
93 /// List of indices of boundary particles that are in the cell
94 FoFCell() = default;
95 };
96
97 //=========================================================================
98 /// Internal method: bin particles to a grid.
99 /// NB: this method assumes the boundary particles are *unwrapped*
100 /// when we run with a periodic box.
101 /// i.e. on task 1 they should have x<0 (-0.1, not 0.9 if inside the box)
102 /// and on task N-1 they should have x>1 (1.1, not 0.1 if inside the box)
103 //=========================================================================
104 template <class T, int NDIM>
105 void ParticlesToCells(int Ngrid,
106 int & Local_nx,
107 double dx_boundary,
108 T * part,
109 size_t NumPart,
110 T * part_boundary,
111 size_t NumPart_boundary,
112 std::vector<FoFCell> & PartCells,
113 std::vector<size_t> & particlegriddata) {
114
115 // Total length of domain
116 const double dx_cells = 1.0 / Ngrid;
117 const double xmin_box = FML::xmin_domain - dx_boundary;
118 const double xmax_box = FML::xmax_domain + dx_boundary;
119 const double dx_box_domain = xmax_box - xmin_box;
120
121 // Total number of local-cells
122 Local_nx = std::ceil(dx_box_domain / dx_cells);
123
124 // Total number of local cells to allocate
125 const size_t NgridTot = size_t(Local_nx) * FML::power(Ngrid, NDIM - 1);
126
127 // Make a grid containing particles
128 PartCells.resize(NgridTot);
129
130 // Get index of the cell the particle lives in
131 auto get_cell_index = [&](size_t ipart, std::vector<int> & coord, int type) {
132 decltype(part[0].get_pos()) pos;
133 if (type == BOUNDARY_PARTICLE)
134 pos = FML::PARTICLE::GetPos(part_boundary[ipart]);
135 else if (type == REGULAR_PARTICLE)
136 pos = FML::PARTICLE::GetPos(part[ipart]);
137 else {
138 throw std::runtime_error("FoF::The particle is somehow marked as not being left/regular/right! "
139 "Should not happen ever!\n");
140 }
141
142 // (clamped to the grid: e.g. y = 1.0 from wrapping -1e-17 to the box)
143 size_t index_cell = 0;
144 for (int idim = 0; idim < NDIM; idim++) {
145 auto dx = (pos[idim] - xmin_box * (idim == 0 ? 1 : 0));
146 coord[idim] = std::clamp(int(dx * Ngrid), 0, (idim == 0 ? Local_nx : Ngrid) - 1);
147 index_cell = index_cell * Ngrid + coord[idim];
148 }
149 return index_cell;
150 };
151
152 // Count number of particles in cells
153 std::vector<int> coord(NDIM);
154 for (size_t i = 0; i < NumPart; i++) {
155 const size_t index_cell = get_cell_index(i, coord, REGULAR_PARTICLE);
156 PartCells[index_cell].np++;
157 }
158 for (size_t i = 0; i < NumPart_boundary; i++) {
159 const size_t index_cell = get_cell_index(i, coord, BOUNDARY_PARTICLE);
160 PartCells[index_cell].np_boundary++;
161 }
162
163 // Allocate all the data
164 particlegriddata.assign(NumPart_boundary + NumPart, 0);
165 size_t * ptr = particlegriddata.data();
166
167 // Allocate cells
168 int np_max = 0;
169 [[maybe_unused]] size_t np_total = 0;
170 [[maybe_unused]] size_t np_boundary_total = 0;
171 for (auto & cell : PartCells) {
172 cell.ParticleIndexBoundary = ptr;
173 ptr += cell.np_boundary;
174 cell.ParticleIndex = ptr;
175 ptr += cell.np;
176
177 np_max = std::max(np_max, cell.np);
178 np_total += cell.np;
179 np_boundary_total += cell.np_boundary;
180 cell.np = 0;
181 cell.np_boundary = 0;
182 }
183
184 // Fill up cells with info about particles
185 for (size_t i = 0; i < NumPart; i++) {
186 const size_t index_cell = get_cell_index(i, coord, 0);
187 auto & np = PartCells[index_cell].np;
188 PartCells[index_cell].ParticleIndex[np] = i;
189 np++;
190 }
191 for (size_t i = 0; i < NumPart_boundary; i++) {
192 const size_t index_cell = get_cell_index(i, coord, -1);
193 auto & np_boundary = PartCells[index_cell].np_boundary;
194 PartCells[index_cell].ParticleIndexBoundary[np_boundary] = i;
195 np_boundary++;
196 }
197 }
198
199 template <class T, int NDIM, class FoFHaloClass = FoFHalo<T, NDIM>>
200 void FriendsOfFriends(T * part,
201 size_t NumPart,
202 double linking_length,
203 int nmin_FoF_group,
204 bool periodic,
205 double Buffersize_over_Boxsize,
206 std::vector<FoFHaloClass> & LocalFoFGroups,
207 int Ngrid) {
208
209 LocalFoFGroups.clear();
210 FML::COMMUNICATION::Count local_count = NumPart;
211 const auto local_counts = FML::GatherFromTasks(&local_count);
212 if (std::all_of(local_counts.begin(), local_counts.end(), [](auto n) { return n == 0; }))
213 return;
215 std::all_of(local_counts.begin(), local_counts.end(), [](auto n) { return n > 0; }),
216 "[FoF] Nonempty global catalogues require particles on every rank");
217 [[maybe_unused]] const bool debug = false;
218
219 // Some basic checks
220 assert_mpi(FML::PARTICLE::GetNDIM(T()) == NDIM,
221 "FriendsOfFriends::The dimensions of particle and method do not match!\n");
222
223 // Compute fof search distance
224 size_t NumPart_tot = NumPart;
225 FML::SumOverTasks(&NumPart_tot);
226 const double mean_particle_separation = 1.0 / std::pow(double(NumPart_tot), 1.0 / NDIM);
227 const double fof_distance = linking_length * mean_particle_separation;
228 const double fof_distance2 = fof_distance * fof_distance;
229
230 // Compute grid-size for faster linking: cells larger than 2 linking distances (so only 2^NDIM cells need to
231 // be searched) and about one particle per cell at most (smaller cells only cost memory)
232 if (Ngrid <= 0)
233 Ngrid = FoF_Ngrid_max;
234 Ngrid = std::min(int(0.5 / fof_distance), Ngrid);
235 Ngrid = std::max(1, std::min(Ngrid, int(1.0 / mean_particle_separation)));
236
237 // Set how the size of the grid-cube we need to search
238 const constexpr int twotondim = FML::power(2, NDIM);
239
240 // Check that the grid is not too small
241 assert_mpi(1.0 / Ngrid > 2 * fof_distance,
242 "FriendsOfFriends::The gridsize is too large (larger than the 2x linking distance)");
243
244 // Sort particles by x position
245 // This speed it up when doing the linking, typically by ~20-30%
246 foftimer.StartTiming("Sort particles");
247 std::sort(part, part + NumPart, [](const T & a, const T & b) {
248 // The y axis seems fastest in benchmarks
249 constexpr int axis = 1;
250 T * f = const_cast<T *>(&a);
251 T * g = const_cast<T *>(&b);
252 const auto pos_a = FML::PARTICLE::GetPos(*f);
253 const auto pos_b = FML::PARTICLE::GetPos(*g);
254 return pos_b[axis] > pos_a[axis];
255 });
256 foftimer.EndTiming("Sort particles");
257
258 // Compute ranges for which to copy over boundary partices
259 const double xmin = FML::xmin_domain;
260 const double xmax = FML::xmax_domain;
261 const double dx_boundary = FML::NTasks == 1 ? 0.0 : Buffersize_over_Boxsize;
262
263 // If the boundary we ask for is too large
264 if (dx_boundary > xmax - xmin) {
265 throw std::runtime_error("FoF::The boundary asked for is larger than the neighbor task. Reduce "
266 "boundary (or the number of CPUs)\n");
267 }
268
269 //=========================================================================
270 // Fetch all the boundary particles
271 // We gather particles within dx_boundary of each side
272 //=========================================================================
273 std::vector<T> boundary_particles{};
274 const auto record_size = FML::PARTICLE::GetSize(part[0]);
275 const size_t bytes_per_particle = record_size > 0 ? size_t(record_size) : 0;
276 // How many particles we send to / receive from the left and right task (used again at the end to send
277 // the FoF IDs of the boundary particles back to the task they belong to)
278 size_t n_send_left = 0;
279 size_t n_send_right = 0;
280 size_t n_recv_left = 0;
281 size_t n_recv_right = 0;
282 [[maybe_unused]] const int RightTask = (FML::ThisTask + 1) % FML::NTasks;
283 [[maybe_unused]] const int LeftTask = (FML::ThisTask - 1 + FML::NTasks) % FML::NTasks;
284#ifdef USE_MPI
285 foftimer.StartTiming("Communicate boundary");
286 if (FML::NTasks > 1) {
287 FML::COMMUNICATION::Count record_bytes = bytes_per_particle;
288 const auto record_sizes = FML::GatherFromTasks(&record_bytes);
290 record_bytes > 0 && std::all_of(record_sizes.begin(),
291 record_sizes.end(),
292 [&](auto n) { return n == record_bytes; }),
293 "[FoF] Boundary exchange requires a uniform positive serialized record size");
294 bool valid_sizes = true;
295 // Count how may particles to send left and right
296 size_t noutside = 0;
297 for (size_t i = 0; i < NumPart; i++) {
298 const auto size = FML::PARTICLE::GetSize(part[i]);
299 valid_sizes &= size > 0 && size_t(size) == bytes_per_particle;
300 const auto * pos = FML::PARTICLE::GetPos(part[i]);
301 if (pos[0] < xmin + dx_boundary)
302 ++n_send_left;
303 if (pos[0] > xmax - dx_boundary)
304 ++n_send_right;
305 if (pos[0] < xmin or pos[0] > xmax)
306 noutside++;
307 }
309 noutside == 0 && valid_sizes,
310 "[FoF] Boundary particles must be in-domain and have a uniform serialized size");
311
312 MPI_Status status;
313
314 // Communicate how many to send and get how many to receive
315
316 // Send left receive from right
317 MPI_Sendrecv(&n_send_left,
318 sizeof(n_send_left),
319 MPI_BYTE,
320 LeftTask,
321 0,
322 &n_recv_right,
323 sizeof(n_recv_right),
324 MPI_BYTE,
325 RightTask,
326 0,
328 &status);
329 // Send right receive from left
330 MPI_Sendrecv(&n_send_right,
331 sizeof(n_send_right),
332 MPI_BYTE,
333 RightTask,
334 0,
335 &n_recv_left,
336 sizeof(n_recv_left),
337 MPI_BYTE,
338 LeftTask,
339 0,
341 &status);
342
343 // If not periodic then left boundary on first task and right boundary on last task is not there
344 if (not periodic) {
345 if (FML::ThisTask == 0)
346 n_recv_left = n_send_left = 0;
347 if (FML::ThisTask == FML::NTasks - 1)
348 n_recv_right = n_send_right = 0;
349 }
350
351 // Debug
352 if (debug) {
353 std::cout << "Task " << FML::ThisTask << " will send " << n_send_right << " to " << RightTask
354 << "\n";
355 std::cout << "Task " << FML::ThisTask << " will send " << n_send_left << " to " << LeftTask
356 << "\n";
357 std::cout << "Task " << FML::ThisTask << " will recv " << n_recv_right << " from " << RightTask
358 << "\n";
359 std::cout << "Task " << FML::ThisTask << " will recv " << n_recv_left << " from " << LeftTask
360 << "\n";
361 std::cout << "Send fraction " << (n_send_left + n_send_right) / double(NumPart) << "\n";
362 }
363
364 // Compute how many bytes to send/recv
365 const size_t bytes_send_left =
366 FML::COMMUNICATION::checked_bytes(n_send_left, bytes_per_particle, INT_MAX);
367 const size_t bytes_send_right =
368 FML::COMMUNICATION::checked_bytes(n_send_right, bytes_per_particle, INT_MAX);
369 const size_t bytes_recv_left =
370 FML::COMMUNICATION::checked_bytes(n_recv_left, bytes_per_particle, INT_MAX);
371 const size_t bytes_recv_right =
372 FML::COMMUNICATION::checked_bytes(n_recv_right, bytes_per_particle, INT_MAX);
373
374 // Set up communication buffer
375 std::vector<char> CommBufferSend;
376 std::vector<char> CommBufferRecv;
377 CommBufferSend.resize(std::max(bytes_send_left, bytes_send_right));
378 CommBufferRecv.resize(std::max(bytes_recv_left, bytes_recv_right));
379
380 // Set up storage for boundary particles
381 const auto incoming = FML::COMMUNICATION::checked_size_layout(
382 {FML::COMMUNICATION::Count(n_recv_left), FML::COMMUNICATION::Count(n_recv_right)},
383 boundary_particles.max_size());
384 boundary_particles.resize(incoming.total);
385
386 // Gather data to send left
387 char * buffer = CommBufferSend.data();
388 if (n_send_left > 0)
389 for (size_t i = 0; i < NumPart; i++) {
390 const auto * pos = FML::PARTICLE::GetPos(part[i]);
391 if (pos[0] < xmin + dx_boundary) {
392 FML::PARTICLE::AppendToBuffer(part[i], buffer);
393 buffer += bytes_per_particle;
394 }
395 }
396
397 // Send left receive from right
398 MPI_Sendrecv(CommBufferSend.data(),
399 bytes_send_left,
400 MPI_BYTE,
401 LeftTask,
402 0,
403 CommBufferRecv.data(),
404 bytes_recv_right,
405 MPI_BYTE,
406 RightTask,
407 0,
409 &status);
410
411 // Generate particles
412 buffer = CommBufferRecv.data();
413 for (size_t i = 0; i < n_recv_right; i++) {
414 FML::PARTICLE::AssignFromBuffer(boundary_particles[i], buffer);
415 buffer += bytes_per_particle;
416 }
417
418 // Gather data to send right
419 buffer = CommBufferSend.data();
420 if (n_send_right > 0)
421 for (size_t i = 0; i < NumPart; i++) {
422 const auto * pos = FML::PARTICLE::GetPos(part[i]);
423 if (pos[0] > xmax - dx_boundary) {
424 FML::PARTICLE::AppendToBuffer(part[i], buffer);
425 buffer += bytes_per_particle;
426 }
427 }
428
429 // Send right receive from left
430 MPI_Sendrecv(CommBufferSend.data(),
431 bytes_send_right,
432 MPI_BYTE,
433 RightTask,
434 0,
435 CommBufferRecv.data(),
436 bytes_recv_left,
437 MPI_BYTE,
438 LeftTask,
439 0,
441 &status);
442
443 // Generate particles
444 buffer = CommBufferRecv.data();
445 for (size_t i = 0; i < n_recv_left; i++) {
446 FML::PARTICLE::AssignFromBuffer(boundary_particles[n_recv_right + i], buffer);
447 buffer += bytes_per_particle;
448 }
449
450 // Free up memory used for communication
451 CommBufferSend = std::vector<char>();
452 CommBufferRecv = std::vector<char>();
453
454 // Make sure the left particles are wrapped to the left of the box on first task
455 // If we don't do this then we need to modify dx[0] comp in get_cell_index in ParticlesInGrid
456 // to wrap + the same in FindAllFriends
457 if (FML::ThisTask == 0) {
458 for (size_t i = 0; i < n_recv_left; i++) {
459 auto * pos = FML::PARTICLE::GetPos(boundary_particles[n_recv_right + i]);
460 pos[0] -= 1.0;
461 }
462 }
463
464 // Make sure the right particles are wrapped to the right of the box on last task
465 if (FML::ThisTask == FML::NTasks - 1) {
466 for (size_t i = 0; i < n_recv_right; i++) {
467 auto * pos = FML::PARTICLE::GetPos(boundary_particles[i]);
468 pos[0] += 1.0;
469 }
470 }
471 }
472 foftimer.EndTiming("Communicate boundary", FML::ThisTask == 0);
473#endif
474
475 const auto NumPart_boundary = boundary_particles.size();
476 const auto NumPart_total = NumPart + NumPart_boundary;
477
478 //=========================================================================
479 // Bin particles to a grid for faster linking
480 //=========================================================================
481 std::vector<FoFCell> PartCells;
482 std::vector<size_t> particlegriddata;
483 int Local_nx{};
484 foftimer.StartTiming("ParticlesToCells");
486 Local_nx,
487 dx_boundary,
488 part,
489 NumPart,
490 boundary_particles.data(),
491 boundary_particles.size(),
492 PartCells,
493 particlegriddata);
494 foftimer.EndTiming("ParticlesToCells");
495
496 //=========================================================================
497 // We now have all the boundary particles and can do the FoF linking
498 //=========================================================================
499 if (FML::ThisTask == 0) {
500 std::cout << "\n";
501 std::cout << "#=====================================================\n";
502 std::cout << "#\n";
503 std::cout << "# ___________________ ___________ \n";
504 std::cout << "# \\_ _____/\\_____ \\ \\_ _____/ \n";
505 std::cout << "# | __) / | \\ | __) \n";
506 std::cout << "# | \\ / | \\| \\ \n";
507 std::cout << "# \\___ / \\_______ /\\___ / \n";
508 std::cout << "# \\/ \\/ \\/ \n";
509 std::cout << "#\n";
510 std::cout << "# FriendsOfFriends linking\n";
511 std::cout << "# FoF Linking Length: " << linking_length << "\n";
512 std::cout << "# FoF Linking Distance: " << fof_distance << "\n";
513 std::cout << "# dx_boundary / Boxsize: " << Buffersize_over_Boxsize << "\n";
514 std::cout << "# Periodic box: " << std::boolalpha << periodic << "\n";
515 std::cout << "# FoF linking Gridsize = " << Ngrid << " Local_nx: " << Local_nx << "\n";
516 std::cout << "# Maximum possible FoF gridsize = " << int(0.5 / fof_distance) << "\n";
517 std::cout << "# Npart_boundary : " << NumPart_boundary << " ( "
518 << NumPart_boundary / std::pow(1024.0, 2) * bytes_per_particle << " MB )\n";
519 std::cout << "# Grid memory per task: "
520 << (double(Local_nx) * FML::power(Ngrid, NDIM - 1) * sizeof(FoFCell) +
521 NumPart_total * sizeof(size_t)) /
522 std::pow(1024.0, 2)
523 << " MB\n";
524 std::cout << "# ...compared to particle memory: " << NumPart * bytes_per_particle / std::pow(1024.0, 2)
525 << " MB\n";
526 std::cout << "#\n";
527 std::cout << "#=====================================================\n";
528 std::cout << "\n";
529 }
530
531 //=========================================================================
532 // Link together all particles in the local domain that are located within
533 // a linkking distance of linking_length times the mean particle separation.
534 // The result is a list of all the particles and an associated FoF group ID
535 // This ID can be arbitrary but is guaranteed to be unique across tasks
536 //=========================================================================
537
538 // Allocate the FoF id for each particle
539 auto particle_id_FoF = std::vector<size_t>(NumPart + NumPart_boundary, no_FoF_ID);
540
541 // Picks out the particle
542 auto type_from_globalindex = [&](size_t globalindex) {
543 if (globalindex < NumPart_boundary)
544 return int(BOUNDARY_PARTICLE);
545 return int(REGULAR_PARTICLE);
546 };
547 auto localindex_from_globalindex = [&](size_t globalindex) {
548 if (globalindex < NumPart_boundary)
549 return globalindex;
550 return globalindex - NumPart_boundary;
551 };
552 auto globalindex_from_localindex_type = [&](size_t localindex, int type) {
553 if (type == BOUNDARY_PARTICLE)
554 return localindex;
555 return localindex + NumPart_boundary;
556 };
557 auto particle_from_localindex_and_type = [&](size_t localindex, int type) {
558 if (type == BOUNDARY_PARTICLE)
559 return &boundary_particles[localindex];
560 return &part[localindex];
561 };
562
563 // Reserve space for 1000 particles in a FoF group
564 std::vector<size_t> friend_local_index_list;
565 std::vector<signed char> friend_type_list;
566 friend_local_index_list.reserve(1000);
567 friend_type_list.reserve(1000);
568
569 // Function to locate and tag all closest friends
570 // This is then used recursively in the next method we have
571 auto FindAllFriends = [&](T * curpart,
572 [[maybe_unused]] int type,
573 [[maybe_unused]] size_t localindex,
574 size_t globalindex,
575 size_t FoFID,
576 std::vector<size_t> & friend_local_index_list,
577 std::vector<signed char> & friend_type_list) {
578 // Get the particle
579 const auto * pos1 = FML::PARTICLE::GetPos(*curpart);
580
581 // Compute coord of cell particle is in
582 std::array<int, NDIM> coord;
583 std::array<int, NDIM> di;
584 for (int idim = 0; idim < NDIM; idim++) {
585 double ix = (pos1[idim] - (xmin - dx_boundary) * (idim == 0 ? 1 : 0)) * Ngrid;
586 coord[idim] = std::clamp(int(ix), 0, (idim == 0 ? Local_nx : Ngrid) - 1);
587 di[idim] = (ix - coord[idim] > 0.5) ? +1 : -1;
588 }
589
590 // Loop through all 2^NDIM nbor cells
591 // We only go to the cells on the same side as the particle position
592 // As long as the cell-size is larger than 2*fof_distance we don't need
593 // to visit the other cells
594 std::array<int, NDIM> icoord;
595 for (int nbcell = 0; nbcell < twotondim; nbcell++) {
596 for (int idim = 0, n = 1; idim < NDIM; idim++, n *= 2) {
597 int go_left_right_or_stay = (nbcell / n % 2);
598 icoord[idim] = coord[idim] + go_left_right_or_stay * di[idim];
599 }
600
601 // For boundary cells in the x direction we don't have a left or a right nbor
602 // unless we only have 1 task
603 if (FML::NTasks > 1) {
604 if (icoord[0] < 0 or icoord[0] >= Local_nx)
605 continue;
606 } else {
607 if (icoord[0] < 0)
608 icoord[0] += Ngrid;
609 if (icoord[0] >= Ngrid)
610 icoord[0] -= Ngrid;
611 }
612
613 // Compute cell-index or nbor cell
614 bool skip = false;
615 size_t index_nbor_cell = icoord[0];
616 for (int idim = 1; idim < NDIM; idim++) {
617 // Periodic boundary conditions
618 if (periodic) {
619 if (icoord[idim] < 0)
620 icoord[idim] += Ngrid;
621 if (icoord[idim] >= Ngrid)
622 icoord[idim] -= Ngrid;
623 } else {
624 if (icoord[idim] < 0 or icoord[idim] >= Ngrid) {
625 skip = true;
626 break;
627 }
628 }
629 index_nbor_cell = index_nbor_cell * Ngrid + icoord[idim];
630 }
631
632 // Cell do not exist in this case
633 if (skip)
634 continue;
635
636 // Get total number of particles in cell
637 const size_t np_boundary = PartCells[index_nbor_cell].np_boundary;
638 const size_t np = PartCells[index_nbor_cell].np;
639 const size_t np_total = np + np_boundary;
640
641 // Loop over all particles in nbor cell
642 for (size_t ii = 0; ii < np_total; ii++) {
643 T * nborpart{};
644 int nbortype{};
645 size_t nborglobalindex{};
646 size_t nborlocalindex{};
647
648 // Type of particle
649 if (ii < np_boundary) {
650 nborlocalindex = PartCells[index_nbor_cell].ParticleIndexBoundary[ii];
651 nborglobalindex = nborlocalindex;
652 nborpart = &boundary_particles[nborlocalindex];
653 nbortype = BOUNDARY_PARTICLE;
654 } else {
655 nborlocalindex = PartCells[index_nbor_cell].ParticleIndex[ii - np_boundary];
656 nborglobalindex = nborlocalindex + NumPart_boundary;
657 nborpart = &part[nborlocalindex];
658 nbortype = REGULAR_PARTICLE;
659 }
660
661 // If same particle or already processed so that it has an ID skip going further
662 if (particle_id_FoF[nborglobalindex] != no_FoF_ID)
663 continue;
664 if (nborglobalindex == globalindex)
665 continue;
666
667 // Compute distance
668 double dist2 = 0.0;
669 const auto * pos2 = FML::PARTICLE::GetPos(*nborpart);
670 std::array<double, NDIM> dx2;
671 for (int idim = 0; idim < NDIM; idim++) {
672 dx2[idim] = std::abs(pos2[idim] - pos1[idim]);
673 if (dx2[idim] > 0.5 and periodic)
674 dx2[idim] -= 1.0;
675 }
676 for (int idim = 0; idim < NDIM; idim++)
677 dist2 += dx2[idim] * dx2[idim];
678
679 // Check if we have a link. Set the FoF ID in the particle list
680 if (dist2 < fof_distance2) {
681 particle_id_FoF[nborglobalindex] = FoFID;
682 // Only need to set this one time so avoid a write by adding if test
683 if (particle_id_FoF[globalindex] == no_FoF_ID)
684 particle_id_FoF[globalindex] = FoFID;
685 // Push partice info to FoF list
686 friend_local_index_list.push_back(nborlocalindex);
687 friend_type_list.push_back(nbortype);
688 }
689 }
690 }
691 };
692
693 // Does a particle lie within one linking length of the outer edge of the buffer? Then its group might
694 // continue outside the buffer (only boundary particles can be there and only with more than one task)
696 auto reaches_edge = [&](T & p) {
697 if (FML::NTasks == 1)
698 return false;
699 const double x = FML::PARTICLE::GetPos(p)[0];
700 return x < xmin - dx_boundary + fof_distance or x > xmax + dx_boundary - fof_distance;
701 };
702
703 // ID of the FoF groups
704 size_t FoFID = 0;
705
706 // Recursively find all friends of friends
707 foftimer.StartTiming("FoFLinking");
708 for (size_t i = 0; i < NumPart_total; i++) {
709
710 // Show progress bar
711 if (FML::ThisTask == 0)
712 if ((10 * i) / NumPart_total != (10 * i + 10) / NumPart_total or i == 0) {
713 std::cout << (100 * i + 100) / NumPart_total << "% " << std::flush;
714 if (i == NumPart_total - 1) {
715 std::cout << std::endl;
716 }
717 }
718
719 // Fetch the particle
720 size_t globalindex = i;
721 size_t localindex = localindex_from_globalindex(globalindex);
722 int type = type_from_globalindex(globalindex);
723 T * curpart = particle_from_localindex_and_type(localindex, type);
724
725 // Check if particle is not already processed
726 if (particle_id_FoF[i] == no_FoF_ID) {
727 // Start new FoF group
728 friend_local_index_list.clear();
729 friend_type_list.clear();
730
731 // Do linking
732 FindAllFriends(curpart,
733 type,
734 localindex,
735 globalindex,
736 FoFID,
737 friend_local_index_list,
738 friend_type_list);
739
740 if (friend_local_index_list.size() == 0)
741 continue;
742
743 // We are here if we found a group (2 or more particles)
744 // Go through all friends and the friend of these friends
745 // until we have found all particles in the halo
746 FoFHaloClass newhalo(FoFID);
747 newhalo.add(*curpart, periodic);
748 bool reaches_buffer_edge = reaches_edge(*curpart);
749
750 while (friend_local_index_list.size() > 0) {
751 // Fetch a particle
752 auto localindex = friend_local_index_list.back();
753 type = int(friend_type_list.back());
754 globalindex = globalindex_from_localindex_type(localindex, type);
755 curpart = particle_from_localindex_and_type(localindex, type);
756
757 // Fetch position relative to first particle
758 newhalo.add(*curpart, periodic);
759 reaches_buffer_edge = reaches_buffer_edge or reaches_edge(*curpart);
760
761 // Remove particle from list
762 friend_local_index_list.pop_back();
763 friend_type_list.pop_back();
764
765 // Do linking
766 FindAllFriends(curpart,
767 type,
768 localindex,
769 globalindex,
770 FoFID,
771 friend_local_index_list,
772 friend_type_list);
773 }
774
775 // Save halo if it lies in the local domain and has more than nmin particles
776 if (int(newhalo.np) >= nmin_FoF_group) {
777 double xhalo = newhalo.get_pos()[0];
778 if (periodic) // Periodic wrap
779 xhalo += (xhalo < 0.0) ? 1.0 : ((xhalo >= 1.0) ? -1.0 : 0.0);
780 if (xhalo >= FML::xmin_domain and xhalo < FML::xmax_domain) {
781 LocalFoFGroups.push_back(newhalo);
782 if (reaches_buffer_edge)
784 }
785 }
786
787 // Increase the FoF ID
788 FoFID++;
789 }
790 }
791#ifdef USE_MPI
792 MPI_Barrier(FML::communicator);
793#endif
794 foftimer.EndTiming("FoFLinking");
795
796 // Grid no longer needed, free up memory
797 particlegriddata = std::vector<size_t>();
798 PartCells = std::vector<FoFCell>();
799
800 // Show timings
801 if (FML::ThisTask == 0)
803
804 // Print how many particles we found
805 auto nhalos = LocalFoFGroups.size();
806 FML::SumOverTasks(&nhalos);
807 if (FML::ThisTask == 0)
808 std::cout << "# We found a total of " << nhalos << " (" << LocalFoFGroups.size()
809 << " on task 0) "
810 "\n";
811
812 // Warn if groups might be cut off by the buffer
815 std::cout << "WARNING: [FriendsOfFriends] " << FoF_number_of_groups_reaching_buffer_edge
816 << " groups reach the edge of the buffer of particles copied from the neighbor tasks ("
817 << Buffersize_over_Boxsize << " of the box). They might be cut off and then also found as "
818 << "a second, partial group on the neighbor task. Increase the buffer (to more than the size "
819 << "of the largest groups) to be sure the result does not depend on the number of tasks\n";
820
821 // Which of the groups found on this task are kept (local FoFID -> kept)
822 std::vector<char> kept_group(FoFID, 0);
823 for (auto & h : LocalFoFGroups)
824 kept_group[h.id] = 1;
825
826 // We need to fix the FoFID of the halos as they start from 0 on each task
827 // so that all just have a unique ID
828 // We do this such that after mpi-sum we have the sum of the FoFIDs
829 std::vector<long long int> addfofid(FML::NTasks, 0);
830 for (int i = FML::ThisTask + 1; i < FML::NTasks; i++)
831 addfofid[i] = (long long int)FoFID;
832#ifdef USE_MPI
833 MPI_Allreduce(MPI_IN_PLACE, addfofid.data(), NTasks, MPI_LONG_LONG, MPI_SUM, FML::communicator);
834#endif
835
836 // Finalize computation of halos
837 const size_t add = size_t(addfofid[FML::ThisTask]);
838 for (auto & h : LocalFoFGroups) {
839 h.id += add;
840 h.finalize(periodic);
841 }
842
843 // If particles have a set_fofid method then set the ID in the particles: the (global) ID of the group it
844 // belongs to, or no_FoF_ID if it does not belong to a group that is kept. A group is kept by the task
845 // where its center is, so the IDs of particles in groups kept by the neighbor task are sent back from
846 // there (the particles we sent to the neighbors come back in the same order)
847 if constexpr (FML::PARTICLE::has_set_fofid<T>()) {
848 auto global_id = [&](size_t localid) {
849 return (localid != no_FoF_ID and kept_group[localid]) ? localid + size_t(add) : no_FoF_ID;
850 };
851 for (size_t i = 0; i < NumPart; i++)
852 FML::PARTICLE::SetFoFID(part[i], global_id(particle_id_FoF[i + NumPart_boundary]));
853#ifdef USE_MPI
854 if (FML::NTasks > 1) {
855 // boundary_particles[0, n_recv_right) came from the right task, the rest from the left task
856 std::vector<size_t> to_right(n_recv_right), to_left(n_recv_left);
857 for (size_t i = 0; i < n_recv_right; i++)
858 to_right[i] = global_id(particle_id_FoF[i]);
859 for (size_t i = 0; i < n_recv_left; i++)
860 to_left[i] = global_id(particle_id_FoF[n_recv_right + i]);
861 std::vector<size_t> from_left(n_send_left), from_right(n_send_right);
862 const int id_bytes_n_recv_right =
863 int(FML::COMMUNICATION::checked_bytes(n_recv_right, sizeof(size_t), INT_MAX));
864 const int id_bytes_n_send_left =
865 int(FML::COMMUNICATION::checked_bytes(n_send_left, sizeof(size_t), INT_MAX));
866 const int id_bytes_n_recv_left =
867 int(FML::COMMUNICATION::checked_bytes(n_recv_left, sizeof(size_t), INT_MAX));
868 const int id_bytes_n_send_right =
869 int(FML::COMMUNICATION::checked_bytes(n_send_right, sizeof(size_t), INT_MAX));
870 MPI_Status status;
871 MPI_Sendrecv(to_right.data(),
872 id_bytes_n_recv_right,
873 MPI_BYTE,
874 RightTask,
875 1,
876 from_left.data(),
877 id_bytes_n_send_left,
878 MPI_BYTE,
879 LeftTask,
880 1,
882 &status);
883 MPI_Sendrecv(to_left.data(),
884 id_bytes_n_recv_left,
885 MPI_BYTE,
886 LeftTask,
887 2,
888 from_right.data(),
889 id_bytes_n_send_right,
890 MPI_BYTE,
891 RightTask,
892 2,
894 &status);
895 size_t il = 0, ir = 0;
896 for (size_t i = 0; i < NumPart; i++) {
897 const auto * pos = FML::PARTICLE::GetPos(part[i]);
898 if (n_send_left > 0 and pos[0] < xmin + dx_boundary) {
899 const auto id = from_left[il++];
900 if (id != no_FoF_ID)
901 FML::PARTICLE::SetFoFID(part[i], id);
902 }
903 if (n_send_right > 0 and pos[0] > xmax - dx_boundary) {
904 const auto id = from_right[ir++];
905 if (id != no_FoF_ID)
906 FML::PARTICLE::SetFoFID(part[i], id);
907 }
908 }
909 }
910#endif
911 }
912
913 // Boundary particles are finally freed here
914 }
915 } // namespace FOF
916} // namespace FML
917#endif
const int NDIM
double f
Definition Minimizer.cpp:28
const double h
Definition Main.cpp:66
const double linking_length
Definition Main.cpp:59
py::dict cell(const Spatial::CellStatistics &s)
Definition bindings.cpp:92
A gridcell in a grid used for speeding up the linking of particles The ID of the particles is their p...
Definition FoF.h:83
size_t * ParticleIndex
List of indices of particles that are in the cell.
Definition FoF.h:90
int np
Number of particles in the cell.
Definition FoF.h:86
size_t * ParticleIndexBoundary
List of indices of particles that are in the cell.
Definition FoF.h:92
int np_boundary
Number of boundary particles in the cell.
Definition FoF.h:88
FoFCell()=default
List of indices of boundary particles that are in the cell.
Class for performing timings of the code using std::chrono.
Definition Timings.h:27
void StartTiming(const char *name)
Start timing.
Definition Timings.h:87
void PrintAllTimings() const
Output all the recorded timings.
Definition Timings.h:61
double EndTiming(const char *name, bool print=false)
End timing (the time since the last StartTiming with this name is added to its total; a second EndTim...
Definition Timings.h:103
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
void require_count(bool valid, const char *message)
Definition MPICounts.h:27
const constexpr size_t no_FoF_ID
If a particle belongs to no FoF group it is given this FoF ID.
Definition FoF.h:25
Timings foftimer
Records timings of the FoF search.
Definition FoF.h:37
ParticleType
Type of particle for book-keeping.
Definition FoF.h:28
@ BOUNDARY_PARTICLE
Definition FoF.h:28
@ REGULAR_PARTICLE
Definition FoF.h:28
void ParticlesToCells(int Ngrid, int &Local_nx, double dx_boundary, T *part, size_t NumPart, T *part_boundary, size_t NumPart_boundary, std::vector< FoFCell > &PartCells, std::vector< size_t > &particlegriddata)
Internal method: bin particles to a grid.
Definition FoF.h:105
void FriendsOfFriends(T *part, size_t NumPart, double linking_length, int nmin_FoF_group, bool periodic, double Buffersize_over_Boxsize, std::vector< FoFHaloClass > &LocalFoFGroups, int Ngrid=FoF_Ngrid_max)
Locate friends of friends groups and bin what you want over these groups.
Definition FoF.h:200
int FoF_Ngrid_max
The maximum grid we are allowed to use to bin the particle to This is just to have a memory limit in ...
Definition FoF.h:33
size_t FoF_number_of_groups_reaching_buffer_edge
The number of groups found in the last call to FriendsOfFriends (summed over tasks) that reach the ed...
Definition FoF.h:42
get_vel constexpr double * GetPos(...)
void AssignFromBuffer(T &t, char *buffer)
constexpr void SetFoFID(...)
void AppendToBuffer(T &t, char *buffer)
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
constexpr long long int power(int base, int exponent)
Simple integer a^b power-function by squaring (b >= 0; returns 0 for b < 0 instead of recursing forev...
Definition Global.h:287
int ThisTask
The MPI task number.
Definition Global.cpp:39
std::vector< T > GatherFromTasks(T *value)
Gather a single value from all tasks. Value from task ThisTask is stored in values[ThisTask].
Definition Global.h:172
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
constexpr int ii[6]
V3 add(V3 a, V3 b)
double periodic(double d)