1#ifndef FFTWGRIDMPI_HEADER
2#define FFTWGRIDMPI_HEADER
27#ifdef FML_ENABLE_PERFORMANCE_COUNTERS
37 return last_coord == 0 || (nmesh % 2 == 0 && last_coord == nmesh / 2) ? 1 : 2;
100 static_assert(N >= 2,
"FFTWGrid: only N >= 2 dimensions are supported");
108#ifdef FML_ENABLE_PERFORMANCE_COUNTERS
118 ptrdiff_t Local_nx{0};
120 ptrdiff_t Local_x_start{0};
123 ptrdiff_t NmeshTotRealAlloc{0};
124 ptrdiff_t NmeshTotComplexAlloc{0};
127 ptrdiff_t NmeshTotReal{0};
128 ptrdiff_t NmeshTotComplex{0};
135 ptrdiff_t NmeshTotRealSlice{0};
136 ptrdiff_t NmeshTotComplexSlice{0};
139 int n_extra_x_slices_left{0};
140 int n_extra_x_slices_right{0};
143 bool grid_is_in_real_space{
true};
145 std::string name{
""};
155 static ptrdiff_t compute_local_size(
int Nmesh, ptrdiff_t & Local_nx, ptrdiff_t & Local_x_start);
159 ptrdiff_t get_nreal_right_to_backup()
const;
163 static void sendrecv_bytes(
char * sendbuf,
char * recvbuf,
size_t bytes,
int dest,
int source);
170 explicit operator bool()
const;
178 FFTWGrid(
int Nmesh,
int n_extra_x_slices_left = 0,
int n_extra_x_slices_right = 0);
286 std::array<double, N> & kvec,
287 double & kmag)
const;
290 std::array<double, N> & kvec,
291 double & kmag2)
const;
314 assert_mpi(nmesh > 0 && nmesh %
FML::NTasks == 0,
"[FFTWGrid::storage_bytes] Invalid mesh size");
316 return size_t(compute_local_size(nmesh, nx, start)) *
sizeof(
ComplexType);
352 assert_mpi(
Nmesh > 0,
"[FFTWGrid::clone_empty] Source must be allocated");
353 FFTWGrid result(
Nmesh, n_extra_x_slices_left, n_extra_x_slices_right);
354 result.grid_is_in_real_space = grid_is_in_real_space;
355 result.add_memory_label(name);
356 const ptrdiff_t begin = n_extra_x_slices_left * NmeshTotComplexSlice;
357 const ptrdiff_t end = begin + Local_nx * NmeshTotComplexSlice;
358 std::copy(fourier_grid_raw.begin(), fourier_grid_raw.begin() + begin, result.fourier_grid_raw.begin());
359 std::copy(fourier_grid_raw.begin() + end,
360 fourier_grid_raw.end(),
361 result.fourier_grid_raw.begin() + end);
362 if (grid_is_in_real_space) {
363 const auto * source =
reinterpret_cast<const FloatType *
>(fourier_grid_raw.data()) + 2 * begin;
364 auto *
target = result.get_real_grid();
365 const ptrdiff_t stride = 2 * (
Nmesh / 2 + 1);
366 for (ptrdiff_t row = 0; row < 2 * (end - begin); row += stride)
367 std::copy(source + row +
Nmesh, source + row + stride,
target + row +
Nmesh);
370 size_t copied = (fourier_grid_raw.size() - size_t(end - begin)) *
sizeof(
ComplexType);
371 if (grid_is_in_real_space)
372 copied += size_t(2 * (end - begin) / (2 * (
Nmesh / 2 + 1))) *
386 int sampling_factor = 4)
const;
391 [[maybe_unused]] std::string label,
392 [[maybe_unused]]
int sampling_factor = 4)
const {
393 return function_of_kBox;
400 return fourier_grid_raw.size() > 0;
436 : real_index(_index + (_Nmesh % 2 == 1 ? 1 : 2) * (_index / _Nmesh)), index(_index),
Nmesh(_Nmesh),
442 if (index %
Nmesh == 0)
443 real_index += odd ? 1 : 2;
491 if (islice_begin == 0 and islice_end == 0)
492 islice_end = int(Local_nx);
495 if (not grid_is_in_real_space) {
497 std::cout <<
"Warning: [FFTWGrid::get_real_range] The grid status is [Fourierspace]. Label: " +
502 IndexIntType cellsperslice = NmeshTotReal / Local_nx;
503 return RealRange(cellsperslice * islice_begin, cellsperslice * islice_end,
Nmesh);
510 if (islice_begin == 0 and islice_end == 0)
511 islice_end = int(Local_nx);
514 if (grid_is_in_real_space) {
516 std::cout <<
"Warning: [FFTWGrid::get_fourier_range] The grid status is [Realspace]. Label: " +
522 return FourierRange(cellsperslice * islice_begin, cellsperslice * islice_end);
528 return reinterpret_cast<FloatType *
>(fourier_grid_raw.data());
533 return get_real_grid_left() + NmeshTotRealSlice * n_extra_x_slices_left;
538#ifdef BOUNDSCHECK_FFTWGRID
539 assert_mpi(-n_extra_x_slices_left <= slice and slice < Local_nx + n_extra_x_slices_right,
540 "[FFTWGrid::get_real_grid] Bounds check failed\n");
542 return get_real_grid_left() + NmeshTotRealSlice * (n_extra_x_slices_left + slice);
547 return get_real_grid_left() + NmeshTotRealSlice * (n_extra_x_slices_left + Local_nx);
552 return fourier_grid_raw.data() + NmeshTotComplexSlice * n_extra_x_slices_left;
557 grid_is_in_real_space = grid_is_a_real_grid;
562 return grid_is_in_real_space;
569 std::string myfloattype =
"[Unknown]";
570 std::string status = grid_is_in_real_space ?
"[Realspace]" :
"[Fourierspace]";
572 myfloattype =
"[Float]";
574 myfloattype =
"[Double]";
575 if (
sizeof(
FloatType) ==
sizeof(
long double))
576 myfloattype =
"[Long Double]";
577 double memory_in_mb = double(fourier_grid_raw.size() *
sizeof(
ComplexType)) / 1e6;
580 std::cout <<
"#=====================================================\n";
582 std::cout <<
"# .___ _____ \n";
583 std::cout <<
"# | | _____/ ____\\____ \n";
584 std::cout <<
"# | |/ \\ __\\/ _ \\ \n";
585 std::cout <<
"# | | | \\ | ( <_> ) \n";
586 std::cout <<
"# |___|___| /__| \\____/ \n";
587 std::cout <<
"# \\/ \n";
589 std::cout <<
"# Info about FFTWGrid. Grid label: [" <<
name <<
"]\n";
590 std::cout <<
"# Status of grid: " << status <<
" NDIM: [" << N <<
"] FloatType: " << myfloattype
592 std::cout <<
"# Grid has allocated " << memory_in_mb <<
" MB\n";
593 std::cout <<
"# Nmesh " <<
Nmesh <<
"\n";
594 std::cout <<
"# Local_nx " << Local_nx <<
"\n";
595 std::cout <<
"# n_extra_x_slices_left " << n_extra_x_slices_left <<
"\n";
596 std::cout <<
"# n_extra_x_slices_right " << n_extra_x_slices_right <<
"\n";
597 std::cout <<
"# NmeshTotComplexAlloc " << NmeshTotComplexAlloc <<
"\n";
598 std::cout <<
"# NmeshTotComplex " << NmeshTotComplex <<
"\n";
599 std::cout <<
"# NmeshTotComplexSlice " << NmeshTotComplexSlice <<
"\n";
600 std::cout <<
"# NmeshTotRealAlloc " << NmeshTotRealAlloc <<
"\n";
601 std::cout <<
"# NmeshTotReal " << NmeshTotReal <<
"\n";
602 std::cout <<
"# NmeshTotRealSlice " << NmeshTotRealSlice <<
"\n";
604 std::cout <<
"#=====================================================\n";
613 if (planner_flag == FFTW_ESTIMATE)
615#ifdef USE_FFTW_THREADS
620 std::cout <<
"[FFTWGrid::create_wisdom] Planning flag " << planner_flag <<
". Label: " +
name +
"\n";
625 std::vector<ptrdiff_t> NmeshPerDim(N,
Nmesh);
627 MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(),
FML::communicator, planner_flag);
629 std::vector<int> NmeshPerDim(N,
Nmesh);
631 MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(), planner_flag);
634 std::cout <<
"[FFTWGrid::create_wisdom] Warning this will clear data in the grid. Label: " +
name +
636 DESTROY_PLAN(plan_r2c);
645 std::cout <<
"[FFTWGrid::load_wisdom] Filename " <<
filename <<
". Label: " +
name +
"\n";
649 IMPORT_WISDOM_FROM_FILENAME(
filename.c_str());
663 EXPORT_WISDOM_TO_FILENAME(
filename.c_str());
666 std::cout <<
"[FFTWGrid::save_wisdom] Filename " <<
filename <<
". Label: " +
name +
"\n";
680 ALIGNMENT_OF(get_real_grid()),
686 PayloadStorage backup;
687 if (flag != FFTW_ESTIMATE)
688 backup = fourier_grid_raw;
691 std::vector<ptrdiff_t> NmeshPerDim(N,
Nmesh);
693 r2c ? MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(),
FML::communicator, flag) :
694 MAKE_PLAN_C2R(N, NmeshPerDim.data(), get_fftw_grid(), get_real_grid(),
FML::
communicator, flag);
696 std::vector<int> NmeshPerDim(N,
Nmesh);
697 my_fftw_plan plan = r2c ? MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(), flag) :
698 MAKE_PLAN_C2R(N, NmeshPerDim.data(), get_fftw_grid(), get_real_grid(), flag);
700 assert_mpi(plan !=
nullptr,
"[FFTWGrid::get_fftw_plan] FFTW failed to create a plan\n");
705 if (flag != FFTW_ESTIMATE) {
706 std::copy(backup.begin(), backup.end(), fourier_grid_raw.begin());
717 return NmeshTotRealSlice;
723 if (not grid_is_in_real_space) {
725 std::cout <<
"Warning: [FFTWGrid::fill_real_grid] The grid status is [Fourierspace]. Label: " +
730 FloatType * end = begin + NmeshTotRealAlloc;
731 std::fill(begin, end, val);
732 grid_is_in_real_space =
true;
738 if (not grid_is_in_real_space) {
740 std::cout <<
"Warning: [FFTWGrid::fill_real_grid] The grid status is [Fourierspace]. Label: " +
746#pragma omp parallel for
748 for (
int islice = 0; islice < Local_nx; islice++) {
749 for (
auto && real_index : get_real_range(islice, islice + 1)) {
750 auto coord = get_coord_from_index(real_index);
751 auto pos = get_real_position(coord);
752 auto value = func(pos);
753 set_real_from_index(real_index,
value);
756 grid_is_in_real_space =
true;
758 communicate_boundaries();
764 if (grid_is_in_real_space) {
766 std::cout <<
"Warning: [FFTWGrid::fill_fourier_grid] The grid status is [Realspace]. Label: " +
770 std::fill(fourier_grid_raw.begin(), fourier_grid_raw.end(), val);
771 grid_is_in_real_space =
false;
777 if (grid_is_in_real_space) {
779 std::cout <<
"Warning: [FFTWGrid::fill_fourier_grid] The grid status is [Realspace]. Label: " +
785#pragma omp parallel for
787 for (
int islice = 0; islice < Local_nx; islice++) {
788 for (
auto && fourier_index : get_fourier_range(islice, islice + 1)) {
789 auto kvec = get_fourier_wavevector_from_index(fourier_index);
790 auto value = func(kvec);
791 set_fourier_from_index(fourier_index,
value);
794 grid_is_in_real_space =
false;
801 const size_t maxchunk = size_t(1) << 30;
804 const int nbytes = int(std::min(maxchunk, bytes - offset));
806 MPI_Sendrecv(sendbuf + offset,
818 offset += size_t(nbytes);
819 }
while (offset < bytes);
830 const int n_to_recv_right = n_extra_x_slices_right;
831 const int n_to_recv_left = n_extra_x_slices_left;
832 if (n_to_recv_right + n_to_recv_left == 0)
834 assert_mpi(Local_nx > 0,
"[FFTWGrid::communicate_boundaries] Grid is not allocated\n");
838 std::cout <<
"[FFTWGrid::communicate_boundaries] Receiving " << n_to_recv_right
839 <<
" from the right and " << n_to_recv_left <<
" slices from the left. Label: " +
name +
"\n";
847 const size_t bytes_slice = size_t(NmeshTotRealSlice) *
sizeof(
FloatType);
851 for (
int i = 0; i < n_to_recv_right; i++) {
852 FloatType * slice_left_tosend = get_real_grid() + NmeshTotRealSlice * (i);
853 FloatType * slice_right_torecv = get_real_grid_right() + NmeshTotRealSlice * (i);
854 char * sendbuf =
reinterpret_cast<char *
>(slice_left_tosend);
855 char * recvbuf =
reinterpret_cast<char *
>(slice_right_torecv);
857 sendrecv_bytes(sendbuf, recvbuf, bytes_slice, leftcpu, rightcpu);
859 std::memcpy(recvbuf, sendbuf, bytes_slice);
865 for (
int i = 0; i < n_to_recv_left; i++) {
866 FloatType * slice_right_tosend = get_real_grid() + NmeshTotRealSlice * (Local_nx - 1 - i);
868 get_real_grid_left() + NmeshTotRealSlice * (n_extra_x_slices_left - 1 - i);
869 char * sendbuf =
reinterpret_cast<char *
>(slice_right_tosend);
870 char * recvbuf =
reinterpret_cast<char *
>(slice_left_torecv);
872 sendrecv_bytes(sendbuf, recvbuf, bytes_slice, rightcpu, leftcpu);
874 std::memcpy(recvbuf, sendbuf, bytes_slice);
881 ptrdiff_t NmeshTotComplex = 0;
882 std::vector<ptrdiff_t> NmeshPerDimFourier(N,
Nmesh);
883 NmeshPerDimFourier[N - 1] =
Nmesh / 2 + 1;
887 MPI_FFTW_LOCAL_SIZE(N, NmeshPerDimFourier.data(),
FML::communicator, &Local_nx, &Local_x_start);
898 for (
int i = 0; i < N; i++)
899 NmeshTotComplex *= NmeshPerDimFourier[i];
901 return NmeshTotComplex;
906 if (n_extra_x_slices_right == 0)
912 const ptrdiff_t nreal_right = NmeshTotRealSlice * n_extra_x_slices_right;
913 const ptrdiff_t nreal_excess = 2 * (NmeshTotComplex - Local_nx * NmeshTotComplexSlice);
914 return std::min(nreal_right, std::max(ptrdiff_t(
Nmesh / 2 + 1), nreal_excess));
919 *
this = std::move(rhs);
927 fourier_grid_raw = std::move(rhs.fourier_grid_raw);
929 Nmesh = std::exchange(rhs.Nmesh, 0);
930 Local_nx = std::exchange(rhs.Local_nx, 0);
931 Local_x_start = std::exchange(rhs.Local_x_start, 0);
932 NmeshTotRealAlloc = std::exchange(rhs.NmeshTotRealAlloc, 0);
933 NmeshTotComplexAlloc = std::exchange(rhs.NmeshTotComplexAlloc, 0);
934 NmeshTotReal = std::exchange(rhs.NmeshTotReal, 0);
935 NmeshTotComplex = std::exchange(rhs.NmeshTotComplex, 0);
936 NmeshTotRealSlice = std::exchange(rhs.NmeshTotRealSlice, 0);
937 NmeshTotComplexSlice = std::exchange(rhs.NmeshTotComplexSlice, 0);
938 n_extra_x_slices_left = std::exchange(rhs.n_extra_x_slices_left, 0);
939 n_extra_x_slices_right = std::exchange(rhs.n_extra_x_slices_right, 0);
940 grid_is_in_real_space = std::exchange(rhs.grid_is_in_real_space,
true);
941 name = std::move(rhs.name);
948 :
Nmesh(
Nmesh), Local_nx(
Nmesh), n_extra_x_slices_left(n_extra_x_slices_left),
949 n_extra_x_slices_right(n_extra_x_slices_right) {
953 assert_mpi(N > 1,
"[FFTWGrid] FFTW r2c and c2r with MPI currently not supported for 1D\n");
955 "[FFTWGrid] The number of CPUs should divide the gridsize. Otherwise there might be issues with "
956 "extra padding in FFTW and in they way we divide the domain\n");
960 NmeshTotComplex = compute_local_size(
Nmesh, Local_nx, Local_x_start);
964 NmeshTotReal = ptrdiff_t(Local_nx) * ptrdiff_t(
FML::power(
Nmesh, N - 1));
967 NmeshTotRealSlice = 2 * NmeshTotComplexSlice;
969 NmeshTotComplexAlloc =
970 NmeshTotComplex + NmeshTotComplexSlice * (n_extra_x_slices_left + n_extra_x_slices_right);
971 NmeshTotRealAlloc = 2 * NmeshTotComplexAlloc;
974 fourier_grid_raw.
resize(NmeshTotComplexAlloc);
976 std::fill(fourier_grid_raw.begin(), fourier_grid_raw.end(), 0.0);
983 std::cout <<
"Warning: FFTWGrid is not 16 byte aligned (only relevant for speed if you have SIMD)\n";
989 std::cout <<
"[FFTWGrid] Creating grid Nmesh = " <<
Nmesh <<
" Local_nx = " << Local_nx <<
" n_extra: ("
990 << n_extra_x_slices_left <<
" + " << n_extra_x_slices_right <<
")\n";
997#ifdef BOUNDSCHECK_FFTWGRID
998 assert_mpi(index_real >= -NmeshTotRealSlice * n_extra_x_slices_left and
999 index_real < NmeshTotRealSlice * (Local_nx + n_extra_x_slices_right),
1000 "[FFTWGrid::get_coord_from_index] Bounds check failed\n");
1002 std::array<int, N> coord;
1003 int nmesh_plus_padding = (2 * (
Nmesh / 2 + 1));
1004 IndexIntType index = index_real;
1005 coord[N - 1] = int(index % nmesh_plus_padding);
1006 index /= nmesh_plus_padding;
1008 if constexpr (N == 2) {
1010 }
else if (N == 3) {
1011 coord[1] = int(index %
Nmesh);
1012 coord[0] = int(index /
Nmesh);
1014 for (
int idim = N - 2; idim >= 1; idim--) {
1015 coord[idim] = int(index %
Nmesh);
1025#ifdef BOUNDSCHECK_FFTWGRID
1026 assert_mpi(coord.size() == N,
"[FFTWGrid::get_index_real] Coord has wrong size\n");
1027 assert_mpi(-n_extra_x_slices_left <= coord[0] and coord[0] < Local_nx + n_extra_x_slices_right,
1028 "[FFTWGrid::get_index_real] Bounds check failed (first coordinate)\n");
1029 for (
int idim = 1; idim < N; idim++) {
1030 assert_mpi(0 <= coord[idim] and coord[idim] <
Nmesh,
1031 "[FFTWGrid::get_index_real] Bounds check failed\n");
1035 if constexpr (N == 2) {
1037 }
else if (N == 3) {
1041 IndexIntType index = coord[0];
1042 for (
int idim = 1; idim < N - 1; idim++) {
1043 index = index *
Nmesh + coord[idim];
1045 index = index * (2 * (
Nmesh / 2 + 1)) + coord[N - 1];
1054#ifdef BOUNDSCHECK_FFTWGRID
1055 assert_mpi(0 <= coord[0] and coord[0] < Local_nx,
"[FFTWGrid::get_index_fourier] Bounds check failed\n");
1056 for (
int idim = 1; idim < N; idim++) {
1057 assert_mpi(0 <= coord[idim] and coord[idim] <
Nmesh,
1058 "[FFTWGrid::get_index_fourier] Bounds check failed\n");
1062 if constexpr (N == 2) {
1064 }
else if (N == 3) {
1067 IndexIntType index = coord[0];
1068 for (
int idim = 1; idim < N - 1; idim++) {
1069 index = index *
Nmesh + coord[idim];
1071 index = index * (
Nmesh / 2 + 1) + coord[N - 1];
1080#ifdef DEBUG_FFTWGRID
1082 std::cout <<
"[FFTWGrid::fftw_r2c] Transforming grid to fourier space. Label: " +
name +
"\n";
1084 if (not grid_is_in_real_space) {
1086 std::cout <<
"Warning: [FFTWGrid::fftw_r2c] Transforming grid whose status is already "
1099 FloatType * real_grid_right = get_real_grid_right();
1100 const ptrdiff_t nright_copy = get_nreal_right_to_backup();
1101 std::vector<FloatType> right_copy(real_grid_right, real_grid_right + nright_copy);
1105 EXECUTE_R2C_NEW_ARRAY(plan_r2c, get_real_grid(), get_fftw_grid());
1107 grid_is_in_real_space =
false;
1110 const FML::GRID::FloatType
norm = 1.0 / std::pow(
double(
Nmesh), N);
1112#pragma omp parallel for
1114 for (
int islice = 0; islice < Local_nx; islice++) {
1115 for (
auto && fourier_index : get_fourier_range(islice, islice + 1)) {
1116 set_fourier_from_index(fourier_index,
norm * get_fourier_from_index(fourier_index));
1123 std::copy(right_copy.begin(), right_copy.end(), real_grid_right);
1127 assert_mpi(
false,
"[FFTWGrid::fftw_r2c] Compiled without FFTW support so cannot take Fourier transforms\n");
1135#ifdef DEBUG_FFTWGRID
1137 std::cout <<
"[FFTWGrid::fftw_c2r] Transforming grid to real space\n";
1139 if (grid_is_in_real_space) {
1142 <<
"Warning: [FFTWGrid::fftw_c2r] Transforming grid whose status is already [Realspace]\n";
1154 FloatType * real_grid_right = get_real_grid_right();
1155 const ptrdiff_t nright_copy = get_nreal_right_to_backup();
1156 std::vector<FloatType> right_copy(real_grid_right, real_grid_right + nright_copy);
1160 EXECUTE_C2R_NEW_ARRAY(plan_c2r, get_fftw_grid(), get_real_grid());
1162 grid_is_in_real_space =
true;
1167 std::copy(right_copy.begin(), right_copy.end(), real_grid_right);
1171 assert_mpi(
false,
"[FFTWGrid::fftw_c2r] Compiled without FFTW support so cannot take Fourier transforms\n");
1177 IndexIntType index = get_index_real(coord);
1179 NmeshTotRealSlice * n_extra_x_slices_left;
1185 IndexIntType index = get_index_real(coord);
1186 get_real_grid()[index] =
value;
1191 IndexIntType index = get_index_real(coord);
1192 get_real_grid()[index] +=
value;
1197 get_real_grid()[index] =
value;
1202 IndexIntType index = get_index_fourier(coord);
1203 return fourier_grid_raw[NmeshTotComplexSlice * n_extra_x_slices_left + index];
1208 return fourier_grid_raw[NmeshTotComplexSlice * n_extra_x_slices_left + index];
1213 get_fourier_grid()[index] =
value;
1218 IndexIntType index = get_index_fourier(coord);
1219 get_fourier_grid()[index] =
value;
1241 return NmeshTotRealSlice * Local_nx;
1246 return NmeshTotComplexSlice * Local_nx;
1251 return NmeshTotComplexAlloc;
1261 return Local_x_start;
1266 std::array<double, N> xcoord;
1267#ifdef CELLCENTERSHIFTED
1268 const constexpr double shift = 0.5;
1270 const constexpr double shift = 0.0;
1272 xcoord[0] = (double(Local_x_start + coord[0]) + shift) /
double(
Nmesh);
1273 for (
int idim = 1; idim < N; idim++)
1274 xcoord[idim] = (coord[idim] + shift) / double(
Nmesh);
1280 std::array<double, N> & kvec,
1281 double & kmag)
const {
1282 get_fourier_wavevector_and_norm2_by_index(index, kvec, kmag);
1283 kmag = std::sqrt(kmag);
1288 const int nover2plus1 =
Nmesh / 2 + 1;
1289 std::array<int, N> coord;
1290 coord[N - 1] = index % nover2plus1;
1291 IndexIntType n = nover2plus1;
1292 for (
int idim = N - 2; idim >= 0; idim--, n *=
Nmesh) {
1293 coord[idim] = (index / n) %
Nmesh;
1300 std::array<double, N> & kvec,
1301 double & kmag2)
const {
1302 const double twopi = 2.0 * M_PI;
1303 const int nover2plus1 =
Nmesh / 2 + 1;
1304 [[maybe_unused]]
const int nover2 =
Nmesh / 2;
1306#ifdef BOUNDSCHECK_FFTWGRID
1307 assert_mpi(kvec.size() == N,
1308 "[FFTWGrid::get_fourier_wavevector_and_norm2_by_index] kvec has the wrong size\n");
1312 auto iz = index % nover2plus1;
1313 auto iy = index / nover2plus1;
1314 auto ix = (iy /
Nmesh) + Local_x_start;
1316 kvec[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1317 kvec[1] = twopi * double(iy <= nover2 ? iy : iy -
Nmesh);
1318 kvec[2] = twopi * double(iz <= nover2 ? iz : iz -
Nmesh);
1319 kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2];
1320 }
else if (N == 2) {
1321 auto iy = index % nover2plus1;
1322 auto ix = (index / nover2plus1) + Local_x_start;
1323 kvec[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1324 kvec[1] = twopi * double(iy <= nover2 ? iy : iy -
Nmesh);
1325 kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1];
1326 }
else if (N == 1) {
1327 auto ix = index + Local_x_start;
1328 kvec[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1329 kmag2 = kvec[0] * kvec[0];
1331 std::array<int, N> coord;
1332 coord[N - 1] = index % nover2plus1;
1333 IndexIntType n = nover2plus1;
1334 for (
int idim = N - 2; idim >= 0; idim--, n *=
Nmesh) {
1335 coord[idim] = (index / n) %
Nmesh;
1337 coord[0] += Local_x_start;
1339 for (
int idim = 0; idim < N; idim++) {
1340 kvec[idim] = twopi * double(coord[idim] <= nover2 ? coord[idim] : coord[idim] -
Nmesh);
1341 kmag2 += kvec[idim] * kvec[idim];
1348 const double twopi = 2.0 * M_PI;
1349 std::array<double, N> fcoord;
1350 fcoord[0] = coord[0] + Local_x_start;
1351 fcoord[0] = twopi * (fcoord[0] <=
Nmesh / 2 ? fcoord[0] : fcoord[0] -
Nmesh);
1352 for (
int idim = 1; idim < N; idim++)
1353 fcoord[idim] = twopi * (coord[idim] <=
Nmesh / 2 ? coord[idim] : coord[idim] -
Nmesh);
1359 const double twopi = 2.0 * M_PI;
1360 const int nover2plus1 =
Nmesh / 2 + 1;
1361 const int nover2 =
Nmesh / 2;
1362 std::array<double, N> fcoord;
1364 if constexpr (N == 3) {
1365 auto iz = index % nover2plus1;
1366 auto iy = index / nover2plus1;
1367 auto ix = (iy /
Nmesh) + Local_x_start;
1369 fcoord[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1370 fcoord[1] = twopi * double(iy <= nover2 ? iy : iy -
Nmesh);
1371 fcoord[2] = twopi * double(iz <= nover2 ? iz : iz -
Nmesh);
1372 }
else if (N == 2) {
1373 auto iy = index % nover2plus1;
1374 auto ix = (index / nover2plus1) + Local_x_start;
1375 fcoord[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1376 fcoord[1] = twopi * double(iy <= nover2 ? iy : iy -
Nmesh);
1377 }
else if (N == 1) {
1378 auto ix = (index % nover2plus1) + Local_x_start;
1379 fcoord[0] = twopi * double(ix <= nover2 ? ix : ix -
Nmesh);
1381 fcoord[N - 1] = index % nover2plus1;
1382 IndexIntType n = nover2plus1;
1383 for (
int idim = N - 2; idim >= 0; idim--, n *=
Nmesh) {
1384 fcoord[idim] = double((index / n) %
Nmesh);
1386 fcoord[0] += Local_x_start;
1387 for (
int idim = 0; idim < N; idim++) {
1388 fcoord[idim] = twopi * double(fcoord[idim] <= nover2 ? fcoord[idim] : fcoord[idim] -
Nmesh);
1396 const int nover2plus1 =
Nmesh / 2 + 1;
1397 const int nover2 =
Nmesh / 2;
1398 std::array<int, N> fcoord;
1400 if constexpr (N == 3) {
1401 auto iz = index % nover2plus1;
1402 auto iy = index / nover2plus1;
1403 auto ix = (iy /
Nmesh) + Local_x_start;
1405 fcoord[0] = (ix <= nover2 ? ix : ix -
Nmesh);
1406 fcoord[1] = (iy <= nover2 ? iy : iy -
Nmesh);
1407 fcoord[2] = (iz <= nover2 ? iz : iz -
Nmesh);
1408 }
else if (N == 2) {
1409 auto iy = index % nover2plus1;
1410 auto ix = (index / nover2plus1) + Local_x_start;
1411 fcoord[0] = (ix <= nover2 ? ix : ix -
Nmesh);
1412 fcoord[1] = (iy <= nover2 ? iy : iy -
Nmesh);
1413 }
else if (N == 1) {
1414 auto ix = (index % nover2plus1) + Local_x_start;
1415 fcoord[0] = (ix <= nover2 ? ix : ix -
Nmesh);
1417 fcoord[N - 1] = index % nover2plus1;
1418 IndexIntType n = nover2plus1;
1419 for (
int idim = N - 2; idim >= 0; idim--, n *=
Nmesh) {
1420 fcoord[idim] = ((index / n) %
Nmesh);
1422 fcoord[0] += Local_x_start;
1423 for (
int idim = 0; idim < N; idim++) {
1424 fcoord[idim] = (fcoord[idim] <= nover2 ? fcoord[idim] : fcoord[idim] -
Nmesh);
1432#ifdef DEBUG_FFTWGRID
1434 std::cout <<
"[fftw_c2r] Transforming grid to real space\n";
1443#ifdef DEBUG_FFTWGRID
1445 std::cout <<
"[fftw_r2c] Transforming grid to real space\n";
1455 std::string label =
name;
1463 NmeshTotRealSlice * n_extra_x_slices_left;
1469 return n_extra_x_slices_left;
1474 return n_extra_x_slices_right;
1480 for (ptrdiff_t i = 0; i < NmeshTotComplexAlloc; i++) {
1482 if (not std::isfinite(z.real()) or not std::isfinite(z.imag())) {
1483 std::cout <<
"[FFTWGrid::nan_in_grids] Found NaN or Inf in grid. Index = " << i <<
"\n";
1493 std::ios_base::sync_with_stdio(
false);
1495 auto myfile = std::fstream(
filename, std::ios::out | std::ios::binary);
1498 if (not myfile.good()) {
1499 std::string
error =
"[FFTWGrid::dump_to_file] Failed to open file for writing on task " +
1501 assert_mpi(
false,
error.c_str());
1506 myfile.write((
char *)&
NDIM,
sizeof(
NDIM));
1508 myfile.write((
char *)&n_extra_x_slices_left,
sizeof(n_extra_x_slices_left));
1509 myfile.write((
char *)&n_extra_x_slices_right,
sizeof(n_extra_x_slices_right));
1510 myfile.write((
char *)&Local_nx,
sizeof(Local_nx));
1511 myfile.write((
char *)&Local_x_start,
sizeof(Local_x_start));
1512 myfile.write((
char *)&NmeshTotComplexAlloc,
sizeof(NmeshTotComplexAlloc));
1513 myfile.write((
char *)&NmeshTotRealAlloc,
sizeof(NmeshTotRealAlloc));
1514 myfile.write((
char *)&NmeshTotComplex,
sizeof(NmeshTotComplex));
1515 myfile.write((
char *)&NmeshTotComplexSlice,
sizeof(NmeshTotComplexSlice));
1516 myfile.write((
char *)&NmeshTotRealSlice,
sizeof(NmeshTotRealSlice));
1517 myfile.write((
char *)&grid_is_in_real_space,
sizeof(grid_is_in_real_space));
1520 size_t bytes =
sizeof(
ComplexType) * NmeshTotComplexAlloc;
1521 myfile.write((
char *)fourier_grid_raw.data(), bytes);
1524 if (myfile.fail()) {
1525 std::string
error =
"[FFTWGrid::dump_to_file] Failed to write the grid data on task " +
1527 assert_mpi(
false,
error.c_str());
1533 std::ios_base::sync_with_stdio(
false);
1535 auto myfile = std::ifstream(
filename, std::ios::binary);
1538 if (not myfile.good()) {
1539 std::string
error =
"[FFTWGrid::load_from_file] Failed to read the grid from file on task " +
1541 assert_mpi(
false,
error.c_str());
1543 auto check_read = [&](
const char * what) {
1544 if (not myfile.good()) {
1545 std::string
error =
"[FFTWGrid::load_from_file] File is truncated or unreadable (failed to read " +
1546 std::string(what) +
") on task " + std::to_string(
FML::ThisTask) +
1548 assert_mpi(
false,
error.c_str());
1553 int NDIM, _Nmesh, _nleft, _nright;
1554 ptrdiff_t _Local_nx, _Local_x_start, _NmeshTotComplexAlloc, _NmeshTotRealAlloc, _NmeshTotComplex,
1555 _NmeshTotComplexSlice, _NmeshTotRealSlice;
1556 bool _grid_is_in_real_space;
1557 myfile.read((
char *)&
NDIM,
sizeof(
NDIM));
1558 check_read(
"the header");
1559 assert_mpi(N ==
NDIM,
1560 "[FFTWGrid::load_from_file] The dimension of the grid does not match what is in the file\n");
1561 myfile.read((
char *)&_Nmesh,
sizeof(_Nmesh));
1562 myfile.read((
char *)&_nleft,
sizeof(_nleft));
1563 myfile.read((
char *)&_nright,
sizeof(_nright));
1564 myfile.read((
char *)&_Local_nx,
sizeof(_Local_nx));
1565 myfile.read((
char *)&_Local_x_start,
sizeof(_Local_x_start));
1566 myfile.read((
char *)&_NmeshTotComplexAlloc,
sizeof(_NmeshTotComplexAlloc));
1567 myfile.read((
char *)&_NmeshTotRealAlloc,
sizeof(_NmeshTotRealAlloc));
1568 myfile.read((
char *)&_NmeshTotComplex,
sizeof(_NmeshTotComplex));
1569 myfile.read((
char *)&_NmeshTotComplexSlice,
sizeof(_NmeshTotComplexSlice));
1570 myfile.read((
char *)&_NmeshTotRealSlice,
sizeof(_NmeshTotRealSlice));
1571 myfile.read((
char *)&_grid_is_in_real_space,
sizeof(_grid_is_in_real_space));
1572 check_read(
"the header");
1575 bool ok = _Nmesh > 0 and _nleft >= 0 and _nright >= 0;
1579 ptrdiff_t expected_Local_nx = 0, expected_Local_x_start = 0, expected_NmeshTotComplex = 0;
1581 expected_NmeshTotComplex = compute_local_size(_Nmesh, expected_Local_nx, expected_Local_x_start);
1582 const ptrdiff_t expected_slice = ptrdiff_t(_Nmesh / 2 + 1) * ptrdiff_t(
FML::power(_Nmesh, N - 2));
1583 ok = ok and _Local_nx == expected_Local_nx and _Local_x_start == expected_Local_x_start and
1584 _NmeshTotComplex == expected_NmeshTotComplex and _NmeshTotComplexSlice == expected_slice and
1585 _NmeshTotRealSlice == 2 * expected_slice and
1586 _NmeshTotComplexAlloc == expected_NmeshTotComplex + expected_slice * (_nleft + _nright) and
1587 _NmeshTotRealAlloc == 2 * _NmeshTotComplexAlloc;
1590 "[FFTWGrid::load_from_file] The grid in the file does not match the current domain decomposition "
1591 "(it must be read with the same number of tasks as it was written with) on task " +
1592 std::to_string(
FML::ThisTask) +
" File has Nmesh = " + std::to_string(_Nmesh) +
1593 " Local_nx = " + std::to_string(_Local_nx) +
" Local_x_start = " + std::to_string(_Local_x_start) +
1594 ", expected Local_nx = " + std::to_string(expected_Local_nx) +
1595 " Local_x_start = " + std::to_string(expected_Local_x_start) +
" Filename: " +
filename +
"\n";
1596 assert_mpi(
false,
error.c_str());
1601 size_t bytes =
sizeof(
ComplexType) * _NmeshTotComplexAlloc;
1602 myfile.read((
char *)data.data(), bytes);
1603 check_read(
"the grid data");
1606 fourier_grid_raw = std::move(data);
1608 n_extra_x_slices_left = _nleft;
1609 n_extra_x_slices_right = _nright;
1610 Local_nx = _Local_nx;
1611 Local_x_start = _Local_x_start;
1612 NmeshTotComplexAlloc = _NmeshTotComplexAlloc;
1613 NmeshTotRealAlloc = _NmeshTotRealAlloc;
1614 NmeshTotComplex = _NmeshTotComplex;
1615 NmeshTotComplexSlice = _NmeshTotComplexSlice;
1616 NmeshTotRealSlice = _NmeshTotRealSlice;
1617 NmeshTotReal = ptrdiff_t(Local_nx) * ptrdiff_t(
FML::power(
Nmesh, N - 1));
1618 grid_is_in_real_space = _grid_is_in_real_space;
1619 add_memory_label(
name.empty() ?
"FFTWGrid" :
name);
1634 int sampling_factor)
const {
1636 FML::assert_mpi(
Nmesh > 0,
"FFTWGrid::make_fourier_spline Grid is not allocated");
1638 sampling_factor = std::max(sampling_factor, 1);
1639 const int npts =
Nmesh * sampling_factor + 1;
1640 const double kmin = 0.0;
1641 const double kmax = 2.0 * M_PI *
Nmesh / 2.0 * std::sqrt(
double(N));
1642 std::vector<double> k_vec(npts);
1643 std::vector<double> func_vec(npts);
1644 for (
int i = 0; i < npts; i++) {
1645 k_vec[i] = kmin + (
kmax - kmin) * i /
double(npts - 1);
1646 func_vec[i] = function_of_kBox(k_vec[i]);
1647 if (func_vec[i] != func_vec[i] or std::isinf(func_vec[i])) {
1648 throw std::runtime_error(
"FFTWGrid::make_fourier_spline The function we asked to make a spline "
1649 "of evaluated to NaN or Inf at kBox = " +
1650 std::to_string(k_vec[i]));
FML::GRID::FFTWGrid< N > FFTWGrid
PhaseKey key(std::uint64_t id)
fftwf_complex my_fftw_complex
std::complex< FloatType > ComplexType
const std::string filename
Class for holding grids and performing real-to-complex and complex-to-real FFTs using FFTW with MPI.
void load_from_file(std::string fileprefix)
Load a grid written by dump_to_file (same number of tasks).
std::function< double(double)> make_fourier_spline(std::function< double(double)> function_of_kBox, std::string label, int sampling_factor=4) const
ComplexType get_fourier(const std::array< int, N > &coord) const
Fetch value in fourier grid by (local) integer coordinate.
int get_nmesh() const
Number of grid-cells per dimension.
void communicate_boundaries()
Send slices to the neighboring CPUs which stores them in the left and right extra slice storage (with...
FloatType * get_real_grid()
The left most slice (slice ix = -nleft_extra,...,-2,-1)
void fftw_c2r()
Perform complex-to-real fourier transform.
void set_real_from_index(const IndexIntType ind, const FloatType value)
Set value in grid from (local) index.
void free()
The fftw_complex cast of get_fourier_gride.
ptrdiff_t get_ntot_fourier_alloc() const
Total number of Fourier space grid-nodes we allocate (same as above + the extra slices)
void fill_real_grid(const FloatType val)
Fill the whole real-grid with a constant value.
void fill_real_grid(const std::function< FloatType(std::array< double, N > &)> &func)
Fill the main grid from a function specifying the value at a given position.
void save_wisdom(std::string filename) const
Save FFTW wisdom.
FFTWGrid clone_empty() const
Allocate matching storage with zero owned field values, preserving label/status, halos,...
FloatType * get_real_grid_by_slice(int slice)
The right grid (slice ix = NLocal_x,NLocal_x+1,...,NLocal_x+nright_extra-1)
static size_t storage_bytes(int nmesh)
Local allocation for a zero-halo grid, without allocating a mesh.
std::array< int, N > get_fourier_integer_wavevector_from_index(const IndexIntType index) const
void add_memory_label(std::string label)
For memory logging: add a label to the grid.
void add_real(const std::array< int, N > &coord, const FloatType value)
Add to value in grid.
void dump_to_file(std::string fileprefix)
Save to file (adds .X to fileprefix where X is ThisTask).
ptrdiff_t get_ntot_fourier() const
Total number of active Fourier space grid-nodes [ e.g. Local_nx * N * N * ... * (N/2 + 1) ].
FloatType get_real_from_index(const IndexIntType index) const
Fetch value in grid by (local) index.
ptrdiff_t get_local_x_start() const
The x-slice the first local slice has in the global grid.
FFTWGrid & operator=(const FFTWGrid &rhs)=default
ptrdiff_t get_ntot_real_slice_alloc() const
The number of cells per slice that we alloc. Useful to jump from slice to slice.
ComplexType * get_fourier_grid()
Get the ix'th slice (i.e. -nleft_extra <= ix < NLocal_x+nright_extra)
FloatType get_real(const std::array< int, N > &coord) const
Fetch value in grid by (local) integer coordinate.
ptrdiff_t get_local_nx() const
Number of local x-slices in the real grid.
std::array< int, N > get_fourier_coord_from_index(const IndexIntType index_fourier) const
Get the (local) cell coordinates from a local index.
FloatType * get_real_grid_left()
void set_fourier_from_index(const IndexIntType ind, const ComplexType value)
Set value of cell in fourier grid using (local) index.
ComplexType get_fourier_from_index(const IndexIntType index) const
Fetch value in fourier grid by (local) index.
FFTWGrid(FFTWGrid &&rhs) noexcept
std::array< double, N > get_fourier_wavevector_from_index(const IndexIntType index) const
Get the wave-vector of a grid-cell in Fourier space (for physical [k] multiply by 1/Boxsize)
int get_ndim() const
Dimension of the grid.
FloatType * get_real_grid_right()
The main grid (slice ix = 0...NLocal_x-1)
FourierRange get_fourier_range(int islice_begin=0, int islice_end=0) const
Range iterator for going through all active cells in the main fourier grid by index [ e....
FFTWGrid & operator=(FFTWGrid &&rhs) noexcept
void fftw_r2c()
Perform real-to-complex fourier transform.
void get_fourier_wavevector_and_norm_by_index(const IndexIntType ind, std::array< double, N > &kvec, double &kmag) const
From index in the grid get the k-vector and the magnitude of it.
void set_grid_status_real(bool grid_is_a_real_grid)
Set the status of the grid: is it currently a real grid or a fourier grid?
IndexIntType get_index_real(const std::array< int, N > &coord) const
From integer (local) coordinate of a cell in Local_nx x [0,Nmesh)^(Ndim-1) to (local) index in alloca...
void get_fourier_wavevector_and_norm2_by_index(const IndexIntType ind, std::array< double, N > &kvec, double &kmag2) const
From index in the grid get the k-vector and the norm of it (square magnitude)
void set_real(const std::array< int, N > &coord, const FloatType value)
Set value in grid from (local) integer coordinate in Local_nx x [0,Nmesh)^(Ndim-1)
void load_wisdom(std::string filename) const
Load FFTW wisdom.
bool get_grid_status_real()
Get the status of the grid: is it currently a real grid or a fourier grid?
FML::INTERPOLATION::SPLINE::Spline make_fourier_spline(std::function< double(double)> function_of_kBox, std::string label, int sampling_factor=4) const
std::function can be slow so for looping through a fourier grid and evaluating a function f(k) in eve...
std::array< int, N > get_coord_from_index(const IndexIntType index_real) const
Get the (local) cell coordinates from a local index.
void create_wisdom(int planner_flag, int numthreads=FML::NThreads)
This creates FFTW wisdom (but overwrites the arrays so must be done before setting the arrays)
FFTWGrid(const FFTWGrid &rhs)=default
ptrdiff_t get_ntot_real() const
The number of active real cells (with padding)
my_fftw_complex * get_fftw_grid()
The Fourier grid (aligns with the main real grid)
IndexIntType get_index_fourier(const std::array< int, N > &coord) const
From integer (local) coordinate in fourier grid in Local_nx x [0,Nmesh)^(Ndim-2) x [0,...
void set_fourier(const std::array< int, N > &coord, const ComplexType value)
Set value of cell in fourier grid using (local) coordinate in Local_nx x [0,Nmesh)^(Ndim-2) x [0,...
int get_n_extra_slices_right() const
How many extra slices we have allocated to the right.
void fill_fourier_grid(const std::function< ComplexType(std::array< double, N > &)> &func)
Fill the main grid from a function specifying the value at a given fourier wave-vector.
size_t allocated_storage_bytes() const
Actual retained payload capacity, including halos/padding; excludes object/allocator overhead.
std::array< double, N > get_real_position(const std::array< int, N > &coord) const
The (global) position of a real grid-cell in [0,1)^Ndim.
void reallocate(int Nmesh, int nleft, int nright)
int get_n_extra_slices_left() const
How many extra slices we have allocated to the left.
void fill_fourier_grid(const ComplexType val)
Fill the whole fourier-grid with a constant value.
FFTWGrid(int Nmesh, int n_extra_x_slices_left=0, int n_extra_x_slices_right=0)
Constructor.
void info()
Print some info about the grid.
bool nan_in_grids() const
Check if we have NaN or Inf anywhere in the allocated grid (including the extra slices)
RealRange get_real_range(int islice_begin=0, int islice_end=0) const
Range iterator for going through all active cells in the main real real grid by index [ e....
std::array< double, N > get_fourier_wavevector(const std::array< int, N > &coord) const
Get the wave-vector of a grid-cell in Fourier space (for physical [k] multiply by 1/Boxsize)
For range based for-loops over the fourier-grid. Loop over all local cells.
FourierRange(IndexIntType _from, IndexIntType _to)
LoopIteratorFourier end() const
LoopIteratorFourier begin() const
An iterator that deal with looping through the fourier grid.
LoopIteratorFourier(IndexIntType _index)
LoopIteratorFourier & operator++()
bool operator!=(LoopIteratorFourier const &other) const
IndexIntType const & operator*() const
An iterator that deal with looping through a real grid.
LoopIteratorReal(IndexIntType _index, int _Nmesh)
const IndexIntType & operator*() const
bool operator!=(LoopIteratorReal const &other) const
LoopIteratorReal & operator++()
For range based for-loops over the real-grid. Loop over all local cells.
LoopIteratorReal begin() const
RealRange(IndexIntType _from, IndexIntType _to, int _Nmesh)
LoopIteratorReal end() const
This is a wrapper class for easy use of GSL splines It is (OpenMP) thread safe as long as splines are...
static MemoryLog * get()
The (only) instance.
void add_label(void *ptr, std::string name)
void resize(size_t count)
my_fftw_plan * find_cached_fftw_plan(const FFTWPlanKey &key)
Returns nullptr if no plan is cached for this key.
int get_fftw_nthreads()
The number of threads FFTW currently makes plans with.
void fftw_c2r(FFTWGrid< N > &in_grid, FFTWGrid< N > &out_grid)
unsigned int get_fftw_planner_flag()
int fourier_mode_multiplicity(int last_coord, int nmesh)
Number of full-complex modes represented by a stored r2c coefficient.
void fftw_r2c(FFTWGrid< N > &in_grid, FFTWGrid< N > &out_grid)
void store_fftw_plan(const FFTWPlanKey &key, my_fftw_plan plan)
void set_fftw_nthreads(int nthreads)
void grid_copy(size_t bytes) noexcept
void record(Counter counter, Count amount=1) noexcept
void grid_allocation(size_t bytes) noexcept
int NThreads
Total number of threads available.
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...
int ThisTask
The MPI task number.
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
std::vector< T, Allocator< T > > Vector
long long int IndexIntType
int NTasks
Total number of MPI tasks.
Vector target(const Vector &c)
ComplexType value(const std::array< int, N > &wave, int generation)
double error(const std::vector< Vector > &a, const std::vector< Vector > &b)