FML
Loading...
Searching...
No Matches
NBody.h
Go to the documentation of this file.
1#ifndef NBODY_HEADER
2#define NBODY_HEADER
3
4#ifdef USE_MPI
5#include <mpi.h>
6#endif
7
8#ifdef USE_OMP
9#include <omp.h>
10#endif
11
13#include <FML/Global/Global.h>
23#include <FML/Timing/Timings.h>
24
25#include <array>
26#include <cmath>
27#include <functional>
28#include <iostream>
29#include <stdexcept>
30#include <string>
31#include <vector>
32
33namespace FML {
34
35 /// This namespace deals with N-body simulations. Computing forces, moving particles
36 /// and generating initial conditions.
37 namespace NBODY {
38
39 // Type aliases
40 template <int N>
42 template <class T>
44
45 template <int N, class T>
46 void DriftParticles(FML::PARTICLE::MPIParticles<T> & part, double delta_time, bool periodic_box = true);
47
48 template <int N, class T>
49 void DriftParticles(T * p, size_t NumPart, double delta_time, bool periodic_box = true);
50
51 template <int N, class T>
52 void KickParticles(std::array<FFTWGrid<N>, N> & force_grid,
53 MPIParticles<T> & part,
54 double delta_time,
55 std::string interpolation_method);
56
57 template <int N, class T>
58 void KickParticles(std::array<FFTWGrid<N>, N> & force_grid,
59 T * p,
60 size_t NumPart,
61 double delta_time,
62 std::string interpolation_method);
63
64 template <int N>
65 void compute_force_from_density_real(const FFTWGrid<N> & density_grid_real,
66 std::array<FFTWGrid<N>, N> & force_real,
67 std::string density_assignment_method_used,
68 double norm_poisson_equation,
69 const ForceOptions & options = {});
70
71 template <int N>
72 void compute_force_from_density_fourier(const FFTWGrid<N> & density_grid_fourier,
73 std::array<FFTWGrid<N>, N> & force_real,
74 std::string density_assignment_method_used,
75 double norm_poisson_equation,
76 const ForceOptions & options = {});
77
78 inline double gradient_kernel_fourier(double k_j, int Nmesh, int KERNEL);
79
80 template <int NDIM>
81 double
82 greens_function_laplace_operator_fourier(double kmag2, std::array<double, NDIM> & kvec, int Nmesh, int KERNEL);
83
84 /// Periodic wrap of a coordinate to [0,1). For positions in [-1,2) (except when the result would round to
85 /// exactly 1.0) this does exactly the same operations as x -= 1 if x >= 1, x += 1 if x < 0 (so the results
86 /// are bit-identical). Larger shifts are wrapped with floor and the (rounding) result 1.0 is mapped to 0.0
87 template <class F>
88 inline void periodic_wrap_unit_box(F & x) {
89 if (x >= 1.0)
90 x -= 1.0;
91 if (x < 0.0)
92 x += 1.0;
93 if (x >= 1.0 or x < 0.0) {
94 x -= std::floor(x);
95 if (x >= 1.0 or x < 0.0)
96 x = 0.0;
97 }
98 }
99
100 /// The finite difference stencils implemented in compute_force_from_potential_real
101 inline bool is_valid_finite_difference_stencil_order(int stencil_order) {
102 return stencil_order == 2 or stencil_order == 4 or stencil_order == 6;
103 }
104
105 template <int N>
107 std::array<FFTWGrid<N>, N> & force_grid_real,
108 std::string force_interpolation_method,
109 int stencil_order,
110 const ForceOptions & options = {});
111
112 template <int N>
113 void compute_potential_real_from_density_fourier(const FFTWGrid<N> & density_grid_fourier,
114 FFTWGrid<N> & potential_real,
115 double norm_poisson_equation,
116 int n_boundary_slices_to_be_allocated,
117 const ForceOptions & options = {});
118
119 //===================================================================================
120 /// @brief Take a N-body step with a simple Kick-Drift-Kick method (this
121 /// method serves mainly as an example for how one can do this).
122 /// 1. Particles to grid to get \f$ \delta \f$
123 /// 2. Compute the Newtonian potential via \f$ \nabla^2 \Phi = {\rm norm} \cdot \delta \f$
124 /// 3. Compute the force \f$ F = \nabla \Phi \f$
125 /// 4. Move the particles using \f$ x \to x + v \Delta t \f$ and \f$ v \to v + F \Delta t \f$
126 /// This method assumes that the velocities are in units of (boxsize / time-step-unit), in other words that \f$
127 /// v\Delta t\f$ gives rise to a shift in [0,1). For cosmological N-body norm_poisson_equation depends on a and
128 /// it should be set at the correct time. If one does simple sims with fixed time-step then the last kick of the
129 /// previous step can be combined with the first kick of the current step to save one force evaluation per step
130 /// (so basically two times as fast).
131 ///
132 /// @tparam N The dimension of the grid.
133 /// @tparam T The particle class.
134 ///
135 /// @param[in] Nmesh The gridsize to use for computing the density and force.
136 /// @param[out] part The particles
137 /// @param[in] delta_time The time \f$ \Delta t \f$ we move forward.
138 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS).
139 /// @param[in] norm_poisson_equation A possible prefactor to the Poisson equation
140 ///
141 //===================================================================================
142 template <int N, class T>
144 MPIParticles<T> & part,
145 double delta_time,
146 std::string density_assignment_method,
147 double norm_poisson_equation,
148 const ForceOptions & options = {}) {
149 options.validate();
150
151 const bool periodic_box = true;
152
153 // Particles -> density field
154 auto nleftright =
156 FFTWGrid<N> density_grid_real(Nmesh, nleftright.first, nleftright.second);
157 density_grid_real.add_memory_label("FFTWGrid::KickDriftKickNBodyStep::density_grid_real");
158 density_grid_real.set_grid_status_real(true);
160 part.get_npart(),
161 part.get_npart_total(),
162 density_grid_real,
163 density_assignment_method);
164
165 // Density field -> force
166 std::array<FFTWGrid<N>, N> force_real;
167 compute_force_from_density_real<N>(density_grid_real,
168 force_real,
169 density_assignment_method,
170 norm_poisson_equation,
171 options);
172
173 // Update velocity of particles
174 KickParticles(force_real, part, delta_time * 0.5, density_assignment_method);
175
176 // Move particles (this does communication)
177 DriftParticles<N, T>(part, delta_time, periodic_box);
178
179 // Particles -> density field
181 part.get_npart(),
182 part.get_npart_total(),
183 density_grid_real,
184 density_assignment_method);
185
186 // Density field -> force
187 compute_force_from_density_real<N>(density_grid_real,
188 force_real,
189 density_assignment_method,
190 norm_poisson_equation,
191 options);
192
193 // Update velocity of particles
194 KickParticles(force_real, part, delta_time * 0.5, density_assignment_method);
195 }
196
197 //===================================================================================
198 /// @brief Take a N-body step with a 4th order symplectic Yoshida method. This method is mainly an illustration,
199 /// for using this with cosmology we should take into account that norm_poisson_equation is a function of time
200 ///
201 /// @tparam N The dimension of the grid.
202 /// @tparam T The particle class.
203 ///
204 /// @param[in] Nmesh The gridsize to use for computing the density and force.
205 /// @param[out] part The particles
206 /// @param[in] delta_time The time \f$ \Delta t \f$ we move forward.
207 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS).
208 /// @param[in] norm_poisson_equation A possible prefactor to the Poisson equation
209 ///
210 //===================================================================================
211 template <int N, class T>
213 MPIParticles<T> & part,
214 double delta_time,
215 std::string density_assignment_method,
216 double norm_poisson_equation,
217 const ForceOptions & options = {}) {
218 options.validate();
219
220 const bool periodic_box = true;
221
222 // The Yoshida coefficients
223 const double w1 = 1.0 / (2 - std::pow(2.0, 1.0 / 3.0));
224 const double w0 = 1.0 - 2.0 * w1;
225 const double c1 = w1 / 2.0, c4 = c1;
226 const double c2 = (w0 + w1) / 2.0, c3 = c2;
227 const double d1 = w1, d3 = d1;
228 const double d2 = w0;
229
230 // They must sum to unity
231 assert(std::fabs(c1 + c2 + c3 + c4 - 1.0) < 1e-10);
232 assert(std::fabs(d1 + d2 + d3 - 1.0) < 1e-10);
233
234 // Set up a density grid to use
235 auto nleftright =
237 FFTWGrid<N> density_grid_real(Nmesh, nleftright.first, nleftright.second);
238 density_grid_real.add_memory_label("FFTWGrid::YoshidaNBodyStep::density_grid_real");
239 density_grid_real.set_grid_status_real(true);
240
241 // Perform one step: delta_time_pos is the advance for pos positions and delta_time_vel is for velocity
242 auto one_step = [&](double delta_time_pos, double delta_time_vel, double norm_poisson) {
243 // Move particles (this does communication)
244 DriftParticles<N, T>(part, delta_time_pos, periodic_box);
245
246 // Particles -> density field
248 part.get_npart(),
249 part.get_npart_total(),
250 density_grid_real,
251 density_assignment_method);
252 // Density field -> force
253 std::array<FFTWGrid<N>, N> force_real;
254 compute_force_from_density_real<N>(density_grid_real,
255 force_real,
256 density_assignment_method,
257 norm_poisson,
258 options);
259
260 // Update velocity of particles
261 KickParticles(force_real, part, delta_time_vel, density_assignment_method);
262 };
263
264 // The norm_poisson_equation in a cosmo sim depends on [aexp] so this should be changed
265 one_step(delta_time * c1, delta_time * d1, norm_poisson_equation);
266 one_step(delta_time * c2, delta_time * d2, norm_poisson_equation);
267 one_step(delta_time * c3, delta_time * d3, norm_poisson_equation);
268
269 // Move particles (this does communication)
270 DriftParticles<N, T>(part, delta_time * c4, periodic_box);
271 }
272
273 //===================================================================================
274 /// @brief Take a density grid in real space and returns the force \f$ \nabla \phi \f$ where
275 /// \f$ \nabla^2 \phi = {\rm norm} \cdot \delta \f$
276 /// Different choices for what kernel to use for \f$ \nabla / \nabla^2\f$ are available through ForceOptions.
277 /// Fiducial choice is the continuous greens function \f$ D^2 =-k^2\f$, and gradient \f$ D = i\vec{k}\f$. We can
278 /// also choose to deconvole the density assignment and force interpolation (ala Gadget). Set
279 /// ForceOptions::deconvolve to enable this.
280 ///
281 /// @tparam N The dimension of the grid
282 ///
283 /// @param[in] density_grid_real The density contrast in real space.
284 /// @param[out] force_real The force in real space.
285 /// @param[in] density_assignment_method_used The density assignment we used to compute the density field.
286 /// @param[in] norm_poisson_equation The prefactor (norm) to the Poisson equation.
287 ///
288 //===================================================================================
289 template <int N>
290 void compute_force_from_density_real(const FFTWGrid<N> & density_grid_real,
291 std::array<FFTWGrid<N>, N> & force_real,
292 std::string density_assignment_method_used,
293 double norm_poisson_equation,
294 const ForceOptions & options) {
295 options.validate();
296
297 FFTWGrid<N> density_grid_fourier = density_grid_real;
298 density_grid_fourier.add_memory_label("FFTWGrid::compute_force_from_density_real::density_grid_fourier");
299 density_grid_fourier.set_grid_status_real(true);
300 density_grid_fourier.fftw_r2c();
301 compute_force_from_density_fourier<N>(density_grid_fourier,
302 force_real,
303 density_assignment_method_used,
304 norm_poisson_equation,
305 options);
306 }
307
308 //===================================================================================
309 /// @brief Take a density grid in fourier space and returns the force \f$ \nabla \phi \f$ where
310 /// \f$ \nabla^2 \phi = {\rm norm} \cdot \delta \f$
311 /// Different choices for what kernel to use for \f$ \nabla / \nabla^2\f$ are available through ForceOptions.
312 /// Fiducial choice is the continuous greens function \f$ D^2 =-k^2\f$, and gradient \f$ D = i\vec{k}\f$. We can
313 /// also choose to deconvole the density assignment and force interpolation (ala Gadget). Set
314 /// ForceOptions::deconvolve to enable this.
315 ///
316 /// @tparam N The dimension of the grid
317 ///
318 /// @param[in] density_grid_fourier The density contrast in fourier space.
319 /// @param[out] force_real The force in real space.
320 /// @param[in] density_assignment_method_used The density assignment we used to compute the density field.
321 /// @param[in] norm_poisson_equation The prefactor (norm) to the Poisson equation.
322 ///
323 //===================================================================================
324 template <int N>
325 void compute_force_from_density_fourier(const FFTWGrid<N> & density_grid_fourier,
326 std::array<FFTWGrid<N>, N> & force_real,
327 std::string density_assignment_method_used,
328 double norm_poisson_equation,
329 const ForceOptions & options) {
330 options.validate();
331
332 const int LAPLACE_KERNEL = options.laplace_kernel;
333 const int GRADIENT_KERNEL = options.gradient_kernel;
334
335 auto Nmesh = density_grid_fourier.get_nmesh();
336 auto Local_nx = density_grid_fourier.get_local_nx();
337 auto Local_x_start = density_grid_fourier.get_local_x_start();
338
339 // Should we deconvolve the density+force-assignment?
340 // We set this to false as standard
341 // If we do so we need the window function for the density assignment
342 const bool DECONVOLVE = options.deconvolve;
343 const int order = FML::INTERPOLATION::interpolation_order_from_name(density_assignment_method_used);
344 const double knyquist = M_PI * Nmesh;
345 [[maybe_unused]] auto window_function = [&](std::array<double, N> & kvec) -> double {
346 double w = 1.0;
347 for (int idim = 0; idim < N; idim++) {
348 const double koverkny = M_PI / 2. * (kvec[idim] / knyquist);
349 w *= koverkny == 0.0 ? 1.0 : std::sin(koverkny) / (koverkny);
350 }
351 // res = pow(w,p);
352 double res = 1;
353 for (int i = 0; i < order; i++)
354 res *= w;
355 return res;
356 };
357
358 // Make the force-kernel (D/i)_j = k_j for the continuous case (zero for the Nyquist component of an even
359 // mesh)
360 std::vector<double> gradient_kernel(2 * (Nmesh / 2 + 1), 0.0);
361 for (int i = -Nmesh / 2; i <= Nmesh / 2; i++) {
362 double k_j = 2.0 * M_PI * i;
363 gradient_kernel[Nmesh / 2 + i] = gradient_kernel_fourier(k_j, Nmesh, GRADIENT_KERNEL);
364 }
365
366 // Allocate grid (just copy it over)
367 for (int idim = 0; idim < N; idim++) {
368 force_real[idim] = density_grid_fourier;
369 force_real[idim].add_memory_label("FFTWGrid::compute_force_from_density_fourier::force_real_" +
370 std::to_string(idim));
371 force_real[idim].set_grid_status_real(idim == 0);
372 }
373
374 // Fast path for N = 3: the same operations in the same order as the general loop below (identical
375 // results) without decoding every Fourier index and with a table for the window function
376 if constexpr (N == 3) {
377 const FML::INTERPOLATION::WindowFunctionTable<N> window_table(density_assignment_method_used, Nmesh);
378 const int nover2 = Nmesh / 2;
379 const int nover2plus1 = Nmesh / 2 + 1;
380 const double twopi = 2.0 * M_PI;
381#ifdef USE_OMP
382#pragma omp parallel for
383#endif
384 for (int islice = 0; islice < Local_nx; islice++) {
385 std::array<double, N> kvec;
386 std::array<int, N> k_vec_integer;
387 std::complex<FML::GRID::FloatType> I(0, 1);
388 const int ix = islice + int(Local_x_start);
389 k_vec_integer[0] = ix <= nover2 ? ix : ix - Nmesh;
390 kvec[0] = twopi * double(k_vec_integer[0]);
391 for (int iy = 0; iy < Nmesh; iy++) {
392 k_vec_integer[1] = iy <= nover2 ? iy : iy - Nmesh;
393 kvec[1] = twopi * double(k_vec_integer[1]);
394 size_t fourier_index = (size_t(islice) * Nmesh + iy) * nover2plus1;
395 for (int iz = 0; iz < nover2plus1; iz++, fourier_index++) {
396 if (Local_x_start == 0 and fourier_index == 0) {
397 for (int idim = 0; idim < N; idim++)
398 force_real[idim].set_fourier_from_index(0, 0.0);
399 continue; // DC mode (k=0)
400 }
401 k_vec_integer[2] = iz <= nover2 ? iz : iz - Nmesh;
402 kvec[2] = twopi * double(k_vec_integer[2]);
403 const double kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2];
404 auto value = force_real[0].get_fourier_from_index(fourier_index);
405 if (LAPLACE_KERNEL == CONTINUOUS_GREENS_FUNCTION) {
406 value *= -1.0 / kmag2;
407 } else {
408 value *=
409 greens_function_laplace_operator_fourier<N>(kmag2, kvec, Nmesh, LAPLACE_KERNEL);
410 }
411 if (DECONVOLVE) {
412 double W = window_table(kvec);
413 value /= (W * W);
414 }
415 for (int idim = 0; idim < N; idim++) {
416 force_real[idim].set_fourier_from_index(
417 fourier_index,
418 I * value *
419 FML::GRID::FloatType(gradient_kernel[Nmesh / 2 + k_vec_integer[idim]] *
420 norm_poisson_equation));
421 }
422 }
423 }
424 }
425 for (int idim = 0; idim < N; idim++)
426 force_real[idim].fftw_c2r();
427 return;
428 }
429
430 // Loop over all local fourier grid cells
431#ifdef USE_OMP
432#pragma omp parallel for
433#endif
434 for (int islice = 0; islice < Local_nx; islice++) {
435 std::array<double, N> kvec;
436 std::complex<FML::GRID::FloatType> I(0, 1);
437 for (auto && fourier_index : force_real[0].get_fourier_range(islice, islice + 1)) {
438 if (Local_x_start == 0 and fourier_index == 0) {
439 for (int idim = 0; idim < N; idim++)
440 force_real[idim].set_fourier_from_index(0, 0.0);
441 continue; // DC mode (k=0)
442 }
443
444 // Fetch value, k_vec_integer, k_vec and |k_vec|
445 auto k_vec_integer = force_real[0].get_fourier_integer_wavevector_from_index(fourier_index);
446 double kmag2 = 0.0;
447 for (int idim = 0; idim < N; idim++) {
448 kvec[idim] = k_vec_integer[idim] * 2.0 * M_PI;
449 kmag2 += kvec[idim] * kvec[idim];
450 }
451 auto value = force_real[0].get_fourier_from_index(fourier_index);
452
453 force_real[0].get_fourier_wavevector_and_norm2_by_index(fourier_index, kvec, kmag2);
454
455 // Apply kernel 1/D^2
456 if (LAPLACE_KERNEL == CONTINUOUS_GREENS_FUNCTION) {
457 value *= -1.0 / kmag2;
458 } else {
459 value *= greens_function_laplace_operator_fourier<N>(kmag2, kvec, Nmesh, LAPLACE_KERNEL);
460 }
461
462 // Deconvolve the density assignment?
463 if (DECONVOLVE) {
464 double W = window_function(kvec);
465 value /= (W * W);
466 }
467
468 // Apply kernel for D to get force so in the end we have
469 // -ik/k^2 delta(k) for continuous kernels
470 for (int idim = 0; idim < N; idim++) {
471 force_real[idim].set_fourier_from_index(
472 fourier_index,
473 I * value *
474 FML::GRID::FloatType(gradient_kernel[Nmesh / 2 + k_vec_integer[idim]] *
475 norm_poisson_equation));
476 }
477 }
478 }
479
480 // Fourier transform back to real space
481 for (int idim = 0; idim < N; idim++)
482 force_real[idim].fftw_c2r();
483 }
484
485 //===================================================================================
486 /// @brief This moves the particles according to \f$ x_{\rm new} = x + v \Delta t \f$. Note that we assume the
487 /// velocities are in such units that \f$ v \Delta t\f$ is a dimensionless shift in [0,1).
488 ///
489 /// @tparam N The dimension of the grid
490 /// @tparam T The particle class
491 ///
492 /// @param[out] part MPIParticles containing the particles.
493 /// @param[in] delta_time The size of the timestep.
494 /// @param[in] periodic_box Is the box periodic?
495 ///
496 //===================================================================================
497 template <int N, class T>
498 void DriftParticles(MPIParticles<T> & part, double delta_time, bool periodic_box) {
499 // NB: no early return for tasks without particles: the drift and the communication of the particles
500 // are collective so all tasks have to take part (delta_time is the same on all tasks)
501 if (delta_time == 0.0)
502 return;
503
504 // Sanity check on particle
505 assert_mpi(FML::PARTICLE::GetNDIM(T()) == N,
506 "[DriftParticles] NDIM of particles and of grid does not match");
507
508 DriftParticles<N, T>(part.get_particles_ptr(), part.get_npart(), delta_time, periodic_box);
509
510 // Particles might have left the current task
512 }
513
514 //===================================================================================
515 /// @brief This moves the particles according to \f$ x_{\rm new} = x + v \Delta t \f$. Note that we assume the
516 /// velocities are in such units that \f$ v \Delta t\f$ is a dimensionless shift in [0,1). NB: after this
517 /// methods is done the particles might have left the current task and must be communicated (this is done
518 /// automatically if you use the MPIParticles version of this method).
519 ///
520 /// @tparam N The dimension of the grid
521 /// @tparam T The particle class
522 ///
523 /// @param[out] p Pointer to the first particle.
524 /// @param[in] NumPart The number of local particles.
525 /// @param[in] delta_time The size of the timestep.
526 /// @param[in] periodic_box Is the box periodic?
527 ///
528 //===================================================================================
529 template <int N, class T>
530 void DriftParticles(T * p, size_t NumPart, double delta_time, bool periodic_box) {
531 // NB: no early return if NumPart == 0 as MaxOverTasks below is collective
532 if (delta_time == 0.0)
533 return;
534
535 // Sanity check on particle
536 assert_mpi(FML::PARTICLE::GetNDIM(T()) == N,
537 "[DriftParticles] NDIM of particles and of grid does not match");
538 static_assert(FML::PARTICLE::has_get_pos<T>(),
539 "[DriftParticles] Particle class must have a get_pos method to use this method");
540 static_assert(FML::PARTICLE::has_get_vel<T>(),
541 "[DriftParticles] Particle class must have a get_vel method to use this method");
542
543 double max_disp = 0.0;
544#ifdef USE_OMP
545#pragma omp parallel for reduction(max : max_disp)
546#endif
547 for (size_t i = 0; i < NumPart; i++) {
548 auto * pos = FML::PARTICLE::GetPos(p[i]);
549 auto * vel = FML::PARTICLE::GetVel(p[i]);
550 for (int idim = 0; idim < N; idim++) {
551 double disp = vel[idim] * delta_time;
552 pos[idim] += disp;
553 max_disp = std::max(max_disp, std::abs(disp));
554
555 // Periodic wrap (to [0,1) also for displacements larger than the box)
556 if (periodic_box)
557 periodic_wrap_unit_box(pos[idim]);
558 }
559 }
560 FML::MaxOverTasks(&max_disp);
561
562 if (FML::ThisTask == 0)
563 std::cout << "[Drift] Max displacement: " << max_disp << "\n";
564 }
565
566 //===================================================================================
567 /// @brief This moves the particle velocities according to \f$ v_{\rm new} = v + F \Delta t \f$. This method
568 /// assumes the force is normalized such that \f$ F \Delta t \f$ has the same units as your v.
569 /// If the flag free_force_grids is set in the source then we free up memory of the force grids after we have
570 /// used them. The default is false.
571 ///
572 /// @tparam N The dimension of the grid
573 /// @tparam T The particle class
574 ///
575 /// @param[in] force_grid Grid containing the force.
576 /// @param[out] part MPIParticles containing the particles.
577 /// @param[in] delta_time The size of the timestep.
578 /// @param[in] interpolation_method The interpolation method for interpolating the force to the particle
579 /// positions.
580 ///
581 //===================================================================================
582 template <int N, class T>
583 void KickParticles(std::array<FFTWGrid<N>, N> & force_grid,
584 MPIParticles<T> & part,
585 double delta_time,
586 std::string interpolation_method) {
587 if (delta_time == 0.0)
588 return;
589 KickParticles<N, T>(force_grid,
590 part.get_particles_ptr(),
591 part.get_npart(),
592 delta_time,
594 }
595
596 //===================================================================================
597 /// @brief This moves the particle velocities according to \f$ v_{\rm new} = v + F \Delta t \f$. This method
598 /// assumes the force is normalized such that \f$ F \Delta t \f$ has the same units as your v.
599 /// If the flag free_force_grids is set in the source then we free up memory of the force grids after we have
600 /// used them. The default is false.
601 ///
602 /// @tparam N The dimension of the grid
603 /// @tparam T The particle class
604 ///
605 /// @param[in] force_grid The force \f$ \nabla \Phi \f$.
606 /// @param[out] p Pointer to the first particle.
607 /// @param[in] NumPart The number of local particles.
608 /// @param[in] delta_time The size of the timestep.
609 /// @param[in] interpolation_method The interpolation method for interpolating the force to the particle
610 /// positions.
611 ///
612 //===================================================================================
613 template <int N, class T>
614 void KickParticles(std::array<FFTWGrid<N>, N> & force_grid,
615 T * p,
616 size_t NumPart,
617 double delta_time,
618 std::string interpolation_method) {
619
620 // Nothing to do if delta_time = 0.0
621 if (delta_time == 0.0)
622 return;
623
624 // Sanity check on particle
625 assert_mpi(FML::PARTICLE::GetNDIM(T()) == N, "[KickParticles] Dimension of particle and grid do not match");
626 static_assert(FML::PARTICLE::has_get_vel<T>(),
627 "[KickParticles] Particle must have velocity to use this method");
628
629 // Deallocate the force grids (after interpolating to the particles we don't need it here and probably
630 // not elsewhere so lets save some memory)
631 constexpr bool free_force_grids = false;
632
633 // Interpolate force to particle positions
634 for (int idim = 0; idim < N; idim++) {
635 force_grid[idim].communicate_boundaries();
636 }
637 // Gather, round to the grid value type as before, and kick immediately. Only one particle's
638 // force vector is on the stack; no N x NumPart temporary force arrays are needed.
639 auto kick = [&](size_t index, const std::array<FML::GRID::FloatType, N> & force) {
640 auto * vel = FML::PARTICLE::GetVel(p[index]);
641 double max_change = 0.0;
642 for (int idim = 0; idim < N; idim++) {
643 const double dvel = -force[idim] * delta_time;
644 max_change = std::max(max_change, std::abs(dvel));
645 vel[idim] += dvel;
646 }
647 return max_change;
648 };
649 double max_dvel =
651 p,
652 NumPart,
654 kick);
655 if (free_force_grids) {
656 for (int idim = 0; idim < N; idim++) {
657 force_grid[idim].free();
658 }
659 }
660
661 FML::MaxOverTasks(&max_dvel);
662
663 if (FML::ThisTask == 0)
664 std::cout << "[Kick] Max delta_vel : " << max_dvel << "\n";
665 }
666
667 template <int N, class T>
669 int Npart_1D,
670 double buffer_factor,
671
672 const FFTWGrid<N> & delta_fourier,
673 std::vector<FFTWGrid<N>> & phi_nLPT_potentials,
674 int LPT_order,
675
676 double box,
677 double zini,
678 std::vector<double> velocity_norms,
679 std::function<double(double)> velocity_norm_1LPT_of_kBox = nullptr,
680 const FFTWGrid<N> * delta_fourier_2LPT_source = nullptr,
681 const FFTWGrid<N> * delta_fourier_1LPT_stored = nullptr,
682 const FFTWGrid<N> * mass_contrast_fourier = nullptr,
683 std::function<double(double)> velocity_norm_2LPT_of_kBox = nullptr);
684
685 //=====================================================================
686 /// @brief Generate particles from a given power-spectrum using Lagrangian perturbation theory.
687 /// We generate particles in [0,1) and velocities are given by \f$ v_{\rm code} = \frac{a^2 \frac{dx}{dt}}{H_0
688 /// B} \f$
689 ///
690 /// @tparam N The dimension we are working in.
691 /// @tparam T The particle class. Must have methods get_pos, get_vel, get_D_1LPT and get_D_2LPT. But only
692 /// get_pos data is required to exist. Return a nullptr if the data does not exist in the particle.
693 ///
694 /// @param[out] part Particle container for particles we are to create.
695 /// @param[in] Npart_1D Number of particles per dimension (i.e. total is \f$ {\rm Npart}_{\rm 1D}^N \f$)
696 /// @param[in] buffer_factor How many more particles to allocate?
697 /// @param[in] Nmesh The grid to generate the IC on
698 /// @param[in] fix_amplitude Amplitude fixed? Only random phases if true.
699 /// @param[in] rng Random number generator
700 /// @param[in] Pofk_of_kBox_over_Pofk_primordal The ratio of the power-spectrum (for delta) at the time you
701 /// want the density field to be created at to the primordial one (the function above).
702 /// @param[in] Pofk_of_kBox_over_volume_primordial The dimensionless function \f$ P/V\f$ where \f$ V = B^N\f$
703 /// is the box volume as function of the dimensionless wavenumber \f$ kB \f$ where \f$ B \f$ is the boxsize and
704 /// \f$ P(k) \f$ is the primordial power-spectrum for \f$\Phi\f$.
705 /// @param[in] LPT_order The LPT order (1 or 2)
706 /// @param[in] type_of_random_field What random field: gaussian, local, equilateral, orthogonal
707 /// @param[in] fNL If non-gaussianity the value of fNL
708 /// @param[in] box The boxsize (only for printing maximum displacement)
709 /// @param[in] zini The initial redshift
710 /// @param[in] velocity_norms A vector of the factors we need to multiply the nLPT displacement fields by to get
711 /// velocities. E.g. \f$ 100 {\rm Box_in_Mpch} f_i(z_{\rm ini}) H(z_{\rm ini})/H_0 \cdot a_{\rm ini} \f$ to
712 /// get peculiar velocities in km/s and \f$ f_i(z_{\rm ini}) H(z_{\rm ini})/H_0 \cdot a_{\rm ini}^2 \f$ to get
713 /// the velocities we use as the fiducial choice in N-body. The order is: 1LPT, 2LPT, 3LPTa, 3LPTb
714 ///
715 //=====================================================================
716 template <int N, class T>
718 int Npart_1D,
719 double buffer_factor,
720
721 int Nmesh,
722 bool fix_amplitude,
724 std::function<double(double)> Pofk_of_kBox_over_Pofk_primordal,
725 std::function<double(double)> Pofk_of_kBox_over_volume_primordial,
726 int LPT_order,
727 std::string type_of_random_field,
728 double fNL,
729
730 double box,
731 double zini,
732 std::vector<double> velocity_norms) {
733
734 // Some sanity checks
735 assert_mpi(Npart_1D > 0 and Nmesh > 0 and zini >= 0.0 and rng != nullptr and box > 0.0,
736 "[NBodyInitialConditions] Invalid parameters");
737
738 // Generate the random field first
740 FFTWGrid<N> delta_fourier(Nmesh, nextra.first, nextra.second);
741 delta_fourier.add_memory_label("FFTWGrid::NBodyInitialConditions::delta_fourier");
742 delta_fourier.set_grid_status_real(false);
743
744 // Make a gaussian or non-local non-gaussian random field in fourier space
745 if (type_of_random_field == "gaussian") {
746 auto Pofk_of_kBox_over_volume = [&](double kBox) {
747 if (kBox == 0.0)
748 return 0.0;
749 return Pofk_of_kBox_over_Pofk_primordal(kBox) * Pofk_of_kBox_over_volume_primordial(kBox);
750 };
752 rng,
753 Pofk_of_kBox_over_volume,
755 } else {
757 delta_fourier,
758 rng,
759 Pofk_of_kBox_over_Pofk_primordal,
760 Pofk_of_kBox_over_volume_primordial,
762 fNL,
764 }
765
766 // Generate IC from a given fourier grid
767 std::vector<FFTWGrid<N>> phi_nLPT_potentials;
769 Npart_1D,
771 delta_fourier,
772 phi_nLPT_potentials,
773 LPT_order,
774 box,
775 zini,
776 velocity_norms);
777 }
778
779 //=====================================================================
780 /// @brief Generate particles from a given initial density field using Lagrangian perturbation theory.
781 /// We generate particles in [0,1) and velocities are given by \f$ v_{\rm code} = \frac{a^2 \frac{dx}{dt}}{H_0
782 /// B} \f$
783 ///
784 /// @tparam N The dimension we are working in.
785 /// @tparam T The particle class. Must have methods get_pos, get_vel, get_D_1LPT and get_D_2LPT. But only
786 /// get_pos data is required to exist. Return a nullptr if the data does not exist in the particle.
787 ///
788 /// @param[out] part Particle container for particles we are to create.
789 /// @param[in] Npart_1D Number of particles per dimension (i.e. total is \f$ {\rm Npart}_{\rm 1D}^N \f$)
790 /// @param[in] buffer_factor How many more particles to allocate?
791 /// @param[in] delta_fourier The initial density field \f$ \delta(k,z_{\rm ini})\f$ in fourier space
792 /// @param[in] phi_nLPT_potentials Return the LPT potentials: 2LPT, 3LPTa, 3LPTb, ... If the vector has zero
793 /// size then nothing will be returned.
794 /// @param[in] LPT_order The LPT order (1 or 2)
795 /// @param[in] box The boxsize (only for printing maximum displacement)
796 /// @param[in] zini The initial redshift
797 /// @param[in] velocity_norms A vector of the factors we need to multiply the nLPT displacement fields by to get
798 /// velocities. E.g. \f$ 100 {\rm Box_in_Mpch} f_i(z_{\rm ini}) H(z_{\rm ini})/H_0 \cdot a_{\rm ini} \f$ to
799 /// get peculiar velocities in km/s and \f$ f_i(z_{\rm ini}) H(z_{\rm ini})/H_0 \cdot a_{\rm ini}^2 \f$ to get
800 /// the velocities we use as the fiducial choice in N-body.
801 /// @param[in] velocity_norm_1LPT_of_kBox Optional. If set the 1LPT velocity is computed with this
802 /// scale-dependent factor (a function of \f$ kB \f$) instead of velocity_norms[0], i.e.
803 /// \f$ v_{\rm 1LPT}(k) = {\rm norm}(k) \Psi_{\rm 1LPT}(k) \f$ (e.g. for a scale-dependent growth rate)
804 /// @param[in] delta_fourier_2LPT_source Optional. If set the 2LPT potential is computed from this density
805 /// field instead of delta_fourier (e.g. the total matter density when making the IC for one of several
806 /// species). Only for LPT_order <= 2
807 /// @param[in] delta_fourier_1LPT_stored Optional. If set the 1LPT displacement field stored in the particles
808 /// (for COLA) is that of this density field instead of the one the particles are displaced with (e.g. the
809 /// total matter density when several species share the same COLA frame)
810 /// @param[in] mass_contrast_fourier Optional. If set the particles get the masses m = 1 + eps(q) where eps is
811 /// this field (in fourier space) at their Lagrangian (lattice) position. The particle class must have a
812 /// set_mass method
813 /// @param[in] velocity_norm_2LPT_of_kBox Optional. As velocity_norm_1LPT_of_kBox for the 2LPT velocity
814 /// (instead of velocity_norms[1]): \f$ v_{\rm 2LPT}(k) = {\rm norm}(k) \Psi_{\rm 2LPT}(k) \f$ with \f$ k \f$
815 /// the wavenumber of the 2LPT field
816 ///
817 //=====================================================================
818 template <int N, class T>
820 int Npart_1D,
821 double buffer_factor,
822
823 const FFTWGrid<N> & delta_fourier,
824 std::vector<FFTWGrid<N>> & phi_nLPT_potentials,
825 int LPT_order,
826
827 double box,
828 double zini,
829 std::vector<double> velocity_norms,
830 std::function<double(double)> velocity_norm_1LPT_of_kBox,
831 const FFTWGrid<N> * delta_fourier_2LPT_source,
832 const FFTWGrid<N> * delta_fourier_1LPT_stored,
833 const FFTWGrid<N> * mass_contrast_fourier,
834 std::function<double(double)> velocity_norm_2LPT_of_kBox) {
835
836 T tmp{};
837 if (FML::ThisTask == 0) {
838 std::cout << "\n";
839 std::cout << "#=====================================================\n";
840 std::cout << "#\n";
841 std::cout << "# .___ _________ \n";
842 std::cout << "# | | \\_ ___ \\ \n";
843 std::cout << "# | | / \\ \\/ \n";
844 std::cout << "# | | \\ \\____ \n";
845 std::cout << "# |___| \\______ / \n";
846 std::cout << "# \\/ \n";
847 std::cout << "#\n";
848 std::cout << "# Generating initial conditions for N-body\n";
849 std::cout << "# Order in LPT = " << LPT_order << "\n";
850 std::cout << "# The boxsize is " << box << " comoving Mpc/h\n";
851 std::cout << "# The initial redshift zini = " << zini << "\n";
852 if (FML::PARTICLE::has_get_pos<T>())
853 std::cout << "# Particle has [Position] x_code = x / Box ("
854 << sizeof(FML::PARTICLE::GetPos(tmp)[0]) * N << " bytes)\n";
855 if (FML::PARTICLE::has_get_vel<T>())
856 std::cout << "# Particle has [Velocity] v_code = a^2 dxdt / (H0 Box) ("
857 << sizeof(FML::PARTICLE::GetVel(tmp)[0]) * N << " bytes)\n";
858 if (FML::PARTICLE::has_set_mass<T>())
859 std::cout << "# Particle has [Mass] (" << sizeof(FML::PARTICLE::GetMass(tmp)) << " bytes)\n";
860 if (FML::PARTICLE::has_set_id<T>())
861 std::cout << "# Particle has [ID] (" << sizeof(FML::PARTICLE::GetID(tmp)) << " bytes)\n";
862 if (FML::PARTICLE::has_get_D_1LPT<T>())
863 std::cout << "# Particle has [1LPT Displacement field] ("
864 << sizeof(FML::PARTICLE::GetD_1LPT(tmp)[0]) * N << " bytes)\n";
865 if (FML::PARTICLE::has_get_D_2LPT<T>())
866 std::cout << "# Particle has [2LPT Displacement field] ("
867 << sizeof(FML::PARTICLE::GetD_2LPT(tmp)[0]) * N << " bytes)\n";
868 if (FML::PARTICLE::has_get_D_3LPTa<T>())
869 std::cout << "# Particle has [3LPTa Displacement field] ("
870 << sizeof(FML::PARTICLE::GetD_3LPTa(tmp)[0]) * N << " bytes)\n";
871 if (FML::PARTICLE::has_get_D_3LPTb<T>())
872 std::cout << "# Particle has [3LPTb Displacement field] ("
873 << sizeof(FML::PARTICLE::GetD_3LPTb(tmp)[0]) * N << " bytes)\n";
874 if (FML::PARTICLE::has_get_q<T>())
875 std::cout << "# Particle has [Lagrangian position] ("
876 << sizeof(FML::PARTICLE::GetLagrangianPos(tmp)[0]) * N << " bytes)\n";
877 std::cout << "# Total size of particle is " << FML::PARTICLE::GetSize(tmp) << " bytes\n";
878 std::cout << "# We will make " << Npart_1D << "^" << N << " particles\n";
879 std::cout << "# Plus a buffer with room for " << (buffer_factor - 1.0) * 100.0 << "% more particles\n";
880 std::cout << "# We will allocate ~"
881 << buffer_factor * double(FML::PARTICLE::GetSize(tmp)) * double(FML::power(Npart_1D, N)) /
882 1e6 / double(FML::NTasks)
883 << " MB per task for the particles\n";
884 std::cout << "#\n";
885 std::cout << "#=====================================================\n";
886 std::cout << "\n";
887 }
888
889 // Sanity checks
890 const auto Nmesh = delta_fourier.get_nmesh();
891 assert_mpi(Nmesh > 0, "[NBodyInitialConditions] delta_fourier has to be already allocated");
892 assert_mpi(delta_fourier_2LPT_source == nullptr or LPT_order <= 2,
893 "[NBodyInitialConditions] A separate 2LPT source is only implemented for LPT_order <= 2");
894 assert_mpi(LPT_order == 1 or LPT_order == 2 or LPT_order == 3,
895 "[NBodyInitialConditions] Only 1LPT, 2LPT and 3LPT implemented so valid choices here are "
896 "LPT_order = 1, 2 or 3");
897 // One velocity factor per displacement field: 1LPT, 2LPT, 3LPTa, 3LPTb
898 const size_t n_velocity_norms_needed = LPT_order == 3 ? 4 : size_t(LPT_order);
899 assert_mpi(velocity_norms.size() >= n_velocity_norms_needed,
900 "[NBodyInitialConditions] velocity_norms must have (at least) one factor per displacement "
901 "field: 1 for LPT_order = 1, 2 for LPT_order = 2 and 4 (1LPT, 2LPT, 3LPTa, 3LPTb) for "
902 "LPT_order = 3");
903 const std::string interpolation_method = "CIC"; // We use n-linear interpolation below
904 const auto nextra_cic =
906 assert_mpi(delta_fourier.get_n_extra_slices_left() >= nextra_cic.first and
907 delta_fourier.get_n_extra_slices_right() >= nextra_cic.second,
908 "[NBodyInitialConditions] We use CIC interpolation in this routine so the grid needs to have "
909 "at least one extra slice on the right");
910
911 // Sanity check on particle
912 assert_mpi(FML::PARTICLE::GetNDIM(T()) == N,
913 "[NBodyInitialConditions] NDIM of particles and of grid does not match");
914 assert_mpi(FML::PARTICLE::has_get_pos<T>(),
915 "[NBodyInitialConditions] Particle class must have a get_pos method");
916
917 // The scalefactor and log(a) at the initial time
918 const double aini = 1.0 / (1.0 + zini);
919
920 FFTWGrid<N> phi_1LPT;
921 FFTWGrid<N> phi_2LPT;
922 FFTWGrid<N> phi_3LPTa;
923 FFTWGrid<N> phi_3LPTb;
924 if (LPT_order == 1) {
925 // Generate the 1LPT potential phi_1LPT = delta(k)/k^2
927 } else if (LPT_order == 2) {
928 // Generate the 1LPT potential phi_1LPT = delta(k)/k^2
930 // Generate the 2LPT potential phi_2LPT = -1/2k^2 F[phi_ii phi_jj - phi_ij^2]
932 delta_fourier_2LPT_source ? *delta_fourier_2LPT_source : delta_fourier,
933 phi_2LPT);
934 } else if (LPT_order == 3) {
935 // Generate the 3LPT potentials phi_3LPTa, phi_3LPTb plus 3LPT curl term
936 // We ignore the curl term in this implementation for simplicity
937 const bool ignore_3LPT_curl_term = true;
938 std::array<FFTWGrid<N>, N> phi_3LPT_Avec_fourier;
940 phi_1LPT,
941 phi_2LPT,
942 phi_3LPTa,
943 phi_3LPTb,
944 phi_3LPT_Avec_fourier,
945 ignore_3LPT_curl_term);
946 }
947
948 //================================================================
949 // Function to compute the displacement from a LPT potential
950 // Frees the memory of phi_nLPT after its used
951 //================================================================
952 auto comp_displacement = [&]([[maybe_unused]] int nLPT,
953 FFTWGrid<N> & phi_nLPT,
954 std::array<std::vector<FML::GRID::FloatType>, N> & displacements_nLPT) {
955 // Generate Psi from phi
956 std::array<FFTWGrid<N>, N> Psi_nLPT_vector;
958 for (int idim = 0; idim < N; idim++) {
959 Psi_nLPT_vector[idim].communicate_boundaries();
960 }
961 phi_nLPT.free();
962
963 // Interpolate it to particle Lagrangian positions
965 part.get_particles_ptr(),
966 part.get_npart(),
967 displacements_nLPT,
969 };
970
971 // The 1LPT displacement field we store in the particles (if it is not the one we displace with)
972 std::array<std::vector<FML::GRID::FloatType>, N> stored_1LPT;
973
974 auto add_displacement = [&]([[maybe_unused]] int nLPT,
975 char type,
976 std::array<std::vector<FML::GRID::FloatType>, N> & displacements_nLPT,
977 double vfac_nLPT,
978 const std::array<std::vector<FML::GRID::FloatType>, N> * velocities_nLPT =
979 nullptr) -> void {
980 // Generate Psi from phi
981 // Add displacement to particle position
982 double max_disp_nLPT = 0.0;
983 double max_vel_nLPT = 0.0;
984 auto * part_ptr = part.get_particles_ptr();
985#ifdef USE_OMP
986#pragma omp parallel for reduction(max : max_disp_nLPT, max_vel_nLPT)
987#endif
988 for (size_t ind = 0; ind < part.get_npart(); ind++) {
989
990 // Fetch displacement
991 std::array<double, N> disp;
992 for (int idim = 0; idim < N; idim++) {
993 disp[idim] = displacements_nLPT[idim][ind];
994 }
995
996 // Add to position (particle must have position)
997 auto * pos = FML::PARTICLE::GetPos(part_ptr[ind]);
998 if (ind == 0 and FML::ThisTask == 0)
999 std::cout << "Adding " << std::to_string(nLPT) << "LPT position to particle\n";
1000 for (int idim = 0; idim < N; idim++) {
1001 const double dpos_nLPT = disp[idim];
1002 pos[idim] += dpos_nLPT;
1003
1004 // Periodic BC
1005 periodic_wrap_unit_box(pos[idim]);
1006
1007 // Compute maximum displacement
1008 if (std::fabs(dpos_nLPT) > max_disp_nLPT)
1009 max_disp_nLPT = std::fabs(dpos_nLPT);
1010 }
1011
1012 // Add to velocity (if it exists)
1013 if constexpr (FML::PARTICLE::has_get_vel<T>()) {
1014 if (ind == 0 and FML::ThisTask == 0)
1015 std::cout << "Adding " << std::to_string(nLPT) << "LPT velocity to particle\n";
1016 auto * vel = FML::PARTICLE::GetVel(part_ptr[ind]);
1017 for (int idim = 0; idim < N; idim++) {
1018 const double dvel =
1019 velocities_nLPT ? double((*velocities_nLPT)[idim][ind]) : vfac_nLPT * disp[idim];
1020 vel[idim] += dvel;
1021
1022 if (std::fabs(dvel) > max_vel_nLPT)
1023 max_vel_nLPT = std::fabs(dvel);
1024 }
1025 }
1026
1027 // Store displacement fields at particle (if it exists)
1028 // This is needed if we want to do COLA
1029 if (nLPT == 1) {
1030 if constexpr (FML::PARTICLE::has_get_D_1LPT<T>()) {
1031 if (ind == 0 and FML::ThisTask == 0)
1032 std::cout << "Storing 1LPT displacement field in particle\n";
1033 auto * D = FML::PARTICLE::GetD_1LPT(part_ptr[ind]);
1034 for (int idim = 0; idim < N; idim++) {
1035 D[idim] = delta_fourier_1LPT_stored ? stored_1LPT[idim][ind] : disp[idim];
1036 }
1037 }
1038 }
1039
1040 if (nLPT == 2) {
1041 if constexpr (FML::PARTICLE::has_get_D_2LPT<T>()) {
1042 if (ind == 0 and FML::ThisTask == 0)
1043 std::cout << "Storing 2LPT displacement field in particle\n";
1044 auto * D2 = FML::PARTICLE::GetD_2LPT(part_ptr[ind]);
1045 for (int idim = 0; idim < N; idim++) {
1046 D2[idim] = disp[idim];
1047 }
1048 }
1049 }
1050
1051 if (nLPT == 3 and type == 'a') {
1052 if constexpr (FML::PARTICLE::has_get_D_3LPTa<T>()) {
1053 if (ind == 0 and FML::ThisTask == 0)
1054 std::cout << "Storing 3LPTa displacement field in particle\n";
1055 auto * D3a = FML::PARTICLE::GetD_3LPTa(part_ptr[ind]);
1056 for (int idim = 0; idim < N; idim++) {
1057 D3a[idim] = disp[idim];
1058 }
1059 }
1060 }
1061
1062 if (nLPT == 3 and type == 'b') {
1063 if constexpr (FML::PARTICLE::has_get_D_3LPTb<T>()) {
1064 if (ind == 0 and FML::ThisTask == 0)
1065 std::cout << "Storing 3LPTb displacement field in particle\n";
1066 auto * D3b = FML::PARTICLE::GetD_3LPTb(part_ptr[ind]);
1067 for (int idim = 0; idim < N; idim++) {
1068 D3b[idim] = disp[idim];
1069 }
1070 }
1071 }
1072 }
1073
1074 // Output the maximum displacement and velocity
1075 FML::MaxOverTasks(&max_disp_nLPT);
1076 FML::MaxOverTasks(&max_vel_nLPT);
1077 if (FML::ThisTask == 0)
1078 std::cout << "Maximum " << std::to_string(nLPT) << "LPT displacements: " << max_disp_nLPT * box
1079 << " Mpc/h\n";
1080 if (FML::ThisTask == 0)
1081 std::cout << "Maximum " << std::to_string(nLPT)
1082 << "LPT velocity: " << max_vel_nLPT * 100.0 * box / aini << " km/s peculiar\n";
1083 };
1084
1085 // Create particles
1087 part.info();
1088
1089 // Set unique IDs if we have that available in the particles
1090 if constexpr (FML::PARTICLE::has_set_id<T>()) {
1091 if (FML::ThisTask == 0)
1092 std::cout << "Storing unique ID in particle\n";
1093 long long int npart_local = part.get_npart();
1094 auto part_per_task = FML::GatherFromTasks(&npart_local);
1095 long long int id_start = 0;
1096 for (int i = 0; i < FML::ThisTask; i++)
1097 id_start += part_per_task[i];
1098 long long int count = 0;
1099 for (auto & p : part) {
1100 FML::PARTICLE::SetID(p, id_start + count++);
1101 }
1102 }
1103
1104 // Set mass if we have that available in the particles
1105 if constexpr (FML::PARTICLE::has_set_mass<T>()) {
1106 if (FML::ThisTask == 0)
1107 std::cout << "Storing Mass (1.0) in particle\n";
1108 for (auto & p : part) {
1109 FML::PARTICLE::SetMass(p, 1.0);
1110 }
1111 }
1112
1113 // Set Lagrangian position of the particle if we have that available
1114 if constexpr (FML::PARTICLE::has_get_q<T>()) {
1115 if (FML::ThisTask == 0)
1116 std::cout << "Storing Lagrangian position q in particle\n";
1117 for (auto & p : part) {
1118 auto pos = FML::PARTICLE::GetPos(p);
1120 for (int idim = 0; idim < N; idim++)
1121 q[idim] = pos[idim];
1122 }
1123 }
1124
1125 // Masses m = 1 + eps(q) from the mass contrast field at the lattice (before the particles are displaced)
1126 if (mass_contrast_fourier) {
1127 if constexpr (FML::PARTICLE::has_set_mass<T>()) {
1128 FFTWGrid<N> eps = *mass_contrast_fourier;
1129 eps.fftw_c2r();
1130 eps.communicate_boundaries();
1131 std::vector<FML::GRID::FloatType> eps_at_part;
1133 part.get_particles_ptr(),
1134 part.get_npart(),
1135 eps_at_part,
1137 double eps_min = 1e100, eps_max = -1e100, eps_mean = 0.0;
1138 size_t ind = 0;
1139 for (auto & p : part) {
1140 const double e = eps_at_part[ind++];
1141 FML::PARTICLE::SetMass(p, 1.0 + e);
1142 eps_min = std::min(eps_min, e);
1143 eps_max = std::max(eps_max, e);
1144 eps_mean += e;
1145 }
1146 FML::MinOverTasks(&eps_min);
1147 FML::MaxOverTasks(&eps_max);
1148 FML::SumOverTasks(&eps_mean);
1149 eps_mean /= double(part.get_npart_total());
1150 if (FML::ThisTask == 0)
1151 std::cout << "Storing Mass 1 + eps(q) in particle: eps in [" << eps_min << ", " << eps_max
1152 << "], mean " << eps_mean << "\n";
1153 } else {
1154 assert_mpi(false, "[NBodyInitialConditions] mass_contrast_fourier needs particles with set_mass");
1155 }
1156 }
1157
1158 // The velocity norm(k) Psi_nLPT(k) for a scale-dependent velocity norm (e.g. a scale-dependent growth rate)
1159 auto comp_scaledependent_velocity = [&](int nLPT,
1160 const FFTWGrid<N> & phi_nLPT,
1161 const std::function<double(double)> & norm_of_kBox,
1162 std::array<std::vector<FML::GRID::FloatType>, N> & velocities) {
1163 FFTWGrid<N> phi_vel = phi_nLPT;
1164 auto Local_nx = phi_vel.get_local_nx();
1165#ifdef USE_OMP
1166#pragma omp parallel for
1167#endif
1168 for (int islice = 0; islice < Local_nx; islice++) {
1169 [[maybe_unused]] double kmag;
1170 [[maybe_unused]] std::array<double, N> kvec;
1171 for (auto && fourier_index : phi_vel.get_fourier_range(islice, islice + 1)) {
1172 phi_vel.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
1173 const double norm = kmag > 0.0 ? norm_of_kBox(kmag) : 0.0;
1174 phi_vel.set_fourier_from_index(fourier_index,
1175 phi_vel.get_fourier_from_index(fourier_index) *
1176 FML::GRID::FloatType(norm));
1177 }
1178 }
1179 comp_displacement(nLPT, phi_vel, velocities);
1180 };
1181
1182 // Compute and add displacements
1183 // NB: we must do this in one go as add_displacement changes the position of the particles
1184 std::array<std::vector<FML::GRID::FloatType>, N> displacements_1LPT;
1185 std::array<std::vector<FML::GRID::FloatType>, N> velocities_1LPT;
1186 if (LPT_order >= 1) {
1187 const int nLPT = 1;
1188 // Scale-dependent 1LPT velocity: the displacement of phi_1LPT(k) * norm(k)
1189 if (velocity_norm_1LPT_of_kBox)
1190 comp_scaledependent_velocity(nLPT, phi_1LPT, velocity_norm_1LPT_of_kBox, velocities_1LPT);
1191 comp_displacement(nLPT, phi_1LPT, displacements_1LPT);
1192 if (delta_fourier_1LPT_stored and FML::PARTICLE::has_get_D_1LPT<T>()) {
1193 FFTWGrid<N> phi_stored;
1194 FML::COSMOLOGY::LPT::compute_1LPT_potential_fourier(*delta_fourier_1LPT_stored, phi_stored);
1195 comp_displacement(nLPT, phi_stored, stored_1LPT);
1196 }
1197 }
1198
1199 std::array<std::vector<FML::GRID::FloatType>, N> displacements_2LPT;
1200 std::array<std::vector<FML::GRID::FloatType>, N> velocities_2LPT;
1201 if (LPT_order >= 2) {
1202 const int nLPT = 2;
1203 // Store potential if asked for
1204 if (phi_nLPT_potentials.size() > 0)
1205 phi_nLPT_potentials[0] = phi_2LPT;
1206 // Scale-dependent 2LPT velocity: the displacement of phi_2LPT(k) * norm(k)
1207 if (velocity_norm_2LPT_of_kBox)
1208 comp_scaledependent_velocity(nLPT, phi_2LPT, velocity_norm_2LPT_of_kBox, velocities_2LPT);
1209 comp_displacement(nLPT, phi_2LPT, displacements_2LPT);
1210 }
1211
1212 std::array<std::vector<FML::GRID::FloatType>, N> displacements_3LPTa;
1213 if (LPT_order >= 3) {
1214 const int nLPT = 3;
1215 // Store potential if asked for
1216 if (phi_nLPT_potentials.size() > 1)
1217 phi_nLPT_potentials[1] = phi_3LPTa;
1218 comp_displacement(nLPT, phi_3LPTa, displacements_3LPTa);
1219 }
1220
1221 std::array<std::vector<FML::GRID::FloatType>, N> displacements_3LPTb;
1222 if (LPT_order >= 3) {
1223 const int nLPT = 3;
1224 // Store potential if asked for
1225 if (phi_nLPT_potentials.size() > 2)
1226 phi_nLPT_potentials[2] = phi_3LPTb;
1227 comp_displacement(nLPT, phi_3LPTb, displacements_3LPTb);
1228 }
1229
1230 if (LPT_order >= 1) {
1231 const int nLPT = 1;
1232 add_displacement(nLPT,
1233 0,
1234 displacements_1LPT,
1235 velocity_norms[0],
1236 velocity_norm_1LPT_of_kBox ? &velocities_1LPT : nullptr);
1237 for (auto & d : displacements_1LPT) {
1238 d.clear();
1239 d.shrink_to_fit();
1240 }
1241 for (auto & d : velocities_1LPT) {
1242 d.clear();
1243 d.shrink_to_fit();
1244 }
1245 }
1246
1247 if (LPT_order >= 2) {
1248 const int nLPT = 2;
1249 add_displacement(nLPT,
1250 0,
1251 displacements_2LPT,
1252 velocity_norms[1],
1253 velocity_norm_2LPT_of_kBox ? &velocities_2LPT : nullptr);
1254 for (auto & d : displacements_2LPT) {
1255 d.clear();
1256 d.shrink_to_fit();
1257 }
1258 for (auto & d : velocities_2LPT) {
1259 d.clear();
1260 d.shrink_to_fit();
1261 }
1262 }
1263
1264 if (LPT_order >= 3) {
1265 const int nLPT = 3;
1266 add_displacement(nLPT, 'a', displacements_3LPTa, velocity_norms[2]);
1267 for (auto & d : displacements_3LPTa) {
1268 d.clear();
1269 d.shrink_to_fit();
1270 }
1271 }
1272
1273 if (LPT_order >= 3) {
1274 const int nLPT = 3;
1275 add_displacement(nLPT, 'b', displacements_3LPTb, velocity_norms[3]);
1276 for (auto & d : displacements_3LPTb) {
1277 d.clear();
1278 d.shrink_to_fit();
1279 }
1280 }
1281
1282 // Communicate particles (they might have left the current task)
1283 part.communicate_particles();
1284 }
1285
1286 //===================================================================================
1287 /// @brief This method computes the fifth-force potential for modified gravity models using the linear
1288 /// approximation This computes \f$ \delta_{\rm MG}(k) \f$ where the total force in fourier space is
1289 /// \f$ F(k) \propto \frac{\vec{k}}{k^2}[\delta(k) + \delta_{\rm MG}(k)] \f$ by solving
1290 /// \f$ \nabla^2 \phi = m^2 \phi + F^{-1}[g(k) \delta(k)] \f$ where \f$ \delta_{\rm MG}(k) = -k^2\phi(k) \f$.
1291 /// For example in \f$ f(R) \f$ gravity we have \f$ g(k) = \frac{1}{3}\frac{k^2}{k^2 + m^2}\f$ and in DGP
1292 /// we have \f$ g(k) = \frac{1}{3\beta} \f$ (independent of scale).
1293 ///
1294 /// @tparam N The dimension we work in.
1295 ///
1296 /// @param[in] density_fourier The density contrast in fourier space.
1297 /// @param[out] density_mg_fourier The force potential.
1298 /// @param[in] coupling_factor_of_kBox The coupling factor \f$ g(k) \f$
1299 ///
1300 //===================================================================================
1301 template <int N>
1302 void compute_delta_fifth_force(const FFTWGrid<N> & density_fourier,
1303 FFTWGrid<N> & density_mg_fourier,
1304 std::function<double(double)> coupling_factor_of_kBox) {
1305
1306 auto coupling_factor_of_kBox_spline =
1307 density_fourier.make_fourier_spline(coupling_factor_of_kBox, "MG coupling(k)");
1308 const auto Local_nx = density_fourier.get_local_nx();
1309 density_mg_fourier = density_fourier;
1310#ifdef USE_OMP
1311#pragma omp parallel for
1312#endif
1313 for (int islice = 0; islice < Local_nx; islice++) {
1314 [[maybe_unused]] double kmag;
1315 [[maybe_unused]] std::array<double, N> kvec;
1316 for (auto && fourier_index : density_mg_fourier.get_fourier_range(islice, islice + 1)) {
1317 // Get wavevector and magnitude
1318 density_mg_fourier.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
1319
1320 // Compute coupling
1321 auto coupling = coupling_factor_of_kBox_spline(kmag);
1322
1323 // Multiply by coupling
1324 auto value = density_mg_fourier.get_fourier_from_index(fourier_index);
1325 density_mg_fourier.set_fourier_from_index(fourier_index, value * FML::GRID::FloatType(coupling));
1326 }
1327 }
1328 }
1329
1330 //===================================================================================
1331 /// @brief This method computes the fifth-force potential for modified gravity models which has a screening
1332 /// mechanism using the approximate method of Winther & Ferreira 2015. This computes \f$ \delta_{\rm MG}(k) \f$
1333 /// where the total force in fourier is given by \f$ F(k) \propto \frac{\vec{k}}{k^2}[\delta(k) + \delta_{\rm
1334 /// MG}(k)] \f$ by solving \f$ \nabla^2 \phi = m^2 \phi + f(\Phi)F^{-1}[g(k) \delta(k)] \f$ where \f$
1335 /// \delta_{\rm MG}(k) = -k^2\phi(k) \f$ For example in \f$ f(R) \f$ gravity we have \f$ g(k) =
1336 /// \frac{1}{3}\frac{k^2}{k^2 + m^2} \f$ and the screening function is \f$ f(\Phi) = \min(1,
1337 /// \left|\frac{3f_R}{2\Phi}\right|) \f$ If you don't want screening then simply pass the function \f$ f \equiv
1338 /// 1
1339 /// \f$ and the equation reduces to the one in the linear regime
1340 ///
1341 /// @tparam N The dimension we work in.
1342 ///
1343 /// @param[in] density_fourier The density contrast in fourier space.
1344 /// @param[out] density_mg_fourier The force potential.
1345 /// @param[in] coupling_factor_of_kBox The coupling factor \f$g(k)\f$
1346 /// @param[in] screening_factor_of_newtonian_potential The screening factor \f$ f(\Phi_N) \f$ Should be in
1347 /// \f$ [0,1] \f$ and go to 1 for \f$ \Phi_N \to 0 \f$ and 0 for very large \f$ \Phi_N \f$
1348 /// @param[in] poisson_norm The factor \f$ C \f$ in \f$ \nabla^2\Phi = C\delta \f$ to get the potential in the
1349 /// metric (not the code-potential) so \f$ C = \frac{3}{2}\Omega_M a \frac{(H_0B)^2}{a^2} \f$
1350 ///
1351 //===================================================================================
1352 template <int N>
1354 const FFTWGrid<N> & density_fourier,
1355 FFTWGrid<N> & density_mg_fourier,
1356 std::function<double(double)> coupling_factor_of_kBox,
1357 std::function<double(double)> screening_factor_of_newtonian_potential,
1358 double poisson_norm) {
1359
1360 const auto Local_nx = density_fourier.get_local_nx();
1361 const auto Local_x_start = density_fourier.get_local_x_start();
1362
1363 // Make copy of density grid
1364 density_mg_fourier = density_fourier;
1365
1366 // Transform to Newtonian potential
1367#ifdef USE_OMP
1368#pragma omp parallel for
1369#endif
1370 for (int islice = 0; islice < Local_nx; islice++) {
1371 [[maybe_unused]] double kmag2;
1372 [[maybe_unused]] std::array<double, N> kvec;
1373 for (auto && fourier_index : density_mg_fourier.get_fourier_range(islice, islice + 1)) {
1374
1375 auto value = density_mg_fourier.get_fourier_from_index(fourier_index);
1376 density_mg_fourier.get_fourier_wavevector_and_norm2_by_index(fourier_index, kvec, kmag2);
1377 value *= -poisson_norm / kmag2;
1378
1379 density_mg_fourier.set_fourier_from_index(fourier_index, value);
1380 }
1381 }
1382
1383 // Set DC mode
1384 if (Local_x_start == 0)
1385 density_mg_fourier.set_fourier_from_index(0, 0.0);
1386
1387 // Take another copy of the density field as we need it in real space
1388 auto delta_real = density_fourier;
1389
1390 // Transform to real space: Phi(x) and delta(x)
1391 density_mg_fourier.fftw_c2r();
1392 delta_real.fftw_c2r();
1393
1394 // Apply screening function
1395#ifdef USE_OMP
1396#pragma omp parallel for
1397#endif
1398 for (int islice = 0; islice < Local_nx; islice++) {
1399 for (auto && real_index : density_mg_fourier.get_real_range(islice, islice + 1)) {
1400 auto phi_newton = density_mg_fourier.get_real_from_index(real_index);
1401 auto delta = delta_real.get_real_from_index(real_index);
1402 auto screening_factor = screening_factor_of_newtonian_potential(phi_newton);
1403 density_mg_fourier.set_real_from_index(real_index, delta * screening_factor);
1404 }
1405 }
1406
1407 // Back to fourier space: delta(k)
1408 density_mg_fourier.fftw_r2c();
1409
1410 // Apply coupling
1411#ifdef USE_OMP
1412#pragma omp parallel for
1413#endif
1414 for (int islice = 0; islice < Local_nx; islice++) {
1415 [[maybe_unused]] double kmag;
1416 [[maybe_unused]] std::array<double, N> kvec;
1417 for (auto && fourier_index : density_mg_fourier.get_fourier_range(islice, islice + 1)) {
1418 auto value = density_mg_fourier.get_fourier_from_index(fourier_index);
1419
1420 // Get wavevector and magnitude
1421 density_mg_fourier.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
1422
1423 // Compute coupling
1424 auto coupling = coupling_factor_of_kBox(kmag);
1425
1426 // Multiply by coupling
1427 density_mg_fourier.set_fourier_from_index(fourier_index, value * FML::GRID::FloatType(coupling));
1428 }
1429 }
1430 }
1431
1432 //===================================================================================
1433 /// @brief This method computes the fifth-force potential for modified gravity models which has a screening
1434 /// mechanism using the approximate method of Winther & Ferreira 2015. This computes \f$ \delta_{\rm MG}(k) \f$
1435 /// where the total force in fourier space is \f$ F(k) \propto \frac{\vec{k}}{k^2}[\delta(k) + \delta_{\rm
1436 /// MG}(k)] \f$ by solving \f$ \nabla^2 \phi = m^2 \phi + f(\rho)F^{-1}[g(k) \delta(k)] \f$ where \f$
1437 /// \delta_{\rm MG}(k) = -k^2\phi(k) \f$ and \f$ \rho \f$ is the density in units of the mean density. For
1438 /// example in DGP gravity we have \f$ g(k) = \frac{1}{3\beta} \f$ (independent of scale) and the screening
1439 /// function is \f$ f(\rho) = 2\frac{\sqrt{1 + C} - 1}{C} \f$ where \f$ C =
1440 /// \frac{8\Omega_M(r_cH_0)^2}{9\beta^2}\rho \f$ If you don't want screening then simply pass the function \f$ f
1441 /// \equiv 1 \f$ and the equation reduces to the one in the linear regime.
1442 ///
1443 /// @tparam N The dimension we work in.
1444 ///
1445 /// @param[in] density_fourier The density contrast in fourier space.
1446 /// @param[out] density_mg_fourier The force potential.
1447 /// @param[in] coupling_factor_of_kBox The coupling factor \f$ g(k) \f$
1448 /// @param[in] screening_factor_of_density The screening factor \f$ f(\rho) \f$ Should be in \f$ [0,1] \f$ and
1449 /// go to 1 for \f$ \rho \to 0 \f$ and to 0 for \f$ \rho \to \infty \f$.
1450 /// @param[in] smoothing_scale The smoothing radius in units of the boxsize.
1451 /// @param[in] smoothing_method The k-space smoothing filter (gaussian, tophat, sharpk).
1452 ///
1453 //===================================================================================
1454 template <int N>
1456 FFTWGrid<N> & density_mg_fourier,
1457 std::function<double(double)> coupling_factor_of_kBox,
1458 std::function<double(double)> screening_factor_of_density,
1459 double smoothing_scale,
1460 std::string smoothing_method) {
1461
1462 const auto Local_nx = density_fourier.get_local_nx();
1463
1464 // Copy over
1465 density_mg_fourier = density_fourier;
1466
1467 // Smooth density field
1468 if (smoothing_scale > 0.0)
1469 FML::GRID::smoothing_filter_fourier_space(density_mg_fourier, smoothing_scale, smoothing_method);
1470
1471 // To real space density field
1472 density_mg_fourier.fftw_c2r();
1473
1474 // Apply screening function
1475#ifdef USE_OMP
1476#pragma omp parallel for
1477#endif
1478 for (int islice = 0; islice < Local_nx; islice++) {
1479 for (auto && real_index : density_mg_fourier.get_real_range(islice, islice + 1)) {
1480 auto delta = density_mg_fourier.get_real_from_index(real_index);
1481 auto screening_factor = screening_factor_of_density(1.0 + delta);
1482 density_mg_fourier.set_real_from_index(real_index, delta * screening_factor);
1483 }
1484 }
1485
1486 // To fourier spacce
1487 density_mg_fourier.fftw_r2c();
1488
1489 // Apply coupling
1490#ifdef USE_OMP
1491#pragma omp parallel for
1492#endif
1493 for (int islice = 0; islice < Local_nx; islice++) {
1494 [[maybe_unused]] double kmag;
1495 [[maybe_unused]] std::array<double, N> kvec;
1496 for (auto && fourier_index : density_mg_fourier.get_fourier_range(islice, islice + 1)) {
1497 auto value = density_mg_fourier.get_fourier_from_index(fourier_index);
1498
1499 // Get wavevector and magnitude
1500 density_mg_fourier.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
1501
1502 // Compute coupling
1503 auto coupling = coupling_factor_of_kBox(kmag);
1504
1505 // Multiply by coupling
1506 density_mg_fourier.set_fourier_from_index(fourier_index, value * FML::GRID::FloatType(coupling));
1507 }
1508 }
1509 }
1510
1511 //===================================================================================
1512 /// @brief Compute the force DPhi from the potential using finite differencing
1513 /// If options.deconvolve is set we deconvolve the density assignment and the force
1514 /// interpolation (the window function of force_interpolation_method squared) exactly as in
1515 /// compute_force_from_density_fourier (we do this on a copy of the potential in Fourier space before taking
1516 /// the finite differences). The potential must have at least stencil_order/2 extra slices on the left and
1517 /// on the right (see compute_potential_real_from_density_fourier).
1518 ///
1519 /// @param[in] potential_real The gravitational potential in real-space
1520 /// @param[out] force_grid_real Grids containing the gradient
1521 /// @param[in] force_interpolation_method Used to set the number of extra slices we allocated on the left and
1522 /// right
1523 /// @param[in] stencil_order The order of the (symmetric) stencil. E.g. 2 is for 2-point stencil [phi(i+1) -
1524 /// phi(i-1)] / 2h,
1525 /// 4 for 4-point stencil using phi(+/-1), phi(+/-2). We also have 6 implemented.
1526 ///
1527 //===================================================================================
1528 template <int N>
1530 std::array<FFTWGrid<N>, N> & force_grid_real,
1531 std::string force_interpolation_method,
1532 int stencil_order,
1533 const ForceOptions & options) {
1534 options.validate();
1535
1536 // Validate the input before any (OpenMP) parallel region: throwing inside it calls std::terminate
1537 assert_mpi(is_valid_finite_difference_stencil_order(stencil_order),
1538 "[compute_force_from_potential_real] Unknown stencil_order: only 2, 4 and 6 are implemented");
1539 assert_mpi(potential_real.get_n_extra_slices_left() >= stencil_order / 2 and
1540 potential_real.get_n_extra_slices_right() >= stencil_order / 2,
1541 "[compute_force_from_potential_real] The potential needs at least stencil_order/2 extra slices "
1542 "on the left and on the right (n_boundary_slices_to_be_allocated in "
1543 "compute_potential_real_from_density_fourier)");
1544
1545 const auto Nmesh = potential_real.get_nmesh();
1546 const auto Local_nx = potential_real.get_local_nx();
1547 const auto Local_x_start = potential_real.get_local_x_start();
1548 const double one_over_h = double(Nmesh);
1549
1550 // Deconvolve the density assignment + force interpolation (as in compute_force_from_density_fourier)
1551 FFTWGrid<N> potential_deconvolved;
1552 if (options.deconvolve) {
1553 const FML::INTERPOLATION::WindowFunctionTable<N> window_table(force_interpolation_method, Nmesh);
1554 potential_deconvolved = potential_real;
1555 potential_deconvolved.add_memory_label(
1556 "FFTWGrid::compute_force_from_potential_real::potential_deconvolved");
1557 potential_deconvolved.fftw_r2c();
1558#ifdef USE_OMP
1559#pragma omp parallel for
1560#endif
1561 for (int islice = 0; islice < Local_nx; islice++) {
1562 double kmag2;
1563 std::array<double, N> kvec;
1564 for (auto && fourier_index : potential_deconvolved.get_fourier_range(islice, islice + 1)) {
1565 if (Local_x_start == 0 and fourier_index == 0)
1566 continue; // DC mode (k=0)
1567 potential_deconvolved.get_fourier_wavevector_and_norm2_by_index(fourier_index, kvec, kmag2);
1568 const double W = window_table(kvec);
1569 auto value = potential_deconvolved.get_fourier_from_index(fourier_index);
1570 value /= (W * W);
1571 potential_deconvolved.set_fourier_from_index(fourier_index, value);
1572 }
1573 }
1574 potential_deconvolved.fftw_c2r();
1575 }
1576 FFTWGrid<N> & potential = options.deconvolve ? potential_deconvolved : potential_real;
1577
1578 // Make sure boundaries are set
1580
1581 // Allocate grid
1582 auto nextra =
1584 for (int idim = 0; idim < N; idim++)
1585 force_grid_real[idim] = FFTWGrid<N>(Nmesh, nextra.first, nextra.second);
1586
1587 // Adds iplus to idim of (i,j,k,...) and does periodic wrap
1588 // Used to compute Phi(i+1,j,k), Phi(i,j,k-2) etc.
1589 auto add_to_coord = [=](std::array<int, N> & coord, int idim, int iplus) {
1590 coord[idim] += iplus;
1591 if (idim == 0) {
1592 if (FML::NTasks == 1 and coord[0] >= Nmesh)
1593 coord[idim] -= Nmesh;
1594 if (FML::NTasks == 1 and coord[0] < 0)
1595 coord[idim] += Nmesh;
1596 } else {
1597 if (coord[idim] >= Nmesh)
1598 coord[idim] -= Nmesh;
1599 if (coord[idim] < 0)
1600 coord[idim] += Nmesh;
1601 }
1602 };
1603
1604#ifdef USE_OMP
1605#pragma omp parallel for
1606#endif
1607 for (int islice = 0; islice < Local_nx; islice++) {
1608 for (auto && real_index : potential.get_real_range(islice, islice + 1)) {
1609 const auto coord = potential.get_coord_from_index(real_index);
1610
1611 [[maybe_unused]] std::array<FML::GRID::FloatType, N> dPhidx_pm1{};
1612 [[maybe_unused]] std::array<FML::GRID::FloatType, N> dPhidx_pm2{};
1613 [[maybe_unused]] std::array<FML::GRID::FloatType, N> dPhidx_pm3{};
1614
1615 // Compute (Phi(i+1) - Phi(i-1))/2
1616 if (stencil_order >= 2) {
1617 for (int idim = 0; idim < N; idim++) {
1618
1619 // Add +/- 1 and do periodic wrap
1620 auto coord_plus = coord;
1621 add_to_coord(coord_plus, idim, +1);
1622 auto coord_minus = coord;
1623 add_to_coord(coord_minus, idim, -1);
1624
1625 // Fetch values and compute derivative
1626 auto Phi_i_plus_one = potential.get_real(coord_plus);
1627 auto Phi_i_minus_one = potential.get_real(coord_minus);
1628 dPhidx_pm1[idim] = (Phi_i_plus_one - Phi_i_minus_one) / 2.0;
1629 }
1630 }
1631
1632 // Compute (Phi(i+2) - Phi(i-2))/4
1633 if (stencil_order >= 4) {
1634 for (int idim = 0; idim < N; idim++) {
1635
1636 // Add +/- 2 and do periodic wrap
1637 auto coord_plus = coord;
1638 add_to_coord(coord_plus, idim, +2);
1639 auto coord_minus = coord;
1640 add_to_coord(coord_minus, idim, -2);
1641
1642 // Fetch values and compute derivative
1643 auto Phi_i_plus_two = potential.get_real(coord_plus);
1644 auto Phi_i_minus_two = potential.get_real(coord_minus);
1645 dPhidx_pm2[idim] = (Phi_i_plus_two - Phi_i_minus_two) / 4.0;
1646 }
1647 }
1648
1649 // Compute (Phi(i+3) - Phi(i-3))/26
1650 if (stencil_order >= 6) {
1651 for (int idim = 0; idim < N; idim++) {
1652
1653 // Add +/- 3 and do periodic wrap
1654 auto coord_plus = coord;
1655 add_to_coord(coord_plus, idim, +3);
1656 auto coord_minus = coord;
1657 add_to_coord(coord_minus, idim, -3);
1658
1659 // Fetch values and compute derivative
1660 auto Phi_i_plus_three = potential.get_real(coord_plus);
1661 auto Phi_i_minus_three = potential.get_real(coord_minus);
1662 dPhidx_pm3[idim] = (Phi_i_plus_three - Phi_i_minus_three) / 6.0;
1663 }
1664 }
1665
1666 // Compute and store the derivative
1667 if (stencil_order == 2) {
1668 for (int idim = 0; idim < N; idim++) {
1669 auto DPhi = dPhidx_pm1[idim] * one_over_h;
1670 force_grid_real[idim].set_real_from_index(real_index, DPhi);
1671 }
1672 } else if (stencil_order == 4) {
1673 for (int idim = 0; idim < N; idim++) {
1674 auto DPhi = (4.0 / 3.0 * dPhidx_pm1[idim] - dPhidx_pm2[idim] / 3.0) * one_over_h;
1675 force_grid_real[idim].set_real_from_index(real_index, DPhi);
1676 }
1677 } else if (stencil_order == 6) {
1678 for (int idim = 0; idim < N; idim++) {
1679 auto DPhi =
1680 (0.1 * dPhidx_pm3[idim] - 0.6 * dPhidx_pm2[idim] + 1.5 * dPhidx_pm1[idim]) * one_over_h;
1681 force_grid_real[idim].set_real_from_index(real_index, DPhi);
1682 }
1683 }
1684 }
1685 }
1686 }
1687
1688 //===================================================================================
1689 /// @brief This function returns the equivalent of -1/k^2 for different kernels
1690 ///
1691 /// @tparam N The dimension of the grid
1692 ///
1693 /// @param[in] kmag2 The norm of the fourier wavevector
1694 /// @param[in] kvec The fourier wavevector
1695 /// @param[in] Nmesh The grid size
1696 /// @param[in] KERNEL The kernel to use for the Greens Function
1697 /// (see enum GreensFunctionLaplaceOperatorKernels for options)
1698 ///
1699 //===================================================================================
1700 template <int NDIM>
1701 double
1702 greens_function_laplace_operator_fourier(double kmag2, std::array<double, NDIM> & kvec, int Nmesh, int KERNEL) {
1703 const double dx = 1.0 / double(Nmesh);
1704 switch (KERNEL) {
1706 return -1.0 / kmag2;
1707 break;
1708 }
1710 double sum1 = 0.0;
1711 for (int idim = 0; idim < NDIM; idim++) {
1712 double _sin_over_two = std::sin(kvec[idim] * dx / 2.0);
1713 sum1 += _sin_over_two * _sin_over_two;
1714 }
1715 sum1 *= 4.0 / (dx * dx);
1716 if (sum1 == 0.0)
1717 return 0.0;
1718 return -1.0 / sum1;
1719 break;
1720 }
1722 double sum2 = 0.0;
1723 for (int idim = 0; idim < NDIM; idim++) {
1724 double _sin = std::sin(kvec[idim] * dx);
1725 double _cos = std::cos(kvec[idim] * dx);
1726 // D^2 = -(D4)^2 with the 4-point gradient D4 = (8 sin(k dx) - sin(2k dx)) / (6 dx) (see
1727 // gradient_kernel_fourier) = sin(k dx) (4 - cos(k dx)) / (3 dx) so that
1728 // D4^2 = sin^2 (16 - 8cos + cos^2) / (9 dx^2) = sin^2 (9 - 8(cos - 1) - sin^2) / (9 dx^2)
1729 sum2 += _sin * _sin * (9.0 - 8.0 * (_cos - 1.0) - _sin * _sin);
1730 }
1731 // D4 vanishes not only for k = 0, but also when every component is 0 or the Nyquist frequency
1732 // (sin(k dx) = 0 up to rounding): we set the potential of these modes to zero (as for k = 0).
1733 // Otherwise sum2 (before the factor 1/(9 dx^2) below) is at least ~ 9 (2pi/Nmesh)^2 > 1e-16 for any
1734 // Nmesh < 10^9, while rounding gives sum2 ~ 1e-31 for these modes. They are self-conjugate
1735 // modes where the gradient is (numerically) zero so this does not change the force.
1736 if (sum2 < 1e-20)
1737 return 0.0;
1738 sum2 *= 1.0 / (9.0 * dx * dx);
1739 return -1.0 / sum2;
1740 break;
1741 }
1742 default: {
1743 FML::assert_mpi(false, "Unknown KERNEL in greens_function_laplace_operator_fourier");
1744 return 0.0;
1745 break;
1746 }
1747 }
1748 }
1749
1750
1751 //===================================================================================
1752 /// @brief This function returns the equivalent of D/i = k_vec for different kernels
1753 ///
1754 /// All kernels are zero for the Nyquist component \f$ |k_j| = k_{\rm Ny} \f$ of an even mesh (see the
1755 /// continuous kernel below).
1756 ///
1757 /// @tparam N The dimension of the grid
1758 ///
1759 /// @param[in] k_j The component of the fourier wavevector
1760 /// @param[in] Nmesh The grid size
1761 /// @param[in] KERNEL The kernel to use for the gradient
1762 /// (see enum GradientKernels for options)
1763 ///
1764 //===================================================================================
1765 inline double gradient_kernel_fourier(double k_j, int Nmesh, int KERNEL) {
1766 const double dx = 1.0 / double(Nmesh);
1767 switch (KERNEL) {
1768 case CONTINUOUS_GRADIENT: {
1769 // On an even mesh the Nyquist mode k_j = k_Ny is its own mirror image k_j = -k_Ny, so i k_j of it
1770 // depends on the sign we pick (FFTWGrid uses +k_Ny) and the force of a reflected density field
1771 // would not be the reflected force. The gradient of the band-limited field is zero there (as
1772 // for the discrete kernels, sin(k_Ny dx) = 0, and the LPT displacements)
1773 return FML::COSMOLOGY::LPT::detail::odd_derivative_wavevector<1>({k_j}, Nmesh)[0];
1774 break;
1775 }
1777 return std::sin(k_j * dx) / dx;
1778 break;
1779 }
1781 return (8.0 * std::sin(k_j * dx) - std::sin(2.0 * k_j * dx)) / (6.0 * dx);
1782 break;
1783 }
1784 default: {
1785 FML::assert_mpi(false, "Unknown KERNEL in gradient_kernel_fourier");
1786 return 0.0;
1787 break;
1788 }
1789 }
1790 }
1791
1792
1793 //===================================================================================
1794 /// @brief Compute Phi(x) from the density field in fourier space Phi = F^-1( 1/D^2 * delta * norm )
1795 /// The kernel used for 1/D^2 is options.laplace_kernel (as in
1796 /// compute_force_from_density_fourier). The deconvolution of the density assignment and force interpolation
1797 /// (options.deconvolve) is not done here (we don't know the assignment method), but in
1798 /// compute_force_from_potential_real.
1799 ///
1800 /// @param[in] density_grid_fourier The density field (already in fourier space)
1801 /// @param[out] potential_real The gravitational potential in real-space
1802 /// @param[in] norm_poisson_equation The prefactor to the Poisson equation D^2 Phi = delta * norm
1803 /// @param[in] n_boundary_slices_to_be_allocated For the potential we compute allocate n extra
1804 /// slices on the left and right (useful if we later want to compute finite difference gradients to
1805 /// get forces)
1806 ///
1807 //===================================================================================
1808 template <int N>
1810 FFTWGrid<N> & potential_real,
1811 double norm_poisson_equation,
1812 int n_boundary_slices_to_be_allocated,
1813 const ForceOptions & options) {
1814 options.validate();
1815
1816 const int LAPLACE_KERNEL = options.laplace_kernel;
1817 const auto Nmesh = density_grid_fourier.get_nmesh();
1818 const auto Local_nx = density_grid_fourier.get_local_nx();
1819 const auto Local_x_start = density_grid_fourier.get_local_x_start();
1820
1821 // Allocate grid with n_boundary_slices_to_be_allocated extra
1822 // cells on the left and right
1823 potential_real = FFTWGrid<N>(Nmesh, n_boundary_slices_to_be_allocated, n_boundary_slices_to_be_allocated);
1824
1825 // Loop over all local fourier grid cells
1826#ifdef USE_OMP
1827#pragma omp parallel for
1828#endif
1829 for (int islice = 0; islice < Local_nx; islice++) {
1830 double kmag2;
1831 std::array<double, N> kvec;
1832 for (auto && fourier_index : density_grid_fourier.get_fourier_range(islice, islice + 1)) {
1833 if (Local_x_start == 0 and fourier_index == 0) {
1834 potential_real.set_fourier_from_index(0, 0.0);
1835 continue; // DC mode (k=0)
1836 }
1837
1838 // Compute potential (1/D^2) * delta(k) * norm (with 1/D^2 = -1/k^2 for the continuous kernel)
1839 density_grid_fourier.get_fourier_wavevector_and_norm2_by_index(fourier_index, kvec, kmag2);
1840 auto value = density_grid_fourier.get_fourier_from_index(fourier_index);
1841 if (LAPLACE_KERNEL == CONTINUOUS_GREENS_FUNCTION) {
1842 value *= -1.0 / kmag2;
1843 } else {
1844 value *= greens_function_laplace_operator_fourier<N>(kmag2, kvec, Nmesh, LAPLACE_KERNEL);
1845 }
1846 potential_real.set_fourier_from_index(fourier_index,
1847 value * FML::GRID::FloatType(norm_poisson_equation));
1848 }
1849 }
1850
1851 // Fourier transform back to real space
1852 potential_real.fftw_c2r();
1853 }
1854
1855#ifdef USE_GSL
1856
1857 //===================================================================================
1858 /// @brief This computes the standard deviation of linear fluctuations smoothed over a sphere of radius, \f$
1859 /// \sigma(R) \f$, by integrating the power-spectrum convolved with a top-hat windowfunction of radius \f$ R
1860 /// \f$. We do this by solving \f$ \sigma^2(R) = \int \frac{k^3P(k)}{2\pi^2} |W(kR)|^2 d\log k \f$
1861 ///
1862 /// @param[in] Pofk_of_kBox_over_volume Dimensionless power-spectrum \f$ P / V \f$ as function of the
1863 /// dimensionless scale \f$ kB \f$ where \f$B\f$ is the boxsize and \f$V = B^3\f$ is the box volume.
1864 /// @param[in] R_mpch R in units of Mpc/h
1865 /// @param[in] boxsize_mpch Boxsize in units of Mpc/h
1866 ///
1867 //===================================================================================
1868 inline double
1869 compute_sigma_of_R(std::function<double(double)> Pofk_of_kBox_over_volume, double R_mpch, double boxsize_mpch) {
1873
1874 // We integrate from k = 1e-5 h/Mpc to k = 100 h/Mpc
1875 const double kBoxmin = 1e-5 * boxsize_mpch;
1876 const double kBoxmax = 1e2 * boxsize_mpch;
1877
1878 ODEFunction deriv = [&](double logkBox, [[maybe_unused]] const double * sigma2, double * dsigma2dlogk) {
1879 const double kBox = std::exp(logkBox);
1880 const double dimless_pofk = kBox * kBox * kBox / (2.0 * M_PI * M_PI) * Pofk_of_kBox_over_volume(kBox);
1881 const double kR = kBox * R_mpch / boxsize_mpch;
1882 const double window = kR > 0.0 ? 3.0 * (std::sin(kR) - kR * std::cos(kR)) / (kR * kR * kR) : 1.0;
1883 dsigma2dlogk[0] = dimless_pofk * window * window;
1884 return GSL_SUCCESS;
1885 };
1886
1887 // The initial conditions
1888 DVector sigmaini{0.0};
1889 DVector logkarr{std::log(kBoxmin), std::log(kBoxmax)};
1890
1891 // Solve the ODE
1892 ODESolver ode(1e-3, 1e-10, 1e-10);
1893 ode.solve(deriv, logkarr, sigmaini);
1894 auto sigma2 = ode.get_final_data_by_component(0);
1895
1896 return std::sqrt(sigma2);
1897 }
1898#endif
1899
1900 } // namespace NBODY
1901} // namespace FML
1902#endif
FML::SOLVERS::FFTLog::DVector DVector
Definition Main.cpp:4
const int NDIM
const double box
Definition Main.cpp:45
const std::string type_of_random_field
Definition Main.cpp:45
const int Npart_1D
Definition Main.cpp:50
const double buffer_factor
Definition Main.cpp:51
const bool fix_amplitude
Definition Main.cpp:44
const int Nmesh
Definition Main.cpp:48
const std::string interpolation_method
Definition Main.cpp:64
const double zini
Definition Main.cpp:40
const double fNL
Definition Main.cpp:46
const double aini
Definition Main.cpp:41
FML::SOLVERS::ODESOLVER::ODEFunction ODEFunction
Definition Main.cpp:83
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 communicate_boundaries()
Send slices to the neighboring CPUs which stores them in the left and right extra slice storage (with...
Definition FFTWGrid.h:829
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 add_memory_label(std::string label)
For memory logging: add a label to the grid.
Definition FFTWGrid.h:404
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
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
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 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
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
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
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
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...
A container class for holding particles that are distributed across many CPUs and to easily deal with...
void create_particle_grid(int Npart_1D, double buffer_factor, double xmin_local, double xmax_local)
Create particles in a rectangular grid spread across all tasks buffer_factor is how much extra to al...
size_t get_npart_total() const
Total number of active particles across all tasks.
T * get_particles_ptr()
Get a pointer to the first particle.
void info()
Show some info about the class.
void communicate_particles(size_t max_message_bytes=std::numeric_limits< int >::max(), bool force_general=false)
Communicate particles across CPU boundaries.
size_t get_npart() const
Number of active particles on the local task.
This is a class for having a unified interface for random numbers in the library.
This is a wrapper around the GSL library to easily solve ODEs and return the data in whatever format ...
Definition ODESolver.h:97
double get_final_data_by_component(int icomponent) const
Get the solution for a given component at the end point.
void solve(ODEFunctionPointer ode_equation, void *parameters, const DVector &xarr, const DVector &yinitial, const gsl_odeiv2_step_type *stepper=ODESOLVER_FIDUCIAL_STEPPER, ODEFunctionPointerJacobian jacobian=nullptr)
void compute_3LPT_potential_fourier(const FFTWGrid< N > &delta_fourier, FFTWGrid< N > &phi_1LPT_fourier, FFTWGrid< N > &phi_2LPT_fourier, FFTWGrid< N > &phi_3LPT_a_fourier, FFTWGrid< N > &phi_3LPT_b_fourier, std::array< FFTWGrid< N >, N > &phi_3LPT_Avec_fourier, bool ignore_curl_term, Dealiasing dealiasing=Dealiasing::None)
Optional Padding uses a >=2N work mesh for all nonlinear sources, retaining the full intermediate sec...
void compute_1LPT_potential_fourier(const FFTWGrid< N > &delta_fourier, FFTWGrid< N > &phi_1LPT_fourier)
Generate the 1LPT potential defined as and .
void compute_2LPT_potential_fourier(const FFTWGrid< N > &delta_fourier, FFTWGrid< N > &phi_2LPT_fourier, Dealiasing dealiasing=Dealiasing::None)
Optional Padding uses a >=3N/2 work mesh for the quadratic source.
void from_LPT_potential_to_displacement_vector(const FFTWGrid< N > &phi_fourier, std::array< FFTWGrid< N >, N > &psi_real, double DoverDini=1.0)
Generate the displaceement field from the LPT potential .
void smoothing_filter_fourier_space(FFTWGrid< N > &fourier_grid, double smoothing_scale, std::string smoothing_method)
This namespace deals with interpolation and density assignment.
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::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 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.
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 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.
@ DISCRETE_GREENS_FUNCTION_FROM_TWO_POINT
@ CONTINUOUS_GREENS_FUNCTION
Definition ForceOptions.h:9
@ DISCRETE_GREENS_FUNCTION_FROM_FOUR_POINT
void KickDriftKickNBodyStep(int Nmesh, MPIParticles< T > &part, double delta_time, std::string density_assignment_method, double norm_poisson_equation, const ForceOptions &options={})
Take a N-body step with a simple Kick-Drift-Kick method (this method serves mainly as an example for ...
Definition NBody.h:143
void KickParticles(std::array< FFTWGrid< N >, N > &force_grid, MPIParticles< T > &part, double delta_time, std::string interpolation_method)
This moves the particle velocities according to .
Definition NBody.h:583
void compute_delta_fifth_force(const FFTWGrid< N > &density_fourier, FFTWGrid< N > &density_mg_fourier, std::function< double(double)> coupling_factor_of_kBox)
This method computes the fifth-force potential for modified gravity models using the linear approxima...
Definition NBody.h:1302
void periodic_wrap_unit_box(F &x)
Periodic wrap of a coordinate to [0,1).
Definition NBody.h:88
void compute_delta_fifth_force_density_screening(const FFTWGrid< N > &density_fourier, FFTWGrid< N > &density_mg_fourier, std::function< double(double)> coupling_factor_of_kBox, std::function< double(double)> screening_factor_of_density, double smoothing_scale, std::string smoothing_method)
This method computes the fifth-force potential for modified gravity models which has a screening mech...
Definition NBody.h:1455
void compute_delta_fifth_force_potential_screening(const FFTWGrid< N > &density_fourier, FFTWGrid< N > &density_mg_fourier, std::function< double(double)> coupling_factor_of_kBox, std::function< double(double)> screening_factor_of_newtonian_potential, double poisson_norm)
This method computes the fifth-force potential for modified gravity models which has a screening mech...
Definition NBody.h:1353
void compute_force_from_density_fourier(const FFTWGrid< N > &density_grid_fourier, std::array< FFTWGrid< N >, N > &force_real, std::string density_assignment_method_used, double norm_poisson_equation, const ForceOptions &options={})
Take a density grid in fourier space and returns the force where Different choices for what kernel ...
Definition NBody.h:325
double gradient_kernel_fourier(double k_j, int Nmesh, int KERNEL)
This function returns the equivalent of D/i = k_vec for different kernels.
Definition NBody.h:1765
double compute_sigma_of_R(std::function< double(double)> Pofk_of_kBox_over_volume, double R_mpch, double boxsize_mpch)
This computes the standard deviation of linear fluctuations smoothed over a sphere of radius,...
Definition NBody.h:1869
FML::GRID::FFTWGrid< N > FFTWGrid
Definition NBody.h:41
double greens_function_laplace_operator_fourier(double kmag2, std::array< double, NDIM > &kvec, int Nmesh, int KERNEL)
This function returns the equivalent of -1/k^2 for different kernels.
Definition NBody.h:1702
void compute_force_from_density_real(const FFTWGrid< N > &density_grid_real, std::array< FFTWGrid< N >, N > &force_real, std::string density_assignment_method_used, double norm_poisson_equation, const ForceOptions &options={})
Take a density grid in real space and returns the force where Different choices for what kernel to ...
Definition NBody.h:290
void compute_potential_real_from_density_fourier(const FFTWGrid< N > &density_grid_fourier, FFTWGrid< N > &potential_real, double norm_poisson_equation, int n_boundary_slices_to_be_allocated, const ForceOptions &options={})
Compute Phi(x) from the density field in fourier space Phi = F^-1( 1/D^2 * delta * norm ) The kernel ...
Definition NBody.h:1809
void compute_force_from_potential_real(FFTWGrid< N > &potential_real, std::array< FFTWGrid< N >, N > &force_grid_real, std::string force_interpolation_method, int stencil_order, const ForceOptions &options={})
Compute the force DPhi from the potential using finite differencing If options.deconvolve is set we d...
Definition NBody.h:1529
void YoshidaNBodyStep(int Nmesh, MPIParticles< T > &part, double delta_time, std::string density_assignment_method, double norm_poisson_equation, const ForceOptions &options={})
Take a N-body step with a 4th order symplectic Yoshida method.
Definition NBody.h:212
void DriftParticles(FML::PARTICLE::MPIParticles< T > &part, double delta_time, bool periodic_box=true)
void NBodyInitialConditions(MPIParticles< T > &part, int Npart_1D, double buffer_factor, const FFTWGrid< N > &delta_fourier, std::vector< FFTWGrid< N > > &phi_nLPT_potentials, int LPT_order, double box, double zini, std::vector< double > velocity_norms, std::function< double(double)> velocity_norm_1LPT_of_kBox=nullptr, const FFTWGrid< N > *delta_fourier_2LPT_source=nullptr, const FFTWGrid< N > *delta_fourier_1LPT_stored=nullptr, const FFTWGrid< N > *mass_contrast_fourier=nullptr, std::function< double(double)> velocity_norm_2LPT_of_kBox=nullptr)
Generate particles from a given initial density field using Lagrangian perturbation theory.
Definition NBody.h:819
@ CONTINUOUS_GRADIENT
@ DISCRETE_TWO_POINT_GRADIENT
@ DISCRETE_FOUR_POINT_GRADIENT
bool is_valid_finite_difference_stencil_order(int stencil_order)
The finite difference stencils implemented in compute_force_from_potential_real.
Definition NBody.h:101
get_vel constexpr double * GetPos(...)
constexpr double * GetLagrangianPos(...)
constexpr double * GetD_3LPTa(...)
constexpr void SetMass(...)
set_id constexpr int GetID(...)
constexpr double * GetVel(...)
constexpr double * GetD_3LPTb(...)
constexpr double * GetD_2LPT(...)
set_mass constexpr double GetMass(Args &... args)
constexpr void SetID(...)
void generate_gaussian_random_field_fourier(FFTWGrid< N > &grid, RandomGenerator *rng, std::function< double(double)> Pofk_of_kBox_over_volume, bool fix_amplitude)
void generate_nonlocal_gaussian_random_field_fourier_cosmology(FFTWGrid< N > &delta_fourier, RandomGenerator *rng, std::function< double(double)> Pofk_of_kBox_over_Pofk_primordal, std::function< double(double)> Pofk_of_kBox_over_volume_primordial, bool fix_amplitude, double fNL, std::string type_of_fnl, double u=0.0, std::vector< double > kernel_values={}, const GAUSSIAN::RandomFieldOptions &random_options={})
This computes a non-gaussian density field at any redshift.
std::vector< double > DVector
Definition ODESolver.h:29
std::function< int(double, const double *, double *)> ODEFunction
Definition ODESolver.h:33
double xmax_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:50
void MinOverTasks(T *value)
Inplace min over tasks of a single value.
Definition Global.h:209
void MaxOverTasks(T *value)
Inplace max over tasks of a single value.
Definition Global.h:189
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
std::vector< T > GatherFromTasks(T *value)
Gather a single value from all tasks. Value from task ThisTask is stored in values[ThisTask].
Definition Global.h:172
void SumOverTasks(T *value)
Inplace sum over tasks of a single value.
Definition Global.h:229
double xmin_domain
The local extent of the domain (global domain goes from 0 to 1)
Definition Global.cpp:49
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
Per-call force discretization. No process-wide mutable defaults.
ComplexType value(const std::array< int, N > &wave, int generation)
std::mt19937_64 rng(1234)
Options options()
void potential()
double norm(Vector a)