FML
Loading...
Searching...
No Matches
ParticleGridInterpolation.h
Go to the documentation of this file.
1#ifndef PARTICLEGRIDINTERPOLATION_HEADER
2#define PARTICLEGRIDINTERPOLATION_HEADER
3
5#include <algorithm>
6#include <array>
7#include <cmath>
8#include <cstdint>
9#include <functional>
10#include <limits>
11#include <stdexcept>
12#include <string>
13#include <type_traits>
14#include <vector>
15
16#ifdef USE_OMP
17#include <omp.h>
18#endif
20#include <FML/Global/Global.h>
24
25namespace FML {
26
27 //============================================================================
28 /// This namespace deals with interpolation and density assignment.
29 ///
30 /// We give methods to assign particles to a grid to compute the density contrast
31 /// and to interpolate a grid to any given position using the same
32 /// B spline kernels (this is basically a convolution of the kernels with the grid).
33 /// This kind of interpolation is useful for computing forces from a density
34 /// field of particles. Using the interpolation method corresponding to the
35 /// density assignment help prevent unphysical self-forces.
36 ///
37 /// If the particle class has a get_mass method then we will use this mass (divided by the mean mass of all
38 /// particles so the absolute size of the masses does not matter) when assigning the particles to the grid.
39 /// Otherwise we will assume all particles have the same mass. The resulting density-field delta will always have
40 /// mean 0.
41 ///
42 /// The assignment function is a B spline kernel of any order,
43 /// i.e. H*H*...*H with H being a tophat and * convolution.
44 /// The fourier space window functions of these are just sinc(pi/2 * k / kny)^ORDER
45 /// Order 1=NGP, 2=CIC, 3=TSC, 4=PCS, 5=PQS and higher orders are easily added if you
46 /// for some strange reason needs this (just add the kernel function).
47 ///
48 /// Also contains a method for doing a convolution of a grid with a general kernel.
49 ///
50 /// Compile time defines:
51 ///
52 /// DEBUG_INTERPOL : Check that the interpolation weights
53 /// sum to unity for density assignment
54 ///
55 /// CELLCENTERSHIFTED : Shift the position of the cell (located at center of cell
56 /// vs at the corners). Use with care. Not using this option
57 /// saves a slice for even order interpoation and using it
58 /// saves a slice for odd ordered interpolation (TSC+).
59 /// Only relevant if memory is really tight and you need to use
60 /// TSC or PQS
61 ///
62 //============================================================================
63
64 namespace INTERPOLATION {
65
66 // The float type that we use for FFTE
67 using FloatType = FML::GRID::FloatType;
68
69 template <int N>
71
72 /// @brief Interpolate a grid to a set of positions given by the positions of particles.
73 ///
74 /// @tparam N The dimension of the grid
75 /// @tparam T The particle class. Must have a get_pos() method.
76 /// @tparam ORDER The order of the B-spline interpolation (1=NGP, 2=CIC, 3=TSC, 4=PCS, 5=PQS, ...)
77 ///
78 /// @param[in] grid A grid.
79 /// @param[in] part A pointer the first particle.
80 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
81 /// @param[out] interpolated_values A vector with the interpolated values, one per particle. Allocated in the
82 /// method.
83 ///
84 template <int N, int ORDER, class T>
86 const T * part,
87 size_t NumPart,
88 std::vector<FloatType> & interpolated_values);
89
90 /// @brief Interpolate a vector of grids (e.g. force vector) to a set of positions given by the positions of
91 /// particles.
92 ///
93 /// @tparam N The dimension of the grid
94 /// @tparam T The particle class. Must have a get_pos() method.
95 /// @tparam ORDER The order of the B-spline interpolation (1=NGP, 2=CIC, 3=TSC, 4=PCS, 5=PQS, ...)
96 ///
97 /// @param[in] grid_vec A N-dimensional array of grids
98 /// @param[in] part A pointer the first particle.
99 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
100 /// @param[out] interpolated_values_vec The interpolated values, one per grid per particle.
101 /// Allocated in the method.
102 ///
103 template <int N, int ORDER, class T>
104 void
105 interpolate_grid_vector_to_particle_positions(const std::array<FFTWGrid<N>, N> & grid_vec,
106 const T * part,
107 size_t NumPart,
108 std::array<std::vector<FloatType>, N> & interpolated_values_vec);
109
110 /// @brief Interpolate a grid to a set of positions given by the positions of particles.
111 ///
112 /// @tparam N The dimension of the grid
113 /// @tparam T The particle class. Must have a get_pos() method.
114 ///
115 /// @param[in] grid A grid.
116 /// @param[in] part A pointer the first particle.
117 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
118 /// @param[out] interpolated_values A vector with the interpolated values, one per particle. Allocated in the
119 /// method.
120 /// @param[in] interpolation_method The interpolation method: NGP, CIC, TSC, PCS or PQS.
121 ///
122 template <int N, class T>
124 const T * part,
125 size_t NumPart,
126 std::vector<FloatType> & interpolated_values,
127 std::string interpolation_method);
128
129 /// @brief Interpolate a vector of grids to a set of positions given by the positions of particles.
130 ///
131 /// @tparam N The dimension of the grid
132 /// @tparam T The particle class. Must have a get_pos() method.
133 ///
134 /// @param[in] grid_vec A vector of grids
135 /// @param[in] part A pointer the first particle.
136 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
137 /// @param[out] interpolated_values_vec The interpolated values, one per grid per particle. Allocated in the
138 /// method.
139 /// @param[in] interpolation_method The interpolation method: NGP, CIC, TSC, PCS or PQS.
140 ///
141 template <int N, class T>
142 void
143 interpolate_grid_vector_to_particle_positions(const std::array<FFTWGrid<N>, N> & grid_vec,
144 const T * part,
145 size_t NumPart,
146 std::array<std::vector<FloatType>, N> & interpolated_values_vec,
147 std::string interpolation_method);
148
149 /// Gather a grid vector and immediately consume each interpolated value, without output arrays.
150 /// apply(index, value) receives an array<FloatType, N>, preserving the buffered gather's rounding.
151 /// It returns a nonnegative double diagnostic; the result is its local maximum (or zero for no particles).
152 /// Calls run concurrently under OpenMP: apply must be thread safe and must not throw. Only the
153 /// calling particle's data should be modified. Grid halos must already have been communicated.
154 template <int N, int ORDER, class T, class Apply>
156 const T * part,
157 size_t NumPart,
158 Apply && apply);
159
160 template <int N, class T, class Apply>
162 const T * part,
163 size_t NumPart,
164 std::string interpolation_method,
165 Apply && apply);
166
167 /// @brief Assign particles to a grid to compute the over density field delta.
168 ///
169 /// @tparam N The dimension of the grid
170 /// @tparam T The particle class. Must have a get_pos() method. If the particle has a get_mass method then this
171 /// is used to weight the particle (we assign the particle with weight mass / mean_mass).
172 ///
173 /// @param[in] part A pointer the first particle.
174 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
175 /// @param[in] NumPartTot How many particles/positions we have in total over all tasks.
176 /// @param[out] density The overdensity field.
177 /// @param[in] density_assignment_method The assignment method: NGP, CIC, TSC, PCS or PQS.
178 ///
179 template <int N, class T>
180 void particles_to_grid(const T * part,
181 size_t NumPart,
182 size_t NumPartTot,
183 FFTWGrid<N> & density,
184 std::string density_assignment_method);
185
186 /// @brief Assign particles to a grid to compute the over density field delta.
187 ///
188 /// @tparam N The dimension of the grid
189 /// @tparam T The particle class. Must have a get_pos() method. If the particle has a get_mass method then this
190 /// is used to weight the particle (we assign the particle with weight mass / mean_mass).
191 /// @tparam ORDER The order of the B-spline interpolation (1=NGP, 2=CIC, 3=TSC, 4=PCS, 5=PQS, ...). If larger
192 /// than 5 then you must implement kernel<ORDER> yourself (a simple Mathematica calculation), see the source.
193 ///
194 /// @param[in] part A pointer the first particle.
195 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
196 /// @param[in] NumPartTot How many particles/positions we have in total over all tasks.
197 /// @param[out] density The overdensity field.
198 ///
199 template <int N, int ORDER, class T>
200 void particles_to_grid(const T * part, size_t NumPart, size_t NumPartTot, FFTWGrid<N> & density);
201
202 /// Deposit at virtual positions x + assignment_offset without changing any particle.
203 /// Offsets are in box units and must satisfy 0 <= offset[d] < 1/Nmesh. The x coordinate is
204 /// left unwrapped for MPI halo deposition; other coordinates wrap periodically. With MPI,
205 /// a positive x offset requires one extra right slice in addition to the assignment stencil.
206 /// wrap_x may be enabled with one MPI task to wrap x before scaling to grid units (the generalized
207 /// interlacing convention). The shifted coordinate is rounded to the particle's position type,
208 /// matching an actual shift; this also preserves float-position arithmetic.
209 template <int N, class T>
210 void particles_to_grid(const T * part,
211 size_t NumPart,
212 size_t NumPartTot,
213 FFTWGrid<N> & density,
214 std::string density_assignment_method,
215 const std::array<double, N> & assignment_offset,
216 bool wrap_x = false);
217
218 template <int N, int ORDER, class T>
219 void particles_to_grid(const T * part,
220 size_t NumPart,
221 size_t NumPartTot,
222 FFTWGrid<N> & density,
223 const std::array<double, N> & assignment_offset,
224 bool wrap_x = false);
225
226 namespace detail {
227 template <int N, int ORDER, class T, bool SHIFTED>
228 void particles_to_grid_impl(const T * part,
229 size_t NumPart,
230 size_t NumPartTot,
231 FFTWGrid<N> & density,
232 const std::array<double, N> & assignment_offset,
233 bool wrap_x);
234 }
235
236 /// Internal method
237 template <int N, class T>
238 void particles_to_fourier_grid_interlacing(const T * part,
239 size_t NumPart,
240 size_t NumPartTot,
241 FFTWGrid<N> & density_grid_fourier,
242 std::string density_assignment_method);
243
244 /// @brief Assign particles to grid to compute the over density.
245 /// Do this for a normal grid and an interlaced grid and return
246 /// the alias-corrected fourier transform of the density field in fourier space.
247 /// This method does not deconvolve the window function
248 ///
249 /// @tparam T The particle class. Must have a get_pos() method. If the particle has a get_mass method then this
250 /// is used to weight the particle (we assign the particle with weight mass / mean_mass).
251 ///
252 /// @param[in] part A pointer the first particle.
253 /// @param[in] NumPart How many particles/positions we have that we want to interpolate the grid to.
254 /// @param[in] NumPartTot How many particles/positions we have in total over all tasks.
255 /// @param[out] density_grid_fourier The output density grid in fourier space (must be initialized)
256 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS).
257 /// @param[in] interlacing If true use interlacing to reduce aliasing
258 ///
259 template <int N, class T>
260 void particles_to_fourier_grid(const T * part,
261 size_t NumPart,
262 size_t NumPartTot,
263 FFTWGrid<N> & density_grid_fourier,
264 std::string density_assignment_method,
265 bool interlacing);
266
267 /// @brief Convolve a grid with a kernel
268 ///
269 /// @tparam N The dimension of the grid
270 /// @tparam ORDER The width of the kernel in units of the cell-size. We consider the \f$ {\rm ORDER}^{\rm N} \f$
271 /// closest grid-cells, so ORDER/2 cells to the left and right in each dimension.
272 ///
273 /// @param[in] grid_in The grid we want to convolve.
274 /// @param[out] grid_out The in grid convolved with the kernel.
275 /// @param[in] convolution_kernel A function taking in the distance to a given cell (in units of the cell size)
276 /// and returns the kernel. For example the NGP kernel would be the function Prod_i ( |dx[i]| < 0.5 ), i.e. 1 if
277 /// all positions are within half a grid cell of the cell center.
278 ///
279 template <int N, int ORDER>
280 void convolve_grid_with_kernel(const FFTWGrid<N> & grid_in,
281 FFTWGrid<N> & grid_out,
282 const std::function<FloatType(std::array<double, N> &)> & convolution_kernel);
283
284 //===================================================================================================
285 //===================================================================================================
286
287 /// Is the name a known density assignment / interpolation method (NGP, CIC, TSC, PCS, PQS)?
288 inline bool is_known_interpolation_method(const std::string & method) {
289 return method == "NGP" or method == "CIC" or method == "TSC" or method == "PCS" or method == "PQS";
290 }
291
292 template <int N, class T>
293 void particles_to_grid(const T * part,
294 size_t NumPart,
295 size_t NumPartTot,
296 FFTWGrid<N> & density,
297 std::string density_assignment_method) {
298 assert_mpi(is_known_interpolation_method(density_assignment_method),
299 ("[particles_to_grid] Unknown density assignment method [" + density_assignment_method +
300 "] (NGP, CIC, TSC, PCS or PQS)\n")
301 .c_str());
302 if (density_assignment_method.compare("NGP") == 0)
303 particles_to_grid<N, 1, T>(part, NumPart, NumPartTot, density);
304 if (density_assignment_method.compare("CIC") == 0)
305 particles_to_grid<N, 2, T>(part, NumPart, NumPartTot, density);
306 if (density_assignment_method.compare("TSC") == 0)
307 particles_to_grid<N, 3, T>(part, NumPart, NumPartTot, density);
308 if (density_assignment_method.compare("PCS") == 0)
309 particles_to_grid<N, 4, T>(part, NumPart, NumPartTot, density);
310 if (density_assignment_method.compare("PQS") == 0)
311 particles_to_grid<N, 5, T>(part, NumPart, NumPartTot, density);
312 }
313
314 template <int N, class T>
315 void particles_to_grid(const T * part,
316 size_t NumPart,
317 size_t NumPartTot,
318 FFTWGrid<N> & density,
319 std::string density_assignment_method,
320 const std::array<double, N> & assignment_offset,
321 bool wrap_x) {
322 assert_mpi(is_known_interpolation_method(density_assignment_method),
323 ("[particles_to_grid] Unknown density assignment method [" + density_assignment_method +
324 "] (NGP, CIC, TSC, PCS or PQS)\n")
325 .c_str());
326 if (density_assignment_method.compare("NGP") == 0)
327 particles_to_grid<N, 1, T>(part, NumPart, NumPartTot, density, assignment_offset, wrap_x);
328 if (density_assignment_method.compare("CIC") == 0)
329 particles_to_grid<N, 2, T>(part, NumPart, NumPartTot, density, assignment_offset, wrap_x);
330 if (density_assignment_method.compare("TSC") == 0)
331 particles_to_grid<N, 3, T>(part, NumPart, NumPartTot, density, assignment_offset, wrap_x);
332 if (density_assignment_method.compare("PCS") == 0)
333 particles_to_grid<N, 4, T>(part, NumPart, NumPartTot, density, assignment_offset, wrap_x);
334 if (density_assignment_method.compare("PQS") == 0)
335 particles_to_grid<N, 5, T>(part, NumPart, NumPartTot, density, assignment_offset, wrap_x);
336 }
337
338 template <int N, class T>
340 const T * part,
341 size_t NumPart,
342 std::vector<FloatType> & interpolated_values,
343 std::string interpolation_method) {
345 ("[interpolate_grid_to_particle_positions] Unknown interpolation method [" +
346 interpolation_method + "] (NGP, CIC, TSC, PCS or PQS)\n")
347 .c_str());
348 if (interpolation_method.compare("NGP") == 0)
349 interpolate_grid_to_particle_positions<N, 1, T>(grid, part, NumPart, interpolated_values);
350 if (interpolation_method.compare("CIC") == 0)
351 interpolate_grid_to_particle_positions<N, 2, T>(grid, part, NumPart, interpolated_values);
352 if (interpolation_method.compare("TSC") == 0)
353 interpolate_grid_to_particle_positions<N, 3, T>(grid, part, NumPart, interpolated_values);
354 if (interpolation_method.compare("PCS") == 0)
355 interpolate_grid_to_particle_positions<N, 4, T>(grid, part, NumPart, interpolated_values);
356 if (interpolation_method.compare("PQS") == 0)
357 interpolate_grid_to_particle_positions<N, 5, T>(grid, part, NumPart, interpolated_values);
358 }
359
360 /// @brief Get the interpolation order from a string holding the density_assignment_method (NGP, CIC, ...).
361 /// Needed for the Fourier-space window function
362 inline int interpolation_order_from_name(std::string density_assignment_method) {
363 if (density_assignment_method.compare("NGP") == 0)
364 return 1;
365 if (density_assignment_method.compare("CIC") == 0)
366 return 2;
367 if (density_assignment_method.compare("TSC") == 0)
368 return 3;
369 if (density_assignment_method.compare("PCS") == 0)
370 return 4;
371 if (density_assignment_method.compare("PQS") == 0)
372 return 5;
373 assert_mpi(false, "[interpolation_order_from_name] Unknown density assignment method\n");
374 return 0;
375 }
376
377 /// @brief Compute how many extra slices we need in the FFTWGrid for a given density assignment / interpolation
378 /// method.
379 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS).
380 /// @return The number of left and right slices.
381 /// @details
382 /// Example usage:
383 ///
384 /// auto nleftright = get_extra_slices_needed_for_density_assignment("CIC");
385 ///
386 /// FFTWGrid<N> grid (Nmesh, nleftright.first, nleftright.second);
387 ///
388 inline std::pair<int, int>
389 get_extra_slices_needed_for_density_assignment(std::string density_assignment_method) {
390 int p = 0;
391 if (density_assignment_method.compare("NGP") == 0)
392 p = 1;
393 if (density_assignment_method.compare("CIC") == 0)
394 p = 2;
395 if (density_assignment_method.compare("TSC") == 0)
396 p = 3;
397 if (density_assignment_method.compare("PCS") == 0)
398 p = 4;
399 if (density_assignment_method.compare("PQS") == 0)
400 p = 5;
401 assert_mpi(p > 0, "[extra_slices_needed_density_assignment] Unknown density assignment method\n");
402 if (p == 1)
403 return {0, 0};
404#ifdef CELLCENTERSHIFTED
405 if (p % 2 == 1)
406 return {p / 2, p / 2};
407 if (p % 2 == 0)
408 return {p / 2, p / 2};
409#else
410 if (p % 2 == 1)
411 return {p / 2, p / 2 + 1};
412 if (p % 2 == 0)
413 return {p / 2 - 1, p / 2};
414#endif
415 return {0, 0};
416 }
417
418 /// @brief Compute how many extra slices we need in the FFTWGrid for a given density assignment order.
419 /// @tparam ORDER The order of the B-spline assignment kernel (NGP=1, CIC=2, TSC=3, PCS=4, PQS=5, ...)
420 /// @return The number of left and right slices.
421 ///
422 template <int ORDER>
423 inline std::pair<int, int> get_extra_slices_needed_by_order() {
424 if (ORDER == 1)
425 return {0, 0};
426#ifdef CELLCENTERSHIFTED
427 if (ORDER % 2 == 1)
428 return {ORDER / 2, ORDER / 2};
429 if (ORDER % 2 == 0)
430 return {ORDER / 2, ORDER / 2};
431#else
432 if (ORDER % 2 == 1)
433 return {ORDER / 2, ORDER / 2 + 1};
434 if (ORDER % 2 == 0)
435 return {ORDER / 2 - 1, ORDER / 2};
436#endif
437 return {0, 0};
438 }
439
440 /// @brief Internal method. The B-spline interpolation kernels for a given order
441 /// \f$ H^{(p)} = H * H * \ldots * H \f$ where H is the tophat \f$ H = [ |dx| < 0.5 ? 1 : 0 ] \f$
442 /// and * is a convolution (easily computed with Mathematica)
443 ///
444 template <int ORDER>
445 inline double kernel([[maybe_unused]] double x) {
446 static_assert(ORDER > 0 and ORDER <= 5, "Error: kernel order is not implemented\n");
447 return 0.0 / 0.0;
448 }
449 /// @brief The NGP kernel
450 template <>
451 inline double kernel<1>(double x) {
452 return (x <= 0.5) ? 1.0 : 0.0;
453 }
454 /// @brief The CIC kernel
455 template <>
456 inline double kernel<2>(double x) {
457 return (x < 1.0) ? 1.0 - x : 0.0;
458 }
459 /// @brief The TSC kernel
460 template <>
461 inline double kernel<3>(double x) {
462 return (x < 0.5) ? 0.75 - x * x : (x < 1.5 ? 0.5 * (1.5 - x) * (1.5 - x) : 0.0);
463 }
464 /// @brief The PCS kernel
465 template <>
466 inline double kernel<4>(double x) {
467 return (x < 1.0) ? 2.0 / 3.0 + x * x * (-1.0 + 0.5 * x) :
468 ((x < 2.0) ? (2 - x) * (2 - x) * (2 - x) / 6.0 : 0.0);
469 }
470 /// @brief The PQS kernel
471 template <>
472 inline double kernel<5>(double x) {
473 return (x < 0.5) ?
474 115.0 / 192.0 + 0.25 * x * x * (x * x - 2.5) :
475 ((x < 1.5) ?
476 (55 + 4 * x * (5 - 2 * x * (15 + 2 * (-5 + x) * x))) / 96.0 :
477 ((x < 2.5) ? (5 - 2.0 * x) * (5 - 2.0 * x) * (5 - 2.0 * x) * (5 - 2.0 * x) / 384. : 0.0));
478 }
479
480 /// @brief Internal method. For communication between tasks needed when adding particles to grid
481 template <int N>
482 void add_contribution_from_extra_slices(FFTWGrid<N> & density, double background = -1.0);
483
484 /// @brief This returns the a function giving the window function for a given density assignment method as
485 /// function of the wave-vector in dimensionless units.
486 /// @tparam N The dimension of the grid
487 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, ...) we used when making the
488 /// density contrast.
489 /// @param[in] Ngrid The grid size (used to set the nyquist frequency)
490 ///
491 template <int N>
492 std::function<double(std::array<double, N> &)> get_window_function(std::string density_assignment_method,
493 int Ngrid) {
494
495 assert_mpi(Ngrid > 0, "[get_window_function_fourier] Ngrid must be positive\n");
496
497 // The order of the method
498 const int p = interpolation_order_from_name(density_assignment_method);
499
500 // Just sinc to the power = order to the method
501 const double knyquist = M_PI * Ngrid;
502 std::function<double(std::array<double, N> &)> window_function = [=](std::array<double, N> & kvec) {
503 double w = 1.0;
504 for (int idim = 0; idim < N; idim++) {
505 const double koverkny = M_PI / 2. * (kvec[idim] / knyquist);
506 w *= koverkny == 0.0 ? 1.0 : std::sin(koverkny) / (koverkny);
507 }
508 // res = pow(w,p);
509 double res = 1;
510 for (int i = 0; i < p; i++)
511 res *= w;
512 return res;
513 };
514
515 return window_function;
516 }
517
518 /// @brief The Fourier window of the density assignment, \f$ W(k) = \prod_i {\rm sinc}(\pi k_i / 2k_{\rm ny})^p
519 /// \f$, from a table of the 1D factors (the wavevector components of a grid are \f$ 2\pi n \f$ with integer n).
520 /// It does the same operations as get_window_function, so the values are identical, without the N sines per
521 /// mode and the std::function call. Only for wavevectors of a grid of size Ngrid.
522 template <int N>
524 public:
525 WindowFunctionTable(std::string density_assignment_method, int Ngrid)
526 : p(interpolation_order_from_name(density_assignment_method)), Ngrid(Ngrid), table(Ngrid + 1) {
527 assert_mpi(Ngrid > 0, "[WindowFunctionTable] Ngrid must be positive\n");
528 const double twopi = 2.0 * M_PI;
529 const double knyquist = M_PI * Ngrid;
530 for (int n = -Ngrid / 2; n <= Ngrid / 2; n++) {
531 const double k = twopi * double(n);
532 const double koverkny = M_PI / 2. * (k / knyquist);
533 table[n + Ngrid / 2] = koverkny == 0.0 ? 1.0 : std::sin(koverkny) / (koverkny);
534 }
535 }
536 double operator()(const std::array<double, N> & kvec) const {
537 double w = 1.0;
538 for (int idim = 0; idim < N; idim++) {
539 // kvec = 2 pi n: round to the nearest integer (inline, std::lround is a library call)
540 const double n = kvec[idim] * (0.5 / M_PI);
541 w *= table[int(n + (n >= 0.0 ? 0.5 : -0.5)) + Ngrid / 2];
542 }
543 double res = 1;
544 for (int i = 0; i < p; i++)
545 res *= w;
546 return res;
547 }
548
549 private:
550 int p;
551 int Ngrid;
552 std::vector<double> table;
553 };
554
555 /// @brief Deconvolves the density assignment kernel in Fourier space. We divide the fourier grid by the
556 /// FFT of the density assignment kernels \f$ FFT[ H*H*H*...*H ] = FT[H]^p\f$.
557 /// @tparam N The dimension of the grid
558 /// @param[out] fourier_grid The Fourier grid of the density contrast that we will deconvolve.
559 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, ...) we used when making the
560 /// density contrast.
561 ///
562 template <int N>
563 void deconvolve_window_function_fourier(FFTWGrid<N> & fourier_grid, std::string density_assignment_method) {
564
565 const auto Ngrid = fourier_grid.get_nmesh();
566 const auto Local_nx = fourier_grid.get_local_nx();
567
568 assert_mpi(Ngrid > 0, "[deconvolve_window_function_fourier] Ngrid must be positive\n");
569
570 const WindowFunctionTable<N> window_function(density_assignment_method, Ngrid);
571
572#ifdef USE_OMP
573#pragma omp parallel for
574#endif
575 for (int islice = 0; islice < Local_nx; islice++) {
576 for (auto && fourier_index : fourier_grid.get_fourier_range(islice, islice + 1)) {
577 auto kvec = fourier_grid.get_fourier_wavevector_from_index(fourier_index);
578 auto w = window_function(kvec);
579 auto value = fourier_grid.get_fourier_from_index(fourier_index);
580 fourier_grid.set_fourier_from_index(fourier_index, value / FML::GRID::FloatType(w));
581 }
582 }
583 }
584
585 //==============================================================================
586 // Bin particles to grid using NGP, CIC, TSC, PCS, PQS, ...
587 // Some of the methods require extra slices, see
588 // get_extra_slices_needed_for_density_assignment
589 //
590 // NumPart: number of particles at the head of part
591 // NumPartTot: total number of particles across tasks
592 // NB: part.size() might not be equal to NumPart as we might have a buffer with
593 //
594 // Particles with get_mass are weighted by their mass (normalized by the mean mass), delta-f particles
595 // (get_deltaf_weight) by their weight
596 //==============================================================================
597
598 template <int N, int ORDER, class T>
599 void particles_to_grid(const T * part, size_t NumPart, size_t NumPartTot, FFTWGrid<N> & density) {
600 detail::particles_to_grid_impl<N, ORDER, T, false>(part, NumPart, NumPartTot, density, {}, false);
601 }
602
603 template <int N, int ORDER, class T>
604 void particles_to_grid(const T * part,
605 size_t NumPart,
606 size_t NumPartTot,
607 FFTWGrid<N> & density,
608 const std::array<double, N> & assignment_offset,
609 bool wrap_x) {
610 assert_mpi(not wrap_x or FML::NTasks == 1, "[particles_to_grid] Wrapped x offsets require one task");
611 const int Nmesh = density.get_nmesh();
612 assert_mpi(Nmesh > 0, "[particles_to_grid] Offset deposition needs an allocated grid");
613 bool shifted = false;
614 for (double offset : assignment_offset) {
615 assert_mpi(std::isfinite(offset) and offset >= 0.0 and offset < 1.0 / Nmesh,
616 "[particles_to_grid] Assignment offsets must be in [0, 1/Nmesh)");
617 shifted = shifted or offset != 0.0;
618 }
619 const auto nextra = get_extra_slices_needed_by_order<ORDER>();
620 assert_mpi(FML::NTasks == 1 or assignment_offset[0] == 0.0 or
621 density.get_n_extra_slices_right() >= nextra.second + 1,
622 "[particles_to_grid] Positive x offset needs one additional right slice");
623 if (shifted)
624 detail::particles_to_grid_impl<N, ORDER, T, true>(part,
625 NumPart,
626 NumPartTot,
627 density,
628 assignment_offset,
629 wrap_x);
630 else
631 particles_to_grid<N, ORDER, T>(part, NumPart, NumPartTot, density);
632 }
633
634 namespace detail {
635 // Match the rounding of a stored position += offset, but only modify a local value.
636 template <class Position>
637 inline Position assignment_coordinate(Position coordinate, double offset, int dimension, bool wrap_x) {
638 coordinate += offset;
639 if (dimension > 0 or wrap_x)
640 coordinate = FML::PARTICLE::wrap_coordinate_periodic(coordinate);
641 return coordinate;
642 }
643 } // namespace detail
644
645 template <int N, int ORDER, class T, bool SHIFTED>
646 void detail::particles_to_grid_impl(const T * part,
647 size_t NumPart,
648 size_t NumPartTot,
649 FFTWGrid<N> & density,
650 const std::array<double, N> & assignment_offset,
651 bool wrap_x) {
652
653 const auto nextra = get_extra_slices_needed_by_order<ORDER>();
654 assert_mpi(density.get_n_extra_slices_left() >= nextra.first and
655 density.get_n_extra_slices_right() >= nextra.second,
656 "[particles_to_grid] Too few extra slices\n");
657
658 //==========================================================
659 // This is a generic method. You have to specify the kernel
660 // and the corresponding width = the number of cells
661 // the point gets distributed to in each dimension which
662 // also corresponds to the order
663 //==========================================================
664
665 // For the kernel above we need to go kernel_width/2 cells to the left and right
666 constexpr int widthtondim = FML::power(ORDER, N);
667
668 // Info about the grid
669 const auto Local_nx = density.get_local_nx();
670 const auto Local_x_start = density.get_local_x_start();
671 const int Nmesh = density.get_nmesh();
672 // Particles may be up to spare_right cells to the right of the local domain if the grid has more extra
673 // slices than the kernel needs (e.g. the half-cell shifted particles for interlacing)
674 const int spare_right = density.get_n_extra_slices_right() - nextra.second;
675 assert_mpi(FML::NTasks == 1 or Local_nx >= std::max(nextra.first, nextra.second + std::max(0, spare_right)),
676 "[particles_to_grid] Fewer slices on a task than extra slices needed by the kernel: the "
677 "contributions to the extra slices would reach beyond the neighbor task (use fewer tasks or a "
678 "larger grid)\n");
679
680 // delta-f particles (get_deltaf_weight) only carry the perturbation: delta = norm * sum w_i W
681 constexpr bool has_deltaf_weight = FML::PARTICLE::has_get_deltaf_weight<T>();
682
683 // Set whole grid (also extra slices) to -1.0 (0 for delta-f particles)
684 density.fill_real_grid(has_deltaf_weight ? 0.0 : -1.0);
685
686 // Factor to normalize density to the mean density
687 double norm_fac = std::pow((double)Nmesh, N) / double(NumPartTot);
688
689 // Check if particles has a get_mass method and if so
690 // compute the mean mass
691 constexpr bool has_mass = FML::PARTICLE::has_get_mass<T>() and not has_deltaf_weight;
692 static_assert(not(FML::PARTICLE::has_get_mass<T>() and has_deltaf_weight),
693 "[particles_to_grid] A particle cannot have both get_mass and get_deltaf_weight");
694 if constexpr (has_mass) {
695 double mean_mass = 0.0;
696 for (size_t i = 0; i < NumPart; i++) {
697 mean_mass += FML::PARTICLE::GetMass(part[i]);
698 }
699 SumOverTasks(&mean_mass);
700 mean_mass /= double(NumPartTot);
701 norm_fac /= mean_mass;
702 }
703
704 // Add one particle to the grid. ATOMIC: atomic adds (a slow compare-and-swap loop for doubles), needed when
705 // several threads can write to the same cell
706 auto * density_raw = density.get_real_grid();
707 auto add_particle = [&](size_t i, auto atomic_tag) {
708 constexpr bool ATOMIC = decltype(atomic_tag)::value;
709
710 // Particle position
711 const auto * pos = FML::PARTICLE::GetPos(const_cast<T *>(part)[i]);
712
713 // Fetch mass if this is available
714 double mass = 1.0;
715 if constexpr (has_mass)
716 mass = FML::PARTICLE::GetMass(part[i]);
717 if constexpr (has_deltaf_weight)
718 mass = FML::PARTICLE::GetDeltafWeight(part[i]);
719
720 std::array<double, N> x;
721 std::array<int, N> ix;
722 [[maybe_unused]] std::array<int, N> ix_nbor;
723 for (int idim = 0; idim < N; idim++) {
724 // Scale positions to be in [0, Nmesh]
725 if constexpr (SHIFTED)
726 x[idim] = assignment_coordinate(pos[idim], assignment_offset[idim], idim, wrap_x) * Nmesh;
727 else
728 x[idim] = pos[idim] * Nmesh;
729 // Grid-index for cell containing particle
730 ix[idim] = (int)x[idim];
731 // Distance relative to cell
732 x[idim] -= ix[idim];
733 }
734
735 // Periodic BC
736 ix[0] -= int(Local_x_start);
737 // NGP uses the cell ix directly: with one task (no extra slices to fold back) wrap x too (e.g. the
738 // half-cell shifted particles for interlacing have x up to 1 + 1/(2Nmesh))
739 if constexpr (ORDER == 1)
740 if (FML::NTasks == 1 and ix[0] >= Nmesh)
741 ix[0] -= Nmesh;
742 // A particle in the local domain can be in the cell just outside it from round-off: xmin_domain =
743 // ThisTask / NTasks is not exactly Local_x_start / Nmesh (e.g. a particle at x = 63/90 has
744 // int(x * 90) = 62 with 10 tasks). Use the nearest cell in the domain (as in the interpolation)
745 if (FML::NTasks > 1) {
746 if (ix[0] < 0) {
747 x[0] += ix[0];
748 ix[0] = 0;
749 } else if (ix[0] > int(Local_nx) - 1 + spare_right) {
750 x[0] += ix[0] - (int(Local_nx) - 1 + spare_right);
751 ix[0] = int(Local_nx) - 1 + spare_right;
752 }
753 }
754 for (int idim = 1; idim < N; idim++) {
755 if (ix[idim] == Nmesh)
756 ix[idim] = 0;
757 }
758
759 // If we are on the left or right of the cell determines how many cells
760 // we have to go left and right
761 std::array<int, N> xstart;
762 if (ORDER % 2 == 0) {
763 for (int idim = 0; idim < N; idim++) {
764 xstart[idim] = -ORDER / 2 + 1;
765#ifdef CELLCENTERSHIFTED
766 xstart[idim] = -ORDER / 2;
767 if (x[idim] > 0.5)
768 xstart[idim] += 1;
769#endif
770 }
771 } else {
772#ifndef CELLCENTERSHIFTED
773 for (int idim = 0; idim < N; idim++) {
774 xstart[idim] = -ORDER / 2;
775 if (x[idim] > 0.5)
776 xstart[idim] += 1;
777 }
778#else
779 // Nodes at the cell centers: the nearest node is the particle's own cell
780 for (int idim = 0; idim < N; idim++)
781 xstart[idim] = -ORDER / 2;
782#endif
783 }
784
785 // The kernel weights and (wrapped) cell indices along each dimension. The weight of a cell is the
786 // product of these (multiplied in the order idim = 0, 1, ..., as before, so the result is identical)
787 [[maybe_unused]] std::array<std::array<double, ORDER>, N> w1d;
788 [[maybe_unused]] std::array<std::array<int, ORDER>, N> i1d;
789 if constexpr (ORDER > 1) {
790 for (int idim = 0; idim < N; idim++) {
791 for (int j = 0; j < ORDER; j++) {
792 const int go_left_right_or_stay = xstart[idim] + j;
793#ifdef CELLCENTERSHIFTED
794 const double dx = std::fabs(-x[idim] + go_left_right_or_stay + 0.5);
795#else
796 const double dx = std::fabs(-x[idim] + go_left_right_or_stay);
797#endif
798 w1d[idim][j] = kernel<ORDER>(dx);
799 // Periodic BC for all but x (we have extra slices - XXX should assert that its not too
800 // large, but covered by boundscheck in FFTWGrid if this is turned on)! If only 1 task then
801 // we should also wrap x
802 int icoord = ix[idim] + go_left_right_or_stay;
803 if (idim > 0 or FML::NTasks == 1) {
804 if (icoord >= Nmesh)
805 icoord -= Nmesh;
806 if (icoord < 0)
807 icoord += Nmesh;
808 }
809 i1d[idim][j] = icoord;
810 }
811 }
812 }
813
814 // Loop over all nbor cells
815 [[maybe_unused]] double sumweights = 0.0;
816 for (int i = 0; i < widthtondim; i++) {
817 double w = 1.0;
818 std::array<int, N> icoord;
819 if constexpr (ORDER == 1) {
820 icoord = ix;
821 } else {
822 for (int idim = 0, n = 1; idim < N; idim++, n *= ORDER) {
823 const int j = i / n % ORDER;
824 w *= w1d[idim][j];
825 icoord[idim] = i1d[idim][j];
826 }
827 }
828
829 // Add particle to grid
830 // Old version when we did not use OMP: density.add_real(icoord, w * norm_fac * mass);
831 auto index = density.get_index_real(icoord);
832 double mass_to_add = w * norm_fac * mass;
833 if constexpr (ATOMIC) {
834#ifdef USE_OMP
835#pragma omp atomic
836#endif
837 density_raw[index] += mass_to_add;
838 } else {
839 density_raw[index] += mass_to_add;
840 }
841
842 // Sum up and unsure weights sum to unity
843 sumweights += w;
844 }
845
846#ifdef DEBUG_INTERPOL
847 // Check that the weights sum up to unity
848 assert_mpi(
849 std::fabs(sumweights - 1.0) < 1e-3,
850 "[particles_to_grid] Possible problem with particles to grid: weights does not sum to unity!");
851#endif
852 };
853
854 //==========================================================
855 // One thread: the particles in order (the results do not depend on how the code is compiled)
856 //
857 // Several threads, without atomics: the local x-range is split into nchunks chunks of at least
858 // 2 ORDER + 2 slices (so the cells written by particles in chunks c and c+2 never overlap; nchunks is even
859 // with one task as the first and last chunk are then neighbors). The particles of the even chunks are added
860 // in parallel, then those of the odd chunks, each chunk in the order of the particles. Every cell then gets
861 // its contributions in the same order for any number of threads > 1 (deterministic; differs from the
862 // one-thread result only by round-off from the order of the sums). The particles are not moved, only
863 // their indices are grouped by chunk (4 bytes per particle). With too few chunks (thin slabs with many
864 // tasks: fewer than 4 (2 ORDER + 2) slices per task, e.g. Nmesh 512 on 32 tasks) we fall back to atomic
865 // adds, and the result then depends on the order of the additions (not bit-identical between runs).
866 //==========================================================
867#ifdef USE_OMP
868 const int nthreads = omp_get_max_threads();
869#else
870 const int nthreads = 1;
871#endif
872 if (nthreads == 1) {
873 for (size_t i = 0; i < NumPart; i++)
874 add_particle(i, std::false_type{});
875 } else {
876 const int Local_nx = density.get_local_nx();
877 int nchunks = Local_nx / (2 * ORDER + 2);
878 if (FML::NTasks == 1 and nchunks % 2 == 1)
879 nchunks--;
880 const bool chunked = nchunks >= 4 and NumPart < size_t(std::numeric_limits<uint32_t>::max());
881 if (not chunked) {
882#ifdef USE_OMP
883#pragma omp parallel for
884#endif
885 for (size_t i = 0; i < NumPart; i++)
886 add_particle(i, std::true_type{});
887 } else {
888 // The chunk of each particle (from the x-slice it is in, clamped to the local range)
889 auto chunk_of = [&](size_t i) {
890 const auto * pos = FML::PARTICLE::GetPos(const_cast<T *>(part)[i]);
891 auto coordinate = pos[0];
892 if constexpr (SHIFTED)
893 coordinate = assignment_coordinate(coordinate, assignment_offset[0], 0, wrap_x);
894 int ix0 = int(coordinate * Nmesh) - int(Local_x_start);
895 ix0 = std::max(0, std::min(ix0, Local_nx - 1));
896 return int((long long)(ix0)*nchunks / Local_nx);
897 };
898 // Counting sort of the particle indices by chunk (stable: each chunk in particle order)
899 std::vector<size_t> start(nchunks + 1, 0);
900 std::vector<uint32_t> chunk(NumPart);
901#ifdef USE_OMP
902#pragma omp parallel for
903#endif
904 for (size_t i = 0; i < NumPart; i++)
905 chunk[i] = uint32_t(chunk_of(i));
906 for (size_t i = 0; i < NumPart; i++)
907 start[chunk[i] + 1]++;
908 for (int c = 0; c < nchunks; c++)
909 start[c + 1] += start[c];
910 std::vector<uint32_t> order(NumPart);
911 {
912 std::vector<size_t> next(start.begin(), start.end() - 1);
913 for (size_t i = 0; i < NumPart; i++)
914 order[next[chunk[i]]++] = uint32_t(i);
915 }
916 std::vector<uint32_t>().swap(chunk);
917 for (int phase = 0; phase < 2; phase++) {
918#ifdef USE_OMP
919#pragma omp parallel for schedule(dynamic, 1)
920#endif
921 for (int c = phase; c < nchunks; c += 2)
922 for (size_t k = start[c]; k < start[c + 1]; k++)
923 add_particle(order[k], std::false_type{});
924 }
925 }
926 }
927
928 // Extra slices only relevant if we have more than 1 task
929 if (FML::NTasks > 1)
930 add_contribution_from_extra_slices<N>(density, has_deltaf_weight ? 0.0 : -1.0);
931 }
932
933 template <int N, int ORDER, class T>
934 void
936 const T * part,
937 size_t NumPart,
938 std::array<std::vector<FloatType>, N> & interpolated_values_vec) {
939 for (auto & values : interpolated_values_vec)
940 if (values.size() < NumPart)
941 values.resize(NumPart);
942 auto store = [&](size_t index, const std::array<FloatType, N> & value) {
943 for (int dimension = 0; dimension < N; dimension++)
944 interpolated_values_vec[dimension][index] = value[dimension];
945 return 0.0;
946 };
948 }
949
950 template <int N, int ORDER, class T, class Apply>
952 const T * part,
953 size_t NumPart,
954 Apply && apply) {
955
957 assert_mpi(grid_vec.size() > 0,
958 "[interpolate_grid_to_particle_positions] Grid vector has to be already allocated!\n");
959 for (auto & g : grid_vec) {
960 assert_mpi(g.get_nmesh() > 0,
961 "[interpolate_grid_to_particle_positions] All grids has to be already allocated!\n");
962 assert_mpi(g.get_nmesh() == grid_vec[0].get_nmesh(),
963 "[interpolate_grid_to_particle_positions] All grids has to have the same size!\n");
964 }
965 for (auto & g : grid_vec) {
966 assert_mpi(g.get_n_extra_slices_left() >= nextra.first and
967 g.get_n_extra_slices_right() >= nextra.second,
968 "[interpolate_grid_to_particle_positions] Too few extra slices in some of the grids\n");
969 }
970
971 // We need to look at width^N cells in total
972 constexpr int widthtondim = FML::power(ORDER, N);
973
974 // Fetch grid information
975 const auto Local_nx = grid_vec[0].get_local_nx();
976 const auto Local_x_start = grid_vec[0].get_local_x_start();
977 const int Nmesh = grid_vec[0].get_nmesh();
978 const int spare_right = std::max(0, grid_vec[0].get_n_extra_slices_right() - nextra.second);
979 assert_mpi(FML::NTasks == 1 or Local_nx >= std::max(nextra.first, nextra.second + spare_right),
980 "[interpolate_grid_to_particle_positions] Fewer slices on a task than extra slices needed by "
981 "the kernel: the extra slices cannot be filled from the neighbor task (use fewer tasks or a "
982 "larger grid)\n");
983
984 double max_result = 0.0;
985
986#ifdef USE_OMP
987#pragma omp parallel for reduction(max : max_result)
988#endif
989 for (size_t ind = 0; ind < NumPart; ind++) {
990
991 // Positions in global grid in units of [Nmesh]
992 const auto * pos = FML::PARTICLE::GetPos(const_cast<T *>(part)[ind]);
993 std::array<double, N> x;
994 for (int idim = 0; idim < N; idim++)
995 x[idim] = pos[idim] * Nmesh;
996
997 // Nearest grid-node in grid
998 // Also do some sanity checks. Probably better to throw here if these tests kick in
999 std::array<int, N> ix;
1000 for (int idim = 0; idim < N; idim++) {
1001 ix[idim] = int(x[idim]);
1002 if (idim == 0) {
1003 // Particles may be up to spare_right cells outside the local domain if the grid has
1004 // more extra slices than the kernel needs (e.g. when the particles have been shifted)
1005 if (ix[0] >= (Local_x_start + Local_nx + spare_right))
1006 ix[0] = int(Local_x_start + Local_nx + spare_right) - 1;
1007 if (ix[0] < Local_x_start)
1008 ix[0] = int(Local_x_start);
1009 } else {
1010 if (ix[idim] == Nmesh)
1011 ix[idim] = Nmesh - 1;
1012 }
1013 }
1014
1015 // Positions to distance from neareste grid-node
1016 for (int idim = 0; idim < N; idim++) {
1017 x[idim] -= ix[idim];
1018 }
1019
1020 // From global ix to local ix
1021 ix[0] -= int(Local_x_start);
1022
1023 // If we are on the left or right of the cell determines how many cells
1024 // we have to go left and right
1025 std::array<int, N> xstart;
1026 if (ORDER % 2 == 0) {
1027 for (int idim = 0; idim < N; idim++) {
1028 xstart[idim] = -ORDER / 2 + 1;
1029#ifdef CELLCENTERSHIFTED
1030 xstart[idim] = -ORDER / 2;
1031 if (x[idim] > 0.5)
1032 xstart[idim] += 1;
1033#endif
1034 }
1035 } else {
1036#ifndef CELLCENTERSHIFTED
1037 for (int idim = 0; idim < N; idim++) {
1038 xstart[idim] = -ORDER / 2;
1039 if (x[idim] > 0.5)
1040 xstart[idim] += 1;
1041 }
1042#else
1043 // Nodes at the cell centers: the nearest node is the particle's own cell
1044 for (int idim = 0; idim < N; idim++)
1045 xstart[idim] = -ORDER / 2;
1046#endif
1047 }
1048
1049 // The kernel weights and cell indices along each dimension (periodic in all but x). The weight of a
1050 // cell is their product, multiplied in the order idim = 0, 1, ... as before (identical results)
1051 std::array<std::array<double, ORDER>, N> w1d;
1052 std::array<std::array<int, ORDER>, N> i1d;
1053 for (int idim = 0; idim < N; idim++) {
1054 for (int j = 0; j < ORDER; j++) {
1055 const int go_left_right_or_stay = ORDER == 1 ? 0 : xstart[idim] + j;
1056#ifdef CELLCENTERSHIFTED
1057 const double dx = std::fabs(-x[idim] + go_left_right_or_stay + 0.5);
1058#else
1059 const double dx = std::fabs(-x[idim] + go_left_right_or_stay);
1060#endif
1061 // (NGP: the particle's own cell, weight 1 as in the scalar version; kernel<1>(dx) is 0 for
1062 // dx > 0.5, i.e. for particles in the right half of their cell)
1063 w1d[idim][j] = ORDER == 1 ? 1.0 : kernel<ORDER>(dx);
1064 int icoord = ix[idim] + go_left_right_or_stay;
1065 if (idim > 0) {
1066 if (icoord >= Nmesh)
1067 icoord -= Nmesh;
1068 if (icoord < 0)
1069 icoord += Nmesh;
1070 }
1071 i1d[idim][j] = icoord;
1072 }
1073 }
1074
1075 // Interpolation
1076 std::array<double, N> value;
1077 value.fill(0.0);
1078 [[maybe_unused]] double sumweight = 0;
1079 for (int i = 0; i < widthtondim; i++) {
1080 double w = 1.0;
1081 std::array<int, N> icoord;
1082 for (int idim = 0, n = 1; idim < N; idim++, n *= ORDER) {
1083 const int j = i / n % ORDER;
1084 w *= w1d[idim][j];
1085 icoord[idim] = i1d[idim][j];
1086 }
1087
1088 // Add up
1089 for (int idim = 0; idim < N; idim++)
1090 value[idim] += grid_vec[idim].get_real(icoord) * w;
1091 sumweight += w;
1092 }
1093
1094#ifdef DEBUG_INTERPOL
1095 // Check that the weights sum up to unity
1096 assert_mpi(std::fabs(sumweight - 1.0) < 1e-3,
1097 "[interpolate_grid_to_particle_positions] Possible problem with interpolation: weights does "
1098 "not sum to unity!");
1099#endif
1100
1101 // Preserve the precision boundary of the original buffered gather before applying an update.
1102 std::array<FloatType, N> interpolated_value;
1103 for (int idim = 0; idim < N; idim++)
1104 interpolated_value[idim] = value[idim];
1105 max_result = std::max(max_result, apply(ind, interpolated_value));
1106 }
1107 return max_result;
1108 }
1109
1110 template <int N, class T>
1112 const T * part,
1113 size_t NumPart,
1114 std::array<std::vector<FloatType>, N> & interpolated_values,
1115 std::string interpolation_method) {
1117 ("[interpolate_grid_vector_to_particle_positions] Unknown interpolation method [" +
1118 interpolation_method + "] (NGP, CIC, TSC, PCS or PQS)\n")
1119 .c_str());
1120 if (interpolation_method.compare("NGP") == 0)
1121 interpolate_grid_vector_to_particle_positions<N, 1, T>(grid, part, NumPart, interpolated_values);
1122 if (interpolation_method.compare("CIC") == 0)
1123 interpolate_grid_vector_to_particle_positions<N, 2, T>(grid, part, NumPart, interpolated_values);
1124 if (interpolation_method.compare("TSC") == 0)
1125 interpolate_grid_vector_to_particle_positions<N, 3, T>(grid, part, NumPart, interpolated_values);
1126 if (interpolation_method.compare("PCS") == 0)
1127 interpolate_grid_vector_to_particle_positions<N, 4, T>(grid, part, NumPart, interpolated_values);
1128 if (interpolation_method.compare("PQS") == 0)
1129 interpolate_grid_vector_to_particle_positions<N, 5, T>(grid, part, NumPart, interpolated_values);
1130 }
1131
1132 template <int N, class T, class Apply>
1134 const T * part,
1135 size_t NumPart,
1136 std::string interpolation_method,
1137 Apply && apply) {
1139 ("[interpolate_grid_vector_to_particle_positions_apply] Unknown interpolation method [" +
1140 interpolation_method + "] (NGP, CIC, TSC, PCS or PQS)\n")
1141 .c_str());
1142 if (interpolation_method == "NGP")
1144 if (interpolation_method == "CIC")
1146 if (interpolation_method == "TSC")
1148 if (interpolation_method == "PCS")
1151 }
1152
1153 template <int N, int ORDER, class T>
1155 const T * part,
1156 size_t NumPart,
1157 std::vector<FloatType> & interpolated_values) {
1158
1160 assert_mpi(grid.get_nmesh() > 0,
1161 "[interpolate_grid_to_particle_positions] Grid has to be already allocated!\n");
1162 assert_mpi(grid.get_n_extra_slices_left() >= nextra.first and
1163 grid.get_n_extra_slices_right() >= nextra.second,
1164 "[interpolate_grid_to_particle_positions] Too few extra slices\n");
1165
1166 // We need to look at width^N cells in total
1167 constexpr int widthtondim = FML::power(ORDER, N);
1168
1169 // Fetch grid information
1170 const auto Local_nx = grid.get_local_nx();
1171 const auto Local_x_start = grid.get_local_x_start();
1172 const int Nmesh = grid.get_nmesh();
1173 const int spare_right = std::max(0, grid.get_n_extra_slices_right() - nextra.second);
1174 assert_mpi(FML::NTasks == 1 or Local_nx >= std::max(nextra.first, nextra.second + spare_right),
1175 "[interpolate_grid_to_particle_positions] Fewer slices on a task than extra slices needed by "
1176 "the kernel: the extra slices cannot be filled from the neighbor task (use fewer tasks or a "
1177 "larger grid)\n");
1178
1179 // Allocate memory needed
1180 interpolated_values.resize(NumPart);
1181
1182#ifdef USE_OMP
1183#pragma omp parallel for
1184#endif
1185 for (size_t ind = 0; ind < NumPart; ind++) {
1186
1187 // Positions in global grid in units of [Nmesh]
1188 const auto * pos = FML::PARTICLE::GetPos(const_cast<T *>(part)[ind]);
1189 std::array<double, N> x;
1190 for (int idim = 0; idim < N; idim++)
1191 x[idim] = pos[idim] * Nmesh;
1192
1193 // Nearest grid-node in grid
1194 // Also do some sanity checks. Probably better to throw here if these tests kick in
1195 std::array<int, N> ix;
1196 [[maybe_unused]] std::array<int, N> ix_nbor;
1197 for (int idim = 0; idim < N; idim++) {
1198 ix[idim] = int(x[idim]);
1199 if (idim == 0) {
1200 // Particles may be up to spare_right cells outside the local domain if the grid has
1201 // more extra slices than the kernel needs (e.g. when the particles have been shifted)
1202 if (ix[0] >= (Local_x_start + Local_nx + spare_right))
1203 ix[0] = int(Local_x_start + Local_nx + spare_right) - 1;
1204 if (ix[0] < Local_x_start)
1205 ix[0] = int(Local_x_start);
1206 } else {
1207 if (ix[idim] == Nmesh)
1208 ix[idim] = Nmesh - 1;
1209 }
1210 }
1211
1212 // Positions to distance from neareste grid-node
1213 for (int idim = 0; idim < N; idim++) {
1214 x[idim] -= ix[idim];
1215 }
1216
1217 // From global ix to local ix
1218 ix[0] -= int(Local_x_start);
1219
1220 // If we are on the left or right of the cell determines how many cells
1221 // we have to go left and right
1222 std::array<int, N> xstart;
1223 if (ORDER % 2 == 0) {
1224 for (int idim = 0; idim < N; idim++) {
1225 xstart[idim] = -ORDER / 2 + 1;
1226#ifdef CELLCENTERSHIFTED
1227 xstart[idim] = -ORDER / 2;
1228 if (x[idim] > 0.5)
1229 xstart[idim] += 1;
1230#endif
1231 }
1232 } else {
1233#ifndef CELLCENTERSHIFTED
1234 for (int idim = 0; idim < N; idim++) {
1235 xstart[idim] = -ORDER / 2;
1236 if (x[idim] > 0.5)
1237 xstart[idim] += 1;
1238 }
1239#else
1240 // Nodes at the cell centers: the nearest node is the particle's own cell
1241 for (int idim = 0; idim < N; idim++)
1242 xstart[idim] = -ORDER / 2;
1243#endif
1244 }
1245
1246 // Interpolation
1247 FloatType value = 0;
1248 [[maybe_unused]] double sumweight = 0;
1249 for (int i = 0; i < widthtondim; i++) {
1250 double w = 1.0;
1251 std::array<int, N> icoord;
1252 if constexpr (ORDER == 1) {
1253 icoord = ix;
1254 } else {
1255 for (int idim = 0, n = 1; idim < N; idim++, n *= ORDER) {
1256 int go_left_right_or_stay = xstart[idim] + (i / n % ORDER);
1257 ix_nbor[idim] = ix[idim] + go_left_right_or_stay;
1258#ifdef CELLCENTERSHIFTED
1259 double dx = std::fabs(-x[idim] + go_left_right_or_stay + 0.5);
1260#else
1261 double dx = std::fabs(-x[idim] + go_left_right_or_stay);
1262#endif
1263 w *= kernel<ORDER>(dx);
1264 }
1265
1266 // Periodic BC
1267 icoord[0] = ix_nbor[0];
1268 for (int idim = 1; idim < N; idim++) {
1269 icoord[idim] = ix_nbor[idim];
1270 if (icoord[idim] >= Nmesh)
1271 icoord[idim] -= Nmesh;
1272 if (icoord[idim] < 0)
1273 icoord[idim] += Nmesh;
1274 }
1275 }
1276
1277 // Add up
1278 value += grid.get_real(icoord) * w;
1279 sumweight += w;
1280 }
1281
1282#ifdef DEBUG_INTERPOL
1283 // Check that the weights sum up to unity
1284 assert_mpi(std::fabs(sumweight - 1.0) < 1e-3,
1285 "[interpolate_grid_to_particle_positions] Possible problem with interpolation: weights does "
1286 "not sum to unity!");
1287#endif
1288
1289 // Store the interpolated value
1290 interpolated_values[ind] = value;
1291 }
1292 }
1293
1294 //=======================================================================
1295 // Communicate what we have added to the extra slices that belong
1296 // on neighbor tasks
1297 //=======================================================================
1298 template <int N>
1299 void add_contribution_from_extra_slices(FFTWGrid<N> & density, double background) {
1300 // The extra slices were initialized to the background value (-1 for delta, 0 for delta-f particles)
1301
1302 auto Local_nx = density.get_local_nx();
1303 auto num_cells_slice = density.get_ntot_real_slice_alloc();
1304 int n_extra_left = density.get_n_extra_slices_left();
1305 int n_extra_right = density.get_n_extra_slices_right();
1306 ;
1307
1308#ifdef USE_MPI
1309 const int slice_bytes = int(FML::COMMUNICATION::checked_bytes(num_cells_slice, sizeof(FloatType), INT_MAX));
1310#endif
1311 std::vector<FloatType> buffer(num_cells_slice);
1312
1313 // [1] Send to the right, receive from left
1314 for (int i = 0; i < n_extra_right; i++) {
1315 FloatType * extra_slice_right = density.get_real_grid_right() + num_cells_slice * i;
1316 FloatType * slice_left = density.get_real_grid() + num_cells_slice * i;
1317 FloatType * temp = buffer.data();
1318
1319#ifdef USE_MPI
1320 MPI_Status status;
1321
1322 int send_to = (ThisTask + 1) % NTasks;
1323 int recv_from = (ThisTask - 1 + NTasks) % NTasks;
1324
1325 MPI_Sendrecv(&(extra_slice_right[0]),
1326 slice_bytes,
1327 MPI_CHAR,
1328 send_to,
1329 0,
1330 &(temp[0]),
1331 slice_bytes,
1332 MPI_CHAR,
1333 int(recv_from),
1334 0,
1336 &status);
1337#else
1338 temp = extra_slice_right;
1339#endif
1340
1341 // Copy over data from temp
1342 for (int j = 0; j < num_cells_slice; j++) {
1343 slice_left[j] += (temp[j] - background);
1344 }
1345 }
1346
1347 // [2] Send to the left, receive from right
1348 for (int i = 1; i <= n_extra_left; i++) {
1349 FloatType * extra_slice_left = density.get_real_grid() - i * num_cells_slice;
1350 FloatType * slice_right = density.get_real_grid() + num_cells_slice * (Local_nx - i);
1351 FloatType * temp = buffer.data();
1352
1353#ifdef USE_MPI
1354 MPI_Status status;
1355
1356 int send_to = (ThisTask - 1 + NTasks) % NTasks;
1357 int recv_from = (ThisTask + 1) % NTasks;
1358
1359 MPI_Sendrecv(&(extra_slice_left[0]),
1360 slice_bytes,
1361 MPI_CHAR,
1362 send_to,
1363 0,
1364 &(temp[0]),
1365 slice_bytes,
1366 MPI_CHAR,
1367 recv_from,
1368 0,
1370 &status);
1371#else
1372 temp = extra_slice_left;
1373#endif
1374
1375 // Copy over data from temp
1376 for (int j = 0; j < num_cells_slice; j++) {
1377 slice_right[j] += (temp[j] - background);
1378 }
1379 }
1380 }
1381
1382 //=========================================================================================
1383 // This performs the convolution (grid * convolution_kernel)
1384 // The argument of the kernel is the number of cells we are away from the cell.
1385 // ORDER is the width of the kernel. We go through all ORDER^N cells
1386 // surrounding a given cell (for even ORDER we choose the cells to the right) and add up
1387 // the field-value at those cells times the kernel.
1388 // If the ORDER = 1 this only multiplies the whole grid by the constant conv_kernel(0,0,0,..)
1389 // If the kernel returns 1.0/ORDER^N then this is just a convolution with a tophat of size
1390 // R = ORDER / Nmesh
1391 //
1392 // Don't know if this will be useful for anything, but its just a copy of the same kind of
1393 // work done in the methods above so it comes for free. Not tested!
1394 //=========================================================================================
1395
1396 template <int N, int ORDER>
1398 FFTWGrid<N> & grid_out,
1399 const std::function<FloatType(std::array<double, N> &)> & convolution_kernel) {
1400
1402 assert_mpi(grid_in.get_n_extra_slices_left() >= nextra.first and
1403 grid_in.get_n_extra_slices_right() >= nextra.second,
1404 "[convolve_grid_with_kernel] Too few extra slices\n");
1405 assert_mpi(grid_in.get_nmesh() > 0, "[convolve_grid_with_kernel] Grid has to be already allocated!\n");
1406
1407 // We need to look at width^N cells in total
1408 constexpr int widthtondim = FML::power(ORDER, N);
1409 std::array<int, N> xstart;
1410 if (ORDER % 2 == 0)
1411 xstart.fill(-ORDER / 2 + 1);
1412 else
1413 xstart.fill(-ORDER / 2);
1414
1415 // Fetch grid information
1416 const int Nmesh = grid_in.get_nmesh();
1417 const auto Local_nx = grid_in.get_local_nx();
1418 const auto Local_x_start = grid_in.get_local_x_start();
1419
1420 // Make outputgrid (this initializes it to zero)
1421 grid_out = FFTWGrid<N>(Nmesh, grid_in.get_n_extra_slices_left(), grid_in.get_n_extra_slices_right());
1422
1423 // Loop over all cells in in-grid
1424#ifdef USE_OMP
1425#pragma omp parallel for
1426#endif
1427 for (int islice = 0; islice < Local_nx; islice++) {
1428 std::array<double, N> dx;
1429 for (auto && real_index : grid_in.get_real_range(islice, islice + 1)) {
1430
1431 // Coordinate of cell
1432 auto ix = grid_in.coord_from_index(real_index);
1433
1434 // Neighbor coord
1435 [[maybe_unused]] std::array<int, N> ix_nbor;
1436 ix_nbor[0] = ix[0];
1437 for (int idim = 1; idim < N; idim++) {
1438 ix_nbor[idim] = ix[idim] + 1;
1439 if (ix_nbor[idim] >= Nmesh)
1440 ix_nbor[idim] -= Nmesh;
1441 }
1442
1443 // Interpolation
1444 FloatType value = 0;
1445 for (int i = 0; i < widthtondim; i++) {
1446 std::array<int, N> icoord;
1447 double w = 1.0;
1448 if constexpr (ORDER == 1) {
1449 icoord = ix;
1450 } else {
1451 for (int idim = 0, n = 1; idim < N; idim++, n *= ORDER) {
1452 int go_left_right_or_stay = xstart[idim] + (i / n % ORDER);
1453 ix_nbor[idim] = ix[idim] + go_left_right_or_stay;
1454 dx[idim] = go_left_right_or_stay;
1455 }
1456 w = convolution_kernel(dx);
1457
1458 // Periodic BC
1459 icoord[0] = ix_nbor[0];
1460 for (int idim = 1; idim < N; idim++) {
1461 icoord[idim] = ix_nbor[idim];
1462 if (icoord[idim] >= Nmesh)
1463 icoord[idim] -= Nmesh;
1464 if (icoord[idim] < 0)
1465 icoord[idim] += Nmesh;
1466 }
1467 }
1468
1469 // Add up
1470 value += w * grid_in.get_real(icoord);
1471 }
1472
1473 // Store the interpolated value
1474 grid_out.set_real(ix, value);
1475 }
1476 }
1477 }
1478
1479 template <int N, class T>
1481 size_t NumPart,
1482 size_t NumPartTot,
1483 FFTWGrid<N> & density_grid_fourier,
1484 std::string density_assignment_method) {
1485
1486 auto Ngrid = density_grid_fourier.get_nmesh();
1487
1488 // Set how many extra slices we need for the density assignment to go smoothly
1489 // One extra slice in general as we need to shift the particle half a grid-cell
1490 auto nleftright = get_extra_slices_needed_for_density_assignment(density_assignment_method);
1491 int nleft = nleftright.first;
1492 int nright = nleftright.second + 1;
1493
1494 // If the grid has too few slices then we must reallocate it
1495 if (density_grid_fourier.get_n_extra_slices_left() < nleft or
1496 density_grid_fourier.get_n_extra_slices_right() < nright) {
1497 density_grid_fourier = FFTWGrid<N>(Ngrid, nleft, nright);
1498 density_grid_fourier.add_memory_label(
1499 "FFTWGrid::particles_to_grid_interlacing::density_grid_fourier (reallocated)");
1500 }
1501
1502 // Bin particles to grid
1503 particles_to_grid<N, T>(part, NumPart, NumPartTot, density_grid_fourier, density_assignment_method);
1504
1505 // Deposit at virtual half-cell shifted positions; the particles remain untouched.
1506 const double shift = 1.0 / double(2 * Ngrid);
1507 std::array<double, N> assignment_offset;
1508 assignment_offset.fill(shift);
1509 FFTWGrid<N> density_grid_fourier2(Ngrid, nleft, nright);
1510 density_grid_fourier2.add_memory_label(
1511 "FFTWGrid::particles_to_fourier_grid_interlacing::density_grid_fourier2");
1513 NumPart,
1514 NumPartTot,
1515 density_grid_fourier2,
1516 density_assignment_method,
1517 assignment_offset);
1518
1519 // Fourier transform
1520 density_grid_fourier.fftw_r2c();
1521 density_grid_fourier2.fftw_r2c();
1522
1523 // The mean of the two grids (alias cancellation)
1524 auto Local_nx = density_grid_fourier.get_local_nx();
1525
1526#ifdef USE_OMP
1527#pragma omp parallel for
1528#endif
1529 for (int islice = 0; islice < Local_nx; islice++) {
1530 const std::complex<FML::GRID::FloatType> I(0, 1);
1531 for (auto && fourier_index : density_grid_fourier.get_fourier_range(islice, islice + 1)) {
1532 // NB: on the Nyquist planes this is not the shift of the (real) grid (that is cos(k_d s), as in
1533 // shift_grid_fourier), so the result is not Hermitian symmetric there. It is used for P(k), where
1534 // only |delta(k)|^2 enters, so it is kept as it is (cos(k_N s) = 0 for the half-cell shift would
1535 // drop the shifted grid on these planes and change the last P(k) bins by ~3%)
1536 auto kvec = density_grid_fourier.get_fourier_wavevector_from_index(fourier_index);
1537 auto ksum = kvec[0];
1538 for (int idim = 1; idim < N; idim++)
1539 ksum += kvec[idim];
1540 auto norm = std::exp(I * FML::GRID::FloatType(ksum * shift));
1541 auto grid1 = density_grid_fourier.get_fourier_from_index(fourier_index);
1542 auto grid2 = density_grid_fourier2.get_fourier_from_index(fourier_index);
1543 density_grid_fourier.set_fourier_from_index(fourier_index,
1544 (grid1 + norm * grid2) / FML::GRID::FloatType(2.0));
1545 }
1546 }
1547 }
1548
1549 template <int N, class T>
1550 void particles_to_fourier_grid(const T * part,
1551 size_t NumPart,
1552 size_t NumPartTot,
1553 FFTWGrid<N> & density_grid_fourier,
1554 std::string density_assignment_method,
1555 bool interlacing) {
1556
1557 if (interlacing) {
1559 NumPart,
1560 NumPartTot,
1561 density_grid_fourier,
1562 density_assignment_method);
1563 } else {
1564 particles_to_grid<N, T>(part, NumPart, NumPartTot, density_grid_fourier, density_assignment_method);
1565 density_grid_fourier.fftw_r2c();
1566 }
1567 }
1568
1569 //===================================================================================
1570 /// @brief Generate the set of shifts used for interlacing (alias reduction by averaging the density field
1571 /// computed from several copies of the particle distribution shifted by a fraction of a cell).
1572 ///
1573 /// The order is the number of grids (including the unshifted one). Supported orders:
1574 /// - 1: no interlacing (only the zero shift)
1575 /// - any order in 1D: shifts i/order * dx
1576 /// - 2 in any dimension: 0 and (1/2,...,1/2) dx. Cancels the aliases (images at k + 2 k_Ny n) with odd
1577 /// sum(n)
1578 /// - 2^(NDIM-1) for NDIM >= 3 (e.g. 4 in 3D): all corners of the half-cell cube with an even number of
1579 /// 1/2's: 0, (1/2,1/2,0), (1/2,0,1/2), (0,1/2,1/2). Cancels all aliases except those with all n_i odd
1580 /// (the (1,1,1) family which has the smallest amplitude)
1581 /// - n^NDIM: a regular sub-lattice with n points per dimension (e.g. 8 = 2^3 in 3D cancels all aliases with
1582 /// some odd n_i)
1583 /// - 2^m >= 2^NDIM: the 2^NDIM corners of the half-cell cube, recursively refined along the diagonal
1584 /// The shifts are in [0, dx) in each coordinate.
1585 ///
1586 /// @tparam NDIM The dimension
1587 /// @param[in] interlacing_order The number of grids
1588 /// @param[in] dx The cell size
1589 //===================================================================================
1590 template <int NDIM>
1591 std::vector<std::array<double, NDIM>> generate_interlacing_shifts(int interlacing_order, double dx) {
1592 std::vector<std::array<double, NDIM>> shifts;
1593
1594 // No interlacing: just the zero shift
1595 if (interlacing_order <= 1) {
1596 shifts.push_back(std::array<double, NDIM>{});
1597 return shifts;
1598 }
1599
1600 // Any order in 1D
1601 if constexpr (NDIM == 1) {
1602 for (int i = 0; i < interlacing_order; i++)
1603 shifts.push_back({i / double(interlacing_order) * dx});
1604 return shifts;
1605 }
1606
1607 // Order 2 in any dimension: the body diagonal
1608 if (interlacing_order == 2) {
1609 std::array<double, NDIM> shift{};
1610 shifts.push_back(shift);
1611 shift.fill(0.5 * dx);
1612 shifts.push_back(shift);
1613 return shifts;
1614 }
1615
1616 // Order 2^(NDIM-1) for NDIM >= 3: corners of the half-cell cube with an even number of 1/2's
1617 if (NDIM >= 3 and interlacing_order == FML::power(2, NDIM - 1)) {
1618 for (int i = 0; i < FML::power(2, NDIM); i++) {
1619 std::array<double, NDIM> shift{};
1620 int nhalf = 0;
1621 for (int idim = 0; idim < NDIM; idim++) {
1622 int bit = (i >> idim) & 1;
1623 nhalf += bit;
1624 shift[idim] = 0.5 * dx * bit;
1625 }
1626 if (nhalf % 2 == 0)
1627 shifts.push_back(shift);
1628 }
1629 return shifts;
1630 }
1631
1632 // Order n^NDIM: a regular sub-lattice
1633 const int n1d = int(std::round(std::pow(double(interlacing_order), 1.0 / NDIM)));
1634 if (FML::power(n1d, NDIM) == interlacing_order) {
1635 for (int i = 0; i < interlacing_order; i++) {
1636 std::array<double, NDIM> shift{};
1637 for (int idim = 0, n = 1; idim < NDIM; idim++, n *= n1d)
1638 shift[idim] = ((i / n) % n1d) / double(n1d) * dx;
1639 shifts.push_back(shift);
1640 }
1641 return shifts;
1642 }
1643
1644 // Order 2^m with m >= NDIM: the 2^NDIM corners of the half-cell cube, then recursively add copies
1645 // shifted by dx/4, dx/8, ... along the diagonal
1646 int log2order = 0;
1647 while ((1 << (log2order + 1)) <= interlacing_order)
1648 log2order++;
1649 if ((1 << log2order) == interlacing_order and log2order >= NDIM) {
1650 for (int i = 0; i < FML::power(2, NDIM); i++) {
1651 std::array<double, NDIM> shift{};
1652 for (int idim = 0; idim < NDIM; idim++)
1653 shift[idim] = 0.5 * dx * ((i >> idim) & 1);
1654 shifts.push_back(shift);
1655 }
1656 for (int level = 1; level <= log2order - NDIM; level++) {
1657 const double extra = dx / std::pow(2.0, level + 1);
1658 const size_t nold = shifts.size();
1659 for (size_t j = 0; j < nold; j++) {
1660 auto shift = shifts[j];
1661 for (int idim = 0; idim < NDIM; idim++)
1662 shift[idim] += extra;
1663 shifts.push_back(shift);
1664 }
1665 }
1666 return shifts;
1667 }
1668
1669 throw std::runtime_error("[generate_interlacing_shifts] Interlacing order " +
1670 std::to_string(interlacing_order) + " is not supported in " +
1671 std::to_string(NDIM) + "D");
1672 }
1673
1674 //===================================================================================
1675 /// @brief Assign particles to a grid with interlacing of any (supported) order and return the density
1676 /// contrast in Fourier space: \f$ \delta(k) = \frac{1}{M}\sum_j e^{i k\cdot s_j} \delta_{s_j}(k) \f$ where
1677 /// \f$ \delta_{s}\f$ is the density of the particles shifted by \f$ s \f$. The window function is not
1678 /// deconvolved. Order 1 is the standard assignment, order 2 is the usual interlacing. See
1679 /// generate_interlacing_shifts for the orders available. Particle positions are never modified.
1680 ///
1681 /// @tparam N The dimension of the grid
1682 /// @tparam T The particle class
1683 /// @param[in] part Pointer to the first particle
1684 /// @param[in] NumPart Number of local particles
1685 /// @param[in] NumPartTot Total number of particles over all tasks
1686 /// @param[out] density_grid_fourier The density contrast in Fourier space (must have Nmesh set; it is
1687 /// reallocated if it has too few extra slices)
1688 /// @param[in] density_assignment_method NGP, CIC, TSC, PCS or PQS
1689 /// @param[in] interlacing_order The number of shifted grids
1690 //===================================================================================
1691 template <int N, class T>
1693 size_t NumPart,
1694 size_t NumPartTot,
1695 FFTWGrid<N> & density_grid_fourier,
1696 std::string density_assignment_method,
1697 int interlacing_order) {
1698
1699 const int Ngrid = density_grid_fourier.get_nmesh();
1700 assert_mpi(Ngrid > 0, "[particles_to_fourier_grid_interlaced] Grid must be allocated\n");
1701
1702 // One extra slice on the right as the particles are shifted by less than a cell without wrapping in x
1703 auto nleftright = get_extra_slices_needed_for_density_assignment(density_assignment_method);
1704 const int nleft = nleftright.first;
1705 const int nright = nleftright.second + (interlacing_order > 1 ? 1 : 0);
1706 if (density_grid_fourier.get_n_extra_slices_left() < nleft or
1707 density_grid_fourier.get_n_extra_slices_right() < nright) {
1708 density_grid_fourier = FFTWGrid<N>(Ngrid, nleft, nright);
1709 density_grid_fourier.add_memory_label(
1710 "FFTWGrid::particles_to_fourier_grid_interlaced::density_grid_fourier (reallocated)");
1711 }
1712
1713 if (interlacing_order <= 1) {
1714 particles_to_grid<N, T>(part, NumPart, NumPartTot, density_grid_fourier, density_assignment_method);
1715 density_grid_fourier.fftw_r2c();
1716 return;
1717 }
1718
1719 const auto shifts = generate_interlacing_shifts<N>(interlacing_order, 1.0 / double(Ngrid));
1720 const FloatType norm = FloatType(1.0 / double(shifts.size()));
1721
1722 FFTWGrid<N> grid_shifted(Ngrid, nleft, nright);
1723 grid_shifted.add_memory_label("FFTWGrid::particles_to_fourier_grid_interlaced::grid_shifted");
1724 density_grid_fourier.fill_fourier_grid(0.0);
1725 density_grid_fourier.set_grid_status_real(false);
1726 for (auto & shift : shifts) {
1727 particles_to_grid<N, T>(part,
1728 NumPart,
1729 NumPartTot,
1730 grid_shifted,
1731 density_assignment_method,
1732 shift,
1733 FML::NTasks == 1);
1734 grid_shifted.fftw_r2c();
1735
1736 // Virtual positions are offset by +s, giving delta(x - s): undo the Fourier phase
1737 FML::GRID::shift_grid_fourier<N>(grid_shifted, shift, +1.0);
1738
1739 const auto Local_nx = density_grid_fourier.get_local_nx();
1740#ifdef USE_OMP
1741#pragma omp parallel for
1742#endif
1743 for (int islice = 0; islice < Local_nx; islice++) {
1744 for (auto && fourier_index : density_grid_fourier.get_fourier_range(islice, islice + 1)) {
1745 auto value = density_grid_fourier.get_fourier_from_index(fourier_index);
1746 value += grid_shifted.get_fourier_from_index(fourier_index) * norm;
1747 density_grid_fourier.set_fourier_from_index(fourier_index, value);
1748 }
1749 }
1750 }
1751 }
1752
1753 } // namespace INTERPOLATION
1754} // namespace FML
1755#endif
FML::GRID::FFTWGrid< N > FFTWGrid
Definition Main.cpp:13
float FloatType
Definition FFTWGlobal.h:29
const int NDIM
const int Nmesh
Definition Main.cpp:48
const std::string interpolation_method
Definition Main.cpp:64
Class for holding grids and performing real-to-complex and complex-to-real FFTs using FFTW with MPI.
Definition FFTWGrid.h:98
int get_nmesh() const
Number of grid-cells per dimension.
Definition FFTWGrid.h:1230
void add_memory_label(std::string label)
For memory logging: add a label to the grid.
Definition FFTWGrid.h:404
ptrdiff_t get_local_x_start() const
The x-slice the first local slice has in the global grid.
Definition FFTWGrid.h:1260
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
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
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
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
void fftw_r2c()
Perform real-to-complex fourier transform.
Definition FFTWGrid.h:1077
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
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
int get_n_extra_slices_right() const
How many extra slices we have allocated to the right.
Definition FFTWGrid.h:1473
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
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
The Fourier window of the density assignment, , from a table of the 1D factors (the wavevector compo...
WindowFunctionTable(std::string density_assignment_method, int Ngrid)
double operator()(const std::array< double, N > &kvec) const
size_t checked_bytes(Count count, Count extent, Count limit=std::numeric_limits< size_t >::max())
Definition MPICounts.h:33
void shift_grid_fourier(FFTWGrid< N > &fourier_grid, const std::array< double, N > &shift, double sign=+1.0)
Translate a field given in Fourier space: , i.e.
This namespace deals with interpolation and density assignment.
double kernel(double x)
Internal method.
double kernel< 3 >(double x)
The TSC kernel.
void particles_to_fourier_grid_interlaced(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density_grid_fourier, std::string density_assignment_method, int interlacing_order)
Assign particles to a grid with interlacing of any (supported) order and return the density contrast ...
void convolve_grid_with_kernel(const FFTWGrid< N > &grid_in, FFTWGrid< N > &grid_out, const std::function< FloatType(std::array< double, N > &)> &convolution_kernel)
Convolve a grid with a kernel.
void particles_to_fourier_grid(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density_grid_fourier, std::string density_assignment_method, bool interlacing)
Assign particles to grid to compute the over density.
void interpolate_grid_vector_to_particle_positions(const std::array< FFTWGrid< N >, N > &grid_vec, const T *part, size_t NumPart, std::array< std::vector< FloatType >, N > &interpolated_values_vec)
Interpolate a vector of grids (e.g.
std::function< double(std::array< double, N > &)> get_window_function(std::string density_assignment_method, int Ngrid)
This returns the a function giving the window function for a given density assignment method as funct...
std::pair< int, int > get_extra_slices_needed_for_density_assignment(std::string density_assignment_method)
Compute how many extra slices we need in the FFTWGrid for a given density assignment / interpolation ...
double kernel< 5 >(double x)
The PQS kernel.
FML::GRID::FloatType FloatType
void add_contribution_from_extra_slices(FFTWGrid< N > &density, double background=-1.0)
Internal method. For communication between tasks needed when adding particles to grid.
double interpolate_grid_vector_to_particle_positions_apply(const std::array< FFTWGrid< N >, N > &grid, const T *part, size_t NumPart, Apply &&apply)
Gather a grid vector and immediately consume each interpolated value, without output arrays.
bool is_known_interpolation_method(const std::string &method)
Is the name a known density assignment / interpolation method (NGP, CIC, TSC, PCS,...
void particles_to_fourier_grid_interlacing(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density_grid_fourier, std::string density_assignment_method)
Internal method.
FML::GRID::FFTWGrid< N > FFTWGrid
void interpolate_grid_to_particle_positions(const FFTWGrid< N > &grid, const T *part, size_t NumPart, std::vector< FloatType > &interpolated_values)
Interpolate a grid to a set of positions given by the positions of particles.
int interpolation_order_from_name(std::string density_assignment_method)
Get the interpolation order from a string holding the density_assignment_method (NGP,...
void deconvolve_window_function_fourier(FFTWGrid< N > &fourier_grid, std::string density_assignment_method)
Deconvolves the density assignment kernel in Fourier space.
double kernel< 1 >(double x)
The NGP kernel.
double kernel< 2 >(double x)
The CIC kernel.
std::pair< int, int > get_extra_slices_needed_by_order()
Compute how many extra slices we need in the FFTWGrid for a given density assignment order.
std::vector< std::array< double, NDIM > > generate_interlacing_shifts(int interlacing_order, double dx)
Generate the set of shifts used for interlacing (alias reduction by averaging the density field compu...
void particles_to_grid(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density, std::string density_assignment_method)
Assign particles to a grid to compute the over density field delta.
double kernel< 4 >(double x)
The PCS kernel.
U wrap_coordinate_periodic(U x)
Wrap a coordinate periodically into [0,1) assuming it is in [-1,2) (i.e.
get_vel constexpr double * GetPos(...)
set_mass constexpr double GetMass(Args &... args)
FML_UNITS_INLINE constexpr double density
Definition Units.h:49
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
void SumOverTasks(T *value)
Inplace sum over tasks of a single value.
Definition Global.h:229
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
list ORDER
Definition cases.py:640
ComplexType value(const std::array< int, N > &wave, int generation)
Vector grid(size_t n)
double norm(Vector a)