FML
Loading...
Searching...
No Matches
MPIParticles.h
Go to the documentation of this file.
1#ifndef MPIPARTICLES_HEADER
2#define MPIPARTICLES_HEADER
3
5#include <algorithm>
6#include <cassert>
7#include <cmath>
8#include <cstdint>
9#include <cstdio>
10#include <fstream>
11#include <functional>
12#include <ios>
13#include <iostream>
14#include <limits>
15#include <string>
16#include <vector>
17
18#ifdef USE_MPI
19#include <mpi.h>
20#endif
21
22#include <FML/Global/Global.h>
25
26namespace FML {
27
28 /// This namespace contains things related to particles: different types, containers for holding shared particles
29 /// across tasks and algorithms for doing stuff with particles.
30 namespace PARTICLE {
31
33
34 //===========================================================
35 ///
36 /// A container class for holding particles that are distributed
37 /// across many CPUs and to easily deal with communication
38 /// of these particles if they cross the domain boundary (simply
39 /// call communicate_particles() at any time to do this)
40 ///
41 /// Contains methods for setting up MPIParticles from a set of particles
42 /// or creating regular grids of particles and so on
43 ///
44 /// Templated on particle class. Particle must at a minimum have the methods
45 ///
46 /// get_pos() : Ptr to position
47 ///
48 /// int get_ndim() : How many dimensions pos have
49 ///
50 /// If the particle has any dynamical allocations you must also provide (these are automatically provided
51 /// otherwise):
52 ///
53 /// get_particle_byte_size() : How many bytes does the particle store
54 ///
55 /// append_to_buffer(char *) : append all the particle data to a char array moving buffer forward as we
56 /// read
57 ///
58 /// assign_from_buffer(char *) : assign data to a particle after it has been received moving buffer forward
59 /// as we do this
60 ///
61 /// Compile time defines:
62 ///
63 /// DEBUG_MPIPARTICLES : Show some info when running
64 ///
65 /// External variables/methods we rely on:
66 ///
67 /// int ThisTask;
68 ///
69 /// int NTasks;
70 ///
71 /// assert_mpi(Expr, Msg)
72 ///
73 /// T power(T base, int exponent);
74 ///
75 //===========================================================
76
77 template <class T>
79 private:
80 // Particle container
81 // std::vector<T> p;
82 Vector<T> p{};
83
84 // Info about the particle distribution
85 size_t NpartTotal{0}; // Total number of particles across all tasks
86 MigrationRoute last_migration_route{MigrationRoute::Serial};
87 size_t NpartLocal_in_use{0}; // Number of particles in use (total allocated given by p.size())
88
89 // The range of x-values in [0,1] that belongs to each task
90 std::vector<double> x_min_per_task{};
91 std::vector<double> x_max_per_task{};
92
93 // If we create particles from scratch according to a grid
94 double buffer_factor{1.0}; // Allocate a factor of this more particles than needed
95
96 // If we created a uniform grid of particles
97 int Npart_1D{0}; // Total number of particles slices
98 int Local_Npart_1D{0}; // Number of slices in current task
99 int Local_p_start{0}; // Start index of local particle slice in [0,Npart_1D)
100
101 // Swap particles
102 void swap_particles(T & a, T & b);
103
104 // The byte-size of particle ipart
105 size_t get_particle_byte_size(size_t ipart);
106
107 // For communication
108 void copy_over_received_data(std::vector<char> & recv_buffer, size_t Npart_received);
109
110 public:
111 /// Iterator for looping through all the active particles i.e. allow for(auto &&p: mpiparticles)
112 class iterator {
113 public:
114 iterator(T * ptr) : ptr(ptr) {}
115 iterator operator++() {
116 ++ptr;
117 return *this;
118 }
119 bool operator!=(const iterator & other) { return ptr != other.ptr; }
120 T & operator*() { return *ptr; }
121
122 private:
123 T * ptr;
124 };
125
126 /// Iterator: points to the first local particle
127 iterator begin() { return iterator(p.data()); }
128 /// Iterator: points to one past the last active local particle
129 iterator end() { return iterator(p.data() + NpartLocal_in_use); }
130
131 /// Create MPIParticles from a set of particles. We only keep the particles in part that are in the correct
132 /// x-range if all_tasks_has_the_same_particles is true nallocate is the total amount of particles we
133 /// allocate for locally (we do buffered read if only one task reads particles to avoid having to allocate
134 /// too much).
135 /// @param[in] part Pointer to a set of particles
136 /// @param[in] NumParts Number of particles we have
137 /// @param[in] nallocate How many particles to allocate for locally (in case we want to have a buffer)
138 /// @param[in] xmin_local The min of the x-range in [0,1] the current task is responsible for
139 /// @param[in] xmax_local The max of the x-range in [0,1] the current task is responsible for
140 /// @param[in] all_tasks_has_the_same_particles Set this to be true if all tasks has the same set of
141 /// particles (e.g. they come from reading the same file). If false then we assume all tasks that has
142 /// particles has distinct particles
143 void create(T * part,
144 size_t NumParts,
145 size_t nallocate,
146 double xmin_local,
147 double xmax_local,
148 bool all_tasks_has_the_same_particles);
149
150 /// Create from a vector of particles with a given selection function
151 /// This could for example be that xmin < x < xmax and if particles have a type only select a particular
152 /// type
153 void create(std::vector<T> & part, size_t nallocate, std::function<bool(T &)> selection_function);
154
155 /// Moves a vector of particles into internal storage (so no copies are being done).
156 /// The extra storage (if needed) needs to already be in part!
157 /// Assumes we have distinct particles on different tasks. This saves having to do allocations
158 /// and copies, but its safer and flexible to just use create() so its best to not use this unless
159 /// you really need to
160 void move_from(Vector<T> && part);
161
162 /// Create \f$ {\rm Npart}_{1D}^{\rm NDIM} \f$ particles in a rectangular grid spread across all tasks
163 /// buffer_factor is how much extra to allocate in case particles moves
164 /// xmin, xmax specifies the domain in [0,1] that the current task is responsible for
165 /// This method only sets the positions of the particles not id or vel or anything else
166 void create_particle_grid(int Npart_1D, double buffer_factor, double xmin_local, double xmax_local);
167
168 MPIParticles() = default;
169
170 // Has the mpiparticles been created?
171 explicit operator bool() const;
172
173 /// Get reference to particle vector. NB: due to we allow a buffer the size of the vector returned is
174 /// not equal to the number of active particles!
176 /// Get a pointer to the first particle.
178
179 /// Access particles through indexing operator
180 T & operator[](size_t i);
181 /// Get a reference to the i'th particle
182 T & get_part(size_t i);
183
184 /// Get the idim component of the position for particle ipart
185 auto get_pos(size_t ipart, int idim);
186 /// Get the idim component of the velocity for particle ipart (if its available)
187 auto get_vel(size_t ipart, int idim);
188
189 /// Total number of active particles across all tasks
190 size_t get_npart_total() const;
191 /// Number of active particles on the local task
192 size_t get_npart() const;
193
194 /// Communicate particles across CPU boundaries
195 void communicate_particles(size_t max_message_bytes = std::numeric_limits<int>::max(),
196 bool force_general = false);
197 /// Last route selected by communicate_particles (same on every rank).
198 MigrationRoute get_last_migration_route() const { return last_migration_route; }
199
200 /// Get a vector of xmin of the domain for each task
201 std::vector<double> get_x_min_per_task();
202 /// Get a vector of xmax of the domain for each task
203 std::vector<double> get_x_max_per_task();
204
205 /// Free all memory of the stored particles
206 void free();
207
208 /// For memory logging add a tag to the vector we have allocated
209 void add_memory_label(std::string name);
210
211 /// Dump data to file (internal format: a raw copy of the particles, one file fileprefix.X per task).
212 /// Meant for checkpointing within the same program: the files can only be read back with
213 /// load_from_file using the same particle type, the same number of tasks and the same machine
214 /// architecture. For portable output use e.g. GADGET (HDF5) files (GadgetUtils)
215 void dump_to_file(std::string fileprefix, size_t max_bytesize_buffer = 100 * 1000 * 1000);
216 /// Load data written by dump_to_file (same particle type and number of tasks)
217 void load_from_file(std::string fileprefix);
218
219 /// Show some info about the class
220 void info();
221
222 /// Reorder the local particles by position (see sort_particles_by_position) so that particles close in
223 /// space are close in memory. Speeds up assigning particles to a grid and interpolating from it
224 void sort_by_position(int nblocks_per_dim);
225 };
226
227 /// @brief Reorder particles by position: stable counting sort by the block of a nblocks_per_dim^N grid the
228 /// particle is in, the blocks in x-major order (the memory order of FFTWGrid real grids). Particles close in
229 /// space end up close in memory, which makes assigning them to a grid and interpolating from it faster (4x for
230 /// shuffled vs ordered particles with CIC). The reordering is done in place (following the cycles of the
231 /// permutation) and needs 4 bytes per particle (8 for more than 2^32 particles) plus a counter per block in
232 /// the local x-range. The particles keep all their data (IDs etc.), only the order changes.
233 template <class T, class IndexType>
234 void sort_particles_by_position_impl(T * part, size_t NumPart, int nblocks_per_dim) {
235 if (NumPart < 2)
236 return;
237 T tmp{};
238 constexpr int N = FML::PARTICLE::GetNDIM(tmp);
239 const int nb = nblocks_per_dim;
240 auto block_coord = [&](double x) { return std::max(0, std::min(int(x * nb), nb - 1)); };
241
242 // The x-range of the blocks of the local particles
243 int bxmin = nb, bxmax = -1;
244 for (size_t i = 0; i < NumPart; i++) {
245 const int bx = block_coord(FML::PARTICLE::GetPos(part[i])[0]);
246 bxmin = std::min(bxmin, bx);
247 bxmax = std::max(bxmax, bx);
248 }
249 size_t nblocks = size_t(bxmax - bxmin + 1);
250 for (int idim = 1; idim < N; idim++)
251 nblocks *= size_t(nb);
252 auto block_of = [&](size_t i) {
253 const auto * pos = FML::PARTICLE::GetPos(part[i]);
254 size_t b = size_t(block_coord(pos[0]) - bxmin);
255 for (int idim = 1; idim < N; idim++)
256 b = b * nb + size_t(block_coord(pos[idim]));
257 return b;
258 };
259
260 // Destination of each particle (stable counting sort)
261 std::vector<size_t> start(nblocks + 1, 0);
262 for (size_t i = 0; i < NumPart; i++)
263 start[block_of(i) + 1]++;
264 for (size_t b = 0; b < nblocks; b++)
265 start[b + 1] += start[b];
266 std::vector<IndexType> dest(NumPart);
267 for (size_t i = 0; i < NumPart; i++)
268 dest[i] = IndexType(start[block_of(i)]++);
269 std::vector<size_t>().swap(start);
270
271 // Apply the permutation in place: put the particle at i where it should go until the one at i belongs there
272 for (size_t i = 0; i < NumPart; i++) {
273 while (size_t(dest[i]) != i) {
274 const size_t j = dest[i];
275 std::swap(part[i], part[j]);
276 std::swap(dest[i], dest[j]);
277 }
278 }
279 }
280
281 template <class T>
282 void sort_particles_by_position(T * part, size_t NumPart, int nblocks_per_dim) {
283 assert_mpi(nblocks_per_dim > 0, "[sort_particles_by_position] nblocks_per_dim must be positive\n");
284 if (NumPart < size_t(std::numeric_limits<uint32_t>::max()))
285 sort_particles_by_position_impl<T, uint32_t>(part, NumPart, nblocks_per_dim);
286 else
287 sort_particles_by_position_impl<T, size_t>(part, NumPart, nblocks_per_dim);
288 }
289
290 template <class T>
291 void MPIParticles<T>::sort_by_position(int nblocks_per_dim) {
292 sort_particles_by_position(p.data(), NpartLocal_in_use, nblocks_per_dim);
293 }
294
295 template <class T>
297 return p.size() > 0;
298 }
299
300 template <class T>
302 auto NDIM = FML::PARTICLE::GetNDIM(T());
303 double memory_in_mb = 0;
304 for (auto & part : p)
305 memory_in_mb += FML::PARTICLE::GetSize(part);
306 memory_in_mb /= 1e6;
307 double max_memory_in_mb = memory_in_mb;
308 double min_memory_in_mb = memory_in_mb;
309 double mean_memory_in_mb = memory_in_mb / double(FML::NTasks);
310 FML::MaxOverTasks(&max_memory_in_mb);
311 FML::MinOverTasks(&min_memory_in_mb);
312 FML::SumOverTasks(&mean_memory_in_mb);
313 double fraction_filled = double(NpartLocal_in_use) / double(p.size()) * 100;
314 double max_fraction_filled = fraction_filled;
315 double min_fraction_filled = fraction_filled;
316 double mean_fraction_filled = fraction_filled / double(FML::NTasks);
317 FML::MaxOverTasks(&max_fraction_filled);
318 FML::MinOverTasks(&min_fraction_filled);
319 FML::SumOverTasks(&mean_fraction_filled);
320
321 if (FML::ThisTask == 0) {
322 std::cout << "\n";
323 std::cout << "#=====================================================\n";
324 std::cout << "#\n";
325 std::cout << "# .___ _____ \n";
326 std::cout << "# | | _____/ ____\\____ \n";
327 std::cout << "# | |/ \\ __\\/ _ \\ \n";
328 std::cout << "# | | | \\ | ( <_> ) \n";
329 std::cout << "# |___|___| /__| \\____/ \n";
330 std::cout << "# \\/ \n";
331 std::cout << "#\n";
332 std::cout << "# Info about MPIParticles. Dimension of particles is " << NDIM << "\n";
333 std::cout << "# We have allocated " << mean_memory_in_mb << " MB (mean)\n";
334 std::cout << "# " << min_memory_in_mb << " MB (min)\n";
335 std::cout << "# " << max_memory_in_mb << " MB (max)\n";
336 std::cout << "# Total particles across all tasks is " << NpartTotal << "\n";
337 std::cout << "# Task 0 has " << NpartLocal_in_use << " parts. Capacity: " << p.size() << "\n";
338 std::cout << "# The buffer is " << mean_fraction_filled << " % (mean)\n";
339 std::cout << "# " << min_fraction_filled << " % (min)\n";
340 std::cout << "# " << max_fraction_filled << " % (max) filled across tasks\n";
341 std::cout << "#\n";
342 std::cout << "#=====================================================\n";
343 std::cout << "\n";
344 }
345 }
346
347 template <class T>
348 void MPIParticles<T>::add_memory_label([[maybe_unused]] std::string name) {
349#ifdef MEMORY_LOGGING
350 FML::MemoryLog::get()->add_label(p.data(), p.capacity(), name);
351#endif
352 }
353
354 template <class T>
356 p.clear();
357 p.shrink_to_fit();
358 }
359
360 template <class T>
362 // Set the xmin/xmax
363 x_min_per_task = FML::GatherFromTasks(&FML::xmin_domain);
364 x_max_per_task = FML::GatherFromTasks(&FML::xmax_domain);
365 // Move data from particles into internal storage
366 p = std::move(part);
367 // Set number of particles
368 NpartLocal_in_use = p.size();
369 NpartTotal = NpartLocal_in_use;
370 FML::SumOverTasks(&NpartTotal);
371 // Resize to capacity - we keep size in NpartLocal_in_use
372 p.resize(p.capacity());
373 }
374
375 // Create from a vector of particles with a given selection function
376 template <class T>
377 void
378 MPIParticles<T>::create(std::vector<T> & part, size_t nallocate, std::function<bool(T &)> selection_function) {
379
380 // Set the xmin/xmax
381 x_min_per_task = FML::GatherFromTasks(&FML::xmin_domain);
382 x_max_per_task = FML::GatherFromTasks(&FML::xmax_domain);
383 p.clear();
384 p.reserve(nallocate + 1);
385
386 size_t count = 0;
387 for (auto & curpart : part) {
388 if (selection_function(curpart)) {
389 p.push_back(curpart);
390 count++;
391 if (count > nallocate) {
392 assert_mpi(false, "[MPIParticle::create] Reached allocation limit. Increase nallocate\n");
393 }
394 }
395 }
396 // Set number of particles
397 NpartLocal_in_use = count;
398 NpartTotal = NpartLocal_in_use;
399 FML::SumOverTasks(&NpartTotal);
400 // Resize to capacity - we keep size in NpartLocal_in_use
401 p.resize(p.capacity());
402 }
403
404 /// Bring the x-coordinate of a particle given to MPIParticles::create into [0,1): x = 1.0 (or a tiny
405 /// negative x that wraps to 1.0 after rounding, e.g. -1e-17) is a valid periodic position that would otherwise
406 /// be in no task's range [xmin,xmax). x = 1.0 is treated as communicate_particles does (just below 1.0) and a
407 /// tiny negative x becomes 0.0. Anything else outside [0,1) (or NaN) is an error
408 template <class U>
410 if (x == U(1.0))
411 x = std::nextafter(x, U(0.0));
412 else if (x < U(0.0) and x + U(1.0) == U(1.0))
413 x = U(0.0);
414 if (not(x >= U(0.0) and x < U(1.0))) {
415 std::string errmsg = "[MPIParticles::create] Particle with x = " + std::to_string(double(x)) +
416 " is outside [0,1). Particles must be wrapped (periodic) before calling create\n";
417 assert_mpi(false, errmsg.c_str());
418 }
419 }
420
421 template <class T>
423 size_t NumPartinpart,
424 size_t nallocate,
425 double xmin,
426 double xmax,
427 bool all_tasks_has_the_same_particles) {
428 if (FML::NTasks == 1)
429 all_tasks_has_the_same_particles = true;
430
431 // Set the xmin/xmax
432 x_min_per_task = FML::GatherFromTasks(&xmin);
433 x_max_per_task = FML::GatherFromTasks(&xmax);
434
435#ifdef DEBUG_MPIPARTICLES
436 if (ThisTask == 0) {
437 for (int i = 0; i < NTasks; i++) {
438 std::cout << "Task: " << i << " / " << NTasks << " xmin: " << x_min_per_task[i]
439 << " xmax: " << x_max_per_task[i] << "\n";
440 }
441 }
442#endif
443
444 // Allocate memory
445 p.resize(nallocate);
446 add_memory_label("MPIParticles::create");
447
448 // If all tasks has the same particles
449 // we read all the particles and only keep the particles in range
450 if (all_tasks_has_the_same_particles) {
451 size_t count = 0;
452 for (size_t i = 0; i < NumPartinpart; i++) {
453 auto x = FML::PARTICLE::GetPos(part[i])[0];
455 if (x >= xmin and x < xmax) {
456 // Check that we are not past allocation limit before writing
457 assert_mpi(count < nallocate,
458 "[MPIParticle::create] Reached allocation limit. Increase nallocate\n");
459 p[count] = part[i];
460 FML::PARTICLE::GetPos(p[count])[0] = x;
461 count++;
462 }
463 }
464
465 NpartLocal_in_use = count;
466
467 NpartTotal = NpartLocal_in_use;
468 FML::SumOverTasks(&NpartTotal);
469 }
470
471#ifdef USE_MPI
472 std::cout << std::flush;
473 MPI_Barrier(FML::communicator);
474#endif
475
476 // If only one or more task has particles then read in batches and communicate as we go along
477 // just in case the total amount of particles are too large
478 if (not all_tasks_has_the_same_particles) {
479
480 // Read in batches
481 size_t start = 0;
482 size_t count = 0;
483 bool more_to_process_globally = true;
484 bool more_to_process_locally = NumPartinpart > 0;
485 while (more_to_process_globally) {
486 if (more_to_process_locally) {
487 // We can only read as many as we have free space for (we keep the particles that belong
488 // to us from earlier batches and receive particles from other tasks)
489 const size_t nmax_per_batch = nallocate - count;
490 assert_mpi(nmax_per_batch > 0,
491 "[MPIParticle::create] Reached allocation limit while reading particles in batches "
492 "(no room for more particles). Increase nallocate\n");
493 size_t nbatch = start + nmax_per_batch < NumPartinpart ? start + nmax_per_batch : NumPartinpart;
494 more_to_process_locally = nbatch < NumPartinpart;
495
496 for (size_t i = start; i < nbatch; i++) {
497 // Check that we are not past allocation limit before writing
498 assert_mpi(count < nallocate,
499 "[MPIParticle::create] Reached allocation limit. Increase nallocate\n");
500 p[count] = part[i];
502 count++;
503 }
504 start = nbatch;
505 }
506
507 // Set the number of particles read
508 NpartLocal_in_use = count;
509
510#ifdef DEBUG_MPIPARTICLES
511 std::cout << "Task: " << ThisTask << " NpartLocal_in_use: " << NpartLocal_in_use << " precomm\n";
512#endif
513
514 // Send particles to where they belong
515 communicate_particles();
516
517#ifdef DEBUG_MPIPARTICLES
518 std::cout << "Task: " << ThisTask << " NpartLocal_in_use: " << NpartLocal_in_use << " postcomm\n";
519#endif
520
521 // Update how many particles we now have
522 count = NpartLocal_in_use;
523
524 // The while loop continues until all tasks are done reading particles
525 int moretodo = more_to_process_locally ? 1 : 0;
526 FML::SumOverTasks(&moretodo);
527 more_to_process_globally = (moretodo >= 1);
528 }
529 }
530
531 // Set total number of particles
532 NpartTotal = NpartLocal_in_use;
533 FML::SumOverTasks(&NpartTotal);
534
535#ifdef DEBUG_MPIPARTICLES
536 std::cout << "Task: " << ThisTask << " NpartLocal_in_use: " << NpartLocal_in_use << "\n";
537#endif
538 }
539
540 template <class T>
542 return p[i];
543 }
544
545 template <class T>
547 return NpartLocal_in_use;
548 }
549
550 template <class T>
552 return NpartTotal;
553 }
554
555 template <class T>
557 return p;
558 }
559
560 template <class T>
562 return p.data();
563 }
564
565 template <class T>
567 return x_min_per_task;
568 }
569
570 template <class T>
572 return x_max_per_task;
573 }
574
575 template <class T>
577 return p[i];
578 }
579
580 template <class T>
581 void MPIParticles<T>::swap_particles(T & a, T & b) {
582 T tmp = a;
583 a = b;
584 b = tmp;
585 }
586
587 template <class T>
589 double buffer_factor,
590 double xmin_local,
591 double xmax_local) {
592 this->Npart_1D = Npart_1D;
593 this->buffer_factor = buffer_factor;
594
595 // Use the local xmin,xmax values to compute how many slices per task
596 int imin = 0;
597 while (imin / double(Npart_1D) < xmin_local) {
598 imin++;
599 }
600 int imax = imin;
601 while (imax / double(Npart_1D) < xmax_local) {
602 imax++;
603 }
604 Local_p_start = imin;
605 Local_Npart_1D = imax - imin;
606
607 // Sanity check
608 auto Local_Npart_1D_per_task = FML::GatherFromTasks(&Local_Npart_1D);
609 int Local_p_start_computed = 0, Npart_1D_computed = 0;
610 for (int i = 0; i < NTasks; i++) {
611 if (i < ThisTask)
612 Local_p_start_computed += Local_Npart_1D_per_task[i];
613 Npart_1D_computed += Local_Npart_1D_per_task[i];
614 }
615 assert_mpi(Npart_1D_computed == Npart_1D,
616 "[MPIParticles::create_particle_grid] Computed Npart does not match Npart\n");
617 assert_mpi(Local_p_start_computed == Local_p_start,
618 "[MPIParticles::create_particle_grid] Computed Local_p_start does not match Local_p_start\n");
619
620 // Get the min and max x-positions (in [0,1]) that each of the tasks is responsible for
621 x_min_per_task = std::vector<double>(NTasks, 0.0);
622 x_max_per_task = std::vector<double>(NTasks, 0.0);
623
624 // If we don't have xmin,xmax available
625 // x_min_per_task[ThisTask] = Local_p_start / double(Npart_1D);
626 // x_max_per_task[ThisTask] = (Local_p_start + Local_Npart_1D) / double(Npart_1D);
627
628 // Fetch these values
629 x_min_per_task = FML::GatherFromTasks(&xmin_local);
630 x_max_per_task = FML::GatherFromTasks(&xmax_local);
631
632#ifdef DEBUG_MPIPARTICLES
633 // Output some info
634 for (int taskid = 0; taskid < NTasks; taskid++) {
635 if (ThisTask == 0) {
636 std::cout << "Task[" << taskid << "] xmin: " << x_min_per_task[taskid]
637 << " xmax: " << x_max_per_task[taskid] << "\n";
638 }
639 }
640#endif
641
642 // Total number of particles
643 T tmp_ndim; // (GetNDIM(T()) needs a particle that can be built at compile time)
644 constexpr int ndim = FML::PARTICLE::GetNDIM(tmp_ndim);
645 NpartTotal = FML::power(Npart_1D, ndim);
646 NpartLocal_in_use = Local_Npart_1D * FML::power(Npart_1D, ndim - 1);
647
648 // Allocate particle struct. The capacity is buffer_factor times the largest number of lattice slices
649 // that the local x-range [xmin_local, xmax_local) can hold (for any uniform shift of the lattice), not
650 // times the number of slices we got: with Npart_1D not divisible by NTasks a task can get fewer slices
651 // than its share of the volume (or no slice at all if Npart_1D < NTasks) and would otherwise have no room
652 // for particles moving in. When the domain holds a whole number of slices (the usual case) this is the
653 // same as buffer_factor * NpartLocal_in_use
654 const double nslices_domain = double(Npart_1D) * (xmax_local - xmin_local);
655 const size_t max_slices = size_t(std::max(0.0, std::ceil(nslices_domain - 1e-9)));
656 const size_t npart_per_slice = size_t(FML::power(Npart_1D, ndim - 1));
657 size_t NpartToAllocate =
658 size_t(std::ceil(std::max(buffer_factor, 1.0) * double(max_slices * npart_per_slice)));
659 NpartToAllocate = std::max(NpartToAllocate, size_t(NpartLocal_in_use));
660 assert_mpi(NpartToAllocate >= NpartLocal_in_use,
661 "[MPIParticles::create_particle_grid] Allocation is smaller than the number of particles\n");
662 p.resize(NpartToAllocate);
663 add_memory_label("MPIParticles::create_particle_grid");
664
665 // Initialize the coordinate to the first cell in the local grid
666 std::vector<double> Pos(ndim, 0.0);
667 std::vector<int> coord(ndim, 0);
668 coord[0] = Local_p_start;
669 for (size_t i = 0; i < NpartLocal_in_use; i++) {
670 auto * Pos = FML::PARTICLE::GetPos(p[i]);
671
672 // Position regular grid
673 for (int idim = 0; idim < ndim; idim++) {
674 Pos[idim] = coord[idim] / double(Npart_1D);
675 }
676
677 // This is adding 1 very time in base Npart_1D storing the digits in reverse order in [coord]
678 int idim = ndim - 1;
679 while (++coord[idim] == Npart_1D) {
680 coord[idim--] = 0;
681 if (idim < 0)
682 break;
683 }
684 }
685 }
686
687 template <class T>
688 auto MPIParticles<T>::get_pos(size_t ipart, int i) {
689 auto pos = FML::PARTICLE::GetPos(p[ipart]);
690 if (pos == nullptr)
691 assert(false);
692 return pos[i];
693 }
694
695 template <class T>
696 auto MPIParticles<T>::get_vel(size_t ipart, int i) {
697 auto vel = FML::PARTICLE::GetVel(p[ipart]);
698 if (vel == nullptr)
699 assert(false);
700 return vel[i];
701 }
702
703 template <class T>
704 size_t MPIParticles<T>::get_particle_byte_size(size_t ipart) {
705 return FML::PARTICLE::GetSize(p[ipart]);
706 }
707
708 template <class T>
709 void MPIParticles<T>::copy_over_received_data(std::vector<char> & recv_buffer, size_t Npart_recv) {
710 assert_mpi(NpartLocal_in_use <= p.size() && Npart_recv <= p.size() - NpartLocal_in_use,
711 "[MPIParticles::copy_over_received_data] Too many particles received! Increase buffer\n");
712
713 char * buffer = recv_buffer.data();
714 size_t bytes_processed = 0;
715 for (size_t i = 0; i < Npart_recv; i++) {
716 FML::PARTICLE::AssignFromBuffer(p[NpartLocal_in_use + i], buffer);
717 auto size = FML::PARTICLE::GetSize(p[NpartLocal_in_use + i]);
718 assert_mpi(size > 0 && size_t(size) <= recv_buffer.size() - bytes_processed,
719 "[MPIParticles] Invalid deserialized particle byte size");
720 buffer += size;
721 bytes_processed += size_t(size);
722 }
723
724 // Update the total number of particles in use
725 NpartLocal_in_use += Npart_recv;
726 }
727
728 template <class T>
729 void MPIParticles<T>::communicate_particles([[maybe_unused]] size_t max_message_bytes,
730 [[maybe_unused]] bool force_general) {
731 if (FML::NTasks == 1) {
732 last_migration_route = MigrationRoute::Serial;
733 return;
734 }
735#ifdef USE_MPI
736
737 FML::COMMUNICATION::Count max_chunk_bytes =
738 std::min(max_message_bytes, size_t(std::numeric_limits<int>::max()));
739 FML::MinOverTasks(&max_chunk_bytes);
740 FML::COMMUNICATION::require_count(max_chunk_bytes > 0, "[MPIParticles] Message limit must be positive");
741
742 // Binary lookup requires a finite, contiguous rank-ordered partition. Empty slabs are allowed.
743 bool valid_partition = x_min_per_task.size() == size_t(NTasks) && x_max_per_task.size() == size_t(NTasks);
744 if (valid_partition) {
745 valid_partition = x_min_per_task.front() == 0.0 && x_max_per_task.back() == 1.0;
746 for (int task = 0; task < NTasks; ++task)
747 valid_partition &= std::isfinite(x_min_per_task[task]) && std::isfinite(x_max_per_task[task]) &&
748 x_min_per_task[task] <= x_max_per_task[task] &&
749 (!task || x_min_per_task[task] == x_max_per_task[task - 1]);
750 }
751 FML::COMMUNICATION::require_count(valid_partition,
752 "[MPIParticles] Slabs must partition [0,1] in rank order");
753 const int left = int((static_cast<long long>(ThisTask) + NTasks - 1) % NTasks);
754 const int right = int((static_cast<long long>(ThisTask) + 1) % NTasks);
755 auto owner_of = [&](const auto & x) {
756 // Most departures end on a neighbor; avoid even a logarithmic search in that case.
757 if (x >= x_min_per_task[right] && x < x_max_per_task[right])
758 return right;
759 if (x >= x_min_per_task[left] && x < x_max_per_task[left])
760 return left;
761 return int(std::upper_bound(x_max_per_task.begin(), x_max_per_task.end(), x) - x_max_per_task.begin());
762 };
763 int route = force_general ? 2 : 0; // 0: no traffic, 1: neighbors, 2: general (including forced).
764
765 // The number of particles we start with
766 size_t NpartLocal_in_use_pre_comm = NpartLocal_in_use;
767
768#ifdef DEBUG_MPIPARTICLES
769 if (ThisTask == 0) {
770 std::cout << "Communicating particles task: " << ThisTask
771 << " Nparticles: " << NpartLocal_in_use_pre_comm << "\n"
772 << std::flush;
773 }
774#endif
775
776 T tmp{};
777 using PosType = std::remove_reference_t<decltype(tmp.get_pos()[0])>;
778
779 // Count how many particles to send to each task
780 // and move the particles to be send to the back of the array
781 // and reduce the NumPartLocal_in_use if a partice is to be sent
782 // After this is done we have all the particles to be send in
783 // location [NpartLocal_in_use, NpartLocal_in_use_pre_comm)
785 std::vector<Count> n_to_send(NTasks, 0), n_to_recv(NTasks, 0);
786 std::vector<Count> nbytes_to_send(NTasks, 0), nbytes_to_recv(NTasks, 0);
787 bool valid_counts = true;
788 auto count_outgoing = [&](int task, T & particle) {
789 route = std::max(route, task == left || task == right ? 1 : 2);
790 auto bytes = FML::PARTICLE::GetSize(particle);
791 valid_counts = valid_counts && bytes > 0;
792 if (bytes > 0) {
793 valid_counts &= FML::COMMUNICATION::add_count(n_to_send[task], 1);
794 valid_counts &= FML::COMMUNICATION::add_count(nbytes_to_send[task], Count(bytes));
795 }
796 };
797 size_t i = 0;
798 while (i < NpartLocal_in_use) {
799 auto & x = FML::PARTICLE::GetPos(p[i])[0];
800
801 // To fix issues appearing when we are exactly on the boundary
802 if (x == 1.0)
803 x = std::nextafter(x, PosType(0.0));
804 if (x == 0.0)
805 x = std::numeric_limits<PosType>::min();
806
807 // Particles must be wrapped inside [0,1) (this also catches NaN)
808 if (not(x >= 0.0 and x < 1.0)) {
809 std::string errmsg =
810 "[MPIParticles::communicate_particles] Particle with x = " + std::to_string(double(x)) +
811 " is outside [0,1). Particles must be wrapped (periodic) before communication\n";
812 assert_mpi(false, errmsg.c_str());
813 }
814
815 if (x < x_min_per_task[ThisTask] || x >= x_max_per_task[ThisTask]) {
816 const int taskid = owner_of(x);
817 count_outgoing(taskid, p[i]);
818 swap_particles(p[i], p[--NpartLocal_in_use]);
819
820 } else {
821 i++;
822 }
823 }
824
825 // Communicate to get how many particles and bytes to receive from each task
826 FML::COMMUNICATION::require_count(valid_counts, "[MPIParticles] Outgoing particle/byte count overflow");
827 FML::MaxOverTasks(&route);
828 if (route == 0) {
829 last_migration_route = MigrationRoute::NoTraffic;
830 return;
831 }
832 last_migration_route = route == 1 ? MigrationRoute::Neighbors : MigrationRoute::General;
833 std::vector<int> peer_steps;
834 if (route == 1) {
835 peer_steps.push_back(1);
836 if (NTasks > 2)
837 peer_steps.push_back(NTasks - 1);
838 for (int step : peer_steps) {
839 const int dest = int((static_cast<long long>(ThisTask) + step) % NTasks);
840 const int source = int((static_cast<long long>(ThisTask) - step + NTasks) % NTasks);
841 const Count outgoing[2] = {n_to_send[dest], nbytes_to_send[dest]};
842 Count incoming[2]{};
843 MPI_Sendrecv(outgoing,
844 2,
845 MPI_UNSIGNED_LONG_LONG,
846 dest,
847 0,
848 incoming,
849 2,
850 MPI_UNSIGNED_LONG_LONG,
851 source,
852 0,
854 MPI_STATUS_IGNORE);
855 n_to_recv[source] = incoming[0];
856 nbytes_to_recv[source] = incoming[1];
857 }
858 } else {
859 for (int step = 1; step < NTasks; ++step)
860 peer_steps.push_back(step);
861 MPI_Alltoall(n_to_send.data(),
862 1,
863 MPI_UNSIGNED_LONG_LONG,
864 n_to_recv.data(),
865 1,
866 MPI_UNSIGNED_LONG_LONG,
868 MPI_Alltoall(nbytes_to_send.data(),
869 1,
870 MPI_UNSIGNED_LONG_LONG,
871 nbytes_to_recv.data(),
872 1,
873 MPI_UNSIGNED_LONG_LONG,
875 }
876
877#ifdef DEBUG_MPIPARTICLES
878 // Show some info
879 if (ThisTask == 0) {
880 for (int i = 0; i < NTasks; i++) {
881 std::cout << "Task " << ThisTask << " send to " << i << " : " << n_to_send[i] << "\n"
882 << std::flush;
883 std::cout << "Task " << ThisTask << " recv from " << i << " : " << n_to_recv[i] << "\n"
884 << std::flush;
885 }
886 }
887#endif
888
889 // Total number to send and recv
890 const auto send_particles = FML::COMMUNICATION::checked_size_layout(n_to_send, p.max_size());
891 const auto recv_particles = FML::COMMUNICATION::checked_size_layout(n_to_recv, p.max_size());
892 const auto send_bytes =
893 FML::COMMUNICATION::checked_size_layout(nbytes_to_send, std::vector<char>().max_size());
894 const auto recv_bytes =
895 FML::COMMUNICATION::checked_size_layout(nbytes_to_recv, std::vector<char>().max_size());
896 const size_t ntot_to_send = send_particles.total, ntot_to_recv = recv_particles.total;
897 const size_t ntot_bytes_to_send = send_bytes.total, ntot_bytes_to_recv = recv_bytes.total;
898
899 // Sanity check
900 std::string error =
901 "[MPIParticles::communicate_particles] Number to particles to communicate does not match\n" +
902 std::to_string(NpartLocal_in_use_pre_comm) + " vs " + std::to_string(NpartLocal_in_use + ntot_to_send) +
903 "\n";
904 error += "Possible cause is particles not being wrapped inside [0,1) or not communicated after they have "
905 "moved across boundaries!\n";
906 assert_mpi(NpartLocal_in_use <= NpartLocal_in_use_pre_comm &&
907 ntot_to_send == NpartLocal_in_use_pre_comm - NpartLocal_in_use,
908 error.c_str());
909
910 FML::COMMUNICATION::require_count(NpartLocal_in_use <= p.size() &&
911 ntot_to_recv <= p.size() - NpartLocal_in_use,
912 "[MPIParticles] Receive count exceeds allocated particle capacity");
913
914 // Allocate send buffer
915 std::vector<char> send_buffer(ntot_bytes_to_send);
916 std::vector<char> recv_buffer(ntot_bytes_to_recv);
917 FML::PERFORMANCE::transport_allocation(send_buffer.capacity());
918 FML::PERFORMANCE::transport_allocation(recv_buffer.capacity());
919
920 // Pointers to each send-recv place in the send-recv buffer
921 std::vector<size_t> offset_in_send_buffer(NTasks, 0);
922 std::vector<size_t> offset_in_recv_buffer(NTasks, 0);
923 std::vector<char *> send_buffer_by_task(NTasks, send_buffer.data());
924 std::vector<char *> recv_buffer_by_task(NTasks, recv_buffer.data());
925 for (int i = 1; i < NTasks; i++) {
926 offset_in_send_buffer[i] = offset_in_send_buffer[i - 1] + nbytes_to_send[i - 1];
927 offset_in_recv_buffer[i] = offset_in_recv_buffer[i - 1] + nbytes_to_recv[i - 1];
928 send_buffer_by_task[i] =
929 (send_buffer.empty() ? nullptr : send_buffer.data() + offset_in_send_buffer[i]);
930 recv_buffer_by_task[i] =
931 (recv_buffer.empty() ? nullptr : recv_buffer.data() + offset_in_recv_buffer[i]);
932 }
933
934 std::vector<size_t> packed(NTasks, 0);
935 auto append_particle = [&](size_t index, int task) {
936 auto bytes = FML::PARTICLE::GetSize(p[index]);
937 if (bytes <= 0 || size_t(bytes) > size_t(nbytes_to_send[task]) - packed[task]) {
938 valid_counts = false;
939 return;
940 }
941 FML::PARTICLE::AppendToBuffer(p[index], send_buffer_by_task[task]);
942 send_buffer_by_task[task] += size_t(bytes);
943 packed[task] += size_t(bytes);
944 };
945
946 // Gather particle data
947 for (size_t i = 0; i < ntot_to_send; i++) {
948 size_t index = NpartLocal_in_use + i;
949 auto x = FML::PARTICLE::GetPos(p[index])[0];
950
951 const int taskid = owner_of(x);
952 assert_mpi(taskid != ThisTask, "[MPIParticles] Outgoing particle is still locally owned");
953 append_particle(index, taskid);
954 }
955
956 for (int task = 0; task < NTasks; ++task)
957 valid_counts &= packed[task] == size_t(nbytes_to_send[task]);
959 "[MPIParticles] Serialized particle sizes changed while packing");
960 FML::PERFORMANCE::record(FML::PERFORMANCE::Counter::TransportPackedBytes, ntot_bytes_to_send);
961
962 // We changed the send-recv pointers above so reset them
963 for (int i = 0; i < NTasks; i++) {
964 send_buffer_by_task[i] =
965 (send_buffer.empty() ? nullptr : send_buffer.data() + offset_in_send_buffer[i]);
966 recv_buffer_by_task[i] =
967 (recv_buffer.empty() ? nullptr : recv_buffer.data() + offset_in_recv_buffer[i]);
968 }
969
970 // Communicate the particle data. MPI counts are int so we send in chunks of
971 // at most INT_MAX bytes. All tasks do the same number of chunks so that the
972 // send/recv pairs always match up (most of the time this is just 1 chunk)
973 Count max_bytes = 0;
974 for (int i = 0; i < NTasks; i++)
975 max_bytes = std::max(max_bytes, std::max(nbytes_to_send[i], nbytes_to_recv[i]));
976 FML::MaxOverTasks(&max_bytes);
977 const Count nchunks = max_bytes / max_chunk_bytes + (max_bytes % max_chunk_bytes != 0);
978
979 for (int step : peer_steps) {
980 int send_request_to = int((static_cast<long long>(ThisTask) + step) % NTasks);
981 int get_request_from = int((static_cast<long long>(ThisTask) - step + NTasks) % NTasks);
982
983 for (Count ichunk = 0; ichunk < nchunks; ichunk++) {
984 const Count offset = ichunk * max_chunk_bytes;
985 const int nsend = int(offset < nbytes_to_send[send_request_to] ?
986 std::min(nbytes_to_send[send_request_to] - offset, max_chunk_bytes) :
987 0);
988 const int nrecv = int(offset < nbytes_to_recv[get_request_from] ?
989 std::min(nbytes_to_recv[get_request_from] - offset, max_chunk_bytes) :
990 0);
991 char * send_ptr = nsend ? send_buffer_by_task[send_request_to] + size_t(offset) : nullptr;
992 char * recv_ptr = nrecv ? recv_buffer_by_task[get_request_from] + size_t(offset) : nullptr;
993
994 // Send to the right, receive from left
995 MPI_Status status;
996 MPI_Sendrecv(send_ptr,
997 nsend,
998 MPI_CHAR,
999 send_request_to,
1000 0,
1001 recv_ptr,
1002 nrecv,
1003 MPI_CHAR,
1004 get_request_from,
1005 0,
1007 &status);
1008 FML::PERFORMANCE::payload(size_t(nsend), size_t(nrecv));
1009 }
1010 }
1011
1012 // Copy over the particle data (this also updates the total number of particles)
1013 copy_over_received_data(recv_buffer, ntot_to_recv);
1014 FML::PERFORMANCE::record(FML::PERFORMANCE::Counter::TransportUnpackedBytes, ntot_bytes_to_recv);
1015#endif
1016 }
1017
1018 template <class T>
1019 void MPIParticles<T>::dump_to_file(std::string fileprefix, size_t max_bytesize_buffer) {
1020 std::string filename = fileprefix + "." + std::to_string(FML::ThisTask);
1021 auto myfile = std::fstream(filename, std::ios::out | std::ios::binary);
1022
1023 // If we fail to write give a warning, but continue
1024 if (not myfile.good()) {
1025 std::string error = "[MPIParticles::dump_to_file] Failed to save the particle data on task " +
1026 std::to_string(FML::ThisTask) + " Filename: " + filename;
1027 std::cout << error << "\n";
1028 return;
1029 }
1030
1031 int ndim = FML::PARTICLE::GetNDIM(T());
1032
1033 // Write header data
1034 size_t NpartLocalAllocated = p.size();
1035 myfile.write((char *)&ndim, sizeof(ndim));
1036 myfile.write((char *)&NpartTotal, sizeof(NpartTotal));
1037 myfile.write((char *)&NpartLocal_in_use, sizeof(NpartLocal_in_use));
1038 myfile.write((char *)&NpartLocalAllocated, sizeof(NpartLocalAllocated));
1039 myfile.write((char *)x_min_per_task.data(), sizeof(double) * FML::NTasks);
1040 myfile.write((char *)x_max_per_task.data(), sizeof(double) * FML::NTasks);
1041
1042 if (NpartLocal_in_use == 0) {
1043 myfile.close();
1044 return;
1045 }
1046
1047 // Allocate a write buffer
1048 std::vector<char> buffer_data(max_bytesize_buffer);
1049 assert_mpi(max_bytesize_buffer > 0 && FML::PARTICLE::GetSize(p[0]) > 0 &&
1050 size_t(FML::PARTICLE::GetSize(p[0])) <= (max_bytesize_buffer - 1) / 100,
1051 "[MPIParticles::dump_to_file] Buffer size is likely too small, can't even fit 100 particles\n");
1052
1053 if (FML::ThisTask == 0)
1054 std::cout << "# Writing particles to " << fileprefix << ".X\n";
1055
1056 // Write in chunks (only the particles in use)
1057 size_t nwritten = 0;
1058 while (nwritten < NpartLocal_in_use) {
1059
1060 size_t n_to_write = NpartLocal_in_use - nwritten;
1061 size_t nbytes_to_write = 0;
1062
1063 char * buffer = buffer_data.data();
1064 for (size_t i = 0; i < n_to_write; i++) {
1065 auto bytes = FML::PARTICLE::GetSize(p[nwritten + i]);
1066 if (bytes <= 0 || size_t(bytes) > max_bytesize_buffer - nbytes_to_write) {
1067 n_to_write = i;
1068 break;
1069 }
1070 FML::PARTICLE::AppendToBuffer(p[nwritten + i], buffer);
1071 buffer += bytes;
1072 nbytes_to_write += bytes;
1073 }
1074 assert_mpi(n_to_write > 0,
1075 "[MPIParticles::dump_to_file] A particle does not fit in the buffer. Increase "
1076 "max_bytesize_buffer\n");
1077 myfile.write((char *)&n_to_write, sizeof(n_to_write));
1078 myfile.write((char *)&nbytes_to_write, sizeof(nbytes_to_write));
1079 myfile.write((char *)buffer_data.data(), nbytes_to_write);
1080
1081 nwritten += n_to_write;
1082 }
1083 if (not myfile.good())
1084 std::cout << "[MPIParticles::dump_to_file] Error writing the particle data on task " +
1085 std::to_string(FML::ThisTask) + " Filename: " + filename + "\n";
1086 myfile.close();
1087 }
1088
1089 template <class T>
1090 void MPIParticles<T>::load_from_file(std::string fileprefix) {
1091 std::string filename = fileprefix + "." + std::to_string(FML::ThisTask);
1092 auto myfile = std::ifstream(filename, std::ios::binary);
1093
1094 // If we fail to load a file throw an error
1095 if (not myfile.good()) {
1096 std::string error = "[MPIParticles::load_from_file] Failed to read the particles on task " +
1097 std::to_string(FML::ThisTask) + " Filename: " + filename;
1098 assert_mpi(false, error.c_str());
1099 }
1100
1101 int ndim_expected = FML::PARTICLE::GetNDIM(T());
1102 int ndim;
1103
1104 // Read header data
1105 myfile.read((char *)&ndim, sizeof(ndim));
1106 assert_mpi(ndim == ndim_expected,
1107 "[MPIParticles::load_from_file] Particle dimension do not match the one in the file");
1108 myfile.read((char *)&NpartTotal, sizeof(NpartTotal));
1109 myfile.read((char *)&NpartLocal_in_use, sizeof(NpartLocal_in_use));
1110 size_t NpartLocalAllocated;
1111 myfile.read((char *)&NpartLocalAllocated, sizeof(NpartLocalAllocated));
1112 x_min_per_task.resize(FML::NTasks);
1113 x_max_per_task.resize(FML::NTasks);
1114 myfile.read((char *)x_min_per_task.data(), sizeof(double) * FML::NTasks);
1115 myfile.read((char *)x_max_per_task.data(), sizeof(double) * FML::NTasks);
1116 assert_mpi(myfile.good() and NpartLocal_in_use <= NpartLocalAllocated,
1117 "[MPIParticles::load_from_file] Error reading the header of the file\n");
1118
1119 // Allocate memory
1120 p.resize(NpartLocalAllocated);
1121 if (NpartLocal_in_use == 0)
1122 return;
1123
1124 if (FML::ThisTask == 0)
1125 std::cout << "# Reading particles from " << fileprefix << ".X\n";
1126
1127 // Allocate a read buffer
1128 std::vector<char> buffer_data;
1129
1130 // Read in chunks
1131 size_t nread = 0;
1132 while (nread < NpartLocal_in_use) {
1133
1134 size_t n_to_read{};
1135 size_t nbytes_to_read{};
1136 myfile.read((char *)&n_to_read, sizeof(n_to_read));
1137 myfile.read((char *)&nbytes_to_read, sizeof(nbytes_to_read));
1138 // Never read more particles than the file says we have (files from older versions could contain
1139 // more, and n_to_read = 0 would never finish)
1140 assert_mpi(myfile.good() and n_to_read > 0 and n_to_read <= NpartLocal_in_use - nread,
1141 "[MPIParticles::load_from_file] Corrupt file: the chunks do not add up to the number of "
1142 "particles in the header\n");
1143 assert_mpi(nbytes_to_read <= buffer_data.max_size() &&
1144 nbytes_to_read <= size_t(std::numeric_limits<std::streamsize>::max()),
1145 "[MPIParticles::load_from_file] Chunk byte count exceeds supported storage");
1146 if (buffer_data.size() < nbytes_to_read)
1147 buffer_data.resize(nbytes_to_read);
1148 char * buffer = buffer_data.data();
1149 myfile.read(buffer, nbytes_to_read);
1150 assert_mpi(myfile.good(), "[MPIParticles::load_from_file] Error reading particle data\n");
1151 size_t bytes_processed = 0;
1152 for (size_t i = 0; i < n_to_read; i++) {
1153 FML::PARTICLE::AssignFromBuffer(p[nread + i], buffer);
1154 auto bytes = FML::PARTICLE::GetSize(p[nread + i]);
1155 assert_mpi(bytes > 0 && size_t(bytes) <= nbytes_to_read - bytes_processed,
1156 "[MPIParticles::load_from_file] Corrupt file: particle data larger than the chunk\n");
1157 buffer += size_t(bytes);
1158 bytes_processed += size_t(bytes);
1159 }
1160
1161 nread += n_to_read;
1162 }
1163 myfile.close();
1164 }
1165
1166 } // namespace PARTICLE
1167} // namespace FML
1168#endif
const int NDIM
const std::string filename
Definition Main.cpp:63
const int Npart_1D
Definition Main.cpp:50
const double buffer_factor
Definition Main.cpp:51
std::string name
FML::PERFORMANCE::Count Count
Definition Main.cpp:15
static MemoryLog * get()
The (only) instance.
void add_label(void *ptr, std::string name)
A container class for holding particles that are distributed across many CPUs and to easily deal with...
void create_particle_grid(int Npart_1D, double buffer_factor, double xmin_local, double xmax_local)
Create particles in a rectangular grid spread across all tasks buffer_factor is how much extra to al...
std::vector< double > get_x_min_per_task()
Get a vector of xmin of the domain for each task.
MigrationRoute get_last_migration_route() const
Last route selected by communicate_particles (same on every rank).
size_t get_npart_total() const
Total number of active particles across all tasks.
T & operator[](size_t i)
Access particles through indexing operator.
T * get_particles_ptr()
Get a pointer to the first particle.
void dump_to_file(std::string fileprefix, size_t max_bytesize_buffer=100 *1000 *1000)
Dump data to file (internal format: a raw copy of the particles, one file fileprefix....
void create(std::vector< T > &part, size_t nallocate, std::function< bool(T &)> selection_function)
Create from a vector of particles with a given selection function This could for example be that xmin...
void create(T *part, size_t NumParts, size_t nallocate, double xmin_local, double xmax_local, bool all_tasks_has_the_same_particles)
Create MPIParticles from a set of particles.
void info()
Show some info about the class.
void communicate_particles(size_t max_message_bytes=std::numeric_limits< int >::max(), bool force_general=false)
Communicate particles across CPU boundaries.
void load_from_file(std::string fileprefix)
Load data written by dump_to_file (same particle type and number of tasks)
size_t get_npart() const
Number of active particles on the local task.
std::vector< double > get_x_max_per_task()
Get a vector of xmax of the domain for each task.
iterator end()
Iterator: points to one past the last active local particle.
Vector< T > & get_particles()
Get reference to particle vector.
auto get_pos(size_t ipart, int idim)
Get the idim component of the position for particle ipart.
void free()
Free all memory of the stored particles.
void add_memory_label(std::string name)
For memory logging add a tag to the vector we have allocated.
iterator begin()
Iterator: points to the first local particle.
T & get_part(size_t i)
Get a reference to the i'th particle.
auto get_vel(size_t ipart, int idim)
Get the idim component of the velocity for particle ipart (if its available)
void move_from(Vector< T > &&part)
Moves a vector of particles into internal storage (so no copies are being done).
void sort_by_position(int nblocks_per_dim)
Reorder the local particles by position (see sort_particles_by_position) so that particles close in s...
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
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
get_vel constexpr double * GetPos(...)
void AssignFromBuffer(T &t, char *buffer)
void sort_particles_by_position_impl(T *part, size_t NumPart, int nblocks_per_dim)
Reorder particles by position: stable counting sort by the block of a nblocks_per_dim^N grid the part...
void AppendToBuffer(T &t, char *buffer)
constexpr double * GetVel(...)
void mpiparticles_wrap_boundary_position(U &x)
Bring the x-coordinate of a particle given to MPIParticles::create into [0,1): x = 1....
void sort_particles_by_position(T *part, size_t NumPart, int nblocks_per_dim)
void record(Counter counter, Count amount=1) noexcept
Definition Counters.h:65
void payload(size_t sent, size_t received) noexcept
Definition Counters.h:118
void transport_allocation(size_t bytes) noexcept
Definition Counters.h:112
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
void MinOverTasks(T *value)
Inplace min over tasks of a single value.
Definition Global.h:209
void MaxOverTasks(T *value)
Inplace max over tasks of a single value.
Definition Global.h:189
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
bool operator!=(const LogAllocator< T > &a, const LogAllocator< U > &b)
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
Definition Global.cpp:26
std::vector< T, Allocator< T > > Vector
Definition Global.h:105
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
double error(const std::vector< Vector > &a, const std::vector< Vector > &b)