FML
Loading...
Searching...
No Matches
FFTWGrid.h
Go to the documentation of this file.
1#ifndef FFTWGRIDMPI_HEADER
2#define FFTWGRIDMPI_HEADER
3#include <array>
4#include <cassert>
5#include <complex>
6#include <cstring>
7#include <fstream>
8#include <functional>
9#include <iostream>
10#include <utility>
11#include <vector>
12#ifdef USE_FFTW
13#include <fftw3.h>
14#endif
15#ifdef USE_MPI
16#include <mpi.h>
17#ifdef USE_FFTW
18#include <fftw3-mpi.h>
19#endif
20#endif
21#ifdef USE_GSL
22#include <FML/Spline/Spline.h>
23#endif
24
25#include <FML/Global/Global.h>
27#ifdef FML_ENABLE_PERFORMANCE_COUNTERS
29#endif
30
31namespace FML {
32
33 /// This namespace contains various grids for holding data shared across different tasks.
34 namespace GRID {
35 /// Number of full-complex modes represented by a stored r2c coefficient.
36 inline int fourier_mode_multiplicity(int last_coord, int nmesh) {
37 return last_coord == 0 || (nmesh % 2 == 0 && last_coord == nmesh / 2) ? 1 : 2;
38 }
39
40
41 // Include type definitions
42#include "FFTWGlobal.h"
43
44 // Forward declaration of range classes
45 class FourierRange;
46 class RealRange;
47
48 //==========================================================================
49 ///
50 /// Class for holding grids and performing real-to-complex and complex-to-real
51 /// FFTs using FFTW with MPI. Templated on dimension.
52 ///
53 /// The real and fourier grid is stored in the same array to save memory
54 /// and all transforms are done in-place. Keeps track of the status of the grid, i.e.
55 /// if its in real-space or fourier-space (set with set_grid_status_real)
56 ///
57 /// The default constructor arguments in (Nmesh, n_extra_left, n_extra_right) is:
58 ///
59 /// N : Dimension of the grid
60 ///
61 /// Nmesh : Number of grid-nodes per dimension (assuming the same)
62 ///
63 /// n_extra : Alloc extra slices of the grid in the x-dimension (left and/or right)
64 ///
65 /// Compile-time defines:
66 ///
67 /// BOUNDSCHECK_FFTWGRID : bound checks when setting and getting values
68 ///
69 /// SINGLE_PRECISION_FFTW : use float instead of double
70 ///
71 /// LONG_DOUBLE_PRECISION_FFTW : use load double instead of double
72 ///
73 /// DEBUG_FFTWGRID : Show some info while running
74 ///
75 /// USE_FFTW_THREADS : Use threads if possible. With this we assume the maximum number of threads
76 /// If you want to use fewer then you can call create_wisdom(..., nthreads) to
77 /// change this
78 ///
79 /// See FFTWGlobal.h for type definitions and the defines that deal with the precision we want.
80 ///
81 /// External variables/methods we rely on:
82 ///
83 /// ThisTask : The MPI task number
84 ///
85 /// NTasks : Number of MPI tasks
86 ///
87 /// assert_mpi(Expr, Msg)
88 ///
89 /// T power(T base, int exponent);
90 ///
91 /// The grid-stucture is only compatible with in-place FFTW transforms so
92 /// for using the methods that FT from one grid to another we copy the grid and
93 /// transforms that.
94 ///
95 //==========================================================================
96
97 template <int N>
98 class FFTWGrid {
99 // The slab layout (slices of Nmesh^(N-2) * (Nmesh/2+1) complex cells) needs N >= 2
100 static_assert(N >= 2, "FFTWGrid: only N >= 2 dimensions are supported");
101
102 private:
103 // Index for local cells. Using long long int as standard
104 using IndexIntType = FML::IndexIntType;
105
106 // The raw data vectors. These have the format [extra slices left][main grid][extra slices right]
107 // Vector = std::vector<ComplexType> with possible custom allocator
108#ifdef FML_ENABLE_PERFORMANCE_COUNTERS
110#else
112#endif
113 PayloadStorage fourier_grid_raw{};
114
115 // Mesh size and the dimension of the grid
116 int Nmesh{0};
117 // Number of local slices in real and Fourier space (the same)
118 ptrdiff_t Local_nx{0};
119 // The index in the global grid the local grid starts at
120 ptrdiff_t Local_x_start{0};
121
122 // The total number of grid-cells we allocate
123 ptrdiff_t NmeshTotRealAlloc{0};
124 ptrdiff_t NmeshTotComplexAlloc{0};
125
126 // The number of grid-cells that is active in the main part of the grid
127 ptrdiff_t NmeshTotReal{0};
128 ptrdiff_t NmeshTotComplex{0};
129
130 // XXX Add below and remove non-needed things
131 // NComplexCellsBeforeMain
132 // NComplexCellsBeforeRight
133
134 // Number of extra cells per slice
135 ptrdiff_t NmeshTotRealSlice{0};
136 ptrdiff_t NmeshTotComplexSlice{0};
137
138 // Number of extra slices to the left and right of the grid
139 int n_extra_x_slices_left{0};
140 int n_extra_x_slices_right{0};
141
142 // If you want to keep track of the field is in real space or in Fourier space
143 bool grid_is_in_real_space{true};
144
145 std::string name{""};
146
147#ifdef USE_FFTW
148 // Get a (cached) FFTW plan for transforming this grid. r2c = true for real to complex
149 // (the grid data is preserved and stays at the same address)
150 my_fftw_plan get_fftw_plan(bool r2c);
151#endif
152
153 // The local slab decomposition for a given Nmesh. Returns the number of complex cells FFTW needs
154 // locally for the main grid (can be larger than Local_nx * NmeshTotComplexSlice)
155 static ptrdiff_t compute_local_size(int Nmesh, ptrdiff_t & Local_nx, ptrdiff_t & Local_x_start);
156
157 // Number of reals at the start of the right extra slices that FFTW may use as scratch space
158 // in an in-place transform (and that we therefore must back up)
159 ptrdiff_t get_nreal_right_to_backup() const;
160
161#ifdef USE_MPI
162 // MPI_Sendrecv of a byte buffer of any size (split into chunks whose count fits in an int)
163 static void sendrecv_bytes(char * sendbuf, char * recvbuf, size_t bytes, int dest, int source);
164#endif
165
166 public:
167 FFTWGrid() = default;
168
169 /// Has the grid been allocated
170 explicit operator bool() const;
171
172 /// Constructor
173 /// @param[in] Nmesh Total number of grid-cells per dimension
174 /// @param[in] n_extra_x_slices_left Number of extra x-slices to the left of the grid (for keeping boundary
175 /// data from neighbor)
176 /// @param[in] n_extra_x_slices_right Number of extra x-slices to the right of the grid (for keeping
177 /// boundary data from neighbor)
178 FFTWGrid(int Nmesh, int n_extra_x_slices_left = 0, int n_extra_x_slices_right = 0);
179
180 // Copying and assignment from grids with the same dimension only is allowed
181 FFTWGrid(const FFTWGrid & rhs) = default;
182 FFTWGrid & operator=(const FFTWGrid & rhs) = default;
183 // Moving takes over the memory. The moved-from grid is left empty (as a default constructed grid)
184 FFTWGrid(FFTWGrid && rhs) noexcept;
185 FFTWGrid & operator=(FFTWGrid && rhs) noexcept;
186
187 // Pointers to various parts of the grid
188 FloatType * get_real_grid_left(); /// The left most slice (slice ix = -nleft_extra,...,-2,-1)
189 FloatType * get_real_grid(); /// The main grid (slice ix = 0...NLocal_x-1)
190 FloatType *
191 get_real_grid_right(); /// The right grid (slice ix = NLocal_x,NLocal_x+1,...,NLocal_x+nright_extra-1)
192 FloatType *
193 get_real_grid_by_slice(int slice); /// Get the ix'th slice (i.e. -nleft_extra <= ix < NLocal_x+nright_extra)
194 ComplexType * get_fourier_grid(); /// The Fourier grid (aligns with the main real grid)
195#ifdef USE_FFTW
196 my_fftw_complex * get_fftw_grid(); /// The fftw_complex cast of get_fourier_gride
197#endif
198 /// Free all the memory associated with the grid and reset it to an empty grid (as if default
199 /// constructed, only the label is kept)
200 void free();
201
202 /// Perform real-to-complex fourier transform
203 void fftw_r2c();
204
205 /// Perform complex-to-real fourier transform
206 void fftw_c2r();
207
208 /// Fill the whole real-grid with a constant value
209 void fill_real_grid(const FloatType val);
210 /// Fill the whole fourier-grid with a constant value
212
213 /// Fill the main grid from a function specifying the value at a given position
214 void fill_real_grid(const std::function<FloatType(std::array<double, N> &)> & func);
215 /// Fill the main grid from a function specifying the value at a given fourier wave-vector
216 void fill_fourier_grid(const std::function<ComplexType(std::array<double, N> &)> & func);
217
218 /// Get the (local) cell coordinates from a local index
219 std::array<int, N> get_coord_from_index(const IndexIntType index_real) const;
220 /// Get the (local) cell coordinates from a local index
221 std::array<int, N> get_fourier_coord_from_index(const IndexIntType index_fourier) const;
222
223 /// From integer (local) coordinate of a cell in Local_nx x [0,Nmesh)^(Ndim-1) to (local) index in allocated
224 /// grid
225 IndexIntType get_index_real(const std::array<int, N> & coord) const;
226
227 /// From integer (local) coordinate in fourier grid in Local_nx x [0,Nmesh)^(Ndim-2) x [0,Nmesh/2+1) to
228 /// index in allocated grid
229 IndexIntType get_index_fourier(const std::array<int, N> & coord) const;
230
231 /// Fetch value in grid by (local) integer coordinate
232 FloatType get_real(const std::array<int, N> & coord) const;
233 /// Fetch value in grid by (local) index
234 FloatType get_real_from_index(const IndexIntType index) const;
235
236 /// Fetch value in fourier grid by (local) integer coordinate
237 ComplexType get_fourier(const std::array<int, N> & coord) const;
238 /// Fetch value in fourier grid by (local) index
239 ComplexType get_fourier_from_index(const IndexIntType index) const;
240
241 /// The (global) position of a real grid-cell in [0,1)^Ndim
242 std::array<double, N> get_real_position(const std::array<int, N> & coord) const;
243
244 /// Get the wave-vector of a grid-cell in Fourier space (for physical [k] multiply by 1/Boxsize)
245 std::array<double, N> get_fourier_wavevector(const std::array<int, N> & coord) const;
246 /// Get the wave-vector of a grid-cell in Fourier space (for physical [k] multiply by 1/Boxsize)
247 std::array<double, N> get_fourier_wavevector_from_index(const IndexIntType index) const;
248 std::array<int, N> get_fourier_integer_wavevector_from_index(const IndexIntType index) const;
249
250 /// Set value in grid from (local) integer coordinate in Local_nx x [0,Nmesh)^(Ndim-1)
251 void set_real(const std::array<int, N> & coord, const FloatType value);
252 /// Set value in grid from (local) index
253 void set_real_from_index(const IndexIntType ind, const FloatType value);
254 /// Add to value in grid
255 void add_real(const std::array<int, N> & coord, const FloatType value);
256
257 /// Set value of cell in fourier grid using (local) coordinate in Local_nx x [0,Nmesh)^(Ndim-2) x
258 /// [0,Nmesh/2+1)
259 void set_fourier(const std::array<int, N> & coord, const ComplexType value);
260 /// Set value of cell in fourier grid using (local) index
261 void set_fourier_from_index(const IndexIntType ind, const ComplexType value);
262
263 /// How many extra slices we have allocated to the left
265 /// How many extra slices we have allocated to the right
267 /// Number of grid-cells per dimension
268 int get_nmesh() const;
269 /// Dimension of the grid
270 int get_ndim() const;
271
272 /// Number of local x-slices in the real grid
273 ptrdiff_t get_local_nx() const;
274 /// The x-slice the first local slice has in the global grid
275 ptrdiff_t get_local_x_start() const;
276
277 /// The number of active real cells (with padding)
278 ptrdiff_t get_ntot_real() const;
279 /// Total number of active Fourier space grid-nodes [ e.g. Local_nx * N * N * ... * (N/2 + 1) ]
280 ptrdiff_t get_ntot_fourier() const;
281 /// Total number of Fourier space grid-nodes we allocate (same as above + the extra slices)
282 ptrdiff_t get_ntot_fourier_alloc() const;
283
284 /// From index in the grid get the k-vector and the magnitude of it
285 void get_fourier_wavevector_and_norm_by_index(const IndexIntType ind,
286 std::array<double, N> & kvec,
287 double & kmag) const;
288 /// From index in the grid get the k-vector and the norm of it (square magnitude)
289 void get_fourier_wavevector_and_norm2_by_index(const IndexIntType ind,
290 std::array<double, N> & kvec,
291 double & kmag2) const;
292
293 /// Range iterator for going through all active cells in the main real real grid by index
294 /// [ e.g. for(auto and real_index: grid.real_range()) ]
295 /// If you add the slice numbers we only loop over the given slice range
296 RealRange get_real_range(int islice_begin = 0, int islice_end = 0) const;
297 /// Range iterator for going through all active cells in the main fourier grid by index
298 /// [ e.g. for(auto and real_index: grid.real_range()) ]
299 /// If you add the slice numbers we only loop over the given slice range
300 /// For the Fourier range islice denotes the ikx value
301 FourierRange get_fourier_range(int islice_begin = 0, int islice_end = 0) const;
302
303 /// The number of cells per slice that we alloc. Useful to jump from slice to slice
304 ptrdiff_t get_ntot_real_slice_alloc() const;
305
306 /// Check if we have NaN or Inf anywhere in the allocated grid (including the extra slices)
307 bool nan_in_grids() const;
308
309 /// Actual retained payload capacity, including halos/padding; excludes object/allocator overhead.
310 size_t allocated_storage_bytes() const { return fourier_grid_raw.capacity() * sizeof(ComplexType); }
311
312 /// Local allocation for a zero-halo grid, without allocating a mesh.
313 static size_t storage_bytes(int nmesh) {
314 assert_mpi(nmesh > 0 && nmesh % FML::NTasks == 0, "[FFTWGrid::storage_bytes] Invalid mesh size");
315 ptrdiff_t nx, start;
316 return size_t(compute_local_size(nmesh, nx, start)) * sizeof(ComplexType);
317 }
318
319 /// Send slices to the neighboring CPUs which stores them in the left and right extra slice storage
320 /// (with more extra slices than local slices they are forwarded from tasks further away)
322
323 /// This creates FFTW wisdom (but overwrites the arrays so must be done before setting the arrays)
324 void create_wisdom(int planner_flag, int numthreads = FML::NThreads);
325 /// Load FFTW wisdom
326 void load_wisdom(std::string filename) const;
327 /// Save FFTW wisdom
328 void save_wisdom(std::string filename) const;
329
330 /// Print some info about the grid
331 void info();
332
333 /// Get the status of the grid: is it currently a real grid or a fourier grid?
335 /// Set the status of the grid: is it currently a real grid or a fourier grid?
336 void set_grid_status_real(bool grid_is_a_real_grid);
337
338 /// For memory logging: add a label to the grid
339 void add_memory_label(std::string label);
340
341 /// Save to file (adds .X to fileprefix where X is ThisTask). A raw copy of the grid meant for
342 /// checkpointing: read it back with load_from_file with the same number of tasks.
343 /// Aborts (assert_mpi) if the file cannot be written
344 void dump_to_file(std::string fileprefix);
345 /// Load a grid written by dump_to_file (same number of tasks). Aborts (assert_mpi) if the file
346 /// cannot be read, is truncated or does not match the current domain decomposition
347 void load_from_file(std::string fileprefix);
348
349 /// Allocate matching storage with zero owned field values, preserving label/status,
350 /// halos, FFTW excess allocation contents and real-row padding (not the owned field).
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);
368 }
369 if constexpr (FML::PERFORMANCE::enabled) {
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))) *
373 size_t(2 * (Nmesh / 2 + 1) - Nmesh) * sizeof(FloatType);
375 }
376 return result;
377 }
378
379 void reallocate(int Nmesh, int nleft, int nright) { *this = FFTWGrid(Nmesh, nleft, nright); }
380
381#ifdef USE_GSL
382 // For making a spline that we can later use to evaluate a function of the magnitude of the fourier vector
383 // in each cell
384 FML::INTERPOLATION::SPLINE::Spline make_fourier_spline(std::function<double(double)> function_of_kBox,
385 std::string label,
386 int sampling_factor = 4) const;
387#else
388 // If we don't have GSL we simply return the function. This way we can use the same method in both cases
389 // without having a lot of ifdefs
390 std::function<double(double)> make_fourier_spline(std::function<double(double)> function_of_kBox,
391 [[maybe_unused]] std::string label,
392 [[maybe_unused]] int sampling_factor = 4) const {
393 return function_of_kBox;
394 }
395#endif
396 };
397
398 template <int N>
400 return fourier_grid_raw.size() > 0;
401 }
402
403 template <int N>
404 void FFTWGrid<N>::add_memory_label([[maybe_unused]] std::string label) {
405 name = label;
406#ifdef MEMORY_LOGGING
407 FML::MemoryLog::get()->add_label(fourier_grid_raw.data(),
408 fourier_grid_raw.capacity() * sizeof(ComplexType),
409 label);
410#endif
411 }
412
413 // Perform a real-to-complex FFT from one grid to another
414 template <int N>
415 void fftw_r2c(FFTWGrid<N> & in_grid, FFTWGrid<N> & out_grid);
416
417 // Perform a complex-to-real FFT from one grid to another
418 template <int N>
419 void fftw_c2r(FFTWGrid<N> & in_grid, FFTWGrid<N> & out_grid);
420
421 //===================================================================================
422 // For range based loop over the real grid
423 // For In-Place FFTW arrays there are 2 extra cells per dimension in the last dimension
424 // that we need to skip when looping through all the real cells
425 //===================================================================================
426
427 /// An iterator that deal with looping through a real grid. The real grid has padding so we need to skip
428 /// some cells when looping through the real grid
430 private:
431 IndexIntType real_index, index;
432 int Nmesh, odd;
433
434 public:
435 LoopIteratorReal(IndexIntType _index, int _Nmesh)
436 : real_index(_index + (_Nmesh % 2 == 1 ? 1 : 2) * (_index / _Nmesh)), index(_index), Nmesh(_Nmesh),
437 odd(_Nmesh % 2) {}
438 bool operator!=(LoopIteratorReal const & other) const { return index != other.index; }
439 const IndexIntType & operator*() const { return real_index; }
441 ++index;
442 if (index % Nmesh == 0)
443 real_index += odd ? 1 : 2;
444 ++real_index;
445 return *this;
446 }
447 };
448
449 /// For range based for-loops over the real-grid. Loop over all local cells.
450 class RealRange {
451 private:
452 const IndexIntType from, to;
453 const int Nmesh;
454
455 public:
456 RealRange(IndexIntType _from, IndexIntType _to, int _Nmesh) : from(_from), to(_to), Nmesh(_Nmesh) {}
457 LoopIteratorReal begin() const { return {from, Nmesh}; }
458 LoopIteratorReal end() const { return {to, Nmesh}; }
459 };
460
461 /// An iterator that deal with looping through the fourier grid
463 private:
464 IndexIntType index;
465
466 public:
467 LoopIteratorFourier(IndexIntType _index) : index(_index) {}
468 bool operator!=(LoopIteratorFourier const & other) const { return index != other.index; }
469 IndexIntType const & operator*() const { return index; }
471 ++index;
472 return *this;
473 }
474 };
475
476 /// For range based for-loops over the fourier-grid. Loop over all local cells.
478 private:
479 const IndexIntType from, to;
480
481 public:
482 FourierRange(IndexIntType _from, IndexIntType _to) : from(_from), to(_to) {}
483 LoopIteratorFourier begin() const { return {from}; }
484 LoopIteratorFourier end() const { return {to}; }
485 };
486
487 template <int N>
488 RealRange FFTWGrid<N>::get_real_range(int islice_begin, int islice_end) const {
489
490 // If fiducial parameters are used then we loop over all cells
491 if (islice_begin == 0 and islice_end == 0)
492 islice_end = int(Local_nx);
493
494#ifdef DEBUG_FFTWGRID
495 if (not grid_is_in_real_space) {
496 if (FML::ThisTask == 0)
497 std::cout << "Warning: [FFTWGrid::get_real_range] The grid status is [Fourierspace]. Label: " +
498 name + "\n";
499 }
500#endif
501 // Here NmeshTotReal = LocalNx * Nmesh^N-1
502 IndexIntType cellsperslice = NmeshTotReal / Local_nx;
503 return RealRange(cellsperslice * islice_begin, cellsperslice * islice_end, Nmesh);
504 }
505
506 template <int N>
507 FourierRange FFTWGrid<N>::get_fourier_range(int islice_begin, int islice_end) const {
508
509 // If fiducial parameters are used then we loop over all cells
510 if (islice_begin == 0 and islice_end == 0)
511 islice_end = int(Local_nx);
512
513#ifdef DEBUG_FFTWGRID
514 if (grid_is_in_real_space) {
515 if (FML::ThisTask == 0)
516 std::cout << "Warning: [FFTWGrid::get_fourier_range] The grid status is [Realspace]. Label: " +
517 name + "\n";
518 }
519#endif
520
521 IndexIntType cellsperslice = FML::power(Nmesh, N - 2) * IndexIntType(Nmesh / 2 + 1);
522 return FourierRange(cellsperslice * islice_begin, cellsperslice * islice_end);
523 // return FourierRange(0, NmeshTotComplex);
524 }
525
526 template <int N>
528 return reinterpret_cast<FloatType *>(fourier_grid_raw.data());
529 }
530
531 template <int N>
533 return get_real_grid_left() + NmeshTotRealSlice * n_extra_x_slices_left;
534 }
535
536 template <int N>
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");
541#endif
542 return get_real_grid_left() + NmeshTotRealSlice * (n_extra_x_slices_left + slice);
543 }
544
545 template <int N>
547 return get_real_grid_left() + NmeshTotRealSlice * (n_extra_x_slices_left + Local_nx);
548 }
549
550 template <int N>
552 return fourier_grid_raw.data() + NmeshTotComplexSlice * n_extra_x_slices_left;
553 }
554
555 template <int N>
556 void FFTWGrid<N>::set_grid_status_real(bool grid_is_a_real_grid) {
557 grid_is_in_real_space = grid_is_a_real_grid;
558 }
559
560 template <int N>
562 return grid_is_in_real_space;
563 }
564
565 template <int N>
567 if (FML::ThisTask > 0)
568 return;
569 std::string myfloattype = "[Unknown]";
570 std::string status = grid_is_in_real_space ? "[Realspace]" : "[Fourierspace]";
571 if (sizeof(FloatType) == sizeof(float))
572 myfloattype = "[Float]";
573 if (sizeof(FloatType) == sizeof(double))
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;
578 if (FML::ThisTask == 0) {
579 std::cout << "\n";
580 std::cout << "#=====================================================\n";
581 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";
588 std::cout << "#\n";
589 std::cout << "# Info about FFTWGrid. Grid label: [" << name << "]\n";
590 std::cout << "# Status of grid: " << status << " NDIM: [" << N << "] FloatType: " << myfloattype
591 << "\n";
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";
603 std::cout << "#\n";
604 std::cout << "#=====================================================\n";
605 std::cout << "\n";
606 }
607 }
608
609 // Make FFTW plans with FFTW_MEASURE, FFTW_PATIENT, FFTW_EXHAUSTIVE
610 template <int N>
611 void FFTWGrid<N>::create_wisdom([[maybe_unused]] int planner_flag, [[maybe_unused]] int nthreads) {
612#ifdef USE_FFTW
613 if (planner_flag == FFTW_ESTIMATE)
614 return;
615#ifdef USE_FFTW_THREADS
616 set_fftw_nthreads(nthreads);
617#endif
618#ifdef DEBUG_FFTWGRID
619 if (FML::ThisTask == 0) {
620 std::cout << "[FFTWGrid::create_wisdom] Planning flag " << planner_flag << ". Label: " + name + "\n";
621 }
622#endif
623
624#ifdef USE_MPI
625 std::vector<ptrdiff_t> NmeshPerDim(N, Nmesh);
626 my_fftw_plan plan_r2c =
627 MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(), FML::communicator, planner_flag);
628#else
629 std::vector<int> NmeshPerDim(N, Nmesh);
630 my_fftw_plan plan_r2c =
631 MAKE_PLAN_R2C(N, NmeshPerDim.data(), get_real_grid(), get_fftw_grid(), planner_flag);
632#endif
633 if (FML::ThisTask == 0)
634 std::cout << "[FFTWGrid::create_wisdom] Warning this will clear data in the grid. Label: " + name +
635 "\n";
636 DESTROY_PLAN(plan_r2c);
637#endif
638 }
639
640 template <int N>
641 void FFTWGrid<N>::load_wisdom([[maybe_unused]] std::string filename) const {
642#ifdef USE_FFTW
643#ifdef DEBUG_FFTWGRID
644 if (FML::ThisTask == 0) {
645 std::cout << "[FFTWGrid::load_wisdom] Filename " << filename << ". Label: " + name + "\n";
646 }
647#endif
648 if (FML::ThisTask == 0)
649 IMPORT_WISDOM_FROM_FILENAME(filename.c_str());
650#ifdef USE_MPI
651 MPI_BROADCAST_WISDOM(FML::communicator);
652#endif
653#endif
654 }
655
656 template <int N>
657 void FFTWGrid<N>::save_wisdom([[maybe_unused]] std::string filename) const {
658#ifdef USE_FFTW
659#ifdef USE_MPI
660 MPI_GATHER_WISDOM(FML::communicator);
661#endif
662 if (FML::ThisTask == 0)
663 EXPORT_WISDOM_TO_FILENAME(filename.c_str());
664#ifdef DEBUG_FFTWGRID
665 if (FML::ThisTask == 0) {
666 std::cout << "[FFTWGrid::save_wisdom] Filename " << filename << ". Label: " + name + "\n";
667 }
668#endif
669#endif
670 }
671
672#ifdef USE_FFTW
673 template <int N>
675 const unsigned int flag = FML::GRID::get_fftw_planner_flag();
677 Nmesh,
678 r2c ? 1 : -1,
680 ALIGNMENT_OF(get_real_grid()),
681 flag};
682 if (auto * plan = FML::GRID::find_cached_fftw_plan(key))
683 return *plan;
684
685 // Planning with anything but FFTW_ESTIMATE overwrites the arrays so keep a copy
686 PayloadStorage backup;
687 if (flag != FFTW_ESTIMATE)
688 backup = fourier_grid_raw;
689
690#ifdef USE_MPI
691 std::vector<ptrdiff_t> NmeshPerDim(N, Nmesh);
692 my_fftw_plan plan =
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);
695#else
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);
699#endif
700 assert_mpi(plan != nullptr, "[FFTWGrid::get_fftw_plan] FFTW failed to create a plan\n");
701 FML::PERFORMANCE::record(FML::PERFORMANCE::Counter::FFTPlans);
702
703 // Restore the data in place: the buffer must keep its address (callers may hold pointers into it)
704 // and its alignment (the plan is cached for this alignment)
705 if (flag != FFTW_ESTIMATE) {
706 std::copy(backup.begin(), backup.end(), fourier_grid_raw.begin());
707 FML::PERFORMANCE::grid_copy(backup.size() * sizeof(ComplexType));
708 }
709
711 return plan;
712 }
713#endif
714
715 template <int N>
717 return NmeshTotRealSlice;
718 }
719
720 template <int N>
722#ifdef DEBUG_FFTWGRID
723 if (not grid_is_in_real_space) {
724 if (FML::ThisTask == 0)
725 std::cout << "Warning: [FFTWGrid::fill_real_grid] The grid status is [Fourierspace]. Label: " +
726 name + "\n";
727 }
728#endif
729 FloatType * begin = (FloatType *)fourier_grid_raw.data();
730 FloatType * end = begin + NmeshTotRealAlloc;
731 std::fill(begin, end, val);
732 grid_is_in_real_space = true;
733 }
734
735 template <int N>
736 void FFTWGrid<N>::fill_real_grid(const std::function<FloatType(std::array<double, N> &)> & func) {
737#ifdef DEBUG_FFTWGRID
738 if (not grid_is_in_real_space) {
739 if (FML::ThisTask == 0)
740 std::cout << "Warning: [FFTWGrid::fill_real_grid] The grid status is [Fourierspace]. Label: " +
741 name + "\n";
742 }
743#endif
744
745#ifdef USE_OMP
746#pragma omp parallel for
747#endif
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);
754 }
755 }
756 grid_is_in_real_space = true;
757
758 communicate_boundaries();
759 }
760
761 template <int N>
763#ifdef DEBUG_FFTWGRID
764 if (grid_is_in_real_space) {
765 if (FML::ThisTask == 0)
766 std::cout << "Warning: [FFTWGrid::fill_fourier_grid] The grid status is [Realspace]. Label: " +
767 name + "\n";
768 }
769#endif
770 std::fill(fourier_grid_raw.begin(), fourier_grid_raw.end(), val);
771 grid_is_in_real_space = false;
772 }
773
774 template <int N>
775 void FFTWGrid<N>::fill_fourier_grid(const std::function<ComplexType(std::array<double, N> &)> & func) {
776#ifdef DEBUG_FFTWGRID
777 if (grid_is_in_real_space) {
778 if (FML::ThisTask == 0)
779 std::cout << "Warning: [FFTWGrid::fill_fourier_grid] The grid status is [Realspace]. Label: " +
780 name + "\n";
781 }
782#endif
783
784#ifdef USE_OMP
785#pragma omp parallel for
786#endif
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);
792 }
793 }
794 grid_is_in_real_space = false;
795 }
796
797#ifdef USE_MPI
798 template <int N>
799 void FFTWGrid<N>::sendrecv_bytes(char * sendbuf, char * recvbuf, size_t bytes, int dest, int source) {
800 // MPI counts are int so send large buffers in chunks (a slice can be > 2GB for huge grids)
801 const size_t maxchunk = size_t(1) << 30;
802 size_t offset = 0;
803 do {
804 const int nbytes = int(std::min(maxchunk, bytes - offset));
805 MPI_Status status;
806 MPI_Sendrecv(sendbuf + offset,
807 nbytes,
808 MPI_CHAR,
809 dest,
810 0,
811 recvbuf + offset,
812 nbytes,
813 MPI_CHAR,
814 source,
815 0,
817 &status);
818 offset += size_t(nbytes);
819 } while (offset < bytes);
820 }
821#endif
822
823 // We copy over slices. If we have more extra slices than local slices (thin slabs) then the slices
824 // beyond the local ones are taken from the neighbors extra slices, which have already been received at that
825 // point (the right slices are filled from the nearest one and outwards, the left ones likewise), so the
826 // ghosts always hold the (periodic) neighbor slices no matter how many we have. This relies on all tasks
827 // having the same Local_nx (true as we require NTasks to divide Nmesh)
828 template <int N>
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)
833 return;
834 assert_mpi(Local_nx > 0, "[FFTWGrid::communicate_boundaries] Grid is not allocated\n");
835
836#ifdef DEBUG_FFTWGRID
837 if (FML::ThisTask == 0) {
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";
840 }
841#endif
842
843#ifdef USE_MPI
844 int rightcpu = (FML::ThisTask + 1) % FML::NTasks;
845 int leftcpu = (FML::ThisTask - 1 + FML::NTasks) % FML::NTasks;
846#endif
847 const size_t bytes_slice = size_t(NmeshTotRealSlice) * sizeof(FloatType);
848
849 // Slice i to the right of the main grid is slice i of the right task (or for i >= Local_nx its extra
850 // slice i - Local_nx which was received in iteration i - Local_nx)
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);
856#ifdef USE_MPI
857 sendrecv_bytes(sendbuf, recvbuf, bytes_slice, leftcpu, rightcpu);
858#else
859 std::memcpy(recvbuf, sendbuf, bytes_slice);
860#endif
861 }
862
863 // Slice -1-i is slice Local_nx-1-i of the left task (or for i >= Local_nx its extra slice
864 // Local_nx-1-i < 0 which was received in iteration i - Local_nx)
865 for (int i = 0; i < n_to_recv_left; i++) {
866 FloatType * slice_right_tosend = get_real_grid() + NmeshTotRealSlice * (Local_nx - 1 - i);
867 FloatType * slice_left_torecv =
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);
871#ifdef USE_MPI
872 sendrecv_bytes(sendbuf, recvbuf, bytes_slice, rightcpu, leftcpu);
873#else
874 std::memcpy(recvbuf, sendbuf, bytes_slice);
875#endif
876 }
877 }
878
879 template <int N>
880 ptrdiff_t FFTWGrid<N>::compute_local_size(int Nmesh, ptrdiff_t & Local_nx, ptrdiff_t & Local_x_start) {
881 ptrdiff_t NmeshTotComplex = 0;
882 std::vector<ptrdiff_t> NmeshPerDimFourier(N, Nmesh);
883 NmeshPerDimFourier[N - 1] = Nmesh / 2 + 1;
884#ifdef USE_MPI
885#ifdef USE_FFTW
886 NmeshTotComplex =
887 MPI_FFTW_LOCAL_SIZE(N, NmeshPerDimFourier.data(), FML::communicator, &Local_nx, &Local_x_start);
888#else
889 // If we don't have FFTW, but want to use this class
890 Local_nx = Nmesh / FML::NTasks;
891 Local_x_start = FML::ThisTask * Local_nx;
892 NmeshTotComplex = ptrdiff_t(Nmesh / 2 + 1) * ptrdiff_t(FML::power(Nmesh, N - 1)) / ptrdiff_t(FML::NTasks);
893#endif
894#else
895 Local_nx = Nmesh;
896 Local_x_start = 0;
897 NmeshTotComplex = 1;
898 for (int i = 0; i < N; i++)
899 NmeshTotComplex *= NmeshPerDimFourier[i];
900#endif
901 return NmeshTotComplex;
902 }
903
904 template <int N>
906 if (n_extra_x_slices_right == 0)
907 return 0;
908 // FFTW may use all of its local array (NmeshTotComplex complex numbers) in an in-place transform. With MPI
909 // this can be larger than the Local_nx slices we use (e.g. in 2D when the transposed dimension
910 // Nmesh/2+1 is not divisible by NTasks) and then the excess overlaps with the right extra slices.
911 // We also always keep the first Nmesh/2+1 reals (as has always been done)
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));
915 }
916
917 template <int N>
919 *this = std::move(rhs);
920 }
921
922 template <int N>
924 if (this == &rhs)
925 return *this;
926 // Take over the buffer (keeps its address and alignment) and leave rhs empty
927 fourier_grid_raw = std::move(rhs.fourier_grid_raw);
928 Vector<ComplexType>().swap(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);
942 rhs.name.clear();
943 return *this;
944 }
945
946 template <int N>
947 FFTWGrid<N>::FFTWGrid(int Nmesh, int n_extra_x_slices_left, int n_extra_x_slices_right)
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) {
950
951#ifdef USE_MPI
952 // FFTW with MPI not implemented in FFTW for Ndim = 1 so abort
953 assert_mpi(N > 1, "[FFTWGrid] FFTW r2c and c2r with MPI currently not supported for 1D\n");
954 assert_mpi(Nmesh % FML::NTasks == 0,
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");
957#endif
958
959 // Total number of complex gridcells in the local grid
960 NmeshTotComplex = compute_local_size(Nmesh, Local_nx, Local_x_start);
961
962 // Total number of real gridcells in the local grid.
963 // NB: This will differ from the number of real cells we allocate!
964 NmeshTotReal = ptrdiff_t(Local_nx) * ptrdiff_t(FML::power(Nmesh, N - 1));
965 // Number of cells for one extra slice
966 NmeshTotComplexSlice = ptrdiff_t(Nmesh / 2 + 1) * ptrdiff_t(FML::power(Nmesh, N - 2));
967 NmeshTotRealSlice = 2 * NmeshTotComplexSlice;
968 // Total number of grid-nodes we allocate including extra slices
969 NmeshTotComplexAlloc =
970 NmeshTotComplex + NmeshTotComplexSlice * (n_extra_x_slices_left + n_extra_x_slices_right);
971 NmeshTotRealAlloc = 2 * NmeshTotComplexAlloc;
972
973 // Allocate memory and initialize to 0
974 fourier_grid_raw.resize(NmeshTotComplexAlloc);
975 add_memory_label("FFTWGrid");
976 std::fill(fourier_grid_raw.begin(), fourier_grid_raw.end(), 0.0);
977
978 // Check alignment (relevant for SIMD instructions) since we don't use fftw_malloc
979 // If you have SIMD and the alignment is off then changing to an alignment allocator
980 // will help speed up the transforms
981#ifdef USE_FFTW
982 if (((unsigned long)get_fftw_grid() & (16 - 1))) {
983 std::cout << "Warning: FFTWGrid is not 16 byte aligned (only relevant for speed if you have SIMD)\n";
984 }
985#endif
986
987#ifdef DEBUG_FFTWGRID
988 if (FML::ThisTask == 0) {
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";
991 }
992#endif
993 }
994
995 template <int N>
996 std::array<int, N> FFTWGrid<N>::get_coord_from_index(const IndexIntType index_real) const {
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");
1001#endif
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;
1007
1008 if constexpr (N == 2) {
1009 coord[0] = index;
1010 } else if (N == 3) {
1011 coord[1] = int(index % Nmesh);
1012 coord[0] = int(index / Nmesh);
1013 } else {
1014 for (int idim = N - 2; idim >= 1; idim--) {
1015 coord[idim] = int(index % Nmesh);
1016 index /= Nmesh;
1017 }
1018 coord[0] = index;
1019 }
1020 return coord;
1021 }
1022
1023 template <int N>
1024 IndexIntType FFTWGrid<N>::get_index_real(const std::array<int, N> & coord) const {
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");
1032 }
1033#endif
1034
1035 if constexpr (N == 2) {
1036 return IndexIntType(coord[0]) * (2 * (Nmesh / 2 + 1)) + coord[1];
1037 } else if (N == 3) {
1038 return (IndexIntType(coord[0]) * Nmesh + coord[1]) * (2 * (Nmesh / 2 + 1)) + coord[2];
1039 } else {
1040
1041 IndexIntType index = coord[0];
1042 for (int idim = 1; idim < N - 1; idim++) {
1043 index = index * Nmesh + coord[idim];
1044 }
1045 index = index * (2 * (Nmesh / 2 + 1)) + coord[N - 1];
1046 return index;
1047 }
1048 return 0;
1049 }
1050
1051 template <int N>
1052 IndexIntType FFTWGrid<N>::get_index_fourier(const std::array<int, N> & coord) const {
1053
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");
1059 }
1060#endif
1061
1062 if constexpr (N == 2) {
1063 return IndexIntType(coord[0]) * (Nmesh / 2 + 1) + coord[1];
1064 } else if (N == 3) {
1065 return (IndexIntType(coord[0]) * Nmesh + coord[1]) * (Nmesh / 2 + 1) + coord[2];
1066 } else {
1067 IndexIntType index = coord[0];
1068 for (int idim = 1; idim < N - 1; idim++) {
1069 index = index * Nmesh + coord[idim];
1070 }
1071 index = index * (Nmesh / 2 + 1) + coord[N - 1];
1072 return index;
1073 }
1074 }
1075
1076 template <int N>
1078#ifdef USE_FFTW
1079
1080#ifdef DEBUG_FFTWGRID
1081 if (FML::ThisTask == 0) {
1082 std::cout << "[FFTWGrid::fftw_r2c] Transforming grid to fourier space. Label: " + name + "\n";
1083 }
1084 if (not grid_is_in_real_space) {
1085 if (FML::ThisTask == 0)
1086 std::cout << "Warning: [FFTWGrid::fftw_r2c] Transforming grid whose status is already "
1087 "[Fourierspace]\n";
1088 }
1089#endif
1090
1091 // Plans are cached so this is only expensive the first time
1092 // (planning preserves the data and the buffer so we fetch pointers after this)
1093 my_fftw_plan plan_r2c = get_fftw_plan(true);
1094
1095 //=================================================================================
1096 // Make a copy of the cells in the right extra slices that FFTW might use as scratch
1097 // space when doing the in-place FFT (see get_nreal_right_to_backup)
1098 //=================================================================================
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);
1102 FML::PERFORMANCE::grid_allocation(right_copy.capacity() * sizeof(FloatType));
1103 FML::PERFORMANCE::grid_copy(size_t(nright_copy) * sizeof(FloatType));
1104
1105 EXECUTE_R2C_NEW_ARRAY(plan_r2c, get_real_grid(), get_fftw_grid());
1106 FML::PERFORMANCE::record(FML::PERFORMANCE::Counter::ForwardFFTs);
1107 grid_is_in_real_space = false;
1108
1109 // Normalize
1110 const FML::GRID::FloatType norm = 1.0 / std::pow(double(Nmesh), N);
1111#ifdef USE_OMP
1112#pragma omp parallel for
1113#endif
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));
1117 }
1118 }
1119
1120 //=================================================================================
1121 // Copy back data we copied
1122 //=================================================================================
1123 std::copy(right_copy.begin(), right_copy.end(), real_grid_right);
1124 FML::PERFORMANCE::grid_copy(size_t(nright_copy) * sizeof(FloatType));
1125
1126#else
1127 assert_mpi(false, "[FFTWGrid::fftw_r2c] Compiled without FFTW support so cannot take Fourier transforms\n");
1128#endif
1129 }
1130
1131 template <int N>
1133#ifdef USE_FFTW
1134
1135#ifdef DEBUG_FFTWGRID
1136 if (FML::ThisTask == 0) {
1137 std::cout << "[FFTWGrid::fftw_c2r] Transforming grid to real space\n";
1138 }
1139 if (grid_is_in_real_space) {
1140 if (FML::ThisTask == 0)
1141 std::cout
1142 << "Warning: [FFTWGrid::fftw_c2r] Transforming grid whose status is already [Realspace]\n";
1143 }
1144#endif
1145
1146 // Plans are cached so this is only expensive the first time
1147 // (planning preserves the data and the buffer so we fetch pointers after this)
1148 my_fftw_plan plan_c2r = get_fftw_plan(false);
1149
1150 //=================================================================================
1151 // Make a copy of the cells in the right extra slices that FFTW might use as scratch
1152 // space when doing the in-place FFT (see get_nreal_right_to_backup)
1153 //=================================================================================
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);
1157 FML::PERFORMANCE::grid_allocation(right_copy.capacity() * sizeof(FloatType));
1158 FML::PERFORMANCE::grid_copy(size_t(nright_copy) * sizeof(FloatType));
1159
1160 EXECUTE_C2R_NEW_ARRAY(plan_c2r, get_fftw_grid(), get_real_grid());
1161 FML::PERFORMANCE::record(FML::PERFORMANCE::Counter::InverseFFTs);
1162 grid_is_in_real_space = true;
1163
1164 //=================================================================================
1165 // Copy back data we copied
1166 //=================================================================================
1167 std::copy(right_copy.begin(), right_copy.end(), real_grid_right);
1168 FML::PERFORMANCE::grid_copy(size_t(nright_copy) * sizeof(FloatType));
1169
1170#else
1171 assert_mpi(false, "[FFTWGrid::fftw_c2r] Compiled without FFTW support so cannot take Fourier transforms\n");
1172#endif
1173 }
1174
1175 template <int N>
1176 FloatType FFTWGrid<N>::get_real(const std::array<int, N> & coord) const {
1177 IndexIntType index = get_index_real(coord);
1178 const FloatType * grid = reinterpret_cast<const FloatType *>(fourier_grid_raw.data()) +
1179 NmeshTotRealSlice * n_extra_x_slices_left;
1180 return grid[index];
1181 }
1182
1183 template <int N>
1184 void FFTWGrid<N>::set_real(const std::array<int, N> & coord, const FloatType value) {
1185 IndexIntType index = get_index_real(coord);
1186 get_real_grid()[index] = value;
1187 }
1188
1189 template <int N>
1190 void FFTWGrid<N>::add_real(const std::array<int, N> & coord, const FloatType value) {
1191 IndexIntType index = get_index_real(coord);
1192 get_real_grid()[index] += value;
1193 }
1194
1195 template <int N>
1196 void FFTWGrid<N>::set_real_from_index(const IndexIntType index, const FloatType value) {
1197 get_real_grid()[index] = value;
1198 }
1199
1200 template <int N>
1201 ComplexType FFTWGrid<N>::get_fourier(const std::array<int, N> & coord) const {
1202 IndexIntType index = get_index_fourier(coord);
1203 return fourier_grid_raw[NmeshTotComplexSlice * n_extra_x_slices_left + index];
1204 }
1205
1206 template <int N>
1207 ComplexType FFTWGrid<N>::get_fourier_from_index(const IndexIntType index) const {
1208 return fourier_grid_raw[NmeshTotComplexSlice * n_extra_x_slices_left + index];
1209 }
1210
1211 template <int N>
1212 void FFTWGrid<N>::set_fourier_from_index(const IndexIntType index, const ComplexType value) {
1213 get_fourier_grid()[index] = value;
1214 }
1215
1216 template <int N>
1217 void FFTWGrid<N>::set_fourier(const std::array<int, N> & coord, const ComplexType value) {
1218 IndexIntType index = get_index_fourier(coord);
1219 get_fourier_grid()[index] = value;
1220 }
1221
1222#ifdef USE_FFTW
1223 template <int N>
1225 return reinterpret_cast<my_fftw_complex *>(get_fourier_grid());
1226 }
1227#endif
1228
1229 template <int N>
1231 return Nmesh;
1232 }
1233
1234 template <int N>
1236 return N;
1237 }
1238
1239 template <int N>
1240 ptrdiff_t FFTWGrid<N>::get_ntot_real() const {
1241 return NmeshTotRealSlice * Local_nx;
1242 }
1243
1244 template <int N>
1246 return NmeshTotComplexSlice * Local_nx;
1247 }
1248
1249 template <int N>
1251 return NmeshTotComplexAlloc;
1252 }
1253
1254 template <int N>
1255 ptrdiff_t FFTWGrid<N>::get_local_nx() const {
1256 return Local_nx;
1257 }
1258
1259 template <int N>
1261 return Local_x_start;
1262 }
1263
1264 template <int N>
1265 std::array<double, N> FFTWGrid<N>::get_real_position(const std::array<int, N> & coord) const {
1266 std::array<double, N> xcoord;
1267#ifdef CELLCENTERSHIFTED
1268 const constexpr double shift = 0.5;
1269#else
1270 const constexpr double shift = 0.0;
1271#endif
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);
1275 return xcoord;
1276 }
1277
1278 template <int N>
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);
1284 }
1285
1286 template <int N>
1287 std::array<int, N> FFTWGrid<N>::get_fourier_coord_from_index(const IndexIntType index) const {
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;
1294 }
1295 return coord;
1296 }
1297
1298 template <int N>
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;
1305
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");
1309#endif
1310
1311 if (N == 3) {
1312 auto iz = index % nover2plus1;
1313 auto iy = index / nover2plus1;
1314 auto ix = (iy / Nmesh) + Local_x_start;
1315 iy = iy % Nmesh;
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];
1330 } else {
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;
1336 }
1337 coord[0] += Local_x_start;
1338 kmag2 = 0.0;
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];
1342 }
1343 }
1344 }
1345
1346 template <int N>
1347 std::array<double, N> FFTWGrid<N>::get_fourier_wavevector(const std::array<int, N> & coord) const {
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);
1354 return fcoord;
1355 }
1356
1357 template <int N>
1358 std::array<double, N> FFTWGrid<N>::get_fourier_wavevector_from_index(const IndexIntType index) const {
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;
1363
1364 if constexpr (N == 3) {
1365 auto iz = index % nover2plus1;
1366 auto iy = index / nover2plus1;
1367 auto ix = (iy / Nmesh) + Local_x_start;
1368 iy = iy % Nmesh;
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);
1380 } else {
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);
1385 }
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);
1389 }
1390 }
1391 return fcoord;
1392 }
1393
1394 template <int N>
1395 std::array<int, N> FFTWGrid<N>::get_fourier_integer_wavevector_from_index(const IndexIntType index) const {
1396 const int nover2plus1 = Nmesh / 2 + 1;
1397 const int nover2 = Nmesh / 2;
1398 std::array<int, N> fcoord;
1399
1400 if constexpr (N == 3) {
1401 auto iz = index % nover2plus1;
1402 auto iy = index / nover2plus1;
1403 auto ix = (iy / Nmesh) + Local_x_start;
1404 iy = iy % Nmesh;
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);
1416 } else {
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);
1421 }
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);
1425 }
1426 }
1427 return fcoord;
1428 }
1429
1430 template <int N>
1431 void fftw_c2r(FFTWGrid<N> & in_grid, FFTWGrid<N> & out_grid) {
1432#ifdef DEBUG_FFTWGRID
1433 if (FML::ThisTask == 0) {
1434 std::cout << "[fftw_c2r] Transforming grid to real space\n";
1435 }
1436#endif
1437 out_grid = in_grid;
1438 out_grid.fftw_c2r();
1439 }
1440
1441 template <int N>
1442 void fftw_r2c(FFTWGrid<N> & in_grid, FFTWGrid<N> & out_grid) {
1443#ifdef DEBUG_FFTWGRID
1444 if (FML::ThisTask == 0) {
1445 std::cout << "[fftw_r2c] Transforming grid to real space\n";
1446 }
1447#endif
1448 out_grid = in_grid;
1449 out_grid.fftw_r2c();
1450 }
1451
1452 template <int N>
1454 // Reset to an empty grid (releases the memory), but keep the label
1455 std::string label = name;
1456 *this = FFTWGrid<N>();
1457 name = label;
1458 }
1459
1460 template <int N>
1461 FloatType FFTWGrid<N>::get_real_from_index(const IndexIntType index) const {
1462 const FloatType * grid = reinterpret_cast<const FloatType *>(fourier_grid_raw.data()) +
1463 NmeshTotRealSlice * n_extra_x_slices_left;
1464 return grid[index];
1465 }
1466
1467 template <int N>
1469 return n_extra_x_slices_left;
1470 }
1471
1472 template <int N>
1474 return n_extra_x_slices_right;
1475 }
1476
1477 template <int N>
1479 bool found = false;
1480 for (ptrdiff_t i = 0; i < NmeshTotComplexAlloc; i++) {
1481 const ComplexType & z = fourier_grid_raw[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";
1484 found = true;
1485 break;
1486 }
1487 }
1488 return found;
1489 }
1490
1491 template <int N>
1492 void FFTWGrid<N>::dump_to_file(std::string fileprefix) {
1493 std::ios_base::sync_with_stdio(false);
1494 std::string filename = fileprefix + "." + std::to_string(FML::ThisTask);
1495 auto myfile = std::fstream(filename, std::ios::out | std::ios::binary);
1496
1497 // If we fail to open the file throw an error (a checkpoint we cannot read back is useless)
1498 if (not myfile.good()) {
1499 std::string error = "[FFTWGrid::dump_to_file] Failed to open file for writing on task " +
1500 std::to_string(FML::ThisTask) + " Filename: " + filename + "\n";
1501 assert_mpi(false, error.c_str());
1502 }
1503
1504 // Write header data
1505 int NDIM = N;
1506 myfile.write((char *)&NDIM, sizeof(NDIM));
1507 myfile.write((char *)&Nmesh, sizeof(Nmesh));
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));
1518
1519 // Write main grid
1520 size_t bytes = sizeof(ComplexType) * NmeshTotComplexAlloc;
1521 myfile.write((char *)fourier_grid_raw.data(), bytes);
1522
1523 myfile.close();
1524 if (myfile.fail()) {
1525 std::string error = "[FFTWGrid::dump_to_file] Failed to write the grid data on task " +
1526 std::to_string(FML::ThisTask) + " Filename: " + filename + "\n";
1527 assert_mpi(false, error.c_str());
1528 }
1529 }
1530
1531 template <int N>
1532 void FFTWGrid<N>::load_from_file(std::string fileprefix) {
1533 std::ios_base::sync_with_stdio(false);
1534 std::string filename = fileprefix + "." + std::to_string(FML::ThisTask);
1535 auto myfile = std::ifstream(filename, std::ios::binary);
1536
1537 // If we fail to load a file throw an error
1538 if (not myfile.good()) {
1539 std::string error = "[FFTWGrid::load_from_file] Failed to read the grid from file on task " +
1540 std::to_string(FML::ThisTask) + " Filename: " + filename + "\n";
1541 assert_mpi(false, error.c_str());
1542 }
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) +
1547 " Filename: " + filename + "\n";
1548 assert_mpi(false, error.c_str());
1549 }
1550 };
1551
1552 // Read header data (into temporaries, the grid is only changed once everything is validated)
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");
1573
1574 // The file must have been written with the same domain decomposition as we have now
1575 bool ok = _Nmesh > 0 and _nleft >= 0 and _nright >= 0;
1576#ifdef USE_MPI
1577 ok = ok and _Nmesh % FML::NTasks == 0;
1578#endif
1579 ptrdiff_t expected_Local_nx = 0, expected_Local_x_start = 0, expected_NmeshTotComplex = 0;
1580 if (ok)
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;
1588 if (not ok) {
1589 std::string error =
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());
1597 }
1598
1599 // Allocate and read main grid
1600 PayloadStorage data(_NmeshTotComplexAlloc);
1601 size_t bytes = sizeof(ComplexType) * _NmeshTotComplexAlloc;
1602 myfile.read((char *)data.data(), bytes);
1603 check_read("the grid data");
1604 myfile.close();
1605
1606 fourier_grid_raw = std::move(data);
1607 Nmesh = _Nmesh;
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);
1620 }
1621
1622#ifdef USE_GSL
1623 /// std::function can be slow so for looping through a fourier grid and evaluating a function f(k)
1624 /// in every cell its faster to make a spline and use this instead. This method makes such a spline.
1625 /// @param[in] function_of_kBox The function f(kBox)
1626 /// @param[in] label The label given to the spline. Useful for giving error messages if the spline ever
1627 /// throw errors
1628 /// @param[in] sampling_factor How many points per integer wavenumber should we sample the function at when
1629 /// making the spline?
1630 template <int N>
1632 FFTWGrid<N>::make_fourier_spline(std::function<double(double)> function_of_kBox,
1633 std::string label,
1634 int sampling_factor) const {
1635
1636 FML::assert_mpi(Nmesh > 0, "FFTWGrid::make_fourier_spline Grid is not allocated");
1637
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]));
1651 }
1652 }
1653 return FML::INTERPOLATION::SPLINE::Spline(k_vec, func_vec, label);
1654 }
1655#endif
1656 } // namespace GRID
1657} // namespace FML
1658#endif
FML::GRID::FFTWGrid< N > FFTWGrid
Definition Main.cpp:13
PhaseKey key(std::uint64_t id)
Definition Main.cpp:6
fftwf_complex my_fftw_complex
Definition FFTWGlobal.h:41
std::complex< FloatType > ComplexType
Definition FFTWGlobal.h:37
float FloatType
Definition FFTWGlobal.h:29
fftwf_plan my_fftw_plan
Definition FFTWGlobal.h:42
const int NDIM
const std::string filename
Definition Main.cpp:63
const int Nmesh
Definition Main.cpp:48
std::string name
Class for holding grids and performing real-to-complex and complex-to-real FFTs using FFTW with MPI.
Definition FFTWGrid.h:98
void load_from_file(std::string fileprefix)
Load a grid written by dump_to_file (same number of tasks).
Definition FFTWGrid.h:1532
std::function< double(double)> make_fourier_spline(std::function< double(double)> function_of_kBox, std::string label, int sampling_factor=4) const
Definition FFTWGrid.h:390
ComplexType get_fourier(const std::array< int, N > &coord) const
Fetch value in fourier grid by (local) integer coordinate.
Definition FFTWGrid.h:1201
int get_nmesh() const
Number of grid-cells per dimension.
Definition FFTWGrid.h:1230
void communicate_boundaries()
Send slices to the neighboring CPUs which stores them in the left and right extra slice storage (with...
Definition FFTWGrid.h:829
FloatType * get_real_grid()
The left most slice (slice ix = -nleft_extra,...,-2,-1)
Definition FFTWGrid.h:532
void fftw_c2r()
Perform complex-to-real fourier transform.
Definition FFTWGrid.h:1132
void set_real_from_index(const IndexIntType ind, const FloatType value)
Set value in grid from (local) index.
Definition FFTWGrid.h:1196
void free()
The fftw_complex cast of get_fourier_gride.
Definition FFTWGrid.h:1453
ptrdiff_t get_ntot_fourier_alloc() const
Total number of Fourier space grid-nodes we allocate (same as above + the extra slices)
Definition FFTWGrid.h:1250
void fill_real_grid(const FloatType val)
Fill the whole real-grid with a constant value.
Definition FFTWGrid.h:721
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.
Definition FFTWGrid.h:736
void save_wisdom(std::string filename) const
Save FFTW wisdom.
Definition FFTWGrid.h:657
FFTWGrid clone_empty() const
Allocate matching storage with zero owned field values, preserving label/status, halos,...
Definition FFTWGrid.h:351
FloatType * get_real_grid_by_slice(int slice)
The right grid (slice ix = NLocal_x,NLocal_x+1,...,NLocal_x+nright_extra-1)
Definition FFTWGrid.h:537
static size_t storage_bytes(int nmesh)
Local allocation for a zero-halo grid, without allocating a mesh.
Definition FFTWGrid.h:313
std::array< int, N > get_fourier_integer_wavevector_from_index(const IndexIntType index) const
Definition FFTWGrid.h:1395
void add_memory_label(std::string label)
For memory logging: add a label to the grid.
Definition FFTWGrid.h:404
void add_real(const std::array< int, N > &coord, const FloatType value)
Add to value in grid.
Definition FFTWGrid.h:1190
void dump_to_file(std::string fileprefix)
Save to file (adds .X to fileprefix where X is ThisTask).
Definition FFTWGrid.h:1492
ptrdiff_t get_ntot_fourier() const
Total number of active Fourier space grid-nodes [ e.g. Local_nx * N * N * ... * (N/2 + 1) ].
Definition FFTWGrid.h:1245
FloatType get_real_from_index(const IndexIntType index) const
Fetch value in grid by (local) index.
Definition FFTWGrid.h:1461
ptrdiff_t get_local_x_start() const
The x-slice the first local slice has in the global grid.
Definition FFTWGrid.h:1260
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.
Definition FFTWGrid.h:716
ComplexType * get_fourier_grid()
Get the ix'th slice (i.e. -nleft_extra <= ix < NLocal_x+nright_extra)
Definition FFTWGrid.h:551
FloatType get_real(const std::array< int, N > &coord) const
Fetch value in grid by (local) integer coordinate.
Definition FFTWGrid.h:1176
ptrdiff_t get_local_nx() const
Number of local x-slices in the real grid.
Definition FFTWGrid.h:1255
std::array< int, N > get_fourier_coord_from_index(const IndexIntType index_fourier) const
Get the (local) cell coordinates from a local index.
Definition FFTWGrid.h:1287
FloatType * get_real_grid_left()
Definition FFTWGrid.h:527
void set_fourier_from_index(const IndexIntType ind, const ComplexType value)
Set value of cell in fourier grid using (local) index.
Definition FFTWGrid.h:1212
ComplexType get_fourier_from_index(const IndexIntType index) const
Fetch value in fourier grid by (local) index.
Definition FFTWGrid.h:1207
FFTWGrid(FFTWGrid &&rhs) noexcept
Definition FFTWGrid.h:918
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)
Definition FFTWGrid.h:1358
int get_ndim() const
Dimension of the grid.
Definition FFTWGrid.h:1235
FloatType * get_real_grid_right()
The main grid (slice ix = 0...NLocal_x-1)
Definition FFTWGrid.h:546
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....
Definition FFTWGrid.h:507
FFTWGrid & operator=(FFTWGrid &&rhs) noexcept
Definition FFTWGrid.h:923
void fftw_r2c()
Perform real-to-complex fourier transform.
Definition FFTWGrid.h:1077
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.
Definition FFTWGrid.h:1279
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?
Definition FFTWGrid.h:556
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...
Definition FFTWGrid.h:1024
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)
Definition FFTWGrid.h:1299
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)
Definition FFTWGrid.h:1184
void load_wisdom(std::string filename) const
Load FFTW wisdom.
Definition FFTWGrid.h:641
bool get_grid_status_real()
Get the status of the grid: is it currently a real grid or a fourier grid?
Definition FFTWGrid.h:561
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...
Definition FFTWGrid.h:1632
std::array< int, N > get_coord_from_index(const IndexIntType index_real) const
Get the (local) cell coordinates from a local index.
Definition FFTWGrid.h:996
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)
Definition FFTWGrid.h:611
FFTWGrid(const FFTWGrid &rhs)=default
ptrdiff_t get_ntot_real() const
The number of active real cells (with padding)
Definition FFTWGrid.h:1240
my_fftw_complex * get_fftw_grid()
The Fourier grid (aligns with the main real grid)
Definition FFTWGrid.h:1224
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,...
Definition FFTWGrid.h:1052
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,...
Definition FFTWGrid.h:1217
int get_n_extra_slices_right() const
How many extra slices we have allocated to the right.
Definition FFTWGrid.h:1473
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.
Definition FFTWGrid.h:775
size_t allocated_storage_bytes() const
Actual retained payload capacity, including halos/padding; excludes object/allocator overhead.
Definition FFTWGrid.h:310
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.
Definition FFTWGrid.h:1265
void reallocate(int Nmesh, int nleft, int nright)
Definition FFTWGrid.h:379
int get_n_extra_slices_left() const
How many extra slices we have allocated to the left.
Definition FFTWGrid.h:1468
void fill_fourier_grid(const ComplexType val)
Fill the whole fourier-grid with a constant value.
Definition FFTWGrid.h:762
FFTWGrid(int Nmesh, int n_extra_x_slices_left=0, int n_extra_x_slices_right=0)
Constructor.
Definition FFTWGrid.h:947
void info()
Print some info about the grid.
Definition FFTWGrid.h:566
bool nan_in_grids() const
Check if we have NaN or Inf anywhere in the allocated grid (including the extra slices)
Definition FFTWGrid.h:1478
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....
Definition FFTWGrid.h:488
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)
Definition FFTWGrid.h:1347
For range based for-loops over the fourier-grid. Loop over all local cells.
Definition FFTWGrid.h:477
FourierRange(IndexIntType _from, IndexIntType _to)
Definition FFTWGrid.h:482
LoopIteratorFourier end() const
Definition FFTWGrid.h:484
LoopIteratorFourier begin() const
Definition FFTWGrid.h:483
An iterator that deal with looping through the fourier grid.
Definition FFTWGrid.h:462
LoopIteratorFourier(IndexIntType _index)
Definition FFTWGrid.h:467
LoopIteratorFourier & operator++()
Definition FFTWGrid.h:470
bool operator!=(LoopIteratorFourier const &other) const
Definition FFTWGrid.h:468
IndexIntType const & operator*() const
Definition FFTWGrid.h:469
An iterator that deal with looping through a real grid.
Definition FFTWGrid.h:429
LoopIteratorReal(IndexIntType _index, int _Nmesh)
Definition FFTWGrid.h:435
const IndexIntType & operator*() const
Definition FFTWGrid.h:439
bool operator!=(LoopIteratorReal const &other) const
Definition FFTWGrid.h:438
LoopIteratorReal & operator++()
Definition FFTWGrid.h:440
For range based for-loops over the real-grid. Loop over all local cells.
Definition FFTWGrid.h:450
LoopIteratorReal begin() const
Definition FFTWGrid.h:457
RealRange(IndexIntType _from, IndexIntType _to, int _Nmesh)
Definition FFTWGrid.h:456
LoopIteratorReal end() const
Definition FFTWGrid.h:458
This is a wrapper class for easy use of GSL splines It is (OpenMP) thread safe as long as splines are...
Definition Spline.h:106
static MemoryLog * get()
The (only) instance.
void add_label(void *ptr, std::string name)
void resize(size_t count)
Definition Storage.h:38
my_fftw_plan * find_cached_fftw_plan(const FFTWPlanKey &key)
Returns nullptr if no plan is cached for this key.
Definition Global.cpp:330
int get_fftw_nthreads()
The number of threads FFTW currently makes plans with.
Definition Global.cpp:317
void fftw_c2r(FFTWGrid< N > &in_grid, FFTWGrid< N > &out_grid)
Definition FFTWGrid.h:1431
unsigned int get_fftw_planner_flag()
Definition Global.cpp:343
int fourier_mode_multiplicity(int last_coord, int nmesh)
Number of full-complex modes represented by a stored r2c coefficient.
Definition FFTWGrid.h:36
void fftw_r2c(FFTWGrid< N > &in_grid, FFTWGrid< N > &out_grid)
Definition FFTWGrid.h:1442
void store_fftw_plan(const FFTWPlanKey &key, my_fftw_plan plan)
Definition Global.cpp:335
void set_fftw_nthreads(int nthreads)
Definition Global.cpp:380
void grid_copy(size_t bytes) noexcept
Definition Counters.h:106
void record(Counter counter, Count amount=1) noexcept
Definition Counters.h:65
void grid_allocation(size_t bytes) noexcept
Definition Counters.h:100
constexpr bool enabled
Definition Counters.h:50
int NThreads
Total number of threads available.
Definition Global.cpp:41
constexpr long long int power(int base, int exponent)
Simple integer a^b power-function by squaring (b >= 0; returns 0 for b < 0 instead of recursing forev...
Definition Global.h:287
int ThisTask
The MPI task number.
Definition Global.cpp:39
MPI_Comm communicator
The MPI communicator used for all communication in the library (fiducial MPI_COMM_WORLD).
Definition Global.cpp:26
std::vector< T, Allocator< T > > Vector
Definition Global.h:105
long long int IndexIntType
Definition Global.h:110
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
Vector target(const Vector &c)
const double kmax
Definition test_fnl.cpp:43
ComplexType value(const std::array< int, N > &wave, int generation)
Vector grid(size_t n)
double error(const std::vector< Vector > &a, const std::vector< Vector > &b)
double norm(Vector a)