423 size_t NumPartinpart,
427 bool all_tasks_has_the_same_particles) {
429 all_tasks_has_the_same_particles =
true;
435#ifdef DEBUG_MPIPARTICLES
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";
446 add_memory_label(
"MPIParticles::create");
450 if (all_tasks_has_the_same_particles) {
452 for (
size_t i = 0; i < NumPartinpart; i++) {
455 if (x >= xmin and x < xmax) {
457 assert_mpi(count < nallocate,
458 "[MPIParticle::create] Reached allocation limit. Increase nallocate\n");
465 NpartLocal_in_use = count;
467 NpartTotal = NpartLocal_in_use;
472 std::cout << std::flush;
478 if (not all_tasks_has_the_same_particles) {
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) {
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;
496 for (
size_t i = start; i < nbatch; i++) {
498 assert_mpi(count < nallocate,
499 "[MPIParticle::create] Reached allocation limit. Increase nallocate\n");
508 NpartLocal_in_use = count;
510#ifdef DEBUG_MPIPARTICLES
511 std::cout <<
"Task: " <<
ThisTask <<
" NpartLocal_in_use: " << NpartLocal_in_use <<
" precomm\n";
515 communicate_particles();
517#ifdef DEBUG_MPIPARTICLES
518 std::cout <<
"Task: " <<
ThisTask <<
" NpartLocal_in_use: " << NpartLocal_in_use <<
" postcomm\n";
522 count = NpartLocal_in_use;
525 int moretodo = more_to_process_locally ? 1 : 0;
527 more_to_process_globally = (moretodo >= 1);
532 NpartTotal = NpartLocal_in_use;
535#ifdef DEBUG_MPIPARTICLES
536 std::cout <<
"Task: " <<
ThisTask <<
" NpartLocal_in_use: " << NpartLocal_in_use <<
"\n";
597 while (imin /
double(
Npart_1D) < xmin_local) {
601 while (imax /
double(
Npart_1D) < xmax_local) {
604 Local_p_start = imin;
605 Local_Npart_1D = imax - imin;
609 int Local_p_start_computed = 0, Npart_1D_computed = 0;
610 for (
int i = 0; i <
NTasks; i++) {
612 Local_p_start_computed += Local_Npart_1D_per_task[i];
613 Npart_1D_computed += Local_Npart_1D_per_task[i];
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");
621 x_min_per_task = std::vector<double>(
NTasks, 0.0);
622 x_max_per_task = std::vector<double>(
NTasks, 0.0);
632#ifdef DEBUG_MPIPARTICLES
634 for (
int taskid = 0; taskid <
NTasks; taskid++) {
636 std::cout <<
"Task[" << taskid <<
"] xmin: " << x_min_per_task[taskid]
637 <<
" xmax: " << x_max_per_task[taskid] <<
"\n";
644 constexpr int ndim = FML::PARTICLE::GetNDIM(tmp_ndim);
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)));
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");
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++) {
673 for (
int idim = 0; idim < ndim; idim++) {
674 Pos[idim] = coord[idim] / double(
Npart_1D);
730 [[maybe_unused]]
bool force_general) {
738 std::min(max_message_bytes,
size_t(std::numeric_limits<int>::max()));
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]);
752 "[MPIParticles] Slabs must partition [0,1] in rank order");
754 const int right = int((
static_cast<long long>(
ThisTask) + 1) %
NTasks);
755 auto owner_of = [&](
const auto & x) {
757 if (x >= x_min_per_task[right] && x < x_max_per_task[right])
759 if (x >= x_min_per_task[left] && x < x_max_per_task[left])
761 return int(std::upper_bound(x_max_per_task.begin(), x_max_per_task.end(), x) - x_max_per_task.begin());
763 int route = force_general ? 2 : 0;
766 size_t NpartLocal_in_use_pre_comm = NpartLocal_in_use;
768#ifdef DEBUG_MPIPARTICLES
770 std::cout <<
"Communicating particles task: " <<
ThisTask
771 <<
" Nparticles: " << NpartLocal_in_use_pre_comm <<
"\n"
777 using PosType = std::remove_reference_t<
decltype(tmp.get_pos()[0])>;
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;
798 while (i < NpartLocal_in_use) {
803 x = std::nextafter(x, PosType(0.0));
805 x = std::numeric_limits<PosType>::min();
808 if (not(x >= 0.0 and x < 1.0)) {
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());
816 const int taskid = owner_of(x);
817 count_outgoing(taskid, p[i]);
818 swap_particles(p[i], p[--NpartLocal_in_use]);
833 std::vector<int> peer_steps;
835 peer_steps.push_back(1);
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);
841 const Count outgoing[2] = {n_to_send[dest], nbytes_to_send[dest]};
843 MPI_Sendrecv(outgoing,
845 MPI_UNSIGNED_LONG_LONG,
850 MPI_UNSIGNED_LONG_LONG,
855 n_to_recv[source] = incoming[0];
856 nbytes_to_recv[source] = incoming[1];
859 for (
int step = 1; step <
NTasks; ++step)
860 peer_steps.push_back(step);
861 MPI_Alltoall(n_to_send.data(),
863 MPI_UNSIGNED_LONG_LONG,
866 MPI_UNSIGNED_LONG_LONG,
868 MPI_Alltoall(nbytes_to_send.data(),
870 MPI_UNSIGNED_LONG_LONG,
871 nbytes_to_recv.data(),
873 MPI_UNSIGNED_LONG_LONG,
877#ifdef DEBUG_MPIPARTICLES
880 for (
int i = 0; i <
NTasks; i++) {
881 std::cout <<
"Task " <<
ThisTask <<
" send to " << i <<
" : " << n_to_send[i] <<
"\n"
883 std::cout <<
"Task " <<
ThisTask <<
" recv from " << i <<
" : " << n_to_recv[i] <<
"\n"
892 const auto send_bytes =
894 const auto recv_bytes =
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;
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) +
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,
911 ntot_to_recv <= p.size() - NpartLocal_in_use,
912 "[MPIParticles] Receive count exceeds allocated particle capacity");
915 std::vector<char> send_buffer(ntot_bytes_to_send);
916 std::vector<char> recv_buffer(ntot_bytes_to_recv);
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]);
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;
942 send_buffer_by_task[task] += size_t(bytes);
943 packed[task] += size_t(bytes);
947 for (
size_t i = 0; i < ntot_to_send; i++) {
948 size_t index = NpartLocal_in_use + i;
951 const int taskid = owner_of(x);
952 assert_mpi(taskid !=
ThisTask,
"[MPIParticles] Outgoing particle is still locally owned");
953 append_particle(index, taskid);
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");
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]);
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]));
977 const Count nchunks = max_bytes / max_chunk_bytes + (max_bytes % max_chunk_bytes != 0);
979 for (
int step : peer_steps) {
980 int send_request_to = int((
static_cast<long long>(
ThisTask) + step) %
NTasks);
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) :
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) :
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;
996 MPI_Sendrecv(send_ptr,
1013 copy_over_received_data(recv_buffer, ntot_to_recv);
1021 auto myfile = std::fstream(
filename, std::ios::out | std::ios::binary);
1024 if (not myfile.good()) {
1025 std::string
error =
"[MPIParticles::dump_to_file] Failed to save the particle data on task " +
1027 std::cout <<
error <<
"\n";
1031 int ndim = FML::PARTICLE::GetNDIM(T());
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);
1042 if (NpartLocal_in_use == 0) {
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");
1054 std::cout <<
"# Writing particles to " << fileprefix <<
".X\n";
1057 size_t nwritten = 0;
1058 while (nwritten < NpartLocal_in_use) {
1060 size_t n_to_write = NpartLocal_in_use - nwritten;
1061 size_t nbytes_to_write = 0;
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) {
1072 nbytes_to_write += bytes;
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);
1081 nwritten += n_to_write;
1083 if (not myfile.good())
1084 std::cout <<
"[MPIParticles::dump_to_file] Error writing the particle data on task " +
1092 auto myfile = std::ifstream(
filename, std::ios::binary);
1095 if (not myfile.good()) {
1096 std::string
error =
"[MPIParticles::load_from_file] Failed to read the particles on task " +
1098 assert_mpi(
false,
error.c_str());
1101 int ndim_expected = FML::PARTICLE::GetNDIM(T());
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));
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");
1120 p.resize(NpartLocalAllocated);
1121 if (NpartLocal_in_use == 0)
1125 std::cout <<
"# Reading particles from " << fileprefix <<
".X\n";
1128 std::vector<char> buffer_data;
1132 while (nread < NpartLocal_in_use) {
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));
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++) {
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);