FML
Loading...
Searching...
No Matches
FML::PARTICLE::MPIParticles< T > Class Template Reference

A container class for holding particles that are distributed across many CPUs and to easily deal with communication of these particles if they cross the domain boundary (simply call communicate_particles() at any time to do this) More...

#include <MPIParticles.h>

Data Structures

class  iterator
 Iterator for looping through all the active particles i.e. allow for(auto &&p: mpiparticles)
 

Public Member Functions

iterator begin ()
 Iterator: points to the first local particle.
 
iterator end ()
 Iterator: points to one past the last active local particle.
 
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 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 < x < xmax and if particles have a type only select a particular type.
 
void move_from (Vector< T > &&part)
 Moves a vector of particles into internal storage (so no copies are being done).
 
void create_particle_grid (int Npart_1D, double buffer_factor, double xmin_local, double xmax_local)
 Create \( {\rm Npart}_{1D}^{\rm NDIM} \) particles in a rectangular grid spread across all tasks buffer_factor is how much extra to allocate in case particles moves xmin, xmax specifies the domain in [0,1] that the current task is responsible for This method only sets the positions of the particles not id or vel or anything else.
 
 MPIParticles ()=default
 
 operator bool () const
 
Vector< T > & get_particles ()
 Get reference to particle vector.
 
T * get_particles_ptr ()
 Get a pointer to the first particle.
 
T & operator[] (size_t i)
 Access particles through indexing operator.
 
T & get_part (size_t i)
 Get a reference to the i'th particle.
 
auto get_pos (size_t ipart, int idim)
 Get the idim component of the position for particle ipart.
 
auto get_vel (size_t ipart, int idim)
 Get the idim component of the velocity for particle ipart (if its available)
 
size_t get_npart_total () const
 Total number of active particles across all tasks.
 
size_t get_npart () const
 Number of active particles on the local task.
 
void communicate_particles (size_t max_message_bytes=std::numeric_limits< int >::max(), bool force_general=false)
 Communicate particles across CPU boundaries.
 
MigrationRoute get_last_migration_route () const
 Last route selected by communicate_particles (same on every rank).
 
std::vector< double > get_x_min_per_task ()
 Get a vector of xmin of the domain for each task.
 
std::vector< double > get_x_max_per_task ()
 Get a vector of xmax of the domain for each task.
 
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.
 
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.X per task).
 
void load_from_file (std::string fileprefix)
 Load data written by dump_to_file (same particle type and number of tasks)
 
void info ()
 Show some info about the class.
 
void sort_by_position (int nblocks_per_dim)
 Reorder the local particles by position (see sort_particles_by_position) so that particles close in space are close in memory.
 

Detailed Description

template<class T>
class FML::PARTICLE::MPIParticles< T >

A container class for holding particles that are distributed across many CPUs and to easily deal with communication of these particles if they cross the domain boundary (simply call communicate_particles() at any time to do this)

Contains methods for setting up MPIParticles from a set of particles or creating regular grids of particles and so on

Templated on particle class. Particle must at a minimum have the methods

get_pos() : Ptr to position

int get_ndim() : How many dimensions pos have

If the particle has any dynamical allocations you must also provide (these are automatically provided otherwise):

get_particle_byte_size() : How many bytes does the particle store

append_to_buffer(char *) : append all the particle data to a char array moving buffer forward as we read

assign_from_buffer(char *) : assign data to a particle after it has been received moving buffer forward as we do this

Compile time defines:

DEBUG_MPIPARTICLES : Show some info when running

External variables/methods we rely on:

int ThisTask;

int NTasks;

assert_mpi(Expr, Msg)

T power(T base, int exponent);

Definition at line 78 of file MPIParticles.h.

Constructor & Destructor Documentation

◆ MPIParticles()

template<class T >
FML::PARTICLE::MPIParticles< T >::MPIParticles ( )
default

Member Function Documentation

◆ add_memory_label()

template<class T >
void FML::PARTICLE::MPIParticles< T >::add_memory_label ( std::string name)

For memory logging add a tag to the vector we have allocated.

Definition at line 348 of file MPIParticles.h.

348 {
349#ifdef MEMORY_LOGGING
350 FML::MemoryLog::get()->add_label(p.data(), p.capacity(), name);
351#endif
352 }
std::string name
static MemoryLog * get()
The (only) instance.
void add_label(void *ptr, std::string name)

◆ begin()

template<class T >
iterator FML::PARTICLE::MPIParticles< T >::begin ( )
inline

Iterator: points to the first local particle.

Definition at line 127 of file MPIParticles.h.

127{ return iterator(p.data()); }

◆ communicate_particles()

template<class T >
void FML::PARTICLE::MPIParticles< T >::communicate_particles ( size_t max_message_bytes = std::numeric_limits<int>::max(),
bool force_general = false )

Communicate particles across CPU boundaries.

Definition at line 729 of file MPIParticles.h.

730 {
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 }
FML::PERFORMANCE::Count Count
Definition Main.cpp:15
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 AppendToBuffer(T &t, char *buffer)
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
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
int ThisTask
The MPI task number.
Definition Global.cpp:39
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
Definition Global.cpp:26
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
double error(const std::vector< Vector > &a, const std::vector< Vector > &b)

◆ create() [1/2]

template<class T >
void FML::PARTICLE::MPIParticles< T >::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 < x < xmax and if particles have a type only select a particular type.

Definition at line 378 of file MPIParticles.h.

378 {
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 }
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
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
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

◆ create() [2/2]

template<class T >
void FML::PARTICLE::MPIParticles< T >::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.

We only keep the particles in part that are in the correct x-range if all_tasks_has_the_same_particles is true nallocate is the total amount of particles we allocate for locally (we do buffered read if only one task reads particles to avoid having to allocate too much).

Parameters
[in]partPointer to a set of particles
[in]NumPartsNumber of particles we have
[in]nallocateHow many particles to allocate for locally (in case we want to have a buffer)
[in]xmin_localThe min of the x-range in [0,1] the current task is responsible for
[in]xmax_localThe max of the x-range in [0,1] the current task is responsible for
[in]all_tasks_has_the_same_particlesSet this to be true if all tasks has the same set of particles (e.g. they come from reading the same file). If false then we assume all tasks that has particles has distinct particles

Definition at line 422 of file MPIParticles.h.

427 {
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
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 }
void communicate_particles(size_t max_message_bytes=std::numeric_limits< int >::max(), bool force_general=false)
Communicate particles across CPU boundaries.
void add_memory_label(std::string name)
For memory logging add a tag to the vector we have allocated.
void mpiparticles_wrap_boundary_position(U &x)
Bring the x-coordinate of a particle given to MPIParticles::create into [0,1): x = 1....

◆ create_particle_grid()

template<class T >
void FML::PARTICLE::MPIParticles< T >::create_particle_grid ( int Npart_1D,
double buffer_factor,
double xmin_local,
double xmax_local )

Create \( {\rm Npart}_{1D}^{\rm NDIM} \) particles in a rectangular grid spread across all tasks buffer_factor is how much extra to allocate in case particles moves xmin, xmax specifies the domain in [0,1] that the current task is responsible for This method only sets the positions of the particles not id or vel or anything else.

Definition at line 588 of file MPIParticles.h.

591 {
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 }
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

◆ dump_to_file()

template<class T >
void FML::PARTICLE::MPIParticles< T >::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.X per task).

Meant for checkpointing within the same program: the files can only be read back with load_from_file using the same particle type, the same number of tasks and the same machine architecture. For portable output use e.g. GADGET (HDF5) files (GadgetUtils)

Definition at line 1019 of file MPIParticles.h.

1019 {
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 }
const std::string filename
Definition Main.cpp:63

◆ end()

template<class T >
iterator FML::PARTICLE::MPIParticles< T >::end ( )
inline

Iterator: points to one past the last active local particle.

Definition at line 129 of file MPIParticles.h.

129{ return iterator(p.data() + NpartLocal_in_use); }

◆ free()

template<class T >
void FML::PARTICLE::MPIParticles< T >::free ( )

Free all memory of the stored particles.

Definition at line 355 of file MPIParticles.h.

355 {
356 p.clear();
357 p.shrink_to_fit();
358 }

◆ get_last_migration_route()

template<class T >
MigrationRoute FML::PARTICLE::MPIParticles< T >::get_last_migration_route ( ) const
inline

Last route selected by communicate_particles (same on every rank).

Definition at line 198 of file MPIParticles.h.

198{ return last_migration_route; }

◆ get_npart()

template<class T >
size_t FML::PARTICLE::MPIParticles< T >::get_npart ( ) const

Number of active particles on the local task.

Definition at line 546 of file MPIParticles.h.

546 {
547 return NpartLocal_in_use;
548 }

◆ get_npart_total()

template<class T >
size_t FML::PARTICLE::MPIParticles< T >::get_npart_total ( ) const

Total number of active particles across all tasks.

Definition at line 551 of file MPIParticles.h.

551 {
552 return NpartTotal;
553 }

◆ get_part()

template<class T >
T & FML::PARTICLE::MPIParticles< T >::get_part ( size_t i)

Get a reference to the i'th particle.

Definition at line 541 of file MPIParticles.h.

541 {
542 return p[i];
543 }

◆ get_particles()

template<class T >
Vector< T > & FML::PARTICLE::MPIParticles< T >::get_particles ( )

Get reference to particle vector.

NB: due to we allow a buffer the size of the vector returned is not equal to the number of active particles!

Definition at line 556 of file MPIParticles.h.

556 {
557 return p;
558 }

◆ get_particles_ptr()

template<class T >
T * FML::PARTICLE::MPIParticles< T >::get_particles_ptr ( )

Get a pointer to the first particle.

Definition at line 561 of file MPIParticles.h.

561 {
562 return p.data();
563 }

◆ get_pos()

template<class T >
auto FML::PARTICLE::MPIParticles< T >::get_pos ( size_t ipart,
int idim )

Get the idim component of the position for particle ipart.

Definition at line 688 of file MPIParticles.h.

688 {
689 auto pos = FML::PARTICLE::GetPos(p[ipart]);
690 if (pos == nullptr)
691 assert(false);
692 return pos[i];
693 }

◆ get_vel()

template<class T >
auto FML::PARTICLE::MPIParticles< T >::get_vel ( size_t ipart,
int idim )

Get the idim component of the velocity for particle ipart (if its available)

Definition at line 696 of file MPIParticles.h.

696 {
697 auto vel = FML::PARTICLE::GetVel(p[ipart]);
698 if (vel == nullptr)
699 assert(false);
700 return vel[i];
701 }
constexpr double * GetVel(...)

◆ get_x_max_per_task()

template<class T >
std::vector< double > FML::PARTICLE::MPIParticles< T >::get_x_max_per_task ( )

Get a vector of xmax of the domain for each task.

Definition at line 571 of file MPIParticles.h.

571 {
572 return x_max_per_task;
573 }

◆ get_x_min_per_task()

template<class T >
std::vector< double > FML::PARTICLE::MPIParticles< T >::get_x_min_per_task ( )

Get a vector of xmin of the domain for each task.

Definition at line 566 of file MPIParticles.h.

566 {
567 return x_min_per_task;
568 }

◆ info()

template<class T >
void FML::PARTICLE::MPIParticles< T >::info ( )

Show some info about the class.

Definition at line 301 of file MPIParticles.h.

301 {
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 }
const int NDIM

◆ load_from_file()

template<class T >
void FML::PARTICLE::MPIParticles< T >::load_from_file ( std::string fileprefix)

Load data written by dump_to_file (same particle type and number of tasks)

Definition at line 1090 of file MPIParticles.h.

1090 {
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 }
void AssignFromBuffer(T &t, char *buffer)

◆ move_from()

template<class T >
void FML::PARTICLE::MPIParticles< T >::move_from ( Vector< T > && part)

Moves a vector of particles into internal storage (so no copies are being done).

The extra storage (if needed) needs to already be in part! Assumes we have distinct particles on different tasks. This saves having to do allocations and copies, but its safer and flexible to just use create() so its best to not use this unless you really need to

Definition at line 361 of file MPIParticles.h.

361 {
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 }

◆ operator bool()

template<class T >
FML::PARTICLE::MPIParticles< T >::operator bool ( ) const
explicit

Definition at line 296 of file MPIParticles.h.

296 {
297 return p.size() > 0;
298 }

◆ operator[]()

template<class T >
T & FML::PARTICLE::MPIParticles< T >::operator[] ( size_t i)

Access particles through indexing operator.

Definition at line 576 of file MPIParticles.h.

576 {
577 return p[i];
578 }

◆ sort_by_position()

template<class T >
void FML::PARTICLE::MPIParticles< T >::sort_by_position ( int nblocks_per_dim)

Reorder the local particles by position (see sort_particles_by_position) so that particles close in space are close in memory.

Speeds up assigning particles to a grid and interpolating from it

Definition at line 291 of file MPIParticles.h.

291 {
292 sort_particles_by_position(p.data(), NpartLocal_in_use, nblocks_per_dim);
293 }
void sort_particles_by_position(T *part, size_t NumPart, int nblocks_per_dim)

The documentation for this class was generated from the following file: