FML
Loading...
Searching...
No Matches
ComputePowerSpectrum.h
Go to the documentation of this file.
1#ifndef COMPUTEPOWERSPECTRUM_HEADER
2#define COMPUTEPOWERSPECTRUM_HEADER
3
4#include <array>
5#include <cassert>
6#include <iostream>
7#include <vector>
8
9#ifdef USE_MPI
10#include <mpi.h>
11#endif
12
13#ifdef USE_OMP
14#include <omp.h>
15#endif
16
19#include <numeric>
20#include <climits>
21#include <FML/Global/Global.h>
23#include <FML/LPT/Reconstruction.h> // For particles->redshiftspace
24#include <FML/MPIParticles/MPIParticles.h> // Only for compute_multipoles from particles
25
26// The classes that define how to bin and return the data
30
31namespace FML {
32
33 //================================================================================
34 /// This namespace deals with computing correlations functions (N-point functions)
35 /// in real and fourier space.
36 //================================================================================
37
38 namespace CORRELATIONFUNCTIONS {
39
40 using namespace FML::INTERPOLATION;
41
42 template <int N>
44
45 //================================================================================
46 // Keep track of everything we need for a binned power-spectrum
47 // The k-spacing (linear or log or ...), the count in each bin,
48 // the power in each bin etc. Its through this interface the results
49 // of the methods below are given. See PowerSpectrumBinning.h for more info
50 //================================================================================
51
52 // The powerspectrum result, see PowerspectrumBinning.h
53 template <int N>
55
56 // General polyspectrum result, see PolyspectrumBinning.h
57 template <int N, int ORDER, bool COMPACT>
59
60 // Type aliases for mono-,bi- and tri-spectrum. See PolyspectrumBinning.h for more info
61 template <int N, bool COMPACT = false>
63
64 template <int N, bool COMPACT = false>
66
67 template <int N, bool COMPACT = false>
69
70 template <int N>
72 template <int N>
74 template <int N>
76
77 //================================================================================
78 /// @brief Assign particles to grid using density_assignment_method = NGP,CIC,TSC,PCS,...
79 /// Fourier transform, decolvolve the window function for the assignment above.
80 /// With interlacing bin to a grid and an interlaced grid (displaced by dx/2 in all directions)
81 /// Fourier transform both and add the together to cancel the leading aliasing contributions
82 /// bin up power-spectrum and subtract shot-noise 1/NumPartTotal. Interlacing uses virtual assignment
83 /// offsets and never modifies particle positions.
84 ///
85 /// @tparam N The dimension of the particles.
86 /// @tparam T The particle class. Must have a get_pos() method.
87 ///
88 /// @param[in] Ngrid Size of the grid to use.
89 /// @param[in] part Pointer to the first particle.
90 /// @param[in] NumPart Number of particles on the local task.
91 /// @param[in] NumPartTotal Total number of particles on all tasks.
92 /// @param[out] pofk The binned power-spectrum. We required it to be initialized with the number of bins, kmin
93 /// and kmax.
94 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS)
95 /// @param[in] interlacing Use interlaced grids for alias reduction. Twice as expensive, but allows us to use a
96 /// smaller grid (so its actually faster if used correctly).
97 ///
98 //================================================================================
99 template <int N, class T>
100 void compute_power_spectrum(int Ngrid,
101 T * part,
102 size_t NumPart,
103 size_t NumPartTotal,
105 std::string density_assignment_method,
106 bool interlacing);
107
108 //================================================================================
109 /// @brief Brute force (but aliasing free) computation of the power spectrum.
110 /// Loop over all grid-cells and all particles and add up contribution and subtracts shot-noise term.
111 /// Since we need to combine all particles with all cells this is not easily parallelizable with MPI
112 /// so we assume all CPUs have exactly the same particles when this is run on more than 1 MPI tasks (so best run
113 /// just using OpenMP).
114 /// This method scales as \f$ \mathcal{O}({\rm Npart}\cdot {\rm Nmesh}^N) \f$ so will be slow!
115 ///
116 /// @tparam N The dimension of the particles.
117 /// @tparam T The particle class. Must have a get_pos() method.
118 ///
119 /// @param[in] Ngrid Size of the grid to use.
120 /// @param[in] part Pointer to the first particle.
121 /// @param[in] NumPart Number of particles on the local task. With MPI assumes all tasks have the same
122 /// particles.
123 /// @param[out] pofk The binned power-spectrum. We required it to be initialized with the number of bins, kmin
124 /// and kmax.
125 ///
126 //================================================================================
127 template <int N, class T>
129 const T * part,
130 size_t NumPart,
132
133 //==========================================================================================
134 /// @brief Compute the power-spectrum of a fourier grid. The result has no scales. Get
135 /// scales by calling pofk.scale(boxsize) which does \f$ k \to k/B \f$ and
136 /// \f$ P(k) \to B^N P(k) \f$ where \f$ B\f$ is the boxsize once spectrum has been computed. The method assumes
137 /// the two grids are fourier transforms of real grids (i.e. \f$ f(-k) = f^*(k) \f$).
138 ///
139 /// @tparam N Dimension of the grid
140 ///
141 /// @param[in] fourier_grid Grid in fourier space
142 /// @param[out] pofk Binned power-spectrum
143 ///
144 //==========================================================================================
145 template <int N>
146 void bin_up_power_spectrum(const FFTWGrid<N> & fourier_grid, PowerSpectrumBinning<N> & pofk);
147
148 //==========================================================================================
149 /// @brief Compute the power-spectrum of a fourier grid. The result has no scales. Get
150 /// scales by calling pofk.scale(boxsize) which does \f$ k \to k/B \f$ and
151 /// \f$ P(k) \to B^N P(k) \f$ where \f$ B\f$ is the boxsize once spectrum has been computed. The method assumes
152 /// the two grids are fourier transforms of real grids (i.e. \f$ f(-k) = f^*(k) \f$).
153 /// This method divides the power-spectrum by the square of the window function corresponding to the density
154 /// assignment method for every mode we bin up.
155 ///
156 /// @tparam N Dimension of the grid
157 ///
158 /// @param[in] fourier_grid Grid in fourier space
159 /// @param[out] pofk Binned power-spectrum
160 /// @param[in] density_assignment_method The density assignment method we use to create the grid
161 ///
162 //==========================================================================================
163 template <int N>
164 void bin_up_deconvolved_power_spectrum(const FFTWGrid<N> & fourier_grid,
166 std::string density_assignment_method);
167
168 //==========================================================================================
169 /// @brief Compute the cross power-spectrum of two fourier grids. The result has no scales. Get
170 /// scales by calling pofk.scale(boxsize) which does k\f$ k \to k/B \f$ and
171 /// \f$ P(k) \to B^N P(k) \f$ where \f$ B\f$ is the boxsize once spectrum has been computed. The method assumes
172 /// the two grids are fourier transforms of real grids (i.e. \f$ f(-k) = f^*(k) \f$) and we only bin up the real
173 /// part of \f$ f_1(k)f_2^*(k) \f$. The imaginary part is also binned up, but not returned.
174 ///
175 /// @tparam N Dimension of the grid
176 ///
177 /// @param[in] fourier_grid_1 Grid in fourier space
178 /// @param[in] fourier_grid_2 Grid in fourier space
179 /// @param[out] pofk Binned cross power-spectrum
180 ///
181 //==========================================================================================
182 template <int N>
183 void bin_up_cross_power_spectrum(const FFTWGrid<N> & fourier_grid_1,
184 const FFTWGrid<N> & fourier_grid_2,
186
187 //================================================================================
188 /// @brief Compute power-spectrum multipoles from a Fourier grid
189 /// where we have a fixed line_of_sight_direction (typical coordinate axes like \f$ (0,0,1) \f$).
190 /// Pell contains \f$ P_0,P_1,P_2,\ldots,P_{\ell_{\rm max}} \f$ where \f$ \ell_{\rm max} = n-1 \f$ is the size
191 /// of Pell
192 ///
193 /// @tparam N The dimension of the particles.
194 /// @tparam T The particle class. Must have a get_pos() method.
195 ///
196 /// @param[in] fourier_grid The fourier grid to compute the multipoles from.
197 /// @param[out] Pell Vector of power-spectrum binnings. The size of Pell is the maximum ell to compute.
198 /// All binnings has to have nbins, kmin and kmax set. At the end Pell[ ell ] is a binning of P_ell(k).
199 /// @param[in] line_of_sight_direction The line of sight direction, e.g. \f$ (0,0,1) \f$ for the z-axis.
200 ///
201 //================================================================================
202 template <int N>
204 std::vector<PowerSpectrumBinning<N>> & Pell,
205 std::vector<double> line_of_sight_direction);
206
207 //================================================================================
208 /// @brief A simple power-spectrum estimator for multipoles in simulations.
209 /// Displacing particles from realspace to redshift-space using their velocities
210 /// along each of the coordinate axes. Result is the mean of this.
211 /// Deconvolving the window-function and subtracting shot-noise (1/NumPartTotal) for monopole.
212 ///
213 /// @tparam N The dimension of the particles.
214 /// @tparam T The particle class. Must have a get_pos() method.
215 ///
216 /// @param[in] Ngrid Size of the grid to use.
217 /// @param[in] part Particles in the form of a MPIParticle container
218 /// @param[in] velocity_to_displacement Factor to convert a velocity to a displacement.
219 /// This is \f$ \frac{c}{aH(a)B} \f$ for peculiar and \f$ \frac{c}{H(a)B} \f$ (where \f$ B\f$ is the boxsize)
220 /// for comoving velocities At \f$ z = 0 \f$ velocity_to_displacement = \f$ \frac{1}{100 {\rm Boxsize}} \f$ when
221 /// Boxsize is in Mpc/h
222 /// @param[out] Pell Vector of power-spectrum binnings. The size of Pell is the maximum ell to compute.
223 /// All binnings has to have nbins, kmin and kmax set. At the end Pell[ ell ] is a binning of P_ell(k).
224 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS) to use.
225 /// @param[in] interlacing Use interlaced grids for alias reduction when computing the density field
226 ///
227 //================================================================================
228 template <int N, class T>
231 double velocity_to_displacement,
232 std::vector<PowerSpectrumBinning<N>> & Pell,
233 std::string density_assignment_method,
234 bool interlacing);
235
236 //================================================================================
237 /// @brief Computes the polyspectrum \f$ P(k_1,k_2,\ldots,k_{\rm ORDER}) = \left<\delta(k_1)\cdots\delta(k_{\rm
238 /// ORDER})\right> \f$ from particles. Note that with interlacing we change the particle positions, but when
239 /// returning they should be in the same state as when we started. This method allocates nbins FFTWGrids at the
240 /// same time and performs \f$ 2{\rm nbins} \f$ fourier transforms and does \f$ {\rm nbins}^{\rm ORDER} \f$
241 /// integrals. If one is to compute many spectra with the same Ngrid and binning then one can precompute N123 in
242 /// polyofk and set it using polyofk.set_bincount(N123). This speeds up the polyspectrum estimation by a factor
243 /// of 2. Shot-noise term is subtracted if ORDER=2 (power) or ORDER=3 (bi). Doing this for higher order requires
244 /// all lower order correlators and we currently only bin up the polyspectrum and the power-spectrum.
245 ///
246 /// @tparam N The dimension of the particles.
247 /// @tparam ORDER The order. 2 is the power-spectrum, 3 is the bispectrum, 4 is the trispectrum.
248 ///
249 /// @param[in] Ngrid Size of the grid to use.
250 /// @param[in] part Pointer to the first particle.
251 /// @param[in] NumPart Number of particles on the local task.
252 /// @param[in] NumPartTotal Total number of particles on all tasks.
253 /// @param[out] polyofk The binned polyspectrum. We required it to be initialized with the number of bins, kmin
254 /// and kmax.
255 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS)
256 /// @param[in] interlacing Use interlaced grids when computing density field for alias reduction
257 ///
258 //================================================================================
259 template <int N, class T, int ORDER, bool COMPACT>
260 void compute_polyspectrum(int Ngrid,
261 T * part,
262 size_t NumPart,
263 size_t NumPartTotal,
265 std::string density_assignment_method,
266 bool interlacing);
267
268 //================================================================================
269 /// @brief Computes the polyspectrum \f$ P(k_1,k_2,\ldots,k_{\rm ORDER}) = \left<\delta(k_1)\cdots\delta(k_{\rm
270 /// ORDER})\right> \f$ from a fourier grid. This method allocates
271 /// nbins FFTWGrids at the same time and performs \f$ 2{\rm nbins} \f$ fourier transforms and does \f$ {\rm
272 /// nbins}^{\rm ORDER} \f$ integrals. If one is to compute many spectra with the same Ngrid and binning then one
273 /// can precompute N123 in polyofk and set it using polyofk.set_bincount(N123). This speeds up the polyspectrum
274 /// estimation by a factor of 2 by avoiding half of the fourier transforms.
275 ///
276 /// @tparam N The dimension of the particles.
277 /// @tparam ORDER The order. 2 is the power-spectrum, 3 is the bispectrum, 4 is the trispectrum.
278 ///
279 /// @param[in] fourier_grid Grid in fourier space
280 /// @param[out] polyofk The binned polyspectrum.
281 ///
282 //================================================================================
283 template <int N, int ORDER, bool COMPACT>
284 void compute_polyspectrum(const FFTWGrid<N> & fourier_grid, PolyspectrumBinning<N, ORDER, COMPACT> & polyofk);
285
286 //================================================================================
287 /// @brief Computes the monospectrum \f$ P(k_1,k_2) = \left<\delta(k_1)\delta(k_2)\right> \f$ from a fourier
288 /// grid. This method allocates nbins FFTWGrids at the same time and performs \f$ 2{\rm nbins} \f$ fourier
289 /// transforms and does \f$ {\rm nbins}^{2} \f$ integrals. This is just an alias for compute_polyspectrum<N, 2>
290 ///
291 /// @tparam N The dimension of the particles.
292 /// @tparam T The particle class. Must have a get_pos() method.
293 ///
294 /// @param[in] fourier_grid A fourier grid.
295 /// @param[out] pofk The binned monospectrum. We required it to be initialized with the number of bins, kmin and
296 /// kmax.
297 ///
298 //================================================================================
299 template <int N, bool COMPACT>
301
302 //================================================================================
303 /// @brief Computes the monospectrum \f$ P(k_1,k_2) = \left<\delta(k_1)\delta(k_2)\right> \f$ from particles.
304 /// Note that with interlacing we change the particle positions, but when returning they should be in the same
305 /// state as when we started. This method allocates nbins FFTWGrids at the same time and performs \f$ 2{\rm
306 /// nbins} \f$ fourier transforms and does \f$ {\rm nbins}^{2} \f$ integrals. This is just an alias for
307 /// compute_polyspectrum<N, 2>. Shot-noise is subtracted
308 ///
309 /// @tparam N The dimension of the particles.
310 /// @tparam T The particle class. Must have a get_pos() method.
311 ///
312 /// @param[in] Ngrid Size of the grid to use.
313 /// @param[in] part Pointer to the first particle.
314 /// @param[in] NumPart Number of particles on the local task.
315 /// @param[in] NumPartTotal Total number of particles on all tasks.
316 /// @param[out] pofk The binned monospectrum. We required it to be initialized with the number of bins, kmin and
317 /// kmax.
318 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS)
319 /// @param[in] interlacing Use interlaced grids when computing density field for alias reduction
320 ///
321 //================================================================================
322 template <int N, class T, bool COMPACT>
323 void compute_monospectrum(int Ngrid,
324 T * part,
325 size_t NumPart,
326 size_t NumPartTotal,
328 std::string density_assignment_method,
329 bool interlacing);
330
331 //================================================================================
332 /// @brief Computes the bispectrum \f$ B(k_1,k_2,k_3) = \left<\delta(k_1)\delta(k_2)\delta(k_3)\right> \f$ from
333 /// particles. Note that with interlacing we change the particle positions, but when returning they should be in
334 /// the same state as when we started. This method allocates nbins FFTWGrids at the same time and performs \f$
335 /// 2{\rm nbins} \f$ fourier transforms and does \f$ {\rm nbins}^{3} \f$ integrals. This is just an alias for
336 /// compute_polyspectrum<N, 3>. Shot-noise is subtracted.
337 ///
338 /// @tparam N The dimension of the particles.
339 /// @tparam T The particle class. Must have a get_pos() method.
340 ///
341 /// @param[in] Ngrid Size of the grid to use.
342 /// @param[in] part Pointer to the first particle.
343 /// @param[in] NumPart Number of particles on the local task.
344 /// @param[in] NumPartTotal Total number of particles on all tasks.
345 /// @param[out] bofk The binned bispectrum. We required it to be initialized with the number of bins, kmin and
346 /// kmax.
347 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS)
348 /// @param[in] interlacing Use interlaced grids when computing density field for alias reduction
349 ///
350 //================================================================================
351 template <int N, class T, bool COMPACT>
352 void compute_bispectrum(int Ngrid,
353 T * part,
354 size_t NumPart,
355 size_t NumPartTotal,
357 std::string density_assignment_method,
358 bool interlacing);
359
360 //================================================================================
361 /// @brief Computes the bispectrum \f$ B(k_1,k_2,k_3) = \left<\delta(k_1)\delta(k_2)\delta(k_3)\right> \f$ from
362 /// a fourier grid. This method allocates nbins FFTWGrids at the same time and performs \f$ 2{\rm nbins} \f$
363 /// fourier transforms and does \f$ {\rm nbins}^{3} \f$ integrals. This is just an alias for
364 /// compute_polyspectrum<N, 3>
365 ///
366 /// @tparam N The dimension of the particles.
367 /// @tparam T The particle class. Must have a get_pos() method.
368 ///
369 /// @param[in] fourier_grid A fourier grid.
370 /// @param[out] bofk The binned bispectrum. We required it to be initialized with the number of bins, kmin and
371 /// kmax.
372 ///
373 //================================================================================
374 template <int N, bool COMPACT>
376
377 //================================================================================
378 /// @brief Computes the trispectrum \f$ T(k_1,k_2,k_3,k_4) =
379 /// \left<\delta(k_1)\delta(k_2)\delta(k_3)\delta(k_4)\right> \f$ from a fourier grid. This method allocates
380 /// nbins FFTWGrids at the same time and performs \f$ 2{\rm nbins} \f$ fourier transforms and does \f$ {\rm
381 /// nbins}^{4} \f$ integrals. This is just an alias for compute_polyspectrum<N, 4>
382 ///
383 /// @tparam N The dimension of the particles.
384 /// @tparam T The particle class. Must have a get_pos() method.
385 ///
386 /// @param[in] fourier_grid A fourier grid.
387 /// @param[out] tofk The binned trispectrum. We required it to be initialized with the number of bins, kmin and
388 /// kmax.
389 ///
390 //================================================================================
391 template <int N, bool COMPACT>
393
394 //================================================================================
395 /// @brief Computes the truspectrum \f$ T(k_1,k_2,k_3,k_4) =
396 /// \left<\delta(k_1)\delta(k_2)\delta(k_3)\delta(k_4)\right> \f$ from particles. Note that with interlacing we
397 /// change the particle positions, but when returning they should be in the same state as when we started. This
398 /// method allocates nbins FFTWGrids at the same time and performs \f$ 2{\rm nbins} \f$ fourier transforms and
399 /// does \f$ {\rm nbins}^{4} \f$ integrals. This is just an alias for compute_polyspectrum<N, 4> The shot-noise
400 /// term (something like (B(123) + cyc)/n + (P1P2 + cyc)/n^2 + 1/n^3) is not subtracted as it requires the
401 /// bispectrum which we currently don't bin up together with the trispectrum
402 ///
403 /// @tparam N The dimension of the particles.
404 /// @tparam T The particle class. Must have a get_pos() method.
405 ///
406 /// @param[in] Ngrid Size of the grid to use.
407 /// @param[in] part Pointer to the first particle.
408 /// @param[in] NumPart Number of particles on the local task.
409 /// @param[in] NumPartTotal Total number of particles on all tasks.
410 /// @param[out] tofk The binned trispectrum. We required it to be initialized with the number of bins, kmin and
411 /// kmax.
412 /// @param[in] density_assignment_method The density assignment method (NGP, CIC, TSC, PCS or PQS)
413 /// @param[in] interlacing Use interlaced grids when computing density field for alias reduction
414 ///
415 //================================================================================
416 template <int N, class T, bool COMPACT>
417 void compute_trispectrum(int Ngrid,
418 T * part,
419 size_t NumPart,
420 size_t NumPartTotal,
422 std::string density_assignment_method,
423 bool interlacing);
424
425 //=====================================================================
426 //=====================================================================
427
428 //==========================================================================================
429 // Compute the power-spectrum multipoles of a fourier grid assuming a fixed line of sight
430 // direction (typically coordinate axes). Provide Pell with [ell+1] initialized binnings to compute
431 // the first \f$ 0,1,\ldots,\ell \f$ multipoles The result has no scales. Get scales by scaling
432 // PowerSpectrumBinning using scale(kscale, pofkscale) with kscale = 1/Boxsize
433 // and pofkscale = Boxsize^N once spectrum has been computed
434 //==========================================================================================
435 template <int N>
437 std::vector<PowerSpectrumBinning<N>> & Pell,
438 std::vector<double> line_of_sight_direction) {
439
440 assert_mpi(
441 line_of_sight_direction.size() == N,
442 "[compute_power_spectrum_multipoles_fourier] Line of sight direction has wrong number of dimensions\n");
443 assert_mpi(Pell.size() > 0, "[compute_power_spectrum_multipoles_fourier] Pell must have size > 0\n");
444 assert_mpi(fourier_grid.get_nmesh() > 0,
445 "[compute_power_spectrum_multipoles_fourier] grid must have Nmesh > 0\n");
446
447 int Nmesh = fourier_grid.get_nmesh();
448 auto Local_nx = fourier_grid.get_local_nx();
449 auto Local_x_start = fourier_grid.get_local_x_start();
450
451 // Norm of LOS vector
452 double rmag = 0.0;
453 for (int idim = 0; idim < N; idim++)
454 rmag += line_of_sight_direction[idim] * line_of_sight_direction[idim];
455 rmag = std::sqrt(rmag);
456 assert_mpi(rmag > 0.0,
457 "[compute_power_spectrum_multipoles_fourier] Line of sight vector has zero length\n");
458
459 // Initialize binning just in case
460 for (size_t ell = 0; ell < Pell.size(); ell++)
461 Pell[ell].reset();
462
463 // Bin up mu^k |delta|^2
464#ifdef USE_OMP
465#pragma omp parallel for
466#endif
467 for (int islice = 0; islice < Local_nx; islice++) {
468 [[maybe_unused]] double kmag;
469 [[maybe_unused]] std::array<double, N> kvec;
470 for (auto && fourier_index : fourier_grid.get_fourier_range(islice, islice + 1)) {
471 if (Local_x_start == 0 and fourier_index == 0)
472 continue; // DC mode( k=0)
473
474 // Special treatment of k = 0 plane
475 auto last_coord = fourier_index % (Nmesh / 2 + 1);
476 double weight = FML::GRID::fourier_mode_multiplicity(last_coord, Nmesh);
477
478 // Compute kvec, |kvec| and |delta|^2
479 fourier_grid.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
480 auto delta = fourier_grid.get_fourier_from_index(fourier_index);
481 double power = std::norm(delta);
482
483 // Compute mu = k_vec*r_vec
484 double mu2 = 0.0;
485 for (int idim = 0; idim < N; idim++)
486 mu2 += kvec[idim] * line_of_sight_direction[idim];
487 mu2 /= (kmag * rmag);
488 mu2 = mu2 * mu2;
489
490 // Add to bin |delta|^2, |delta|^2mu^2, |delta^2|mu^4, ...
491 double mutotwoell = 1.0;
492 for (size_t ell = 0; ell < Pell.size(); ell += 2) {
493 Pell[ell].add_to_bin(kmag, power * mutotwoell, weight);
494 mutotwoell *= mu2;
495 }
496 }
497 }
498
499 // Normalize (sums over the threads and the MPI tasks)
500 for (size_t ell = 0; ell < Pell.size(); ell++)
501 Pell[ell].normalize();
502
503 // Binomial coefficient
504 auto binomial = [](int n, int k) -> double {
505 double res = 1.0;
506 for (int i = 0; i < k; i++) {
507 res *= double(n - i) / double(k - i);
508 }
509 return res;
510 };
511
512 // P_ell(x) = Sum_{k=0}^{ell/2} summand_legendre_polynomial * x^(ell - 2k)
513 auto summand_legendre_polynomial = [&](int k, int ell) -> double {
514 double sign = (k % 2) == 0 ? 1.0 : -1.0;
515 return sign * binomial(ell, k) * binomial(2 * ell - 2 * k, ell) / std::pow(2.0, ell);
516 };
517
518 // Go from <mu^k |delta|^2> to (2ell+1) <L_ell(mu) |delta|^2>
519 std::vector<std::vector<double>> temp;
520 for (int ell = 0; ell < int(Pell.size()); ell++) {
521 std::vector<double> sum(Pell[0].pofk.size(), 0.0);
522 for (int k = 0; k <= ell / 2; k++) {
523 std::vector<double> & mu_power = Pell[ell - 2 * k].pofk;
524 for (size_t i = 0; i < sum.size(); i++)
525 sum[i] += mu_power[i] * summand_legendre_polynomial(k, ell) * double(2 * ell + 1);
526 }
527 temp.push_back(sum);
528 }
529
530 // Copy over data. We now have P0,P1,... in Pell
531 for (size_t ell = 0; ell < Pell.size(); ell++) {
532 Pell[ell].pofk = temp[ell];
533 }
534 }
535
536 /// @brief Loop over the local Fourier modes of a 3D grid (except k = 0) in the order of the Fourier index,
537 /// calling f(fourier_index, kvec, |k|, weight) with weight = 2 for the modes with 0 < k_z < k_ny (they also
538 /// represent -k) and 1 otherwise. kvec and |k| are computed exactly as in
539 /// FFTWGrid::get_fourier_wavevector_and_norm_by_index, but without decoding the index (no integer divisions per
540 /// mode). OpenMP over the slices (f must be thread safe)
541 template <class F>
543 const int Nmesh = grid.get_nmesh();
544 const int Local_nx = grid.get_local_nx();
545 const int Local_x_start = grid.get_local_x_start();
546 const int nover2 = Nmesh / 2;
547 const int nover2plus1 = Nmesh / 2 + 1;
548 const double twopi = 2.0 * M_PI;
549#ifdef USE_OMP
550#pragma omp parallel for
551#endif
552 for (int islice = 0; islice < Local_nx; islice++) {
553 std::array<double, 3> kvec;
554 const int ix = islice + Local_x_start;
555 kvec[0] = twopi * double(ix <= nover2 ? ix : ix - Nmesh);
556 for (int iy = 0; iy < Nmesh; iy++) {
557 kvec[1] = twopi * double(iy <= nover2 ? iy : iy - Nmesh);
558 size_t fourier_index = (size_t(islice) * Nmesh + iy) * nover2plus1;
559 for (int iz = 0; iz < nover2plus1; iz++, fourier_index++) {
560 if (Local_x_start == 0 and fourier_index == 0)
561 continue; // DC mode (k=0)
562 kvec[2] = twopi * double(iz <= nover2 ? iz : iz - Nmesh);
563 const double kmag = std::sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2]);
564 const double weight = FML::GRID::fourier_mode_multiplicity(iz, Nmesh);
565 f(fourier_index, kvec, kmag, weight);
566 }
567 }
568 }
569 }
570
571 template <int N>
574 std::string density_assignment_method) {
575
576 assert_mpi(fourier_grid.get_nmesh() > 0, "[bin_up_deconvolved_power_spectrum] grid must have Nmesh > 0\n");
577 assert_mpi(pofk.n > 0 && pofk.kmax > pofk.kmin && pofk.kmin >= 0.0,
578 "[bin_up_deconvolved_power_spectrum] Binning has inconsistent parameters\n");
579
580 const auto Nmesh = fourier_grid.get_nmesh();
581 const auto Local_nx = fourier_grid.get_local_nx();
582 const auto Local_x_start = fourier_grid.get_local_x_start();
583 const FML::INTERPOLATION::WindowFunctionTable<N> window_function(density_assignment_method, Nmesh);
584
585 // Initialize binning just in case
586 pofk.reset();
587
588 // Bin up P(k)
589 if constexpr (N == 3) {
590 // The same as the general loop below (same values and summation order, so identical results)
591 // without decoding every Fourier index into (ix, iy, iz)
593 fourier_grid,
594 [&](size_t fourier_index, const std::array<double, N> & kvec, double kmag, double weight) {
595 auto delta = fourier_grid.get_fourier_from_index(fourier_index);
596 auto delta_norm = std::norm(delta);
597 auto window = window_function(kvec);
598 delta_norm /= (window * window);
599 pofk.add_to_bin(kmag, delta_norm, weight);
600 });
601 pofk.normalize();
602 return;
603 }
604#ifdef USE_OMP
605#pragma omp parallel for
606#endif
607 for (int islice = 0; islice < Local_nx; islice++) {
608 [[maybe_unused]] double kmag;
609 [[maybe_unused]] std::array<double, N> kvec;
610 for (auto && fourier_index : fourier_grid.get_fourier_range(islice, islice + 1)) {
611 if (Local_x_start == 0 and fourier_index == 0)
612 continue; // DC mode( k=0)
613
614 // Special treatment of k = 0 plane (Safer way: fetch coord)
615 // auto coord = fourier_grid.get_fourier_coord_from_index(fourier_index);
616 // int last_coord = coord[N-1];
617 auto last_coord = fourier_index % (Nmesh / 2 + 1);
618 double weight = FML::GRID::fourier_mode_multiplicity(last_coord, Nmesh);
619
620 fourier_grid.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
621
622 auto delta = fourier_grid.get_fourier_from_index(fourier_index);
623 auto delta_norm = std::norm(delta);
624 auto window = window_function(kvec);
625 delta_norm /= (window * window);
626
627 // Add norm to bin
628 pofk.add_to_bin(kmag, delta_norm, weight);
629 }
630 }
631
632 // Normalize to get P(k) (this communicates over tasks)
633 pofk.normalize();
634 }
635
636 // Bin up the power-spectrum of a given fourier grid
637 template <int N>
638 void bin_up_power_spectrum(const FFTWGrid<N> & fourier_grid, PowerSpectrumBinning<N> & pofk) {
639
640 assert_mpi(fourier_grid.get_nmesh() > 0, "[bin_up_power_spectrum] grid must have Nmesh > 0\n");
641 assert_mpi(pofk.n > 0 && pofk.kmax > pofk.kmin && pofk.kmin >= 0.0,
642 "[bin_up_power_spectrum] Binning has inconsistent parameters\n");
643
644 const auto Nmesh = fourier_grid.get_nmesh();
645 const auto Local_nx = fourier_grid.get_local_nx();
646 const auto Local_x_start = fourier_grid.get_local_x_start();
647
648 // Initialize binning just in case
649 pofk.reset();
650
651 // Bin up P(k)
652 if constexpr (N == 3) {
653 // The same as the general loop below (identical results) without decoding the Fourier indices
655 fourier_grid,
656 [&](size_t fourier_index, const std::array<double, N> &, double kmag, double weight) {
657 auto delta = fourier_grid.get_fourier_from_index(fourier_index);
658 auto delta_norm = std::norm(delta);
659 pofk.add_to_bin(kmag, delta_norm, weight);
660 });
661 pofk.normalize();
662 return;
663 }
664#ifdef USE_OMP
665#pragma omp parallel for
666#endif
667 for (int islice = 0; islice < Local_nx; islice++) {
668 [[maybe_unused]] double kmag;
669 [[maybe_unused]] std::array<double, N> kvec;
670 for (auto && fourier_index : fourier_grid.get_fourier_range(islice, islice + 1)) {
671 if (Local_x_start == 0 and fourier_index == 0)
672 continue; // DC mode( k=0)
673
674 // Special treatment of k = 0 plane (Safer way: fetch coord)
675 // auto coord = fourier_grid.get_fourier_coord_from_index(fourier_index);
676 // int last_coord = coord[N-1];
677 auto last_coord = fourier_index % (Nmesh / 2 + 1);
678 double weight = FML::GRID::fourier_mode_multiplicity(last_coord, Nmesh);
679
680 auto delta = fourier_grid.get_fourier_from_index(fourier_index);
681 auto delta_norm = std::norm(delta);
682
683 // Add norm to bin
684 fourier_grid.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
685 pofk.add_to_bin(kmag, delta_norm, weight);
686 }
687 }
688
689 // Normalize to get P(k) (this communicates over tasks)
690 pofk.normalize();
691 }
692
693 // Bin up the cross power-spectrum of a given fourier grids
694 template <int N>
695 void bin_up_cross_power_spectrum(const FFTWGrid<N> & fourier_grid_1,
696 const FFTWGrid<N> & fourier_grid_2,
698
699 assert_mpi(fourier_grid_1.get_nmesh() > 0, "[bin_up_cross_power_spectrum] grid must have Nmesh > 0\n");
700 assert_mpi(fourier_grid_1.get_nmesh() == fourier_grid_2.get_nmesh(),
701 "[bin_up_cross_power_spectrum] Grids must have the same gridsize\n");
702 assert_mpi(pofk.n > 0 && pofk.kmax > pofk.kmin && pofk.kmin >= 0.0,
703 "[bin_up_cross_power_spectrum] Binning has inconsistent parameters\n");
704
705 const auto Nmesh = fourier_grid_1.get_nmesh();
706 const auto Local_nx = fourier_grid_1.get_local_nx();
707 const auto Local_x_start = fourier_grid_1.get_local_x_start();
708
709 // Initialize binning just in case
710 pofk.reset();
711
712 // Take a copy and bin up the imaginary part also
713 PowerSpectrumBinning<N> pofk_imag = pofk;
714 pofk_imag.reset();
715
716 // Bin up P(k)
717#ifdef USE_OMP
718#pragma omp parallel for
719#endif
720 for (int islice = 0; islice < Local_nx; islice++) {
721 [[maybe_unused]] double kmag;
722 [[maybe_unused]] std::array<double, N> kvec;
723 for (auto && fourier_index : fourier_grid_1.get_fourier_range(islice, islice + 1)) {
724 if (Local_x_start == 0 and fourier_index == 0)
725 continue; // DC mode( k=0)
726
727 // Special treatment of k = 0 plane (Safer way: fetch coord)
728 // auto coord = fourier_grid.get_fourier_coord_from_index(fourier_index);
729 // int last_coord = coord[N-1];
730 auto last_coord = fourier_index % (Nmesh / 2 + 1);
731 double weight = FML::GRID::fourier_mode_multiplicity(last_coord, Nmesh);
732
733 auto delta_1 = fourier_grid_1.get_fourier_from_index(fourier_index);
734 auto delta_2 = fourier_grid_2.get_fourier_from_index(fourier_index);
735 auto delta12_real = delta_1.real() * delta_2.real() + delta_1.imag() * delta_2.imag();
736 auto delta12_imag = -delta_1.real() * delta_2.imag() + delta_1.imag() * delta_2.real();
737
738 // Add norm to bin
739 fourier_grid_1.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag);
740 pofk.add_to_bin(kmag, delta12_real, weight);
741 pofk_imag.add_to_bin(kmag, delta12_imag, weight);
742 }
743 }
744
745 // Normalize to get P(k) (this communicates over tasks)
746 pofk.normalize();
747 pofk_imag.normalize();
748
749 // NB: we currently don't return the imaginary part. For real fields this should be zero
750 // so we just check this and give a warning if its large
751 const bool show_warning = false;
752 if (show_warning) {
753 for (int i = 0; i < pofk.n; i++) {
754 if (std::abs(pofk.pofk[i]) < 1e3 * std::abs(pofk_imag.pofk[i]) and
755 std::abs(pofk_imag.pofk[i]) > 1e-15) {
756 std::cout
757 << "Warning: the imaginary part of the cross spectrum is > 0.1%% times the real part [ k: "
758 << pofk.kbin[i] << " Real(d1d2): " << pofk.pofk[i] << " Imag(d1d2): " << pofk_imag.pofk[i]
759 << "]\n";
760 }
761 }
762 }
763 }
764
765 // Brute force. Add particles to the grid using direct summation
766 //================================================================================
767 /// @brief The shot noise of the density field of a set of particles as assigned by particles_to_grid:
768 /// returns \f$ (S_2, S_3) \f$ with \f$ S_n = \sum m_i^n / (\sum m_i)^n \f$ (the shot noise of the
769 /// power spectrum is \f$ S_2 \f$ and the constant term of the bispectrum \f$ S_3 \f$). For equal masses
770 /// this is \f$ (1/N, 1/N^2) \f$. For particles with get_mass the masses are used and for delta-f particles
771 /// (get_deltaf_weight) \f$ S_n = \sum w_i^n / N^n \f$. Sums over the MPI tasks.
772 //================================================================================
773 template <class T>
774 std::pair<double, double> particle_shotnoise(const T * part, size_t NumPart, size_t NumPartTotal) {
775 const double n = double(NumPartTotal);
776 constexpr bool has_deltaf_weight = FML::PARTICLE::has_get_deltaf_weight<T>();
777 constexpr bool has_mass = FML::PARTICLE::has_get_mass<T>() and not has_deltaf_weight;
778 if constexpr (has_mass or has_deltaf_weight) {
779 double sum1 = 0.0, sum2 = 0.0, sum3 = 0.0;
780 for (size_t i = 0; i < NumPart; i++) {
781 double m;
782 if constexpr (has_deltaf_weight)
783 m = FML::PARTICLE::GetDeltafWeight(const_cast<T &>(part[i]));
784 else
785 m = FML::PARTICLE::GetMass(const_cast<T &>(part[i]));
786 sum1 += m;
787 sum2 += m * m;
788 sum3 += m * m * m;
789 }
790 FML::SumOverTasks(&sum1);
791 FML::SumOverTasks(&sum2);
792 FML::SumOverTasks(&sum3);
793 // delta = sum_i w_i W / (N/Nmesh^N) for delta-f particles, sum_i m_i W / (sum m/Nmesh^N) otherwise
794 const double norm = has_deltaf_weight ? n : sum1;
795 return {sum2 / (norm * norm), sum3 / (norm * norm * norm)};
796 }
797 return {1.0 / n, 1.0 / (n * n)};
798 }
799
800 // This gives alias free P(k), but scales as O(Npart)*O(Nmesh^N)
801 template <int N, class T>
803 const T * part,
804 size_t NumPart,
806
807 static_assert(
808 FML::PARTICLE::has_get_pos<T>(),
809 "[compute_power_spectrum_direct_summation] Particle class needs to have positions to use this method");
810
811 // Very simple check to see if all tasks do have the same particles
812 if (FML::NTasks > 1) {
813 long long int tmp1 = NumPart;
814 FML::MinOverTasks(&tmp1);
815 long long int tmp2 = NumPart;
816 FML::MaxOverTasks(&tmp2);
817 double x = FML::PARTICLE::GetPos(const_cast<T &>(part[0]))[0];
818 double y = x;
821 assert_mpi(tmp1 == tmp2 and std::abs(x - y) < 1e-10,
822 "[direct_summation_power_spectrum] All tasks must have the same particles for this method "
823 "to work\n");
824 }
825
826 assert_mpi(Ngrid > 0, "[direct_summation_power_spectrum] Ngrid > 0 required\n");
827 if (NTasks > 1 and ThisTask == 0)
828 std::cout << "[direct_summation_power_spectrum] Warning: this method assumes all tasks have the same "
829 "particles\n";
830
831 const std::complex<FML::GRID::FloatType> I(0, 1);
832 const FML::GRID::FloatType norm = 1.0 / FML::GRID::FloatType(NumPart);
833
834 FFTWGrid<N> density_k(Ngrid, 1, 1);
835 density_k.add_memory_label("FFTWGrid::compute_power_spectrum_direct_summation::density_k");
836 density_k.set_grid_status_real(false);
837
838 for (auto && fourier_index : density_k.get_fourier_range()) {
839 auto kvec = density_k.get_fourier_wavevector_from_index(fourier_index);
840 FML::GRID::FloatType real = 0.0;
841 FML::GRID::FloatType imag = 0.0;
842#ifdef USE_OMP
843#pragma omp parallel for reduction(+ : real, imag)
844#endif
845 for (size_t i = 0; i < NumPart; i++) {
846 const auto * x = FML::PARTICLE::GetPos(const_cast<T &>(part[i]));
847 FML::GRID::FloatType kx = 0.0;
848 for (int idim = 0; idim < N; idim++) {
849 kx += kvec[idim] * x[idim];
850 }
851 auto val = std::exp(-kx * I);
852 real += val.real();
853 imag += val.imag();
854 }
855
856 std::complex<FML::GRID::FloatType> sum = {real, imag};
857 if (ThisTask == 0 and fourier_index == 0)
858 sum -= 1.0;
859 density_k.set_fourier_from_index(fourier_index, sum * norm);
860 }
861
862 // Bin up the power-spectrum
863 bin_up_power_spectrum<N>(density_k, pofk);
864
865 // Subtract shot-noise
866 if (pofk.subtract_shotnoise)
867 for (int i = 0; i < pofk.n; i++)
868 pofk.pofk[i] -= 1.0 / double(NumPart);
869 }
870
871 // Simple method to estimate multipoles from simulation data
872 // Take particles in realspace and use their velocity to put them into
873 // redshift space. Fourier transform and compute multipoles from this like in the method above.
874 // We do this for all coordinate axes and return the mean P0,P1,... we get from this
875 // velocity_to_displacement is factor to convert your velocity to a coordinate shift in [0,1)
876 // e.g. c/(a H Box) with H ~ 100 h km/s/Mpc and Box boxsize in Mpc/h if velocities are peculiar
877 template <int N, class T>
880 double velocity_to_displacement,
881 std::vector<PowerSpectrumBinning<N>> & Pell,
882 std::string density_assignment_method,
883 bool interlacing) {
884
885 // Sanity check
886 static_assert(FML::PARTICLE::has_get_pos<T>(),
887 "[compute_power_spectrum_multipoles] Particle class needs to have positions to use "
888 "this method");
889 static_assert(
890 FML::PARTICLE::has_get_vel<T>(),
891 "[compute_power_spectrum_multipoles] Particle class needs to have velocity to use this method");
892
893 // Set how many extra slices we need for the density assignment to go smoothly
894 // One extra slice if we use interlacing due to displacing particles by one half cell to the right
895 const auto nleftright = get_extra_slices_needed_for_density_assignment(density_assignment_method);
896 const int nleft = nleftright.first;
897 const int nright = nleftright.second + (interlacing ? 1 : 0);
898
899 // Initialize binning just in case
900 for (size_t ell = 0; ell < Pell.size(); ell++)
901 Pell[ell].reset();
902
903 // Set a binning for each axes
904 std::vector<std::vector<PowerSpectrumBinning<N>>> Pell_all(N);
905 for (int idim = 0; idim < N; idim++) {
906 Pell_all[idim] = Pell;
907 }
908
909 // Allocate density grid
910 FFTWGrid<N> density_k(Ngrid, nleft, nright);
911 density_k.add_memory_label("FFTWGrid::compute_power_spectrum_multipoles::density_k");
912
913 // Loop over all the N axes we are going to put the particles
914 // into redshift space
915 for (int idim = 0; idim < N; idim++) {
916
917 // Set up binning for current axis
918 std::vector<PowerSpectrumBinning<N>> Pell_current = Pell_all[idim];
919 for (size_t ell = 0; ell < Pell_current.size(); ell++)
920 Pell_current[ell].reset();
921
922 // Make line of sight direction unit vector
923 std::vector<double> line_of_sight_direction(N, 0.0);
924 line_of_sight_direction[idim] = 1.0;
925
926 // Transform to redshift-space
927 FML::COSMOLOGY::particles_to_redshiftspace(part, line_of_sight_direction, velocity_to_displacement);
928
929 // Bin particles to grid
930 density_k.set_grid_status_real(true);
931 if (interlacing) {
932
933 // Bin to grid and interlaced grid and deconvolve window function
935 part.get_npart(),
936 part.get_npart_total(),
937 density_k,
938 density_assignment_method);
939 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
940
941 } else {
942
943 // Bin to grid, fourier transform and deconvolve window function
945 part.get_npart(),
946 part.get_npart_total(),
947 density_k,
948 density_assignment_method);
949 density_k.fftw_r2c();
950 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
951 }
952
953 // Compute power-spectrum multipoles
954 compute_power_spectrum_multipoles_fourier(density_k, Pell_current, line_of_sight_direction);
955
956 // Copy over binning we computed
957 Pell_all[idim] = Pell_current;
958
959 // Transform particles back to real-space (we don't want to ruin the particles)
960 // Ideally we should have taken a copy, but this is fine
961 FML::COSMOLOGY::particles_to_redshiftspace(part, line_of_sight_direction, -velocity_to_displacement);
962 }
963
964 // Normalize
965 for (size_t ell = 0; ell < Pell.size(); ell++) {
966 for (int idim = 0; idim < N; idim++) {
967 Pell[ell] += Pell_all[idim][ell];
968 }
969 }
970 for (size_t ell = 0; ell < Pell.size(); ell++) {
971 for (int i = 0; i < Pell[ell].n; i++) {
972 Pell[ell].pofk[i] /= double(N);
973 Pell[ell].count[i] /= double(N);
974 Pell[ell].kbin[i] /= double(N);
975 }
976 }
977
978 // XXX Compute variance of pofk
979
980 // Subtract shotnoise for monopole
981 if (Pell[0].subtract_shotnoise) {
982 const double shotnoise =
984 for (int i = 0; i < Pell[0].n; i++) {
985 Pell[0].pofk[i] -= shotnoise;
986 }
987 }
988 }
989
990 //================================================================================
991 // A simple power-spectrum estimator - nothing fancy
992 // Deconvolving the window-function and subtracting shot-noise (1/NumPartTotal)
993 //================================================================================
994 template <int N, class T>
996 T * part,
997 size_t NumPart,
998 size_t NumPartTotal,
1000 std::string density_assignment_method,
1001 bool interlacing) {
1002
1003 // Set how many extra slices we need for the density assignment to go smoothly
1004 const auto nleftright = get_extra_slices_needed_for_density_assignment(density_assignment_method);
1005 const int nleft = nleftright.first;
1006 const int nright = nleftright.second + (interlacing ? 1 : 0);
1007
1008 // Bin particles to grid
1009 FFTWGrid<N> density_k(Ngrid, nleft, nright);
1010 density_k.add_memory_label("FFTWGrid::compute_power_spectrum::density_k");
1011
1012 if (interlacing) {
1013
1014 // Bin to grid using interlaced grids to produce a fourier space density field
1016 NumPart,
1017 NumPartTotal,
1018 density_k,
1019 density_assignment_method);
1020 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
1021
1022 } else {
1023
1024 // Bin to grid, fourier transform and deconvolves the window function
1025 particles_to_grid<N, T>(part, NumPart, NumPartTotal, density_k, density_assignment_method);
1026 density_k.fftw_r2c();
1027 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
1028 }
1029
1030 // Bin up power-spectrum
1031 bin_up_power_spectrum<N>(density_k, pofk);
1032
1033 // Subtract shotnoise
1034 if (pofk.subtract_shotnoise) {
1035 const double shotnoise = particle_shotnoise(part, NumPart, NumPartTotal).first;
1036 for (int i = 0; i < pofk.n; i++) {
1037 pofk.pofk[i] -= shotnoise;
1038 }
1039 }
1040 }
1041
1042 // https://arxiv.org/pdf/1506.02729.pdf
1043 // The general quadrupole estimator Eq. 20
1044 // P(k) = <delta0(k)delta2^*(k>>
1045 // We compute delta0 and delta2
1046 // template<int N>
1047 // void quadrupole_estimator_3D(FFTWGrid<N> & density_real)
1048 // {
1049
1050 // FFTWGrid<N> Q_xx, Q_yy, Q_zz, Q_xy, Q_yz, Q_zx;
1051
1052 // compute_multipole_Q_term(density_real, Q_xx, {0,0}, origin);
1053 // compute_multipole_Q_term(density_real, Q_xy, {0,1}, origin);
1054 // compute_multipole_Q_term(density_real, Q_yy, {1,1}, origin);
1055 // Q_xx.fftw_r2c();
1056 // Q_xy.fftw_r2c();
1057 // Q_yy.fftw_r2c();
1058 // if constexpr (N > 2){
1059 // compute_multipole_Q_term(density_real, Q_yz, {1,2}, origin);
1060 // compute_multipole_Q_term(density_real, Q_zx, {2,0}, origin);
1061 // compute_multipole_Q_term(density_real, Q_zz, {2,2}, origin);
1062 // Q_yz.fftw_r2c();
1063 // Q_zx.fftw_r2c();
1064 // Q_zz.fftw_r2c();
1065 // }
1066
1067 // // Density to fourier space
1068 // density_real.fftw_r2c();
1069
1070 // FFTWGrid<N> delta2 = density_real;
1071
1072 // double kmag;
1073 // std::array<double,N> kvec;
1074 // for(auto & fourier_index : density_real.get_fourier_range()){
1075 // density_real.get_fourier_wavevector_and_norm_by_index(fourier_index, kvec, kmag2);
1076
1077 // // Unit kvector
1078 // if(kmag > 0.0)
1079 // for(auto & k : kvec)
1080 // k /= kmag;
1081
1082 // auto Q_xx_of_k = Q_xx.get_fourier_from_index(fourier_index);
1083 // auto Q_xy_of_k = Q_xy.get_fourier_from_index(fourier_index);
1084 // auto Q_yy_of_k = Q_yy.get_fourier_from_index(fourier_index);
1085
1086 // auto Q_yz_of_k = Q_yz.get_fourier_from_index(fourier_index);
1087 // auto Q_zx_of_k = Q_zx.get_fourier_from_index(fourier_index);
1088 // auto Q_zz_of_k = Q_zz.get_fourier_from_index(fourier_index);
1089 // auto delta0 = density_real.get_fourier_from_index(fourier_index);
1090
1091 // auto res = Q_xx_of_k * kvec[0] * kvec[0] + Q_yy_of_k * kvec[1] * kvec[1] + 2.0 * (Q_xy_of_k *
1092 // kvec[0] * kvec[1])
1093 // if constexpr (N > 2) res += Q_zz_of_k * kvec[2] * kvec[2] + 2.0 * (Q_yz_of_k * kvec[1] *
1094 // kvec[2] + Q_zx_of_k * kvec[2] * kvec[0]);
1095 // res = 1.5 * res - 0.5 * delta0;
1096
1097 // delta2.set_real_from_fourier(fourier_index, res);
1098 // }
1099 // }
1100
1101 // Compute delta(x) -> delta(x) * xi * xj * xk * .... (i,j,k,... in Qindex)
1102 // where xi's being the i'th component of the unit norm line of sight direction
1103 // For the quadrupole we put Qindex = {ii,jj} and we need the 6 combinations xx,yy,zz,xy,yz,zx
1104 // For the hexadecapole we need {ii,jj,kk,ll} for 15 different combinations
1105 // xxxx + cyc (3), xxxy + cyc, xxyy + cyc and xxyz + cyc
1106 // template<int N>
1107 // void compute_multipole_Q_term(
1108 // FFTWGrid<N> & density_real,
1109 // FFTWGrid<N> & Q_real,
1110 // std::vector<int> Qindex,
1111 // std::vector<double> origin)
1112 // {
1113 // assert(Qindex.size() > 0);
1114 // assert(origin.size() == N);
1115
1116 // for(auto && real_index : density_real.get_real_range()){
1117 // auto coord = density_real.get_coord_from_index(real_index);
1118 // auto pos = density_real.get_real_position(coord);
1119
1120 // double norm = 0.0;
1121 // for(int idim = 0; idim < N; idim++){
1122 // pos[idim] -= origin[idim];
1123 // norm += pos[idim]*pos[idim];
1124 // }
1125 // norm = std::sqrt(norm);
1126 // for(int idim = 0; idim < N; idim++){
1127 // pos[idim] /= norm;
1128 // }
1129 // auto value = density_real.get_real_from_index(real_index);
1130 // for(auto ii: Qindex)
1131 // value *= pos[ii];
1132
1133 // Q_real.set_real_from_index(real_index, value);
1134 // }
1135 // }
1136
1137 template <int N, class T, bool COMPACT>
1138 void compute_monospectrum(int Ngrid,
1139 T * part,
1140 size_t NumPart,
1141 size_t NumPartTotal,
1143 std::string density_assignment_method,
1144 bool interlacing) {
1145
1146 // This will subtract shot-noise if pofk.subtract_shotnoise = true
1148 part,
1149 NumPart,
1150 NumPartTotal,
1151 pofk,
1152 density_assignment_method,
1153 interlacing);
1154 }
1155
1156 template <int N, class T, bool COMPACT>
1157 void compute_bispectrum(int Ngrid,
1158 T * part,
1159 size_t NumPart,
1160 size_t NumPartTotal,
1162 std::string density_assignment_method,
1163 bool interlacing) {
1164
1165 // This will subtract shot-noise if bofk.subtract_shotnoise = true
1167 part,
1168 NumPart,
1169 NumPartTotal,
1170 bofk,
1171 density_assignment_method,
1172 interlacing);
1173 }
1174
1175 template <int N, class T, bool COMPACT>
1176 void compute_trispectrum(int Ngrid,
1177 T * part,
1178 size_t NumPart,
1179 size_t NumPartTotal,
1181 std::string density_assignment_method,
1182 bool interlacing) {
1184 part,
1185 NumPart,
1186 NumPartTotal,
1187 tofk,
1188 density_assignment_method,
1189 interlacing);
1190 }
1191
1192 // Computes the polyspectrum P(k1,k2,k3,...)
1193 template <int N, class T, int ORDER, bool COMPACT>
1194 void compute_polyspectrum(int Ngrid,
1195 T * part,
1196 size_t NumPart,
1197 size_t NumPartTotal,
1199 std::string density_assignment_method,
1200 bool interlacing) {
1201
1202 // Set how many extra slices we need for the density assignment to go smoothly
1203 const auto nleftright = get_extra_slices_needed_for_density_assignment(density_assignment_method);
1204 const int nleft = nleftright.first;
1205 const int nright = nleftright.second + 1;
1206
1207 FFTWGrid<N> density_k(Ngrid, nleft, nright);
1208 density_k.add_memory_label("FFTWGrid::compute_polyspectrum::density_k");
1209
1210 if (interlacing) {
1211
1212 // Bin particles to grid (use interlaced to reduce alias) and deconvolve window
1214 NumPart,
1215 NumPartTotal,
1216 density_k,
1217 density_assignment_method);
1218 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
1219
1220 } else {
1221
1222 // Bin to grid, fourier transform and deconvolve window function
1223 particles_to_grid<N, T>(part, NumPart, NumPartTotal, density_k, density_assignment_method);
1224 density_k.fftw_r2c();
1225 deconvolve_window_function_fourier<N>(density_k, density_assignment_method);
1226 }
1227
1228 // Compute polyspectrum
1229 compute_polyspectrum<N, ORDER>(density_k, polyofk);
1230
1231 // Subtract shotnoise if ORDER = 2 or 3
1232 if constexpr (ORDER == 2) {
1233 // Subtract shot-noise (along the diagonal)
1234 if (polyofk.subtract_shotnoise) {
1235 const double shotnoise = particle_shotnoise(part, NumPart, NumPartTotal).first;
1236 for (int i = 0; i < polyofk.n; i++) {
1237 polyofk.pofk[i] -= shotnoise;
1238 std::array<int, 2> ik{i, i};
1239 if (polyofk.get_bincount(ik) > 0.0)
1240 polyofk.P123[polyofk.get_index_from_coord(ik)] -= shotnoise;
1241 }
1242 }
1243 } else if constexpr (ORDER == 3) {
1244 // Subtract shot-noise for both P(k) and B(k1,k2,k3)
1245 if (polyofk.subtract_shotnoise) {
1246 // S2 = 1/n and S3 = 1/n^2 for equal masses (sum m^2/(sum m)^2 and sum m^3/(sum m)^3 otherwise)
1247 const auto [S2, S3] = particle_shotnoise(part, NumPart, NumPartTotal);
1248 for (int i = 0; i < polyofk.n; i++) {
1249 polyofk.pofk[i] -= S2;
1250 }
1251 // For Poisson sampling <d1 d2 d3> = B + (P1 + P2 + P3) S2 + S3 with P the shot noise
1252 // subtracted power spectrum (which pofk is now)
1253 for (size_t i = 0; i < polyofk.P123.size(); i++) {
1254 if (polyofk.N123[i] <= 0.0)
1255 continue;
1256 auto ik = polyofk.get_coord_from_index(i);
1257 polyofk.P123[i] -= S2 * (polyofk.pofk[ik[0]] + polyofk.pofk[ik[1]] + polyofk.pofk[ik[2]]) + S3;
1258 }
1259 }
1260 }
1261 }
1262
1263 namespace detail {
1264 template <int ORDER>
1265 int polyspectrum_work_mesh(int nmesh, const std::vector<double> & khigh, bool dealias) {
1266 if (!dealias || ORDER == 2 || ORDER * *std::max_element(khigh.begin(), khigh.end()) < 2 * M_PI * nmesh)
1267 return nmesh;
1268 // Only the zero mode of the ORDER-fold product is needed. Excluding
1269 // input Nyquist planes gives |sum n_i| < ORDER*Nmesh/2 in each axis.
1270 const long long multiple = std::lcm(2LL, static_cast<long long>(FML::NTasks));
1271 const long long minimum = (ORDER * static_cast<long long>(nmesh) + 1) / 2;
1272 const long long padded = ((minimum + multiple - 1) / multiple) * multiple;
1273 assert_mpi(padded <= INT_MAX, "[polyspectrum] Padded mesh exceeds int range");
1274 return int(padded);
1275 }
1276 template <int N, int ORDER>
1277 bool polyspectrum_uses_mode(const FFTWGrid<N> & grid,
1278 const std::array<double, N> & wave,
1279 double k2,
1280 double low2,
1281 double high2,
1282 bool dealias) {
1283 if (!(k2 > 0 && k2 >= low2 && k2 < high2))
1284 return false;
1285 if (dealias && ORDER > 2 && grid.get_nmesh() % 2 == 0)
1286 for (auto k : wave)
1287 if (std::abs(k) >= M_PI * grid.get_nmesh())
1288 return false;
1289 return true;
1290 }
1291 } // namespace detail
1292
1293 //================================================================================
1294 /// @brief This method is used by compute_polyspectrum. It computes the number of
1295 /// generalized triangles of the bins needed to normalize the polyspectra up to symmetry (i.e. we only compute
1296 /// it for \f$ k_1 \leq k_2 \leq k_3 \f$ and only for valid triangle configurations \f$ k_1 + k_2 \geq k_3 \f$
1297 /// and then set rest using symmetry). If one is to compute many spectra with the same Nmesh and binning then
1298 /// one can precompute N123 and set it using polyofk.set_bincount(N123) (which sets polyofk.bincount_is_set =
1299 /// true and avoid a call to this function). Counts computed here are cached automatically; reuse checks
1300 /// the source mesh, shell edges and closure policy. Prefer set_bincount(counts, Nmesh) for imported data.
1301 ///
1302 /// @tparam N The dimension we work in
1303 /// @tparam ORDER The order (mono = 2, bi = 3, tri = 4)
1304 ///
1305 /// @param[in] Nmesh The size of the grid we us
1306 /// @param[out] polyofk The binning (we compute and store the volumes of each bin, N123, in this binning).
1307 ///
1308 //================================================================================
1309 template <int N, int ORDER, bool COMPACT>
1311 assert_mpi(Nmesh > 0 && bins.n > 0 && bins.klow.size() == size_t(bins.n) &&
1312 bins.khigh.size() == size_t(bins.n),
1313 "[compute_polyspectrum_bincount] Mesh and shell binning must be initialized");
1314 bins.prepare_storage();
1315 assert_mpi(bins.valid_storage(), "[compute_polyspectrum_bincount] Invalid result storage");
1316 bins.statistics = {};
1317 const auto configs = bins.configurations();
1318 bins.statistics.memory.configuration_bytes = configs.capacity() * sizeof(configs[0]);
1319 double requested_kmax = 0;
1320 for (const auto & cfg : configs)
1321 for (auto bin : cfg)
1322 requested_kmax = std::max(requested_kmax, bins.khigh[bin]);
1323 const int mesh = detail::polyspectrum_work_mesh<ORDER>(Nmesh, {requested_kmax}, bins.dealias);
1324 auto build = [&](int bin) {
1325 FFTWGrid<N> field(Nmesh);
1326 field.set_grid_status_real(false);
1327 for (auto index : field.get_fourier_range()) {
1328 std::array<double, N> wave;
1329 double k2;
1332 index,
1333 detail::polyspectrum_uses_mode<N, ORDER>(field,
1334 wave,
1335 k2,
1336 bins.klow[bin] * bins.klow[bin],
1337 bins.khigh[bin] * bins.khigh[bin],
1338 bins.dealias) ?
1339 1.0 :
1340 0.0);
1341 }
1342 if (mesh != Nmesh) {
1343 auto & memory = bins.statistics.memory;
1344 memory.padding_source_bytes =
1345 std::max(memory.padding_source_bytes, field.allocated_storage_bytes());
1346 FFTWGrid<N> padded(mesh);
1347 FML::GRID::FourierResamplingPlan<N> plan(field, padded);
1348 plan.apply(field, padded);
1349 memory.remapping_bytes = std::max(memory.remapping_bytes, plan.workspace_storage_bytes());
1350 field = std::move(padded);
1351 }
1352 field.fftw_c2r();
1353 return field;
1354 };
1355 detail::ShellCache<N, ORDER> cache(bins.n,
1356 mesh,
1357 configs,
1358 bins.options,
1359 bins.statistics,
1361 build);
1362 std::fill(bins.N123.begin(), bins.N123.end(), 0.0);
1363 const double measure = std::pow(2 * M_PI, N);
1364 const double norm = std::pow(1.0 / mesh / (2 * M_PI), N);
1365 detail::integrate_configurations<N, ORDER>(
1366 cache,
1367 configs,
1370 [&](auto cfg, double sum) {
1371 double value = sum * norm;
1372 if (value * measure < 0.5)
1373 value = 0;
1374 detail::store_permutations<N, ORDER>(bins, bins.N123, cfg, value);
1375 });
1377 detail::finish_memory_report(bins);
1378 }
1379
1380 template <int N, bool COMPACT>
1382 compute_polyspectrum<N, 2>(fourier_grid, pofk);
1383 }
1384
1385 template <int N, bool COMPACT>
1387 compute_polyspectrum<N, 3>(fourier_grid, bofk);
1388 }
1389
1390 template <int N, bool COMPACT>
1392 compute_polyspectrum<N, 4>(fourier_grid, tofk);
1393 }
1394
1395 template <int N, int ORDER, bool COMPACT>
1397 static_assert(ORDER > 1);
1398 const int Nmesh = input.get_nmesh();
1399 assert_mpi(Nmesh > 0 && bins.n > 0 && bins.klow.size() == size_t(bins.n) &&
1400 bins.khigh.size() == size_t(bins.n) && bins.pofk.size() == size_t(bins.n) &&
1401 bins.kmean.size() == size_t(bins.n),
1402 "[compute_polyspectrum] Invalid grid or binning");
1403 bins.prepare_storage();
1404 assert_mpi(bins.valid_storage(), "[compute_polyspectrum] Invalid result storage");
1405 bins.statistics = {};
1406 if (!bins.has_bincount(Nmesh))
1408 const auto configs = bins.configurations();
1409 bins.statistics.memory.configuration_bytes = configs.capacity() * sizeof(configs[0]);
1410 double requested_kmax = 0;
1411 for (const auto & cfg : configs)
1412 for (auto bin : cfg)
1413 requested_kmax = std::max(requested_kmax, bins.khigh[bin]);
1414 const int mesh = detail::polyspectrum_work_mesh<ORDER>(Nmesh, {requested_kmax}, bins.dealias);
1415 // Auxiliary P(k) and mean k cover every shell, including unrequested configurations.
1416 // Their statistics require no shell meshes and one array reduction.
1417 const size_t metadata_count = 3 * size_t(bins.n);
1418 assert_mpi(metadata_count <= size_t(INT_MAX), "[polyspectrum] Too many shell statistics for MPI");
1419 std::vector<double> metadata(metadata_count, 0.0);
1420 for (auto index : input.get_fourier_range()) {
1421 std::array<double, N> wave;
1422 double k2;
1424 for (int bin = 0; bin < bins.n; bin++) {
1425 if (!detail::polyspectrum_uses_mode<N, ORDER>(input,
1426 wave,
1427 k2,
1428 bins.klow[bin] * bins.klow[bin],
1429 bins.khigh[bin] * bins.khigh[bin],
1430 bins.dealias))
1431 continue;
1432 const double weight = FML::GRID::fourier_mode_multiplicity(int(index % (Nmesh / 2 + 1)), Nmesh);
1433 metadata[3 * bin] += weight * std::sqrt(k2);
1434 metadata[3 * bin + 1] += weight * std::norm(input.get_fourier_from_index(index));
1435 metadata[3 * bin + 2] += weight;
1436 }
1437 }
1438 FML::SumArrayOverTasks(metadata.data(), metadata.size());
1440 bins.statistics.memory.metadata_work_bytes = metadata.capacity() * sizeof(double);
1442 for (int bin = 0; bin < bins.n; bin++) {
1443 const double count = metadata[3 * bin + 2];
1444 bins.kmean[bin] = count ? metadata[3 * bin] / count : bins.kbin[bin];
1445 bins.pofk[bin] = count ? metadata[3 * bin + 1] / count : 0.0;
1446 }
1447 auto build = [&](int bin) {
1448 FFTWGrid<N> field(Nmesh);
1449 field.set_grid_status_real(false);
1450 for (auto index : input.get_fourier_range()) {
1451 std::array<double, N> wave;
1452 double k2;
1454 const bool use = detail::polyspectrum_uses_mode<N, ORDER>(input,
1455 wave,
1456 k2,
1457 bins.klow[bin] * bins.klow[bin],
1458 bins.khigh[bin] * bins.khigh[bin],
1459 bins.dealias);
1460 field.set_fourier_from_index(index, use ? input.get_fourier_from_index(index) : 0.0);
1461 }
1462 if (mesh != Nmesh) {
1463 auto & memory = bins.statistics.memory;
1464 memory.padding_source_bytes =
1465 std::max(memory.padding_source_bytes, field.allocated_storage_bytes());
1466 FFTWGrid<N> padded(mesh);
1467 FML::GRID::FourierResamplingPlan<N> plan(field, padded);
1468 plan.apply(field, padded);
1469 memory.remapping_bytes = std::max(memory.remapping_bytes, plan.workspace_storage_bytes());
1470 field = std::move(padded);
1471 }
1472 field.fftw_c2r();
1473 return field;
1474 };
1475 detail::ShellCache<N, ORDER>
1476 cache(bins.n, mesh, configs, bins.options, bins.statistics, bins.statistics.field_shell_builds, build);
1477 std::fill(bins.P123.begin(), bins.P123.end(), 0.0);
1478 const double norm = std::pow(1.0 / mesh / (2 * M_PI), N);
1479 detail::integrate_configurations<N, ORDER>(
1480 cache,
1481 configs,
1484 [&](auto cfg, double sum) {
1485 const double count = bins.N123[bins.get_index_from_coord(cfg)];
1486 detail::store_permutations<N, ORDER>(bins, bins.P123, cfg, count > 0 ? sum * norm / count : 0.0);
1487 });
1488 detail::finish_memory_report(bins);
1489 }
1490 } // namespace CORRELATIONFUNCTIONS
1491} // namespace FML
1492
1493#endif
double f
Definition Minimizer.cpp:28
const int Nmesh
Definition Main.cpp:48
std::array< int, 3 > wave(const Grid &grid, ptrdiff_t index)
Definition Main.cpp:101
Dense results by default; COMPACT stores one slot per canonical tuple.
std::vector< double > pofk
The power-spectrum.
std::array< int, ORDER > get_coord_from_index(size_t index)
The coord (k1,k2,...) corresponding to a given index in the P123 and N123 array These methods determi...
size_t get_index_from_coord(const std::array< int, ORDER > &ik)
std::vector< double > khigh
khigh is higher bin edge
double get_bincount(const std::array< int, ORDER > &ik)
Returns the volume factor N123.
std::vector< double > P123
The polyspectrum.
std::vector< double > kmean
kmean is the mean of wavenumbers added to the bin
std::vector< double > kbin
kbin is center of bin
std::vector< double > N123
The volume (number of generalized triangles) of each bin.
void prepare_storage()
Allocate compact results only when needed. No dense tensor is constructed.
std::vector< double > klow
klow is lower bin edge
bool dealias
True integer-wavevector closure.
bool subtract_shotnoise
Subtract shotnoise? Algorithms (compute_polyspectrum) using this class checks this value.
Class for holding the results after binning up a power-spectrum.
void reset()
Reset everything. Call before starting to bim.
void add_to_bin(double kvalue, double power, double weight=1.0)
Add a new point to a bin.
void normalize()
Normalize (i.e. find mean in each bin) Do summation over MPI tasks.
std::vector< double > pofk
The power-spectrum in the bin.
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 fftw_c2r()
Perform complex-to-real fourier transform.
Definition FFTWGrid.h:1132
void add_memory_label(std::string label)
For memory logging: add a label to the grid.
Definition FFTWGrid.h:404
ptrdiff_t get_local_x_start() const
The x-slice the first local slice has in the global grid.
Definition FFTWGrid.h:1260
ptrdiff_t get_local_nx() const
Number of local x-slices in the real grid.
Definition FFTWGrid.h:1255
void set_fourier_from_index(const IndexIntType ind, const ComplexType value)
Set value of cell in fourier grid using (local) index.
Definition FFTWGrid.h:1212
ComplexType get_fourier_from_index(const IndexIntType index) const
Fetch value in fourier grid by (local) index.
Definition FFTWGrid.h:1207
std::array< double, N > get_fourier_wavevector_from_index(const IndexIntType index) const
Get the wave-vector of a grid-cell in Fourier space (for physical [k] multiply by 1/Boxsize)
Definition FFTWGrid.h:1358
FourierRange get_fourier_range(int islice_begin=0, int islice_end=0) const
Range iterator for going through all active cells in the main fourier grid by index [ e....
Definition FFTWGrid.h:507
void fftw_r2c()
Perform real-to-complex fourier transform.
Definition FFTWGrid.h:1077
void 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
size_t allocated_storage_bytes() const
Actual retained payload capacity, including halos/padding; excludes object/allocator overhead.
Definition FFTWGrid.h:310
Reusable geometry for normalized, non-transposed FFTWGrid slab layouts.
void apply(const Grid &input, Grid &output, size_t max_message_bytes=64 *1024 *1024)
Collective; reuse with different fields having the same meshes and local slab geometry.
size_t workspace_storage_bytes() const
Geometry plus the larger of construction scratch or retained payload buffers.
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...
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.
size_t get_npart() const
Number of active particles on the local task.
void compute_polyspectrum_bincount(int Nmesh, PolyspectrumBinning< N, ORDER, COMPACT > &bins)
This method is used by compute_polyspectrum.
void compute_monospectrum(const FFTWGrid< N > &fourier_grid, MonospectrumBinning< N, COMPACT > &pofk)
Computes the monospectrum from a fourier grid.
void compute_power_spectrum_multipoles_fourier(const FFTWGrid< N > &fourier_grid, std::vector< PowerSpectrumBinning< N > > &Pell, std::vector< double > line_of_sight_direction)
Compute power-spectrum multipoles from a Fourier grid where we have a fixed line_of_sight_direction (...
void bin_up_deconvolved_power_spectrum(const FFTWGrid< N > &fourier_grid, PowerSpectrumBinning< N > &pofk, std::string density_assignment_method)
Compute the power-spectrum of a fourier grid.
void compute_power_spectrum(int Ngrid, T *part, size_t NumPart, size_t NumPartTotal, PowerSpectrumBinning< N > &pofk, std::string density_assignment_method, bool interlacing)
Assign particles to grid using density_assignment_method = NGP,CIC,TSC,PCS,... Fourier transform,...
void compute_trispectrum(const FFTWGrid< N > &fourier_grid, TrispectrumBinning< N, COMPACT > &tofk)
Computes the trispectrum from a fourier grid.
void bin_up_power_spectrum(const FFTWGrid< N > &fourier_grid, PowerSpectrumBinning< N > &pofk)
Compute the power-spectrum of a fourier grid.
void compute_power_spectrum_multipoles(int Ngrid, FML::PARTICLE::MPIParticles< T > &part, double velocity_to_displacement, std::vector< PowerSpectrumBinning< N > > &Pell, std::string density_assignment_method, bool interlacing)
A simple power-spectrum estimator for multipoles in simulations.
void compute_power_spectrum_direct_summation(int Ngrid, const T *part, size_t NumPart, PowerSpectrumBinning< N > &pofk)
Brute force (but aliasing free) computation of the power spectrum.
void compute_bispectrum(int Ngrid, T *part, size_t NumPart, size_t NumPartTotal, BispectrumBinning< N, COMPACT > &bofk, std::string density_assignment_method, bool interlacing)
Computes the bispectrum from particles.
void bin_up_fourier_modes_3d(const FFTWGrid< 3 > &grid, F &&f)
Loop over the local Fourier modes of a 3D grid (except k = 0) in the order of the Fourier index,...
void compute_polyspectrum(int Ngrid, T *part, size_t NumPart, size_t NumPartTotal, PolyspectrumBinning< N, ORDER, COMPACT > &polyofk, std::string density_assignment_method, bool interlacing)
Computes the polyspectrum from particles.
std::pair< double, double > particle_shotnoise(const T *part, size_t NumPart, size_t NumPartTotal)
The shot noise of the density field of a set of particles as assigned by particles_to_grid: returns ...
void bin_up_cross_power_spectrum(const FFTWGrid< N > &fourier_grid_1, const FFTWGrid< N > &fourier_grid_2, PowerSpectrumBinning< N > &pofk)
Compute the cross power-spectrum of two fourier grids.
void particles_to_redshiftspace(FML::PARTICLE::MPIParticles< T > &part, std::vector< double > line_of_sight_direction, double velocity_to_displacement)
This takes a set of particles and displace them from realspace to redshiftspace Using a fixed line of...
int fourier_mode_multiplicity(int last_coord, int nmesh)
Number of full-complex modes represented by a stored r2c coefficient.
Definition FFTWGrid.h:36
This namespace deals with interpolation and density assignment.
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 ...
void particles_to_fourier_grid_interlacing(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density_grid_fourier, std::string density_assignment_method)
Internal method.
void deconvolve_window_function_fourier(FFTWGrid< N > &fourier_grid, std::string density_assignment_method)
Deconvolves the density assignment kernel in Fourier space.
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.
get_vel constexpr double * GetPos(...)
set_mass constexpr double GetMass(Args &... args)
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
return y
Definition Global.h:365
int ThisTask
The MPI task number.
Definition Global.cpp:39
void SumArrayOverTasks(T *value, size_t n)
Inplace sum over tasks of a contiguous array of values.
Definition Global.h:248
void SumOverTasks(T *value)
Inplace sum over tasks of a single value.
Definition Global.h:229
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40
size_t reduction_batch_size
Canonical configurations per collective; zero requests one batch (up to INT_MAX).
constexpr int mesh
Binning measure(double fnl, unsigned int seed)
Definition test_fnl.cpp:121
Vector grid(size_t n)
double norm(Vector a)