FML
Loading...
Searching...
No Matches
NBodySimulation< NDIM, T > Class Template Reference

A particle-mesh N-body simulation (optionally with COLA). More...

#include <Simulation.h>

Data Structures

struct  StepInfo
 

Public Types

template<int N>
using FFTWGrid = FML::GRID::FFTWGrid<N>
 
using MPIParticles = FML::PARTICLE::MPIParticles<T>
 
using ParameterMap = FML::UTILS::ParameterMap
 
using Spline = FML::INTERPOLATION::SPLINE::Spline
 
using DVector = FML::INTERPOLATION::SPLINE::DVector
 
using LinearTransferData = FML::FILEUTILS::LinearTransferData
 
using PowerSpectrumBinning = FML::CORRELATIONFUNCTIONS::PowerSpectrumBinning<NDIM>
 
using Parameters = SIMCODE::SimulationParameters
 

Public Member Functions

 NBodySimulation ()=default
 
 NBodySimulation (std::shared_ptr< Cosmology > cosmo, std::shared_ptr< GravityModel< NDIM > > grav)
 
 NBodySimulation (std::shared_ptr< Cosmology > cosmo, std::shared_ptr< GravityModel< NDIM > > grav, MPIParticles &&_part)
 
void read_parameters (ParameterMap &param)
 Read (and check) the parameters.
 
void init ()
 Generate the initial conditions.
 
void run ()
 Run simulation.
 
void free ()
 Free all memory.
 
const Parameters & get_parameters () const
 
MPIParticles & get_particles ()
 
bool has_baryons () const
 Separate CDM and baryon particles? Then get_particles() are the CDM particles.
 
MPIParticles & get_baryon_particles ()
 
bool has_neutrino_particles () const
 Massive neutrinos as particles (delta-f method)?
 
SIMCODE::NeutrinoParticles< NDIM > & get_neutrinos ()
 
SIMCODE::NeutrinoParticles< NDIM >::Container & get_neutrino_particles ()
 
const std::vector< SIMCODE::SpeciesInfo > & get_species () const
 The particle species (in the order of the IDs)
 
template<class F >
void for_each_cb_species (F &&f)
 Call f(particles, info) for the CDM+baryon species ("cb", or "cdm" and "baryon"; all of type T)
 
template<class F >
void for_each_species (F &&f)
 Call f(particles, info) for all the species (the particle types differ, so use a generic lambda)
 
double species_shotnoise (const SIMCODE::SpeciesInfo &info)
 The shot noise of the density field of a species (in units of the box volume): 1/N (sum w^2 / N^2 for the delta-f neutrinos).
 
double cb_shotnoise ()
 The shot noise of delta_cb = sum_i w_i delta_i: sum_i w_i^2 / N_i.
 
double total_shotnoise (double a=-1.0)
 The shot noise of the total delta_m = (1 - f_nu) delta_cb + f_nu delta_nu with neutrino particles (with force_neutrino_energy_density and a > 0: of (1 - f_nu) delta_cb + f_nu <E/m>(a) delta_nu, the source of the Poisson equation).
 
double neutrino_energy_factor (double a) const
 The mean energy per mass of the neutrinos <E/m>(a) with force_neutrino_energy_density, otherwise 1.
 
bool neutrino_energy_density () const
 Use the energy density of the neutrinos (force_neutrino_energy_density)
 
std::shared_ptr< Cosmology > get_cosmology () const
 
std::shared_ptr< GravityModel< NDIM > > get_gravity_model () const
 
std::shared_ptr< GravityModel< NDIM > > get_gravity_model_ic () const
 
std::shared_ptr< LinearTransferData > get_transferdata () const
 
const Spline & get_power_initial_spline () const
 
const auto & get_pofk_cb_every_step () const
 
const auto & get_pofk_total_every_step () const
 
const auto & get_pofk_species_every_step () const
 
const auto & get_pofk_every_output () const
 
const auto & get_pofk_multipoles_every_output () const
 
const FFTWGrid< NDIM > & get_hybridbias_linear_field () const
 The linear density field delta_cb(zini,k) of the initial conditions (only if hybridbias)
 
SIMCODE::TimeStepping< NDIM > time_stepping () const
 The time-stepping (where the steps are and their sizes)
 
std::pair< std::vector< double >, std::vector< double > > compute_scalefactors_KDK (double amin, double amax, int nsteps)
 The scale factors of positions and velocities after each step from amin to amax.
 
std::pair< std::vector< double >, std::vector< double > > compute_deltatime_KDK (double amin, double amax, int nsteps)
 The size of the drift and kick steps from amin to amax.
 

Protected Member Functions

void compute_lightcone_potential (const FFTWGrid< NDIM > &density_grid_fourier, double a)
 Phi/c^2 in real space from the density contrast delta(k) of the step: Phi/c^2(k) = -1.5 Omega_M (H0/c)^2 delta(k) / (a k^2) (the GR Poisson equation, k in h/Mpc), with the same window deconvolution as the force.
 
void set_force_settings_for_step (double a)
 Choose the force settings for a step where the force is evaluated at scale factor a: the early-time settings (force_early_method) for z > force_early_until_redshift, otherwise the normal ones.
 
void output_background_and_growth_functions ()
 
void setup_initial_power_spectrum ()
 Read the input P(k) / T(k), bring it to the initial redshift, make splines and (optionally) normalize it to a given sigma8.
 
void generate_initial_conditions ()
 Create the particles: either generate the initial conditions from a random field (gaussian / non-gaussian / phases taken from a file) or read them from file.
 
void generate_initial_conditions_two_species (const FFTWGrid< NDIM > &delta_cb_fourier)
 The initial conditions with separate CDM and baryon particles (see two_species_ic_splines and generate_species_from_delta_cb in InitialConditions.h).
 
void apply_lattice_offset ()
 Offset the particle lattice from the nodes of the force grid.
 
void read_ic ()
 Read the particles from gadget files. With COLA we also reconstruct the LPT displacement fields.
 
void read_phases (FFTWGrid< NDIM > &delta_fourier)
 Compute delta(k) from particles in gadget files (used to take the phases from them)
 
void setup_nbody_gauge ()
 Read the N-body gauge source, check it and store the initial density field of the particles.
 
void step (const StepInfo &s)
 One kick-drift step: density -> force -> kick -> COLA kick -> lightcone -> COLA drift -> drift.
 
void drift_and_lightcone (const StepInfo &s)
 The rest of a step after the (PM) kick: COLA kick-drift, lightcone and drift.
 
void kick_with_interlaced_force (const StepInfo &s)
 The kick with force interlacing: the force is computed for force_interlacing_order copies of the particles shifted by a fraction of a cell relative to the grid (see FML::INTERPOLATION::generate_interlacing_shifts), interpolated to the shifted particles and averaged.
 
void compute_density_field_fourier (FFTWGrid< NDIM > &density_grid_fourier, double a)
 Assign the particles to a grid, Fourier transform it and add the other contributions to delta_m (see above).
 
void assign_cb_particles_to_grid (FFTWGrid< NDIM > &density_grid_fourier, double a, bool bin_pofk=true)
 The CDM+baryon density delta_cb(k): particles to grid and Fourier transform (or NUFFT / sheet interpolation).
 
void store_initial_density_field (const FFTWGrid< NDIM > &density_grid_fourier, double a)
 Store delta_cb(k,zini) from the density field of the first force evaluation (at zini).
 
void add_nbody_gauge_source (FFTWGrid< NDIM > &density_grid_fourier, double a)
 N-body gauge: add the linear source from radiation, neutrinos and GR delta_extra(k,a) = delta_cb(k,aini) T_extra(k,a) / T_cb(k,aini)
 
void add_neutrino_particles (FFTWGrid< NDIM > &density_grid_fourier, double a)
 Neutrino particles: delta_m = (1 - f_nu) delta_cb + f_nu delta_nu (and P_nu(k))
 
void add_linear_neutrinos (FFTWGrid< NDIM > &density_grid_fourier, double a)
 Linear massive neutrinos: delta_m = (1 - f_nu) delta_cb + f_nu delta_cb(k,zini) T_nu(k,z) / T_cb(k,zini) (needs the transfer functions, i.e.
 
const FFTWGrid< NDIM > & initial_density_in_particle_frame ()
 The initial density field in the frame of the particles (with force interlacing the particles are shifted by density_shift relative to the grid: delta_s(k) = exp(-ik.s) delta(k)).
 
bool particles_shifted () const
 
void bin_up_power_spectrum_every_step (const FFTWGrid< NDIM > &grid, bool deconvolve, double shotnoise, double a, std::vector< std::pair< double, PowerSpectrumBinning > > &list)
 Bin up P(k) of a density field (deconvolving the window of the force density assignment), subtract the shot noise (if pofk_subtract_shotnoise; shotnoise in units of the box volume) and add it to the list.
 
void analyze_and_output (int ioutput, double redshift)
 Do all the on the fly analysis that is turned on and write the output.
 

Protected Attributes

std::shared_ptr< Cosmology > cosmo
 Everything related to the background evolution.
 
std::shared_ptr< GravityModel< NDIM > > grav
 Everything related to gravity: growth factors, computing forces.
 
std::shared_ptr< GravityModel< NDIM > > grav_ic
 The gravity model used to make the IC (GR if ic_use_gravity_model_GR, otherwise grav)
 
std::shared_ptr< LinearTransferData > transferdata
 Linear perturbations, transfer functions, initial pofk This is only used if ic_type_of_input == transferinfofile.
 
std::shared_ptr< FML::INITIALCONDITIONS::TransferProvider > ic_transfers
 
std::shared_ptr< ParameterMap > parameters
 A copy of the parameterfile (passed on to the models we create)
 
Parameters params
 The parameters of the simulation.
 
std::vector< SIMCODE::SpeciesInfo > species
 The particle species (see Species.h): "cb", or "cdm" and "baryon", and "nu".
 
MPIParticles part
 All the particles (CDM+baryons as one species "cb", or the CDM particles if particle_baryons)
 
MPIParticles part_baryon
 The baryon particles (only if particle_baryons)
 
SIMCODE::NeutrinoParticles< NDIM > neutrinos
 The massive neutrino particles (only if particle_neutrinos; delta-f method)
 
FFTWGrid< NDIM > lightcone_potential
 Phi/c^2 in real space for the lightcone (plc_relativistic_effects), computed at scale factor lightcone_potential_a from the density field of the step.
 
double lightcone_potential_a {-1.0}
 
FFTWGrid< NDIM > initial_density_field_fourier
 The initial density field delta_cb(zini,k) computed with the same Nmesh as the forces (used for linear massive neutrinos and the N-body gauge - not allocated otherwise)
 
FFTWGrid< NDIM > initial_density_field_early
 
FFTWGrid< NDIM > initial_density_field_shifted
 
FFTWGrid< NDIM > hybridbias_linear_field_fourier
 The linear density field delta_cb(zini,k) the particles were displaced with, on a grid of the size of the particle lattice (only if hybridbias)
 
std::array< double, NDIM > density_shift {}
 
SIMCODE::ForceSettings current_force
 
bool early_force {false}
 
FML::NBODY::ForceOptions force_options
 
std::shared_ptr< SIMCODE::NBodyGaugeSource > nbody_gauge
 The linear N-body gauge source (if force_nbody_gauge)
 
ColaState< NDIM, T > cola
 COLA settings and the LPT potentials at the initial time.
 
bool ic_velocities_relative_to_cola_frame {false}
 
std::shared_ptr< Lightcone< NDIM, T > > lightcone
 The lightcone construction.
 
FML::UTILS::Timings timer
 Timings of the code.
 
Spline power_primordial_spline {"P_primordial(k)"}
 
Spline power_initial_spline {"P(k,zini)"}
 
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_cb_every_step
 
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_total_every_step
 
std::map< std::string, std::vector< std::pair< double, PowerSpectrumBinning > > > pofk_species_every_step
 
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_every_output
 
std::vector< std::pair< double, std::vector< PowerSpectrumBinning > > > pofk_multipoles_every_output
 

Detailed Description

template<int NDIM, class T>
class NBodySimulation< NDIM, T >

A particle-mesh N-body simulation (optionally with COLA).

Usage: construct with a cosmology and a gravity model, then call read_parameters(param), init() (creates the initial conditions) and run().

The pieces live in separate headers: SimulationParameters.h : all the parameters (read, printed and validated) TimeStepping.h : where the steps are and the size of the kick/drift steps InitialPowerSpectrum.h : P(k,zini) / T(k,zini) the initial conditions are made from InitialConditions.h : the initial density field and making the particles of a species from it ExternalIC.h : starting from particles read from file COLA.h : the COLA method (ColaState) Species.h : the particle species (CDM+baryons, or CDM and baryons, and neutrinos) NeutrinoParticles.h : massive neutrinos as particles (delta-f method) KickDrift.h : the kick and drift of a species (non-relativistic or relativistic) SimulationDensity.h : the density field the force is computed from (part of this class) AnalyzeOutput.h : on the fly analysis and output

Definition at line 71 of file Simulation.h.

Member Typedef Documentation

◆ DVector

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::DVector = FML::INTERPOLATION::SPLINE::DVector

Definition at line 78 of file Simulation.h.

◆ FFTWGrid

template<int NDIM, class T >
template<int N>
using NBodySimulation< NDIM, T >::FFTWGrid = FML::GRID::FFTWGrid<N>

Definition at line 74 of file Simulation.h.

◆ LinearTransferData

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::LinearTransferData = FML::FILEUTILS::LinearTransferData

Definition at line 79 of file Simulation.h.

◆ MPIParticles

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::MPIParticles = FML::PARTICLE::MPIParticles<T>

Definition at line 75 of file Simulation.h.

◆ ParameterMap

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::ParameterMap = FML::UTILS::ParameterMap

Definition at line 76 of file Simulation.h.

◆ Parameters

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::Parameters = SIMCODE::SimulationParameters

Definition at line 81 of file Simulation.h.

◆ PowerSpectrumBinning

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::PowerSpectrumBinning = FML::CORRELATIONFUNCTIONS::PowerSpectrumBinning<NDIM>

Definition at line 80 of file Simulation.h.

◆ Spline

template<int NDIM, class T >
using NBodySimulation< NDIM, T >::Spline = FML::INTERPOLATION::SPLINE::Spline

Definition at line 77 of file Simulation.h.

Constructor & Destructor Documentation

◆ NBodySimulation() [1/3]

template<int NDIM, class T >
NBodySimulation< NDIM, T >::NBodySimulation ( )
default

◆ NBodySimulation() [2/3]

template<int NDIM, class T >
NBodySimulation< NDIM, T >::NBodySimulation ( std::shared_ptr< Cosmology > cosmo,
std::shared_ptr< GravityModel< NDIM > > grav )
inline

Definition at line 171 of file Simulation.h.

172 : cosmo(cosmo), grav(grav) {
173 timer.StartTiming("The whole simulation");
174 }
void StartTiming(const char *name)
Start timing.
Definition Timings.h:87
std::shared_ptr< GravityModel< NDIM > > grav
Everything related to gravity: growth factors, computing forces.
Definition Simulation.h:88
FML::UTILS::Timings timer
Timings of the code.
Definition Simulation.h:149
std::shared_ptr< Cosmology > cosmo
Everything related to the background evolution.
Definition Simulation.h:85

◆ NBodySimulation() [3/3]

template<int NDIM, class T >
NBodySimulation< NDIM, T >::NBodySimulation ( std::shared_ptr< Cosmology > cosmo,
std::shared_ptr< GravityModel< NDIM > > grav,
MPIParticles && _part )
inline

Definition at line 177 of file Simulation.h.

179 part = std::move(_part);
180 }
MPIParticles part
All the particles (CDM+baryons as one species "cb", or the CDM particles if particle_baryons)
Definition Simulation.h:106
NBodySimulation()=default

Member Function Documentation

◆ add_linear_neutrinos()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::add_linear_neutrinos ( FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

Linear massive neutrinos: delta_m = (1 - f_nu) delta_cb + f_nu delta_cb(k,zini) T_nu(k,z) / T_cb(k,zini) (needs the transfer functions, i.e.

transferinfofile). The first time we store delta_cb(k,zini)

Definition at line 206 of file SimulationDensity.h.

206 {
207 const double ic_initial_redshift = params.ic.initial_redshift;
209 store_initial_density_field(density_grid_fourier, a);
210
211 if (FML::ThisTask == 0) {
212 std::cout << "Adding on the massive neutrinos to the densityfield using linear theory\n";
213 }
214
215 // delta_cb(zini,k) -> delta_nu(z,k) using the transfer functions
216 const double aini = 1.0 / (1.0 + ic_initial_redshift);
217 const double koverkBox = 1.0 / params.simulation.boxsize;
218 auto norm = [&](double kBox) {
219 double T_mnu = transferdata->get_massive_neutrino_transfer_function(kBox * koverkBox, a);
220 double T_cb_ini = transferdata->get_cdm_baryon_transfer_function(kBox * koverkBox, aini);
221 return (T_mnu / T_cb_ini);
222 };
223
224 // The total matter density-field deltaM = (OmegaCB deltaCB + OmegaMNu deltaMNu)/OmegaM. With
225 // force_neutrino_energy_density the neutrino term is f_nu <E/m>(a) delta_nu (delta_nu from the transfer functions
226 // is the energy-density contrast)
227 const double fMNu = cosmo->get_fMNu();
228 const double fMNu_source = fMNu * neutrino_energy_factor(a);
229 const auto & delta_ini_grid = initial_density_in_particle_frame();
230 FML::GRID::for_each_fourier_mode<NDIM>(density_grid_fourier, [&](size_t fourier_index, double kmag) {
231 auto delta_ini = delta_ini_grid.get_fourier_from_index(fourier_index);
232 auto deltaCB = density_grid_fourier.get_fourier_from_index(fourier_index);
233 auto deltaM =
234 deltaCB * FML::GRID::FloatType(1.0 - fMNu) + delta_ini * FML::GRID::FloatType(norm(kmag) * fMNu_source);
235 density_grid_fourier.set_fourier_from_index(fourier_index, deltaM);
236 });
237}
const double aini
Definition Main.cpp:41
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
const FFTWGrid< NDIM > & initial_density_in_particle_frame()
The initial density field in the frame of the particles (with force interlacing the particles are shi...
double neutrino_energy_factor(double a) const
The mean energy per mass of the neutrinos <E/m>(a) with force_neutrino_energy_density,...
Definition Simulation.h:255
void store_initial_density_field(const FFTWGrid< NDIM > &density_grid_fourier, double a)
Store delta_cb(k,zini) from the density field of the first force evaluation (at zini).
std::shared_ptr< LinearTransferData > transferdata
Linear perturbations, transfer functions, initial pofk This is only used if ic_type_of_input == trans...
Definition Simulation.h:94
FFTWGrid< NDIM > initial_density_field_fourier
The initial density field delta_cb(zini,k) computed with the same Nmesh as the forces (used for linea...
Definition Simulation.h:120
void for_each_fourier_mode(const FFTWGrid< N > &fourier_grid, F &&f)
Call f(fourier_index, kmag) for every local mode of a grid in fourier space (OpenMP over the slices; ...
int ThisTask
The MPI task number.
Definition Global.cpp:39
double norm(Vector a)

◆ add_nbody_gauge_source()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::add_nbody_gauge_source ( FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

N-body gauge: add the linear source from radiation, neutrinos and GR delta_extra(k,a) = delta_cb(k,aini) T_extra(k,a) / T_cb(k,aini)

Definition at line 148 of file SimulationDensity.h.

148 {
149 if (FML::ThisTask == 0)
150 std::cout << "Adding the N-body gauge linear source (radiation, neutrinos, GR) to the densityfield\n";
151 const double boxsize = params.simulation.boxsize;
152 const double aini = 1.0 / (1.0 + params.ic.initial_redshift);
153 const Spline ratio = nbody_gauge->ratio_spline(a, aini, *transferdata);
154 const double logkmin = std::log(nbody_gauge->get_kmin_hmpc());
155 const double logkmax = std::log(nbody_gauge->get_kmax_hmpc());
156
157 // The force is normalized to OmegaM = OmegaCB + OmegaMNu so the source is (1-fMNu)(delta_cb + delta_extra)
158 const double fMNu = cosmo->get_fMNu();
160 store_initial_density_field(density_grid_fourier, a);
161 const auto & delta_ini_grid = initial_density_in_particle_frame();
162 FML::GRID::for_each_fourier_mode<NDIM>(density_grid_fourier, [&](size_t fourier_index, double kmag) {
163 const double logk = std::min(std::max(std::log(kmag / boxsize), logkmin), logkmax);
164 const double r = kmag > 0.0 ? ratio(logk) : 0.0;
165 auto delta_ini = delta_ini_grid.get_fourier_from_index(fourier_index);
166 auto deltaCB = density_grid_fourier.get_fourier_from_index(fourier_index);
167 auto delta = (deltaCB + delta_ini * FML::GRID::FloatType(r)) * FML::GRID::FloatType(1.0 - fMNu);
168 density_grid_fourier.set_fourier_from_index(fourier_index, delta);
169 });
170}
const double boxsize
Definition TestHDF5.cpp:47
This is a wrapper class for easy use of GSL splines It is (OpenMP) thread safe as long as splines are...
Definition Spline.h:106
std::shared_ptr< SIMCODE::NBodyGaugeSource > nbody_gauge
The linear N-body gauge source (if force_nbody_gauge)
Definition Simulation.h:137
FFTWGrid< NDIM > initial_density_field_early
Definition Simulation.h:122

◆ add_neutrino_particles()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::add_neutrino_particles ( FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

Neutrino particles: delta_m = (1 - f_nu) delta_cb + f_nu delta_nu (and P_nu(k))

Definition at line 174 of file SimulationDensity.h.

174 {
175 if (FML::ThisTask == 0)
176 std::cout << "Adding the neutrino particles to the densityfield\n";
177 FFTWGrid<NDIM> density_nu(density_grid_fourier.get_nmesh(),
178 density_grid_fourier.get_n_extra_slices_left(),
179 density_grid_fourier.get_n_extra_slices_right());
180 {
181 // With force_neutrino_energy_density the field is the energy-density contrast (weights w E / (m <E/m>))
183 neutrinos,
184 a,
185 params.force.neutrino_energy_density);
186 neutrinos.density_fourier(density_nu, current_force.density_assignment_method);
187 if (params.pofk.every_step and not particles_shifted())
189 true,
190 params.pofk.subtract_shotnoise ? neutrinos.shotnoise() : 0.0,
191 a,
193 }
194 // The source of the Poisson equation (normalized to the non-relativistic matter density Omega_M a^-3):
195 // (1 - f_nu) delta_cb + f_nu <E/m>(a) delta_nu
196 const double fMNu = cosmo->get_fMNu();
198 density_nu,
199 1.0 - fMNu,
200 fMNu * neutrino_energy_factor(a));
201}
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
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
SIMCODE::ForceSettings current_force
Definition Simulation.h:131
void bin_up_power_spectrum_every_step(const FFTWGrid< NDIM > &grid, bool deconvolve, double shotnoise, double a, std::vector< std::pair< double, PowerSpectrumBinning > > &list)
Bin up P(k) of a density field (deconvolving the window of the force density assignment),...
SIMCODE::NeutrinoParticles< NDIM > neutrinos
The massive neutrino particles (only if particle_neutrinos; delta-f method)
Definition Simulation.h:110
std::map< std::string, std::vector< std::pair< double, PowerSpectrumBinning > > > pofk_species_every_step
Definition Simulation.h:163
bool particles_shifted() const
Definition Simulation.h:321
While this object lives the weights of the particles are w_i E_i / (m <E/m>(a)) with E_i / m = sqrt(1...
void linear_combination_fourier(FFTWGrid< N > &a, const FFTWGrid< N > &b, double wa, double wb)
The linear combination a -> wa a + wb b of two grids in fourier space (same layout)

◆ analyze_and_output()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::analyze_and_output ( int ioutput,
double redshift )
protected

Do all the on the fly analysis that is turned on and write the output.

Definition at line 1508 of file Simulation.h.

1508 {
1509
1510 // Create snapshot folder
1511 const std::string snapshot_folder =
1512 params.output.path("snapshot_" + params.simulation.name + "_z" + redshift_to_string(redshift));
1513 if (not FML::create_folder(snapshot_folder)) {
1514 throw std::runtime_error("Failed to create snapshot folder [" + snapshot_folder + "]");
1515 }
1516
1517 if (FML::ThisTask == 0) {
1518 std::cout << "\n";
1519 std::cout << "#=====================================================\n";
1520 std::cout << "# Analyze and output\n";
1521 std::cout << "#=====================================================\n";
1522 std::cout << "Doing output " << ioutput << " at redshift z = " << redshift << "\n";
1523 }
1524
1525 // In the COLA frame the velocities are relative to LPT. While this object exists the
1526 // particles have their true velocities
1527 ScopedLPTVelocity<NDIM, T> true_velocities(cola, part, 1.0 / (1.0 + redshift), &timer);
1528 std::optional<ScopedLPTVelocity<NDIM, T>> true_velocities_baryons;
1529 if (has_baryons())
1530 true_velocities_baryons.emplace(cola, part_baryon, 1.0 / (1.0 + redshift), &timer);
1531
1532 // Every step we (might) have computed Pcb(k) and possibly Ptotal(k). Output these to file
1533 // (only the steps since the last output: the files of earlier steps are already written)
1534 if (pofk_cb_every_step.size() > 0 or pofk_total_every_step.size() > 0) {
1536 pofk_cb_every_step.clear();
1537 pofk_total_every_step.clear();
1539 }
1540
1541 struct Analysis {
1542 std::string name;
1543 bool enabled;
1544 std::function<void()> run;
1545 };
1546 const std::vector<Analysis> analyses{
1547 {"Baryonification",
1548 params.baryonification.enabled,
1549 [&]() {
1550 if constexpr (NDIM == 3)
1553 params,
1554 cosmo,
1555 redshift,
1556 snapshot_folder);
1557 }},
1558 {"Power-spectrum",
1559 params.pofk.enabled,
1560 [&]() { pofk_every_output.push_back({redshift, compute_power_spectrum(*this, redshift, snapshot_folder)}); }},
1561 {"Power-spectrum multipoles",
1562 params.pofk_multipole.enabled,
1563 [&]() {
1565 {redshift, compute_power_spectrum_multipoles(*this, redshift, snapshot_folder)});
1566 }},
1567 {"FOF", params.fof.enabled, [&]() { compute_fof_halos(*this, redshift, snapshot_folder); }},
1568 {"Bispectrum", params.bispectrum.enabled, [&]() { compute_bispectrum(*this, redshift, snapshot_folder); }},
1569 {"Hybrid bias spectra",
1570 params.hybridbias.enabled,
1571 [&]() { compute_hybrid_bias_spectra(*this, redshift, snapshot_folder); }},
1572 {"Output particles",
1573 params.output.particles,
1574 [&]() {
1575 if (params.output.fileformat == SIMCODE::ParticleFileFormat::GADGET)
1576 output_gadget(*this, redshift, snapshot_folder);
1577 else
1578 output_gadget_hdf5(*this, redshift, snapshot_folder);
1579 }},
1580 };
1581 for (auto & analysis : analyses) {
1582 if (not analysis.enabled)
1583 continue;
1584 timer.StartTiming(analysis.name);
1585 analysis.run();
1586 timer.EndTiming(analysis.name);
1587 }
1588}
void compute_hybrid_bias_spectra(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
The hybrid bias (Lagrangian bias basis) spectra P_ab(k) of the operators 1, delta_L,...
void output_pofk_for_every_step(const NBodySimulation< NDIM, T > &sim)
std::vector< FML::CORRELATIONFUNCTIONS::PowerSpectrumBinning< NDIM > > compute_power_spectrum_multipoles(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
Returns P_ell(k) for ell = 0,1,...,ellmax (also written to file)
void output_gadget_hdf5(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
Output the particles as GADGET HDF5 files: one file per task, <prefix>.
void output_gadget(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
void compute_bispectrum(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
void compute_fof_halos(NBodySimulation< NDIM, T > &sim, double redshift, std::string snapshot_folder)
Locate FoF halos (and their spherical overdensity masses), write the halo catalogue and the mass func...
const int NDIM
std::string redshift_to_string(double redshift)
The redshift formatted as used in output filenames.
Definition OutputUtils.h:7
std::string name
void compute_power_spectrum(std::string snapdir, int level=-1, std::vector< std::string > format={}, std::string density_assignment="PCS", bool subtract_shotnoise=false, bool verbose=false)
Definition Main.cpp:18
T * get_particles_ptr()
Get a pointer to the first particle.
size_t get_npart() const
Number of active particles on the local task.
double EndTiming(const char *name, bool print=false)
End timing (the time since the last StartTiming with this name is added to its total; a second EndTim...
Definition Timings.h:103
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_every_output
Definition Simulation.h:165
ColaState< NDIM, T > cola
COLA settings and the LPT potentials at the initial time.
Definition Simulation.h:140
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_cb_every_step
Definition Simulation.h:160
std::vector< std::pair< double, PowerSpectrumBinning > > pofk_total_every_step
Definition Simulation.h:161
bool has_baryons() const
Separate CDM and baryon particles? Then get_particles() are the CDM particles.
Definition Simulation.h:200
std::vector< std::pair< double, std::vector< PowerSpectrumBinning > > > pofk_multipoles_every_output
Definition Simulation.h:167
MPIParticles part_baryon
The baryon particles (only if particle_baryons)
Definition Simulation.h:108
While this object exists the particles have their true velocities (the LPT velocity at scale factor a...
Definition COLA.h:1124
constexpr bool enabled
Definition Counters.h:50
bool create_folder(std::string foldername)
Definition Global.cpp:239
FML::Vector< BaryonificationParticle > copy_baryonification_particles(P *particles, size_t count)
void output_baryonified_snapshot(FML::Vector< Particle > snapshot, const SimulationParameters &params, const std::shared_ptr< Cosmology > &cosmo, double redshift, const std::string &folder)
Definition run.py:1

◆ apply_lattice_offset()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::apply_lattice_offset ( )
protected

Offset the particle lattice from the nodes of the force grid.

With a force grid finer than the particle grid the particles would otherwise start exactly on grid nodes where CIC responds to |displacement| (a rectified response) and this gives large spurious forces (see notes/force_grid_and_lattice.md). This is a uniform translation of all the particles (all species) so it does not change the physics

Definition at line 878 of file Simulation.h.

878 {
879 const auto & ic = params.ic;
880 const bool offset_lattice = ic.lattice_offset == "half_force_cell" or
881 (ic.lattice_offset == "fiducial" and params.force.nmesh > params.particle.Npart_1D);
882 if (not offset_lattice)
883 return;
884 const double shift = 0.5 / double(params.force.nmesh);
885 // Scale-dependent COLA interpolates its LPT potentials (of the lattice before the offset) at q - shift
886 cola.lattice_offset = shift;
887 if (FML::ThisTask == 0)
888 std::cout << "Offsetting the particle lattice by half a force grid cell (" << shift * params.simulation.boxsize
889 << " Mpc/h) in each direction\n";
890 for_each_species([&](auto & particles, const SIMCODE::SpeciesInfo &) {
891 using P = std::remove_reference_t<decltype(*particles.get_particles_ptr())>;
892 for (auto & p : particles) {
893 auto * pos = FML::PARTICLE::GetPos(p);
894 for (int idim = 0; idim < NDIM; idim++) {
895 pos[idim] += shift;
896 if (pos[idim] >= 1.0)
897 pos[idim] -= 1.0;
898 }
899 if constexpr (FML::PARTICLE::has_get_q<P>()) {
901 for (int idim = 0; idim < NDIM; idim++) {
902 q[idim] += shift;
903 if (q[idim] >= 1.0)
904 q[idim] -= 1.0;
905 }
906 }
907 }
908 particles.communicate_particles();
909 });
910}
void for_each_species(F &&f)
Call f(particles, info) for all the species (the particle types differ, so use a generic lambda)
Definition Simulation.h:221
get_vel constexpr double * GetPos(...)
constexpr double * GetLagrangianPos(...)
What the simulation needs to know about a particle species (one particle container each): cb : CDM an...
Definition Species.h:24
std::vector< P > particles(bool empty_rank)

◆ assign_cb_particles_to_grid()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::assign_cb_particles_to_grid ( FFTWGrid< NDIM > & density_grid_fourier,
double a,
bool bin_pofk = true )
protected

The CDM+baryon density delta_cb(k): particles to grid and Fourier transform (or NUFFT / sheet interpolation).

With CDM and baryons as separate particles delta_cb = w_c delta_c + w_b delta_b (and P(k) of each species)

Definition at line 76 of file SimulationDensity.h.

78 {
79 const auto & force = current_force;
80 if (force.density_method == "nufft") {
81 // The exact Fourier modes (no window function, no aliasing) for |m_i| < Nmesh/2
85 density_grid_fourier,
86 force.nufft_epsilon);
87 return;
88 }
89 if (force.density_method == "sheet" or force.density_method == "sheet_nufft") {
90 if constexpr (FML::PARTICLE::has_get_q<T>()) {
94 params.particle.Npart_1D,
95 force.sheet_refinement,
96 density_grid_fourier,
97 force.density_method == "sheet" ? force.density_assignment_method : std::string("NUFFT"),
98 force.nufft_epsilon);
99 } else {
100 FML::assert_mpi(false, "force_density_method = sheet needs particles with a Lagrangian position q");
101 }
102 return;
103 }
104
105 // Each CDM+baryon species to a grid. The first one goes into density_grid_fourier and the others are added
106 // with their weights
107 int ncb = 0;
108 for (auto & info : species)
109 ncb += info.in_cb() ? 1 : 0;
110 const bool bin_species = ncb > 1 and params.pofk.every_step and bin_pofk;
111 int icb = 0;
112 double weight_first = 1.0;
114 auto assign = [&](FFTWGrid<NDIM> & grid) {
116 particles.get_npart(),
117 particles.get_npart_total(),
118 grid,
119 force.density_assignment_method);
120 grid.fftw_r2c();
121 if (bin_species)
123 true,
124 params.pofk.subtract_shotnoise ? species_shotnoise(info) : 0.0,
125 a,
127 };
128 if (icb == 0) {
129 assign(density_grid_fourier);
130 weight_first = info.weight_cb;
131 } else {
132 FFTWGrid<NDIM> grid(density_grid_fourier.get_nmesh(),
133 density_grid_fourier.get_n_extra_slices_left(),
134 density_grid_fourier.get_n_extra_slices_right());
135 assign(grid);
137 grid,
138 icb == 1 ? weight_first : 1.0,
139 info.weight_cb);
140 }
141 icb++;
142 });
143}
void info(HaloModel **hmp)
Definition Wrapper.cpp:88
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.
std::vector< SIMCODE::SpeciesInfo > species
The particle species (see Species.h): "cb", or "cdm" and "baryon", and "nu".
Definition Simulation.h:104
double species_shotnoise(const SIMCODE::SpeciesInfo &info)
The shot noise of the density field of a species (in units of the box volume): 1/N (sum w^2 / N^2 for...
Definition Simulation.h:229
void for_each_cb_species(F &&f)
Call f(particles, info) for the CDM+baryon species ("cb", or "cdm" and "baryon"; all of type T)
Definition Simulation.h:211
void particles_to_fourier_grid_sheet(const T *part, size_t NumPart, int Npart_1D, int refinement, FFTWGrid< N > &density_fourier, std::string density_assignment_method, double nufft_epsilon=1e-6)
The density contrast in Fourier space from spectral sheet interpolation of the particles' own displac...
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.
void particles_to_fourier_grid_nufft(const T *part, size_t NumPart, size_t NumPartTot, FFTWGrid< N > &density_fourier, double epsilon=1e-6, double sigma=2.0)
The density contrast of a set of particles in Fourier space computed with a NUFFT: for and (no win...
Definition NUFFT.h:699
Vector grid(size_t n)

◆ bin_up_power_spectrum_every_step()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::bin_up_power_spectrum_every_step ( const FFTWGrid< NDIM > & grid,
bool deconvolve,
double shotnoise,
double a,
std::vector< std::pair< double, PowerSpectrumBinning > > & list )
protected

Bin up P(k) of a density field (deconvolving the window of the force density assignment), subtract the shot noise (if pofk_subtract_shotnoise; shotnoise in units of the box volume) and add it to the list.

Definition at line 289 of file SimulationDensity.h.

294 {
295 PowerSpectrumBinning pofk(grid.get_nmesh() / 2);
296 pofk.subtract_shotnoise = params.pofk.subtract_shotnoise;
297 if (deconvolve)
299 pofk,
301 else
303 if (params.pofk.subtract_shotnoise and shotnoise != 0.0)
304 for (int i = 0; i < pofk.n; i++)
305 pofk.pofk[i] -= shotnoise;
306 pofk.scale(params.simulation.boxsize);
307 list.push_back({1.0 / a - 1.0, pofk});
308}
FML::CORRELATIONFUNCTIONS::PowerSpectrumBinning< NDIM > PowerSpectrumBinning
Definition Simulation.h:80
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 bin_up_power_spectrum(const FFTWGrid< N > &fourier_grid, PowerSpectrumBinning< N > &pofk)
Compute the power-spectrum of a fourier grid.

◆ cb_shotnoise()

template<int NDIM, class T >
double NBodySimulation< NDIM, T >::cb_shotnoise ( )
inline

The shot noise of delta_cb = sum_i w_i delta_i: sum_i w_i^2 / N_i.

Definition at line 235 of file Simulation.h.

235 {
236 double shotnoise = 0.0;
238 shotnoise += info.weight_cb * info.weight_cb / double(particles.get_npart_total());
239 });
240 return shotnoise;
241 }

◆ compute_deltatime_KDK()

template<int NDIM, class T >
std::pair< std::vector< double >, std::vector< double > > NBodySimulation< NDIM, T >::compute_deltatime_KDK ( double amin,
double amax,
int nsteps )
inline

The size of the drift and kick steps from amin to amax.

Definition at line 286 of file Simulation.h.

286 {
287 return time_stepping().deltatime_KDK(amin, amax, nsteps);
288 }
const int nsteps
Definition Main.cpp:43
SIMCODE::TimeStepping< NDIM > time_stepping() const
The time-stepping (where the steps are and their sizes)
Definition Simulation.h:278

◆ compute_density_field_fourier()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::compute_density_field_fourier ( FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

Assign the particles to a grid, Fourier transform it and add the other contributions to delta_m (see above).

Also bins up P(k) at every step (if pofk_every_step)

Definition at line 19 of file SimulationDensity.h.

19 {
20 const auto & force = current_force;
21 const bool subtract_shotnoise = params.pofk.subtract_shotnoise;
22
23 if (FML::ThisTask == 0) {
24 std::cout << (has_baryons() ? "Adding the CDM and baryon particles to the densityfield\n" :
25 "Adding particles (baryons+CDM) to the densityfield\n");
26 }
27 timer.StartTiming("DensityAssignment+FFT");
28 assign_cb_particles_to_grid(density_grid_fourier, a);
29 timer.EndTiming("DensityAssignment+FFT");
30
31 // P(k) of the CDM+baryon particles. With force interlacing the particles might be shifted relative to the grid:
32 // then we have the linear fields below in the shifted frame and do not bin up P(k) again
33 const bool every_step = params.pofk.every_step and not particles_shifted();
34 const bool deconvolve = not(force.density_method == "nufft" or force.density_method == "sheet_nufft");
35 if (every_step) {
36 timer.StartTiming("PofkEveryStep");
37 bin_up_power_spectrum_every_step(density_grid_fourier,
38 deconvolve,
39 subtract_shotnoise ? cb_shotnoise() : 0.0,
40 a,
42 timer.EndTiming("PofkEveryStep");
43 }
44
45 // The other contributions to delta_m
46 bool has_total = true;
47 double total_shotnoise_value = 0.0;
48 if (nbody_gauge) {
49 add_nbody_gauge_source(density_grid_fourier, a);
50 } else if (has_neutrino_particles()) {
51 add_neutrino_particles(density_grid_fourier, a);
52 if (subtract_shotnoise)
53 total_shotnoise_value = total_shotnoise(a);
54 } else if (force.linear_massive_neutrinos and cosmo->get_fMNu() > 0.0 and transferdata) {
55 add_linear_neutrinos(density_grid_fourier, a);
56 } else {
57 has_total = false;
58 }
59
60 // P(k) of the total. NB: with linear neutrinos / the N-body gauge source the density field is W delta_cb +
61 // delta_extra so the deconvolution of the window W is not fully correct for the last part at large k. One way
62 // to improve this is to bin up <(W delta_cb)^2>, <delta_extra^2> and the cross term and deconvolve them separately
63 if (has_total and every_step)
64 bin_up_power_spectrum_every_step(density_grid_fourier,
65 deconvolve,
66 total_shotnoise_value,
67 a,
69
71}
void add_neutrino_particles(FFTWGrid< NDIM > &density_grid_fourier, double a)
Neutrino particles: delta_m = (1 - f_nu) delta_cb + f_nu delta_nu (and P_nu(k))
void add_linear_neutrinos(FFTWGrid< NDIM > &density_grid_fourier, double a)
Linear massive neutrinos: delta_m = (1 - f_nu) delta_cb + f_nu delta_cb(k,zini) T_nu(k,...
double total_shotnoise(double a=-1.0)
The shot noise of the total delta_m = (1 - f_nu) delta_cb + f_nu delta_nu with neutrino particles (wi...
Definition Simulation.h:245
double cb_shotnoise()
The shot noise of delta_cb = sum_i w_i delta_i: sum_i w_i^2 / N_i.
Definition Simulation.h:235
bool has_neutrino_particles() const
Massive neutrinos as particles (delta-f method)?
Definition Simulation.h:203
FFTWGrid< NDIM > initial_density_field_shifted
Definition Simulation.h:124
void assign_cb_particles_to_grid(FFTWGrid< NDIM > &density_grid_fourier, double a, bool bin_pofk=true)
The CDM+baryon density delta_cb(k): particles to grid and Fourier transform (or NUFFT / sheet interpo...
void add_nbody_gauge_source(FFTWGrid< NDIM > &density_grid_fourier, double a)
N-body gauge: add the linear source from radiation, neutrinos and GR delta_extra(k,...

◆ compute_lightcone_potential()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::compute_lightcone_potential ( const FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

Phi/c^2 in real space from the density contrast delta(k) of the step: Phi/c^2(k) = -1.5 Omega_M (H0/c)^2 delta(k) / (a k^2) (the GR Poisson equation, k in h/Mpc), with the same window deconvolution as the force.

Stored in lightcone_potential (with the boundaries communicated, ready for interpolation)

Definition at line 1608 of file Simulation.h.

1608 {
1609 timer.StartTiming("LightconePotential");
1610 lightcone_potential = density_grid_fourier;
1611 lightcone_potential.add_memory_label("Lightcone potential");
1612 const double boxsize = params.simulation.boxsize;
1613 const double c_over_H0 = 2997.92458; // Mpc/h
1614 const double norm = -1.5 * cosmo->get_OmegaM() / (a * c_over_H0 * c_over_H0) * boxsize * boxsize;
1615 const bool deconvolve = current_force.deconvolve_window;
1617 lightcone_potential.get_nmesh());
1618 const auto Local_nx = lightcone_potential.get_local_nx();
1619#ifdef USE_OMP
1620#pragma omp parallel for
1621#endif
1622 for (int islice = 0; islice < Local_nx; islice++) {
1623 std::array<double, NDIM> kvec;
1624 double kmag2;
1625 for (auto && index : lightcone_potential.get_fourier_range(islice, islice + 1)) {
1626 lightcone_potential.get_fourier_wavevector_and_norm2_by_index(index, kvec, kmag2);
1627 if (kmag2 == 0.0) {
1628 lightcone_potential.set_fourier_from_index(index, 0.0);
1629 continue;
1630 }
1631 double fac = norm / kmag2;
1632 if (deconvolve) {
1633 const double W = window(kvec);
1634 fac /= W * W;
1635 }
1636 lightcone_potential.set_fourier_from_index(index,
1637 lightcone_potential.get_fourier_from_index(index) *
1638 FML::GRID::FloatType(fac));
1639 }
1640 }
1641 lightcone_potential.fftw_c2r();
1642 lightcone_potential.communicate_boundaries();
1644 timer.EndTiming("LightconePotential");
1645}
void add_memory_label(std::string label)
For memory logging: add a label to the grid.
Definition FFTWGrid.h:404
The Fourier window of the density assignment, , from a table of the 1D factors (the wavevector compo...
double lightcone_potential_a
Definition Simulation.h:115
FFTWGrid< NDIM > lightcone_potential
Phi/c^2 in real space for the lightcone (plc_relativistic_effects), computed at scale factor lightcon...
Definition Simulation.h:114

◆ compute_scalefactors_KDK()

template<int NDIM, class T >
std::pair< std::vector< double >, std::vector< double > > NBodySimulation< NDIM, T >::compute_scalefactors_KDK ( double amin,
double amax,
int nsteps )
inline

The scale factors of positions and velocities after each step from amin to amax.

Definition at line 281 of file Simulation.h.

281 {
282 return time_stepping().scalefactors_KDK(amin, amax, nsteps);
283 }

◆ drift_and_lightcone()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::drift_and_lightcone ( const StepInfo & s)
protected

The rest of a step after the (PM) kick: COLA kick-drift, lightcone and drift.

Definition at line 1347 of file Simulation.h.

1347 {
1348 const auto & sim = params.simulation;
1349 if (sim.enforce_LPT_trajectories and FML::ThisTask == 0) {
1350 std::cout << "Enforcing LPT trajectories so we do not compute forces and apply (non COLA) KICK/DRIFT "
1351 "operators\n";
1352 }
1353
1354 // For COLA we can do the kick and drift at the same time. The lightcone drifts the particles from apos with
1355 // their true velocity (which includes the LPT velocity), so then the COLA drift (the LPT displacement over
1356 // the step) is done after the lightcone
1357 const bool make_lightcone = lightcone->lightcone_active() and s.delta_time_drift != 0.0;
1358 if (cola.enabled) {
1359 timer.StartTiming("COLA");
1360 // The COLA kick subtracts the LPT force from the COLA velocities (which get the PM force). When enforcing the
1361 // LPT trajectories there is no PM kick, so there must be no COLA kick either: the COLA velocities stay zero
1362 // and the particles have the LPT velocity (with it the velocities were close to the initial LPT velocity)
1363 const double delta_time_kick_cola = sim.enforce_LPT_trajectories ? 0.0 : s.delta_time_kick;
1365 if (make_lightcone)
1366 cola.kick(particles, s.apos, s.apos_new, delta_time_kick_cola);
1367 else
1368 cola.kick_drift(particles, s.apos, s.apos_new, delta_time_kick_cola, s.delta_time_drift);
1369 });
1370 if (not make_lightcone and not cola.scaledependent and sim.enforce_LPT_trajectories)
1372 timer.EndTiming("COLA");
1373 }
1374
1375 // Build the lightcone (with the true velocities of the particles)
1376 if (make_lightcone) {
1377 ScopedLPTVelocity<NDIM, T> true_velocities(cola, part, s.avel_new, &timer);
1378 timer.StartTiming("Lightcone");
1379 if (lightcone->needs_potential(s.apos, s.apos_new)) {
1380 // The potential of this step (if not computed with the force, e.g. with force interlacing: from the
1381 // CDM+baryon density only) at the particles
1382 if (lightcone_potential_a != s.apos) {
1385 FFTWGrid<NDIM> density(current_force.nmesh, nleftright.first, nleftright.second);
1386 assign_cb_particles_to_grid(density, s.apos);
1387 compute_lightcone_potential(density, s.apos);
1388 }
1389 std::vector<FML::GRID::FloatType> potential;
1393 part.get_npart(),
1394 potential,
1396 lightcone->create_lightcone(part,
1397 s.apos,
1398 s.apos_new,
1399 s.avel_new,
1400 s.delta_time_drift,
1401 &potential,
1404 lightcone_potential.free();
1405 lightcone_potential_a = -1.0;
1406 } else {
1407 lightcone->create_lightcone(part, s.apos, s.apos_new, s.avel_new, s.delta_time_drift);
1408 }
1409 timer.EndTiming("Lightcone");
1410 }
1411 if (cola.enabled and make_lightcone) {
1412 timer.StartTiming("COLA");
1414 [&](MPIParticles & particles, const SIMCODE::SpeciesInfo &) { cola.drift(particles, s.apos, s.apos_new); });
1415 if (not cola.scaledependent and sim.enforce_LPT_trajectories)
1417 timer.EndTiming("COLA");
1418 }
1419
1420 // Drift particles (updates positions)
1421 if (s.delta_time_drift != 0.0 and not sim.enforce_LPT_trajectories) {
1422 timer.StartTiming("Drift");
1424 SIMCODE::drift_particles<NDIM>(particles, info, s.apos, s.apos_new, s.delta_time_drift, sim.boxsize);
1425 });
1426 timer.EndTiming("Drift");
1427 }
1428
1429 // Show info about particles and memory use
1430 for_each_species([&](auto & particles, const SIMCODE::SpeciesInfo &) { particles.info(); });
1432}
void communicate_particles(size_t max_message_bytes=std::numeric_limits< int >::max(), bool force_general=false)
Communicate particles across CPU boundaries.
std::shared_ptr< Lightcone< NDIM, T > > lightcone
The lightcone construction.
Definition Simulation.h:146
void compute_lightcone_potential(const FFTWGrid< NDIM > &density_grid_fourier, double a)
Phi/c^2 in real space from the density contrast delta(k) of the step: Phi/c^2(k) = -1....
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 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.
FML_UNITS_INLINE constexpr double density
Definition Units.h:49
void print_system_memory_use()
Print the resident set size and the peak value of it so far.
Definition Global.cpp:269
void drift_particles(FML::PARTICLE::MPIParticles< P > &part, const SpeciesInfo &info, double apos, double apos_new, double delta_time, double boxsize)
The drift of a species: x -> x + v dt (times 1 / sqrt(1 + u^2) with u at the middle of the drift for ...
Definition KickDrift.h:94
void potential()

◆ for_each_cb_species()

template<int NDIM, class T >
template<class F >
void NBodySimulation< NDIM, T >::for_each_cb_species ( F && f)
inline

Call f(particles, info) for the CDM+baryon species ("cb", or "cdm" and "baryon"; all of type T)

Definition at line 211 of file Simulation.h.

211 {
212 for (auto & info : species) {
213 if (info.name == "cb" or info.name == "cdm")
214 f(part, info);
215 else if (info.name == "baryon")
217 }
218 }
double f
Definition Minimizer.cpp:28

◆ for_each_species()

template<int NDIM, class T >
template<class F >
void NBodySimulation< NDIM, T >::for_each_species ( F && f)
inline

Call f(particles, info) for all the species (the particle types differ, so use a generic lambda)

Definition at line 221 of file Simulation.h.

221 {
223 for (auto & info : species)
224 if (info.name == "nu")
226 }

◆ free()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::free ( )

Free all memory.

Definition at line 1591 of file Simulation.h.

1591 {
1592 part.free();
1593 part_baryon.free();
1594 neutrinos.free();
1598 cola.free();
1599}
void free()
Free all memory of the stored particles.
FFTWGrid< NDIM > hybridbias_linear_field_fourier
The linear density field delta_cb(zini,k) the particles were displaced with, on a grid of the size of...
Definition Simulation.h:127

◆ generate_initial_conditions()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::generate_initial_conditions ( )
protected

Create the particles: either generate the initial conditions from a random field (gaussian / non-gaussian / phases taken from a file) or read them from file.

Definition at line 614 of file Simulation.h.

614 {
615 const auto & ic = params.ic;
616 const double boxsize = params.simulation.boxsize;
617
618 // If we simply read IC from file (useful for testing)
619 if (ic.random_field_type == SIMCODE::ICRandomFieldType::ReadParticles) {
620 read_ic();
621 return;
622 }
623
624 //=============================================================
625 // Make the initial density field delta(k,zini)
626 //=============================================================
628 if (ic.random_field_type == SIMCODE::ICRandomFieldType::ReadPhases) {
629 // If read_phases then delta_ini is computed from particles
630 nextra = FML::INTERPOLATION::get_extra_slices_needed_for_density_assignment(ic.reconstruct_assigment_method);
631 }
632 FFTWGrid<NDIM> delta_ini_fourier(ic.nmesh, nextra.first, nextra.second);
633 delta_ini_fourier.add_memory_label("delta_ini_fourier(k)");
634 delta_ini_fourier.set_grid_status_real(false);
635
636 timer.StartTiming("InitialDensityField");
639 ic,
640 boxsize,
643 cosmo,
644 grav_ic,
645 rng.get());
646 timer.EndTiming("InitialDensityField");
647
648 // Take the phases from the particles in a file, but use our P(k) for the amplitudes
649 if (ic.random_field_type == SIMCODE::ICRandomFieldType::ReadPhases) {
650 read_phases(delta_ini_fourier);
652 }
653
654 // Reverse the phases? For doing pair-fixed simulations
655 if (ic.reverse_phases) {
656 SIMCODE::reverse_phases<NDIM>(delta_ini_fourier);
657 }
658
659 // Keep the linear field for the hybrid bias spectra (the Lagrangian operators are formed at the lattice points so
660 // we only need the modes the lattice resolves)
661 if (params.hybridbias.enabled) {
663 hybridbias_linear_field_fourier.add_memory_label("delta_L(k,zini) for hybrid bias");
664 FML::NUFFT::copy_fourier_modes<NDIM>(delta_ini_fourier,
666 [](const std::array<int, NDIM> &) { return 1.0; });
667 }
668
669 // Massive neutrino particles (made from the same random field)
671 timer.StartTiming("InitialConditionsNeutrinos");
672 FML::assert_mpi(transferdata != nullptr, "particle_neutrinos needs the transfer functions (transferinfofile)");
673 const auto & nu = species.back();
674 neutrinos.generate(delta_ini_fourier,
676 ic.initial_redshift,
677 cosmo->HoverH0_of_a(ic.a_initial()),
678 nu.Npart_1D,
679 params.particle.allocation_factor,
680 ic.random_seed,
681 nu.id_offset);
682 timer.EndTiming("InitialConditionsNeutrinos");
683 }
684
685 // Separate CDM and baryon particles
686 if (has_baryons()) {
687 timer.StartTiming("InitialConditions");
690 timer.EndTiming("InitialConditions");
691 return;
692 }
693
694 //=============================================================
695 // Displace particles from a regular grid using LPT
696 // The growth rate is used to generate the velocities
697 //=============================================================
698 const double aini = ic.a_initial();
699 const double fac = aini * aini * cosmo->HoverH0_of_a(std::exp(std::log(aini)));
700 std::vector<double> velocity_norms{fac * grav_ic->get_f_1LPT(aini),
701 fac * grav_ic->get_f_2LPT(aini),
702 fac * grav_ic->get_f_3LPTa(aini),
703 fac * grav_ic->get_f_3LPTb(aini)};
704 timer.StartTiming("InitialConditions");
705
706 // Which LPT potentials we need to keep for scale-dependent COLA (max 3LPT)
707 const bool store_potentials = cola.enabled and cola.scaledependent;
708 const bool store_1LPT = store_potentials and FML::PARTICLE::has_get_D_1LPT<T>() and cola.LPT_order >= 1;
709 const bool store_2LPT = store_potentials and FML::PARTICLE::has_get_D_2LPT<T>() and cola.LPT_order >= 2;
710 const bool store_3LPT = store_potentials and FML::PARTICLE::has_get_D_3LPTa<T>() and
711 FML::PARTICLE::has_get_D_3LPTb<T>() and cola.LPT_order >= 3;
712
713 // We get 2LPT, 3LPTa, 3LPTb depending on the size of the vector we send in
714 std::vector<FFTWGrid<NDIM>> phi_nLPT_potentials;
715 if (store_2LPT)
716 phi_nLPT_potentials.resize(1);
717 if (store_3LPT)
718 phi_nLPT_potentials.resize(3);
719
720 // In the N-body gauge the growth rate (and so the 1LPT velocity) is scale-dependent on large scales.
721 // We take it from the (N-body gauge) transfer functions
722 std::function<double(double)> velocity_norm_1LPT_of_kBox = nullptr;
723 Spline growth_rate_of_logk{"f_cb(k,zini)"};
724 if (params.force.nbody_gauge) {
725 FML::assert_mpi(transferdata != nullptr, "force_nbody_gauge needs the transfer functions");
726 const double kmin = transferdata->get_kmin_hmpc_splines();
727 const double kmax = transferdata->get_kmax_hmpc_splines();
728 const int nk = 512;
729 DVector logk(nk), f(nk);
730 for (int i = 0; i < nk; i++) {
731 logk[i] = std::log(kmin) + std::log(kmax / kmin) * i / double(nk - 1);
732 f[i] = transferdata->get_cdm_baryon_growth_rate(std::exp(logk[i]), aini);
733 }
734 growth_rate_of_logk.create(logk, f, "f_cb(k,zini)");
735 // With COLA the velocities are relative to the COLA frame, which has the growth rate of the gravity model
736 // (at k = 0 for scale-independent COLA) for 1LPT and all of the 2LPT velocity. Zeroing the velocities (as for
737 // scale-independent growth) would replace f_nbg(k) by f(0) (0.75% too large velocity on the largest scales)
738 const bool relative_to_cola_frame = cola.enabled;
739 velocity_norm_1LPT_of_kBox = [&, kmin, kmax, relative_to_cola_frame](double kBox) {
740 const double k = std::min(std::max(kBox / boxsize, kmin), kmax);
741 const double f_frame = not relative_to_cola_frame ? 0.0 :
742 cola.scaledependent ? grav->get_f_1LPT(aini, kBox / boxsize / grav->H0_hmpc) :
743 grav->get_f_1LPT(aini);
744 return fac * (growth_rate_of_logk(std::log(k)) - f_frame);
745 };
746 if (relative_to_cola_frame)
748 if (FML::ThisTask == 0)
749 std::cout << "# N-body gauge: growth rate at zini f(k) = " << growth_rate_of_logk(std::log(kmin))
750 << " (k = " << kmin << " h/Mpc), " << growth_rate_of_logk(std::log(0.1)) << " (k = 0.1 h/Mpc). "
751 << "Scale-independent value " << grav_ic->get_f_1LPT(aini) << "\n";
752 }
753
754 // Scale-dependent growth (massive neutrinos with the transfer functions, modified gravity): the 1LPT velocity
755 // is f(k, zini) Psi (the growth rate at k = 0 for all k overestimated the velocity: for 0.4 eV neutrinos
756 // f = 0.998 instead of f_cb = 0.976 for k >> k_fs, which gave +1.7% in P_cb(z = 0) on linear scales). With
757 // scale-dependent COLA the COLA frame already has this velocity; with scale-independent COLA it has f(k = 0) Psi
758 // and the particles get the residual (f(k) - f(0)) Psi.
759 // With ic_use_gravity_model_GR and a modified gravity model the IC have the growth rate of GR (grav_ic) but the
760 // COLA frame that of the gravity model (grav): f(k = 0) for scale-independent COLA, f(k) for scale-dependent COLA.
761 // The particles get the residual (f_IC(k) - f_frame(k)) Psi for the orders the frame has. Zeroing the velocities
762 // (or taking the frame growth rate to be that of the IC) started COLA with the velocity of the gravity model and
763 // the run without COLA with that of GR
764 const bool cola_frame_growth_differs = cola.enabled and grav_ic != grav and grav_ic->get_name() != grav->get_name();
765 if (not params.force.nbody_gauge and
766 ((grav_ic->is_growth_scaledependent() and not(cola.enabled and cola.scaledependent)) or
767 cola_frame_growth_differs)) {
768 const double f0 = cola.enabled ? grav->get_f_1LPT(aini) : 0.0;
769 velocity_norm_1LPT_of_kBox = [&, f0](double kBox) {
770 const double f_frame =
771 cola.enabled and cola.scaledependent ? grav->get_f_1LPT(aini, kBox / boxsize / grav->H0_hmpc) : f0;
772 return fac * (grav_ic->get_f_1LPT(aini, kBox / boxsize / grav_ic->H0_hmpc) - f_frame);
773 };
774 if (cola.enabled)
776 if (FML::ThisTask == 0 and cola_frame_growth_differs)
777 std::cout << "# The IC have the growth rate of GR at zini f = " << grav_ic->get_f_1LPT(aini)
778 << ", the COLA frame that of " << grav->get_name()
779 << " f(k) = " << grav->get_f_1LPT(aini, 0.01 / grav->H0_hmpc) << " (k = 0.01 h/Mpc), "
780 << grav->get_f_1LPT(aini, 1.0 / grav->H0_hmpc) << " (k = 1 h/Mpc): the particles get the "
781 << "difference\n";
782 if (FML::ThisTask == 0 and grav_ic->is_growth_scaledependent())
783 std::cout << "# Scale-dependent growth rate at zini f(k) = "
784 << grav_ic->get_f_1LPT(aini, 0.01 / grav_ic->H0_hmpc) << " (k = 0.01 h/Mpc), "
785 << grav_ic->get_f_1LPT(aini, 0.1 / grav_ic->H0_hmpc) << " (k = 0.1 h/Mpc), "
786 << grav_ic->get_f_1LPT(aini, 1.0 / grav_ic->H0_hmpc) << " (k = 1 h/Mpc). Scale-independent value "
787 << grav_ic->get_f_1LPT(aini) << "\n";
788 }
789
790 // With COLA the velocities in the particles are relative to the COLA frame, which only has the LPT orders up to
791 // simulation_cola_LPT_order (1LPT, 2LPT). The higher orders (2LPT with simulation_cola_LPT_order = 1, 3LPT) keep
792 // their full IC velocity: zeroing all the velocities (cola_initialize_velocities) dropped them (1.7% rms in the
793 // velocity at z = 20 with ic_LPT_order = 2 and simulation_cola_LPT_order = 1)
794 if (cola.enabled and ic.LPT_order > cola.LPT_order)
797 // velocity_norms = {1LPT, 2LPT, 3LPTa, 3LPTb}: the frame has the first cola.LPT_order (<= 2) of them
798 for (int i = 0; i < cola.LPT_order; i++)
799 velocity_norms[i] = 0.0;
800 }
801
802 // The same for the 2LPT velocity: f_2LPT(k, zini) Psi_2LPT with k the wavenumber of the 2LPT field (as in the
803 // COLA frame of scale-dependent COLA, which therefore needs nothing extra). Using f_2LPT(k = 0) for all k gave
804 // velocities that differed from those of scale-dependent COLA by 4.3e-4 rms for 0.4 eV neutrinos. With
805 // scale-independent COLA the frame has f_2LPT(0) Psi_2LPT and the particles get the residual. In the N-body gauge
806 // (above) only the 1LPT growth rate differs from that of the gravity model (on horizon scales, from the transfer
807 // functions); the 2LPT velocity is that of the gravity model in both cases (as in the COLA frame).
808 // With simulation_cola_LPT_order = 1 the frame has no 2LPT velocity and the particles get all of it. With
809 // ic_use_gravity_model_GR and modified gravity the residual relative to the frame of the gravity model (see above)
810 std::function<double(double)> velocity_norm_2LPT_of_kBox = nullptr;
811 const bool cola_frame_has_2LPT = cola.enabled and cola.LPT_order >= 2;
812 if (ic.LPT_order >= 2 and
813 ((grav_ic->is_growth_scaledependent() and (not cola_frame_has_2LPT or not cola.scaledependent)) or
814 (cola_frame_has_2LPT and cola_frame_growth_differs))) {
815 const double f2_frame0 = cola_frame_has_2LPT ? grav->get_f_2LPT(aini) : 0.0;
816 velocity_norm_2LPT_of_kBox = [&, f2_frame0, cola_frame_has_2LPT](double kBox) {
817 const double f2_frame = cola_frame_has_2LPT and cola.scaledependent ?
818 grav->get_f_2LPT(aini, kBox / boxsize / grav->H0_hmpc) :
819 f2_frame0;
820 return fac * (grav_ic->get_f_2LPT(aini, kBox / boxsize / grav_ic->H0_hmpc) - f2_frame);
821 };
822 // (with COLA the velocities are already relative to the frame, see above)
823 FML::assert_mpi(not cola.enabled or ic_velocities_relative_to_cola_frame,
824 "Internal error: scale-dependent 2LPT velocity with COLA must be relative to the COLA frame");
825 if (FML::ThisTask == 0 and grav_ic->is_growth_scaledependent())
826 std::cout << "# Scale-dependent 2LPT growth rate at zini f_2(k) = "
827 << grav_ic->get_f_2LPT(aini, 0.01 / grav_ic->H0_hmpc) << " (k = 0.01 h/Mpc), "
828 << grav_ic->get_f_2LPT(aini, 0.1 / grav_ic->H0_hmpc) << " (k = 0.1 h/Mpc), "
829 << grav_ic->get_f_2LPT(aini, 1.0 / grav_ic->H0_hmpc) << " (k = 1 h/Mpc). Scale-independent value "
830 << grav_ic->get_f_2LPT(aini) << "\n";
831 }
832
834 params.particle.Npart_1D,
835 params.particle.allocation_factor,
836 delta_ini_fourier,
837 phi_nLPT_potentials,
838 ic.LPT_order,
839 boxsize,
840 ic.initial_redshift,
841 velocity_norms,
842 velocity_norm_1LPT_of_kBox,
843 nullptr,
844 nullptr,
845 nullptr,
846 velocity_norm_2LPT_of_kBox);
847
849
850 // Store the potentials
851 if (store_1LPT) {
852 cola.phi_1LPT_ini_fourier = SIMCODE::compute_phi_1LPT_from_delta<NDIM>(delta_ini_fourier);
853 cola.phi_1LPT_ini_fourier.add_memory_label("phi_1LPT(k,zini)");
854 }
855 if (store_2LPT) {
856 if (FML::ThisTask == 0)
857 std::cout << "Storing phi_2LPT(k,zini) for scale-dependent COLA\n";
858 cola.phi_2LPT_ini_fourier = phi_nLPT_potentials[0];
859 cola.phi_2LPT_ini_fourier.add_memory_label("phi_2LPT(k,zini)");
860 }
861 if (store_3LPT) {
862 if (FML::ThisTask == 0)
863 std::cout << "Storing phi_3LPTa(k,zini) and phi_3LPTb(k,zini) for scale-dependent COLA\n";
864 cola.phi_3LPTa_ini_fourier = phi_nLPT_potentials[1];
865 cola.phi_3LPTb_ini_fourier = phi_nLPT_potentials[2];
866 cola.phi_3LPTa_ini_fourier.add_memory_label("phi_3LPTa(k,zini)");
867 cola.phi_3LPTb_ini_fourier.add_memory_label("phi_3LPTb(k,zini)");
868 }
869
870 timer.EndTiming("InitialConditions");
871}
FML::SOLVERS::FFTLog::DVector DVector
Definition Main.cpp:4
Spline power_initial_spline
Definition Simulation.h:153
void generate_initial_conditions_two_species(const FFTWGrid< NDIM > &delta_cb_fourier)
The initial conditions with separate CDM and baryon particles (see two_species_ic_splines and generat...
Definition Simulation.h:921
void apply_lattice_offset()
Offset the particle lattice from the nodes of the force grid.
Definition Simulation.h:878
bool ic_velocities_relative_to_cola_frame
Definition Simulation.h:143
void read_ic()
Read the particles from gadget files. With COLA we also reconstruct the LPT displacement fields.
std::shared_ptr< GravityModel< NDIM > > grav_ic
The gravity model used to make the IC (GR if ic_use_gravity_model_GR, otherwise grav)
Definition Simulation.h:90
void read_phases(FFTWGrid< NDIM > &delta_fourier)
Compute delta(k) from particles in gadget files (used to take the phases from them)
Spline power_primordial_spline
Definition Simulation.h:152
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
void copy_fourier_modes(const FFTWGrid< N > &src, FFTWGrid< N > &dst, const std::function< double(const std::array< int, N > &)> &factor)
Copy all Fourier modes with from one grid to another of a different size, multiplying by factor(m).
Definition NUFFT.h:544
void reverse_phases(FFTWGrid< NDIM > &delta_fourier)
delta(k) -> -delta(k) (for paired simulations)
void whiten_and_set_power_spectrum(FFTWGrid< NDIM > &delta_fourier, const Spline &power_initial_spline, double boxsize)
Keep the phases of delta(k), but set the amplitudes to sqrt(P(k,zini)): |delta(k)| -> sqrt(P(k))
std::shared_ptr< RandomGenerator > make_random_generator(const ICSettings &ic)
The random number generator to use for the initial conditions.
FFTWGrid< NDIM > compute_phi_1LPT_from_delta(const FFTWGrid< NDIM > &delta_fourier)
The 1LPT potential phi_1LPT(k) = delta(k) / k^2 (i.e. D^2 phi_1LPT = -delta)
void generate_initial_density_field(FFTWGrid< NDIM > &delta_ini_fourier, const ICSettings &ic, double boxsize, const Spline &power_initial_spline, const Spline &power_primordial_spline, std::shared_ptr< Cosmology > cosmo, std::shared_ptr< GravityModel< NDIM > > grav_ic, RandomGenerator *rng)
Generate a gaussian or non-gaussian (non-local fNL) random field delta(k,zini) in fourier space with ...
const double kmax
Definition test_fnl.cpp:43
std::mt19937_64 rng(1234)

◆ generate_initial_conditions_two_species()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::generate_initial_conditions_two_species ( const FFTWGrid< NDIM > & delta_cb_fourier)
protected

The initial conditions with separate CDM and baryon particles (see two_species_ic_splines and generate_species_from_delta_cb in InitialConditions.h).

The 2LPT displacement is that of the total (CDM+baryon) field for both. By default (particle_baryon_lattice = same) the baryons start from the same lattice as the CDM. With "offset" their lattice is offset by half a particle spacing in each direction. Their IDs follow those of the CDM. NB: interleaved (offset) lattices give a large spurious growth of the baryon-CDM difference on scales k > k_Ny/8 of the particles (and a few % too little CDM+baryon power at k ~ k_Ny/2) in this PM code; with the same lattice the difference follows linear theory on all scales and the CDM+baryon P(k) is that of one species (see the README)

Definition at line 921 of file Simulation.h.

921 {
922 const auto & ic = params.ic;
923 const double boxsize = params.simulation.boxsize;
924 const double aini = ic.a_initial();
925 FML::assert_mpi(ic_transfers != nullptr, "particle_baryons needs the transfer functions (transferinfofile)");
926 const auto & cdm = species[0];
927 const auto & baryon = species[1];
929 *grav_ic,
930 ic.initial_redshift,
931 cdm.weight_cb,
932 baryon.weight_cb);
933
934 const double fac = aini * aini * cosmo->HoverH0_of_a(aini);
935 const std::vector<double> velocity_norms{fac * grav_ic->get_f_1LPT(aini),
936 fac * grav_ic->get_f_2LPT(aini),
937 fac * grav_ic->get_f_3LPTa(aini),
938 fac * grav_ic->get_f_3LPTb(aini)};
939 const double kmin = ic_transfers->range().kmin_hmpc;
940 const double kmax = ic_transfers->range().kmax_hmpc;
941 auto clamp_logk = [&](double kBox) { return std::log(std::min(std::max(kBox / boxsize, kmin), kmax)); };
942 // The baryon-CDM relative mode: in the displacement (each species its own displacement and velocity), the
943 // masses m = 1 + eps (mass: shared CDM+baryon flow, eps = the linear relative mode today; mass_ini: shared
944 // displacement, eps at zini and each species its own velocity)
945 const std::string & relative_mode = params.particle.baryon_relative_mode;
946 const bool mass_mode = relative_mode == "mass" or relative_mode == "mass_ini";
947 std::pair<Spline, Spline> eps_today;
948 if (relative_mode == "mass") {
949 eps_today = SIMCODE::two_species_mass_contrast_today(*ic_transfers, ic.initial_redshift);
950 if (FML::ThisTask == 0) {
951 std::cout << "# Mass-encoded relative mode: eps_b / delta_cb(zini) = ";
952 for (double k : {0.01, 0.1, 1.0})
953 std::cout << eps_today.second(std::log(k)) << " (k = " << k << ") ";
954 std::cout << "\n";
955 }
956 }
957 auto make_species = [&](MPIParticles & particles,
959 const Spline & ratio,
960 const Spline & growth_rate,
961 const Spline * eps_of_logk,
962 double shift) {
963 if (FML::ThisTask == 0)
964 std::cout << "# Making the " << info.name << " particles\n";
965 // With COLA the species share the COLA frame of the total CDM+baryon field and the velocities we set are
966 // relative to it: v_i - v_frame = a^2 H [(f_i - f_frame / R_i) Psi_i] for 1LPT (Psi_i = R_i Psi_cb) and zero
967 // for 2LPT (the same for all species; all of the 2LPT velocity with simulation_cola_LPT_order = 1 as the frame
968 // then has none, see generate_initial_conditions). The frame velocity is f_frame Psi_cb with f_frame = f_cb(k)
969 // for scale-dependent COLA, but the growth rate at k = 0 for scale-independent COLA (the frame adds back
970 // grav->get_f_1LPT(a), as for one species). Using f_cb(k) there with scale-dependent growth gave the
971 // velocities (f_cb(k) - f(0)) Psi_cb too little (-1.75% rms for 0.4 eV neutrinos). The frame has the growth
972 // rate of the gravity model (grav), also with ic_use_gravity_model_GR where the IC have that of GR (grav_ic)
973 std::vector<double> residual_velocity_norms = velocity_norms;
974 for (int i = 0; i < cola.LPT_order; i++)
975 residual_velocity_norms[i] = 0.0;
976 auto f_frame = [&](double logk) {
977 return cola.scaledependent ? grav->get_f_1LPT(aini, std::exp(logk) / grav->H0_hmpc) :
978 grav->get_f_1LPT(aini);
979 };
980 std::function<double(double)> velocity_norm_1LPT = [&](double kBox) {
981 const double logk = clamp_logk(kBox);
982 if (not cola.enabled)
983 return fac * growth_rate(logk);
984 return fac * (growth_rate(logk) - f_frame(logk) / ratio(logk));
985 };
986 // The 2LPT velocity with scale-dependent growth: f_2LPT(k) Psi_2LPT (relative to the frame with f_2LPT(0) for
987 // scale-independent COLA, nothing for scale-dependent COLA whose frame has f_2LPT(k); see
988 // generate_initial_conditions; all of it with simulation_cola_LPT_order = 1 where the frame has no 2LPT). With
989 // ic_use_gravity_model_GR and modified gravity (f_2LPT,GR - f_2LPT,frame(k)) Psi_2LPT
990 std::function<double(double)> velocity_norm_2LPT = nullptr;
991 const bool cola_frame_has_2LPT = cola.enabled and cola.LPT_order >= 2;
992 const bool cola_frame_growth_differs =
993 cola.enabled and grav_ic != grav and grav_ic->get_name() != grav->get_name();
994 if (ic.LPT_order >= 2 and
995 ((grav_ic->is_growth_scaledependent() and (not cola_frame_has_2LPT or not cola.scaledependent)) or
996 (cola_frame_has_2LPT and cola_frame_growth_differs))) {
997 const double f2_frame0 = cola_frame_has_2LPT ? grav->get_f_2LPT(aini) : 0.0;
998 velocity_norm_2LPT = [&, f2_frame0, cola_frame_has_2LPT](double kBox) {
999 const double f2_frame = cola_frame_has_2LPT and cola.scaledependent ?
1000 grav->get_f_2LPT(aini, kBox / boxsize / grav->H0_hmpc) :
1001 f2_frame0;
1002 return fac * (grav_ic->get_f_2LPT(aini, kBox / boxsize / grav_ic->H0_hmpc) - f2_frame);
1003 };
1004 }
1005 std::function<double(double)> displacement_ratio = [&](double kBox) { return ratio(clamp_logk(kBox)); };
1006 std::function<double(double)> mass_contrast = nullptr;
1007 if (mass_mode) {
1008 // Both species are displaced by Psi_cb. mass: the CDM+baryon velocity f_cb Psi_cb. mass_ini: the velocity
1009 // of the species v_i = f_i R_i Psi_cb. With COLA relative to the frame velocity f_frame Psi_cb
1010 displacement_ratio = [](double) { return 1.0; };
1011 velocity_norm_1LPT = [&](double kBox) {
1012 const double logk = clamp_logk(kBox);
1013 const double f_cb = grav_ic->get_f_1LPT(aini, std::exp(logk) / grav_ic->H0_hmpc);
1014 const double f_i = relative_mode == "mass" ? f_cb : growth_rate(logk) * ratio(logk);
1015 return fac * (cola.enabled ? f_i - f_frame(logk) : f_i);
1016 };
1017 if (relative_mode == "mass")
1018 mass_contrast = [&](double kBox) { return (*eps_of_logk)(clamp_logk(kBox)); };
1019 else
1020 mass_contrast = [&](double kBox) { return ratio(clamp_logk(kBox)) - 1.0; };
1021 }
1023 delta_cb_fourier,
1024 displacement_ratio,
1025 velocity_norm_1LPT,
1026 cola.enabled ? residual_velocity_norms : velocity_norms,
1027 ic.LPT_order,
1028 info.Npart_1D,
1029 params.particle.allocation_factor,
1030 boxsize,
1031 ic.initial_redshift,
1032 shift,
1033 info.id_offset,
1034 cola.enabled,
1035 mass_contrast,
1036 velocity_norm_2LPT);
1037 };
1038 make_species(part, cdm, splines.ratio_cdm, splines.f_cdm, &eps_today.first, 0.0);
1039 const double baryon_shift = params.particle.baryon_lattice == "offset" ? 0.5 / double(baryon.Npart_1D) : 0.0;
1040 make_species(part_baryon, baryon, splines.ratio_baryon, splines.f_baryon, &eps_today.second, baryon_shift);
1041
1042 // Scale-dependent COLA: the LPT potentials of the total CDM+baryon field (the shared COLA frame)
1043 if (cola.enabled and cola.scaledependent) {
1044 if (FML::PARTICLE::has_get_D_1LPT<T>() and cola.LPT_order >= 1) {
1045 cola.phi_1LPT_ini_fourier = SIMCODE::compute_phi_1LPT_from_delta<NDIM>(delta_cb_fourier);
1046 cola.phi_1LPT_ini_fourier.add_memory_label("phi_1LPT(k,zini)");
1047 }
1048 if (FML::PARTICLE::has_get_D_2LPT<T>() and cola.LPT_order >= 2 and ic.LPT_order >= 2) {
1049 FML::COSMOLOGY::LPT::compute_2LPT_potential_fourier(delta_cb_fourier, cola.phi_2LPT_ini_fourier);
1050 cola.phi_2LPT_ini_fourier.add_memory_label("phi_2LPT(k,zini)");
1051 }
1052 // The baryons on the offset lattice: the potentials of the shifted field, as for their IC (see
1053 // ColaState::ShiftedSpecies)
1054 if (baryon_shift != 0.0) {
1055 if (FML::ThisTask == 0)
1056 std::cout << "Storing the LPT potentials of the offset baryon lattice for scale-dependent COLA\n";
1058 sp.part = &part_baryon;
1059 sp.shift = baryon_shift;
1060 FFTWGrid<NDIM> delta_shifted = delta_cb_fourier;
1061 std::array<double, NDIM> shift_vec;
1062 shift_vec.fill(baryon_shift);
1063 FML::GRID::shift_grid_fourier<NDIM>(delta_shifted, shift_vec, +1.0);
1064 if (cola.phi_1LPT_ini_fourier) {
1066 sp.phi_1LPT_ini_fourier.add_memory_label("phi_1LPT(k,zini) baryons");
1067 }
1068 if (cola.phi_2LPT_ini_fourier) {
1070 sp.phi_2LPT_ini_fourier.add_memory_label("phi_2LPT(k,zini) baryons");
1071 }
1072 cola.shifted_species.push_back(std::move(sp));
1073 }
1074 }
1075}
const int Npart_1D
Definition Main.cpp:50
std::shared_ptr< FML::INITIALCONDITIONS::TransferProvider > ic_transfers
Definition Simulation.h:95
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 shift_grid_fourier(FFTWGrid< N > &fourier_grid, const std::array< double, N > &shift, double sign=+1.0)
Translate a field given in Fourier space: , i.e.
TwoSpeciesICSplines two_species_ic_splines(const FML::INITIALCONDITIONS::TransferProvider &provider, const GravityModel< NDIM > &grav_ic, double zini, double weight_cdm, double weight_baryon)
FFTWGrid< NDIM > generate_species_from_delta_cb(FML::PARTICLE::MPIParticles< P > &particles, const FFTWGrid< NDIM > &delta_cb_fourier, const std::function< double(double)> &ratio_of_kBox, std::function< double(double)> velocity_norm_1LPT_of_kBox, const std::vector< double > &velocity_norms, int LPT_order, int Npart_1D, double allocation_factor, double boxsize, double zini, double lattice_shift, long long int id_offset, bool store_cb_LPT_fields=false, std::function< double(double)> mass_contrast_of_kBox=nullptr, std::function< double(double)> velocity_norm_2LPT_of_kBox=nullptr)
Make the particles of a species i from the CDM+baryon density field delta_cb(k,zini): delta_i(k) = de...
A species on its own lattice, offset by shift (in each direction) from the lattice of the potentials ...
Definition COLA.h:1010
const FML::PARTICLE::MPIParticles< T > * part
Definition COLA.h:1011
FML::GRID::FFTWGrid< NDIM > phi_2LPT_ini_fourier
Definition COLA.h:1014
FML::GRID::FFTWGrid< NDIM > phi_1LPT_ini_fourier
Definition COLA.h:1013

◆ get_baryon_particles()

template<int NDIM, class T >
MPIParticles & NBodySimulation< NDIM, T >::get_baryon_particles ( )
inline

Definition at line 201 of file Simulation.h.

201{ return part_baryon; }

◆ get_cosmology()

template<int NDIM, class T >
std::shared_ptr< Cosmology > NBodySimulation< NDIM, T >::get_cosmology ( ) const
inline

Definition at line 264 of file Simulation.h.

264{ return cosmo; }

◆ get_gravity_model()

template<int NDIM, class T >
std::shared_ptr< GravityModel< NDIM > > NBodySimulation< NDIM, T >::get_gravity_model ( ) const
inline

Definition at line 265 of file Simulation.h.

265{ return grav; }

◆ get_gravity_model_ic()

template<int NDIM, class T >
std::shared_ptr< GravityModel< NDIM > > NBodySimulation< NDIM, T >::get_gravity_model_ic ( ) const
inline

Definition at line 266 of file Simulation.h.

266{ return grav_ic; }

◆ get_hybridbias_linear_field()

template<int NDIM, class T >
const FFTWGrid< NDIM > & NBodySimulation< NDIM, T >::get_hybridbias_linear_field ( ) const
inline

The linear density field delta_cb(zini,k) of the initial conditions (only if hybridbias)

Definition at line 275 of file Simulation.h.

◆ get_neutrino_particles()

template<int NDIM, class T >
SIMCODE::NeutrinoParticles< NDIM >::Container & NBodySimulation< NDIM, T >::get_neutrino_particles ( )
inline

Definition at line 205 of file Simulation.h.

205{ return neutrinos.particles(); }

◆ get_neutrinos()

template<int NDIM, class T >
SIMCODE::NeutrinoParticles< NDIM > & NBodySimulation< NDIM, T >::get_neutrinos ( )
inline

Definition at line 204 of file Simulation.h.

204{ return neutrinos; }

◆ get_parameters()

template<int NDIM, class T >
const Parameters & NBodySimulation< NDIM, T >::get_parameters ( ) const
inline

Definition at line 197 of file Simulation.h.

197{ return params; }
Parameters params
The parameters of the simulation.
Definition Simulation.h:101

◆ get_particles()

template<int NDIM, class T >
MPIParticles & NBodySimulation< NDIM, T >::get_particles ( )
inline

Definition at line 198 of file Simulation.h.

198{ return part; }

◆ get_pofk_cb_every_step()

template<int NDIM, class T >
const auto & NBodySimulation< NDIM, T >::get_pofk_cb_every_step ( ) const
inline

Definition at line 269 of file Simulation.h.

269{ return pofk_cb_every_step; }

◆ get_pofk_every_output()

template<int NDIM, class T >
const auto & NBodySimulation< NDIM, T >::get_pofk_every_output ( ) const
inline

Definition at line 272 of file Simulation.h.

272{ return pofk_every_output; }

◆ get_pofk_multipoles_every_output()

template<int NDIM, class T >
const auto & NBodySimulation< NDIM, T >::get_pofk_multipoles_every_output ( ) const
inline

Definition at line 273 of file Simulation.h.

◆ get_pofk_species_every_step()

template<int NDIM, class T >
const auto & NBodySimulation< NDIM, T >::get_pofk_species_every_step ( ) const
inline

Definition at line 271 of file Simulation.h.

271{ return pofk_species_every_step; }

◆ get_pofk_total_every_step()

template<int NDIM, class T >
const auto & NBodySimulation< NDIM, T >::get_pofk_total_every_step ( ) const
inline

Definition at line 270 of file Simulation.h.

270{ return pofk_total_every_step; }

◆ get_power_initial_spline()

template<int NDIM, class T >
const Spline & NBodySimulation< NDIM, T >::get_power_initial_spline ( ) const
inline

Definition at line 268 of file Simulation.h.

268{ return power_initial_spline; }

◆ get_species()

template<int NDIM, class T >
const std::vector< SIMCODE::SpeciesInfo > & NBodySimulation< NDIM, T >::get_species ( ) const
inline

The particle species (in the order of the IDs)

Definition at line 208 of file Simulation.h.

208{ return species; }

◆ get_transferdata()

template<int NDIM, class T >
std::shared_ptr< LinearTransferData > NBodySimulation< NDIM, T >::get_transferdata ( ) const
inline

Definition at line 267 of file Simulation.h.

267{ return transferdata; }

◆ has_baryons()

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::has_baryons ( ) const
inline

Separate CDM and baryon particles? Then get_particles() are the CDM particles.

Definition at line 200 of file Simulation.h.

200{ return params.particle.baryons; }

◆ has_neutrino_particles()

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::has_neutrino_particles ( ) const
inline

Massive neutrinos as particles (delta-f method)?

Definition at line 203 of file Simulation.h.

203{ return params.particle.neutrinos; }

◆ init()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::init ( )

Generate the initial conditions.

Definition at line 426 of file Simulation.h.

426 {
427
428 if (FML::ThisTask == 0) {
429 std::cout << "\n";
430 std::cout << "#=====================================================\n";
431 std::cout << "# Create initial conditions\n";
432 std::cout << "#=====================================================\n";
433 }
434
435 // Empty output_folder means to output to current directory. Otherwise make folder
436 if (params.output.folder != "") {
437 if (not FML::create_folder(params.output.folder)) {
438 throw std::runtime_error("Cannot create output directory [" + params.output.folder + "]");
439 }
440 }
441
443
444 // The particle species (CDM+baryons as one, or CDM and baryons, and massive neutrinos)
445 if (has_neutrino_particles() and not(cosmo->get_OmegaMNu() > 0.0 and cosmo->get_Mnu_eV() > 0.0))
446 throw std::runtime_error("particle_neutrinos = true needs massive neutrinos (cosmology_OmegaMNu > 0)");
448 if (FML::ThisTask == 0 and species.size() > 1) {
449 std::cout << "# Particle species (name, Npart_1D, GADGET type, Omega_i / OmegaM, weight in delta_cb):\n";
450 for (auto & info : species)
451 std::cout << "# " << info.name << " " << info.Npart_1D << " " << info.gadget_type << " "
452 << info.mass_fraction << " " << info.weight_cb << "\n";
453 }
455 const double mnu_eV = cosmo->get_Mnu_eV() / cosmo->get_N_nu();
456 const double Tnu0_eV = cosmo->get_neutrino_temperature_eV(1.0);
457 neutrinos.init(mnu_eV, Tnu0_eV, params.simulation.boxsize, params.particle.neutrino_deltaf);
458 if (FML::ThisTask == 0)
459 std::cout << "# Massive neutrinos as particles (delta-f weights: " << std::boolalpha
460 << params.particle.neutrino_deltaf << "). m_nu = " << mnu_eV << " eV (x" << cosmo->get_N_nu()
461 << "), T_nu0 = " << Tnu0_eV << " eV, f_nu = " << cosmo->get_fMNu() << "\n";
462 }
463
464 // If we have a MG model and want exactly the same IC as for LCDM
465 // we can supply LCDM P(k) and use the GR growth factors to scale it back
466 if (params.ic.use_gravity_model_GR) {
467 grav_ic = std::make_shared<GravityModelGR<NDIM>>(cosmo);
468 grav_ic->read_parameters(*parameters);
469 grav_ic->init();
470 } else {
471 grav_ic = grav;
472 }
473
475
477
478 // The N-body gauge source needs the initial density field of the particles
479 if (params.force.nbody_gauge)
481
482 // In the COLA frame v=0 so reset velocities. With CDM and baryons as separate particles the initial conditions
483 // already have the velocities relative to the shared COLA frame (the baryon-CDM relative velocity)
484 if (cola.enabled and not has_baryons() and not ic_velocities_relative_to_cola_frame) {
486 }
487
488 // Set up the lightcone
489 std::vector<std::string> particle_types_lightcone{"cb"};
490 lightcone = std::make_shared<Lightcone<NDIM, T>>(cosmo);
491 lightcone->read_parameters(*parameters);
492 lightcone->init(particle_types_lightcone);
493}
void cola_initialize_velocities(FML::PARTICLE::MPIParticles< T > &part)
Definition COLA.h:33
void output_background_and_growth_functions()
Definition Simulation.h:496
void generate_initial_conditions()
Create the particles: either generate the initial conditions from a random field (gaussian / non-gaus...
Definition Simulation.h:614
void setup_initial_power_spectrum()
Read the input P(k) / T(k), bring it to the initial redshift, make splines and (optionally) normalize...
Definition Simulation.h:516
void setup_nbody_gauge()
Read the N-body gauge source, check it and store the initial density field of the particles.
std::shared_ptr< ParameterMap > parameters
A copy of the parameterfile (passed on to the models we create)
Definition Simulation.h:98
std::vector< SpeciesInfo > make_species_list(const ParticleSettings &particle, const Cosmology &cosmo, int ndim)
The particle species of a simulation (in the order of the IDs)
Definition Species.h:38

◆ initial_density_in_particle_frame()

template<int NDIM, class T >
const FML::GRID::FFTWGrid< NDIM > & NBodySimulation< NDIM, T >::initial_density_in_particle_frame ( )
protected

The initial density field in the frame of the particles (with force interlacing the particles are shifted by density_shift relative to the grid: delta_s(k) = exp(-ik.s) delta(k)).

During the early-time force: the one with its density assignment

Definition at line 274 of file SimulationDensity.h.

274 {
275 const auto & delta_ini =
277 if (not particles_shifted())
278 return delta_ini;
282 }
284}
std::array< double, NDIM > density_shift
Definition Simulation.h:129

◆ kick_with_interlaced_force()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::kick_with_interlaced_force ( const StepInfo & s)
protected

The kick with force interlacing: the force is computed for force_interlacing_order copies of the particles shifted by a fraction of a cell relative to the grid (see FML::INTERPOLATION::generate_interlacing_shifts), interpolated to the shifted particles and averaged.

This cancels the leading aliasing terms of both the density assignment and the force interpolation

Definition at line 1439 of file Simulation.h.

1439 {
1440 const auto & sim = params.simulation;
1441 const auto & force = current_force;
1442 const auto nleftright =
1444 const auto shifts =
1445 FML::INTERPOLATION::generate_interlacing_shifts<NDIM>(force.interlacing_order, 1.0 / double(force.nmesh));
1446 // With one task the shifted particles can be wrapped in all directions. Otherwise not in x (they stay on
1447 // their task and the grid has one extra slice on the right for the ones that end up outside the domain)
1448 const int wrap_type = FML::NTasks == 1 ? 1 : 2;
1449
1450 auto * p = part.get_particles_ptr();
1451 const size_t npart = part.get_npart();
1452 std::array<std::vector<FML::GRID::FloatType>, NDIM> force_sum;
1453 for (auto & f : force_sum)
1454 f.assign(npart, 0.0);
1455 // The positions are restored exactly after each shift (shifting back changes them in the last digit)
1456 const auto saved_pos = FML::PARTICLE::save_particle_positions<T, NDIM>(p, npart);
1457 for (auto & shift : shifts) {
1458 FML::PARTICLE::shift_particles<T, NDIM>(p, npart, shift, +1.0, wrap_type);
1459 density_shift = shift;
1460
1461 FFTWGrid<NDIM> density_grid_fourier(force.nmesh, nleftright.first, nleftright.second + 1);
1462 timer.StartTiming("ComputeDensityField");
1463 compute_density_field_fourier(density_grid_fourier, s.apos);
1464 timer.EndTiming("ComputeDensityField");
1465
1466 timer.StartTiming("ComputeForce");
1467 std::array<FFTWGrid<NDIM>, NDIM> force_real;
1468 grav->compute_force(s.apos,
1469 grav->H0_hmpc * sim.boxsize,
1470 density_grid_fourier,
1471 force.density_assignment_method,
1472 force_real,
1474 timer.EndTiming("ComputeForce");
1475
1476 timer.StartTiming("Kick");
1477 for (int idim = 0; idim < NDIM; idim++)
1478 force_real[idim].communicate_boundaries();
1479 std::array<std::vector<FML::GRID::FloatType>, NDIM> force_particle;
1481 p,
1482 npart,
1483 force_particle,
1484 force.density_assignment_method);
1485 const double norm = 1.0 / double(shifts.size());
1486 for (int idim = 0; idim < NDIM; idim++)
1487 for (size_t i = 0; i < npart; i++)
1488 force_sum[idim][i] += force_particle[idim][i] * norm;
1489 timer.EndTiming("Kick");
1490
1492 }
1493 density_shift = {};
1494
1495 // Kick: v -> velocity_scale * v - F dt
1496#ifdef USE_OMP
1497#pragma omp parallel for
1498#endif
1499 for (size_t i = 0; i < npart; i++) {
1500 auto * vel = FML::PARTICLE::GetVel(p[i]);
1501 for (int idim = 0; idim < NDIM; idim++)
1502 vel[idim] = vel[idim] * s.velocity_scale - force_sum[idim][i] * s.delta_time_kick;
1503 }
1504}
void compute_density_field_fourier(FFTWGrid< NDIM > &density_grid_fourier, double a)
Assign the particles to a grid, Fourier transform it and add the other contributions to delta_m (see ...
FML::NBODY::ForceOptions force_options
Definition Simulation.h:133
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::vector< std::array< double, NDIM > > generate_interlacing_shifts(int interlacing_order, double dx)
Generate the set of shifts used for interlacing (alias reduction by averaging the density field compu...
void restore_particle_positions(T *part, size_t NumPart, const std::vector< U > &saved)
Restore the positions saved by save_particle_positions (bit-for-bit)
auto save_particle_positions(T *part, size_t NumPart)
Copy of the positions of a set of particles (NDIM values per particle) so that they can be restored e...
constexpr double * GetVel(...)
void shift_particles(T *part, size_t NumPart, const std::array< double, NDIM > &shift, double sign=1.0, int wrap_type=1)
Shift the positions of a set of particles: .
int NTasks
Total number of MPI tasks.
Definition Global.cpp:40

◆ neutrino_energy_density()

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::neutrino_energy_density ( ) const
inline

Use the energy density of the neutrinos (force_neutrino_energy_density)

Definition at line 263 of file Simulation.h.

263{ return params.force.neutrino_energy_density; }

◆ neutrino_energy_factor()

template<int NDIM, class T >
double NBodySimulation< NDIM, T >::neutrino_energy_factor ( double a) const
inline

The mean energy per mass of the neutrinos <E/m>(a) with force_neutrino_energy_density, otherwise 1.

Definition at line 255 of file Simulation.h.

255 {
256 if (not params.force.neutrino_energy_density)
257 return 1.0;
259 cosmo->get_Mnu_eV() / cosmo->get_N_nu(),
260 cosmo->get_neutrino_temperature_eV(1.0));
261 }
double mean_energy_factor(double a, double mnu_eV, double Tnu0_eV)
The mean energy per mass of the unperturbed neutrinos, <E/m> = <sqrt(1 + u^2)> over the Fermi-Dirac d...
Definition Neutrinos.h:34

◆ output_background_and_growth_functions()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::output_background_and_growth_functions ( )
protected

Definition at line 496 of file Simulation.h.

496 {
497 if (FML::ThisTask != 0)
498 return;
499 const std::string cosmoprefix = params.output.path("cosmology_" + params.simulation.name);
500 const std::string gravprefix = params.output.path("gravitymodel_" + params.simulation.name);
501 cosmo->output(cosmoprefix + ".txt");
502 grav->output(gravprefix + "_k0.00001.txt", 1e-5 / grav->H0_hmpc);
503 grav->output(gravprefix + "_k0.0001.txt", 1e-4 / grav->H0_hmpc);
504 grav->output(gravprefix + "_k0.001.txt", 1e-3 / grav->H0_hmpc);
505 grav->output(gravprefix + "_k0.01.txt", 1e-2 / grav->H0_hmpc);
506 grav->output(gravprefix + "_k0.1.txt", 1e-1 / grav->H0_hmpc);
507 grav->output(gravprefix + "_k1.0.txt", 1e+0 / grav->H0_hmpc);
508 grav->output(gravprefix + "_k10.0.txt", 1e+1 / grav->H0_hmpc);
509}

◆ particles_shifted()

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::particles_shifted ( ) const
inlineprotected

Definition at line 321 of file Simulation.h.

321 {
322 return std::any_of(density_shift.begin(), density_shift.end(), [](double x) { return x != 0.0; });
323 }

◆ read_ic()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::read_ic ( )
protected

Read the particles from gadget files. With COLA we also reconstruct the LPT displacement fields.

Definition at line 1125 of file Simulation.h.

1125 {
1127 params,
1128 cosmo,
1129 grav_ic,
1130 cola.phi_1LPT_ini_fourier,
1131 cola.phi_2LPT_ini_fourier);
1132
1133 // With the LPT fields reconstructed from the density field the COLA frame velocity is only an approximation to the
1134 // velocities in the file (smoothed, from the Eulerian density). Keep the velocities of the file: store them
1135 // relative to the frame instead of replacing them by it. (The exact reconstruction reproduces them, so nothing to
1136 // do there)
1137 if (cola.enabled and not params.ic.reconstruct_exact) {
1138 cola.add_on_LPT_velocity(part, params.ic.a_initial(), -1.0);
1140 }
1141}
void read_ic_from_gadget(FML::PARTICLE::MPIParticles< T > &part, const SimulationParameters &params, std::shared_ptr< Cosmology > cosmo, std::shared_ptr< GravityModel< NDIM > > grav_ic, FML::GRID::FFTWGrid< NDIM > &phi_1LPT_ini_fourier, FML::GRID::FFTWGrid< NDIM > &phi_2LPT_ini_fourier)
Read the particles from gadget files into part.
Definition ExternalIC.h:340

◆ read_parameters()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::read_parameters ( ParameterMap & param)

Read (and check) the parameters.

Definition at line 333 of file Simulation.h.

333 {
334 parameters = std::make_shared<ParameterMap>(param);
335 params.read(param);
336 if (params.baryonification.enabled) {
337 if (NDIM != 3 || grav->get_name() != "GR" || cosmo->get_OmegaMNu() != 0.0)
338 throw std::runtime_error(
339 "baryonification currently requires NDIM=3, gravity_model=GR and cosmology_OmegaMNu=0");
340 params.baryonification.profile_model(cosmo->get_Omegab() / cosmo->get_OmegaM()).validate();
341 }
342
343 // We cannot use COLA if the particle type is not compatible with it
344 if (params.simulation.use_cola and not FML::PARTICLE::has_get_D_1LPT<T>()) {
345 throw std::runtime_error("Set to use COLA, but particle-type does not even have 1LPT growthfactors!");
346 }
347
349
350 // The fiducial gradient kernel: the continuous kernel (D = ik) is the most accurate when the force grid is
351 // the same as the particle grid. When the force grid is finer the regular particle lattice (of the IC) puts
352 // power just below the Nyquist frequency of the grid where ik is large, which gives large spurious forces
353 // (tens of percent errors in the growth of individual large-scale modes and too much small-scale power).
354 // The finite difference kernels (which vanish at the Nyquist frequency) suppress this. Together with the
355 // half-cell lattice offset (ic_lattice_offset = fiducial) the four-point kernel gives the most accurate
356 // nonlinear P(k) for force grids up to 3 times the particle grid and the two-point kernel for finer grids
357 // (see the README)
358 std::string gradient_kernel = params.force.gradient_kernel;
359 if ((gradient_kernel == "fiducial" or gradient_kernel == "") and params.force.nmesh > params.particle.Npart_1D) {
360 gradient_kernel = params.force.nmesh <= 3 * params.particle.Npart_1D ? "discrete_4pt" : "discrete_2pt";
361 if (FML::ThisTask == 0)
362 std::cout << "NB: force_nmesh > particle_Npart_1D so we use force_gradient_kernel = " << gradient_kernel
363 << " (set force_gradient_kernel to continuous, discrete_2pt or discrete_4pt to change this)\n";
364 }
366 force_options.deconvolve = params.force.deconvolve_window;
367 current_force = params.force;
368
369 // The (experimental) finite difference force: only the stencils 2, 4 and 6 are implemented and the gradient is
370 // the finite difference stencil, so an explicitly chosen Fourier gradient kernel would be ignored
371 if (SIMCODE::get_parameter<bool>(param, "force_use_finite_difference_force")) {
372 const int stencil_order = SIMCODE::get_parameter<int>(param, "force_finite_difference_stencil_order");
374 throw std::runtime_error("Parameterfile: force_finite_difference_stencil_order = " +
375 std::to_string(stencil_order) + " is not implemented. Valid options are: 2 4 6");
376 if (params.force.gradient_kernel != "fiducial" and params.force.gradient_kernel != "")
377 throw std::runtime_error("Parameterfile: force_gradient_kernel = " + params.force.gradient_kernel +
378 " is not used with force_use_finite_difference_force = true (the gradient is "
379 "the finite difference stencil set by force_finite_difference_stencil_order). "
380 "Use force_gradient_kernel = fiducial");
381 }
382
383 // The accurate force options (NUFFT, deconvolution, early-time force) remove the smoothing of the force
384 // near the grid Nyquist frequency. With a grid finer than the particle grid the modes between the particle
385 // and the grid Nyquist frequency are dominated by the discreteness of the particles and these options then
386 // give far too much small-scale power (+15-60% at k = 0.2 h/Mpc in tests with a 2x grid)
387 const bool exact_force = params.force.density_method != "assignment" or params.force.deconvolve_window or
388 params.force.interpolation_method == "nufft" or params.force.early_method != "none";
389 if (exact_force and params.force.nmesh > params.particle.Npart_1D and FML::ThisTask == 0)
390 std::cout << "WARNING: force_density_method / force_deconvolve_window / force_early_method are meant for "
391 "force_nmesh = particle_Npart_1D. With a finer force grid they amplify the discreteness of the "
392 "particles (see README)\n";
393
394 // Starting from the Big Bang the force at early times (particles close to the lattice) has to be accurate: the
395 // CIC and interlaced forces make the modes with k > ~k_Ny/8 grow wrongly there (see README)
396 if (params.ic.initial_redshift > 100.0 and params.force.early_method == "none" and
397 params.force.density_method == "assignment" and params.force.interpolation_method != "nufft" and
398 FML::ThisTask == 0)
399 std::cout << "WARNING: starting at z = " << params.ic.initial_redshift
400 << " without force_early_method: use force_early_method = nufft (force_early_until_redshift ~ 10) "
401 "for an accurate force while the particles are close to the lattice (see README)\n";
402
403 // The baryon-CDM relative mode in the displacements of the particles (a ~50 kpc/h CDM-baryon offset per pair)
404 // gets a spurious discrete-mode growth once the force grid resolves it, and is partly lost in collapsed regions
405 // (P(delta_c - delta_b) ~ 0.5 of linear theory at z = 0 on large scales). See README
406 // (also the part of it that grows after zini with mass_ini)
407 if (params.particle.baryons and params.particle.baryon_relative_mode != "mass" and
408 params.force.nmesh > 2 * params.particle.Npart_1D and FML::ThisTask == 0)
409 std::cout << "WARNING: particle_baryon_relative_mode = " << params.particle.baryon_relative_mode
410 << " with force_nmesh > 2 particle_Npart_1D: the baryon-CDM relative mode is not reliable (use "
411 "particle_baryon_relative_mode = mass, see README)\n";
412
413 cola.enabled = params.simulation.use_cola;
414 cola.scaledependent = params.simulation.use_scaledependent_cola;
415 cola.LPT_order = params.simulation.cola_LPT_order;
416 cola.aini = params.ic.a_initial();
417 cola.H0Box = grav->H0_hmpc * params.simulation.boxsize;
418 cola.grav = grav;
419}
GreensFunctionLaplaceOperatorKernels laplace_kernel_from_name(std::string kernel)
GradientKernels gradient_kernel_from_name(std::string kernel)
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
T get_parameter(const FML::UTILS::ParameterMap &param, const std::string &name)
Read a parameter: the value in param if it is there, otherwise the default value from the parameter t...
GradientKernels gradient_kernel
GreensFunctionLaplaceOperatorKernels laplace_kernel

◆ read_phases()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::read_phases ( FFTWGrid< NDIM > & delta_fourier)
protected

Compute delta(k) from particles in gadget files (used to take the phases from them)

Definition at line 1119 of file Simulation.h.

1119 {
1121}
void delta_from_gadget_particles(FML::GRID::FFTWGrid< NDIM > &delta_fourier, const SimulationParameters &params, const Cosmology &cosmo)
Compute delta(k) from particles in gadget files (used to take the phases from them).
Definition ExternalIC.h:299

◆ run()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::run ( )

Run simulation.

Definition at line 1148 of file Simulation.h.

1148 {
1149 timer.StartTiming("Timestepping");
1150
1151 const auto & output_redshifts = params.output.redshifts;
1152 const double zini = params.ic.initial_redshift;
1153 const auto stepper = time_stepping();
1154
1155 // If we only give the total number of steps then compute how many steps between outputs
1156 std::vector<int> nsteps = params.timestep.nsteps;
1157 if (nsteps.size() == 1) {
1158 nsteps = stepper.steps_between_outputs(zini, output_redshifts, nsteps[0]);
1159 // An output with no steps would write the particles of the previous output at another redshift
1160 for (size_t i = 0; i < nsteps.size(); i++)
1161 if (not(nsteps[i] > 0 or (i == 0 and output_redshifts[0] == zini)))
1162 throw std::runtime_error("Splitting timestep_nsteps over the outputs gives 0 steps before output z = " +
1163 std::to_string(output_redshifts[i]) +
1164 ": use more steps or give the number of steps for every output");
1165 }
1166 stepper.print_steps(zini, output_redshifts, nsteps);
1167
1168 if (FML::ThisTask == 0) {
1169 std::cout << "\n";
1170 std::cout << "#=====================================================\n";
1171 std::cout << "# Starting main time-stepping loop\n";
1172 std::cout << "#=====================================================\n\n";
1173 }
1174
1175 int istep_total = 0;
1176 for (size_t ioutput = 0; ioutput < output_redshifts.size(); ioutput++) {
1177
1178 // The steps to take till the next output
1179 const double amin = (ioutput == 0) ? 1.0 / (1.0 + zini) : 1.0 / (1.0 + output_redshifts[ioutput - 1]);
1180 const double amax = 1.0 / (1.0 + output_redshifts[ioutput]);
1181 const auto steps = stepper.steps(amin, amax, nsteps[ioutput]);
1182
1183 if (nsteps[ioutput] > 0) {
1184 for (int istep = 0; istep <= nsteps[ioutput]; istep++) {
1185 // The last step is just a sync step so don't count towards the total
1186 if (istep < nsteps[ioutput])
1187 istep_total++;
1188
1189 if (FML::ThisTask == 0) {
1190 std::cout << std::setprecision(5) << "\n";
1191 std::cout << "#=====================================================\n";
1192 std::cout << "# Step " << istep_total << " (" << istep << " / " << nsteps[ioutput]
1193 << " till output " << ioutput << ")\n";
1194 std::cout << "# Pos: " << steps[istep].apos << " -> " << steps[istep].apos_new
1195 << " Vel: " << steps[istep].avel << " -> " << steps[istep].avel_new << "\n";
1196 std::cout << "#=====================================================\n";
1197 }
1198
1199 // Reorder the particles in memory by position (faster density assignment and interpolation)
1200 const int sort_every = params.particle.sort_every_nsteps;
1201 if (sort_every > 0 and istep < nsteps[ioutput] and istep_total % sort_every == 0) {
1202 timer.StartTiming("SortParticles");
1203 const int nblocks = std::max(1, params.force.nmesh / 4);
1205 [&](auto & particles, const SIMCODE::SpeciesInfo &) { particles.sort_by_position(nblocks); });
1206 timer.EndTiming("SortParticles");
1207 }
1208
1209 const auto & s = steps[istep];
1210 step({s.apos, s.apos_new, s.avel_new, s.delta_time_drift, s.delta_time_kick, s.velocity_scale});
1211 }
1212 }
1213
1214 analyze_and_output(ioutput, output_redshifts[ioutput]);
1215 }
1216 timer.EndTiming("Timestepping");
1217
1218 // Lightcone create kappa maps
1219 if (lightcone->lightcone_active()) {
1220 lightcone->create_weak_lensing_maps();
1221 }
1222
1223 timer.EndTiming("The whole simulation");
1224 if (FML::ThisTask == 0) {
1226 }
1227
1228#ifdef MEMORY_LOGGING
1229 // Simulation is over, output the memory usage (of what we log)
1231#endif
1232}
const double zini
Definition Main.cpp:40
static MemoryLog * get()
The (only) instance.
void print()
Print the memory in use (collective with MPI: all tasks must call it)
void PrintAllTimings() const
Output all the recorded timings.
Definition Timings.h:61
void analyze_and_output(int ioutput, double redshift)
Do all the on the fly analysis that is turned on and write the output.
void step(const StepInfo &s)
One kick-drift step: density -> force -> kick -> COLA kick -> lightcone -> COLA drift -> drift.

◆ set_force_settings_for_step()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::set_force_settings_for_step ( double a)
protected

Choose the force settings for a step where the force is evaluated at scale factor a: the early-time settings (force_early_method) for z > force_early_until_redshift, otherwise the normal ones.

Definition at line 1237 of file Simulation.h.

1237 {
1238 const auto & f = params.force;
1239 current_force = f;
1240 const bool early = f.early_method != "none" and 1.0 / a - 1.0 > f.early_until_redshift;
1241 if (early and f.early_method == "nufft") {
1242 current_force.density_method = "nufft";
1246 }
1247 if (early and f.early_method == "interlaced") {
1248 current_force.density_method = "assignment";
1249 current_force.interpolation_method = "assignment";
1250 current_force.interlacing_order = f.early_interlacing_order;
1251 current_force.density_assignment_method = f.early_density_assignment_method;
1253 }
1255 early_force = early;
1256 if (not early)
1258 if (early and FML::ThisTask == 0)
1259 std::cout << "Using the early-time force (" << f.early_method << ") at z = " << 1.0 / a - 1.0 << "\n";
1260}

◆ setup_initial_power_spectrum()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::setup_initial_power_spectrum ( )
protected

Read the input P(k) / T(k), bring it to the initial redshift, make splines and (optionally) normalize it to a given sigma8.

Definition at line 516 of file Simulation.h.

516 {
517 const auto & ic = params.ic;
518 const double boxsize = params.simulation.boxsize;
519
521 cosmo,
522 grav,
523 grav_ic,
526 params.simulation.boxsize);
527 auto make_splines = [&](std::string label) {
528 power_initial_spline.create(table.k, table.power, "P(k,zini)" + label);
529 power_primordial_spline.create(table.k, table.power_primordial, "P_primordial(k)" + label);
530 };
531 make_splines("");
532
533 // The splines are constant beyond the table, so modes of the IC grid with k > k_max of the input would silently get
534 // P(k_max). Only a warning: the power there is often negligible (and a table only slightly too short is common)
535 const double kmax_grid = std::sqrt(double(NDIM)) * M_PI * ic.nmesh / boxsize;
536 if (FML::ThisTask == 0 and ic.random_field_type != SIMCODE::ICRandomFieldType::ReadParticles and
537 not table.k.empty() and table.k.back() < kmax_grid)
538 std::cout << "WARNING: the input P(k) / T(k) only goes to k = " << table.k.back()
539 << " h/Mpc, but the IC grid has modes up to sqrt(NDIM) pi ic_nmesh / simulation_boxsize = "
540 << kmax_grid << " h/Mpc. P(k) is taken to be constant (P(k_max)) beyond the table\n";
541
542 if (FML::ThisTask == 0) {
543 std::cout << "\n";
544 std::cout << "#=====================================================\n";
545 std::cout << "# Testing splines: \n";
546 std::cout << "#=====================================================\n";
547 for (double k : {0.01, 0.1, 1.0, 10.0})
548 std::cout << "k = " << std::setw(5) << k << ": P(k,zini) = " << power_initial_spline(k) << " (Mpc/h)^3\n";
549 FML::assert_mpi(power_initial_spline(0.01) == power_initial_spline(0.01), "NaN detected");
550 }
551
552 // sigma(R,z) from the current P(k,zini)
553 auto sigma_of_R = [&](double R_mpch, double redshift) {
554 return SIMCODE::sigma_of_R<NDIM>(power_initial_spline, grav_ic, boxsize, ic.initial_redshift, redshift, R_mpch);
555 };
556 const bool sigma8_covered = ic.type_of_input != SIMCODE::ICInputType::InternalTransfer ||
557 (table.k.front() <= 1e-5 && table.k.back() >= 100.0);
558 const double sigma8_today = sigma8_covered ? sigma_of_R(8.0, 0.0) : 0.0;
559
560 // Normalize P(k) to a given sigma8 value. We then need to update the splines,
561 // the transfer data and the cosmology
562 double pofk_norm_factor = 1.0;
563 if (ic.sigma8_normalization) {
564 const double sigma8 = sigma_of_R(8.0, ic.sigma8_redshift);
565 pofk_norm_factor = std::pow(ic.sigma8 / sigma8, 2);
566 }
567 if (pofk_norm_factor != 1.0) {
568 table.scale(pofk_norm_factor);
569 make_splines(" sigma8 normalized");
570
571 // Update transfer data. This also updates data in gravity model (as its the same object)
572 if (transferdata) {
573 transferdata->set_As(transferdata->get_As() * pofk_norm_factor);
574 }
576 ic_transfers->rescale_primordial_power(pofk_norm_factor);
577 cosmo->set_As(cosmo->get_As() * pofk_norm_factor);
578
579 if (FML::ThisTask == 0) {
580 std::cout << "\n";
581 std::cout << "#=====================================================\n";
582 std::cout << "Updated cosmology and gravitymodel to reflect change of As:\n";
583 std::cout << "#=====================================================\n";
584 cosmo->info();
585 grav->info();
586 }
587 }
588
589 if (FML::ThisTask == 0) {
590 std::cout << "\n";
591 std::cout << "#=====================================================\n";
592 if (sigma8_covered)
593 std::cout << "# Sigma(R = 8 Mpc/h, z = 0.0 ) : " << std::setw(15) << sigma8_today << "\n";
594 else
595 std::cout << "# Sigma8 not evaluated: strict transfer input does not cover the integration range "
596 "[1e-5,100] h/Mpc\n";
597 if (ic.sigma8_normalization) {
598 std::cout << "# We will normalize to Sigma8 = " << std::setw(15) << ic.sigma8 << " at z = " << std::setw(15)
599 << ic.sigma8_redshift << "\n";
600 std::cout << "# New Sigma(R = 8 Mpc/h, z = 0.0 ) : " << std::setw(15)
601 << sigma8_today * std::sqrt(pofk_norm_factor) << "\n";
602 std::cout << "# Sigma(R = Box/ic_nmesh, z = zini) : " << std::setw(15)
603 << sigma_of_R(boxsize / ic.nmesh, ic.initial_redshift) << "\n";
604 }
605 std::cout << "#=====================================================\n";
606 }
607}
void create(const double *x, const double *y, int nx, std::string splinename="NoName", const gsl_interp_type *interpoltype=SPLINE_FIDUCIAL_INTERPOL_TYPE)
Create a spline from pointers to x and y. Both must have nx elements.
Definition Spline.cpp:159
double sigma_of_R(const std::function< double(double)> &pofk, double R, double kmin, double kmax)
sigma(R) of a linear power-spectrum P(k) (k in h/Mpc, R in Mpc/h) with a top-hat filter
LinearPowerSpectrumTable read_initial_power_spectrum(const ICSettings &ic, std::shared_ptr< Cosmology > cosmo, std::shared_ptr< GravityModel< NDIM > > grav, std::shared_ptr< GravityModel< NDIM > > grav_ic, std::shared_ptr< LinearTransferData > &transferdata, std::shared_ptr< FML::INITIALCONDITIONS::TransferProvider > *provider_out=nullptr, double boxsize_mpch=0.0)
Read the input power-spectrum / transfer function (as given by ic.type_of_input) and bring it to the ...

◆ setup_nbody_gauge()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::setup_nbody_gauge ( )
protected

Read the N-body gauge source, check it and store the initial density field of the particles.

Definition at line 1079 of file Simulation.h.

1079 {
1080 const auto & force = params.force;
1081 if (grav->get_name() != "GR" or cosmo->get_name() != "LCDM")
1082 throw std::runtime_error("force_nbody_gauge is only implemented for cosmology_model = LCDM and gravity_model "
1083 "= GR (the source is computed with CLASS)");
1084 FML::assert_mpi(transferdata != nullptr, "force_nbody_gauge needs the transfer functions");
1085
1086 if (FML::ThisTask == 0)
1087 std::cout << "# Running in the N-body gauge. Reading the linear source [" << force.nbody_gauge_filename
1088 << "]\n";
1089 nbody_gauge = std::make_shared<SIMCODE::NBodyGaugeSource>();
1090 nbody_gauge->read(force.nbody_gauge_filename);
1091 nbody_gauge->check_cosmology(*cosmo, params.ic.initial_redshift, params.simulation.boxsize, force.nmesh);
1092
1093 if (FML::ThisTask == 0) {
1094 const double aini = params.ic.a_initial();
1095 for (double a : {aini, 0.5, 1.0}) {
1096 const auto ratio = nbody_gauge->ratio_spline(a, aini, *transferdata);
1097 std::cout << "# N-body gauge source: delta_extra(k,z) / delta_cb(k,zini) at z = " << 1.0 / a - 1.0 << ":";
1098 for (double k : {1e-3, 1e-2, 1e-1})
1099 std::cout << " " << ratio(std::log(k)) << " (k = " << k << ")";
1100 std::cout << "\n";
1101 }
1102 }
1103
1104 // delta_cb(k,zini) of the particles on the force grid
1105 const auto nleftright =
1107 initial_density_field_fourier = FFTWGrid<NDIM>(force.nmesh, nleftright.first, nleftright.second);
1108 initial_density_field_fourier.add_memory_label("density(k,zini)");
1110 part.get_npart(),
1113 force.density_assignment_method);
1115}

◆ species_shotnoise()

template<int NDIM, class T >
double NBodySimulation< NDIM, T >::species_shotnoise ( const SIMCODE::SpeciesInfo & info)
inline

The shot noise of the density field of a species (in units of the box volume): 1/N (sum w^2 / N^2 for the delta-f neutrinos).

Collective

Definition at line 229 of file Simulation.h.

229 {
230 if (info.name == "nu")
231 return neutrinos.shotnoise();
232 return 1.0 / double((info.name == "baryon" ? part_baryon : part).get_npart_total());
233 }

◆ step()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::step ( const StepInfo & s)
protected

One kick-drift step: density -> force -> kick -> COLA kick -> lightcone -> COLA drift -> drift.

Definition at line 1264 of file Simulation.h.

1264 {
1265 const auto & sim = params.simulation;
1267 const auto & force = current_force;
1268
1269 // Force interlacing: average the force over copies of the particles shifted relative to the grid
1270 const auto nleftright =
1272 if (force.interlacing_order > 1 and s.delta_time_kick != 0.0 and not sim.enforce_LPT_trajectories) {
1274 return drift_and_lightcone(s);
1275 }
1276
1277 // Compute total density field
1278 FFTWGrid<NDIM> density_grid_fourier(force.nmesh, nleftright.first, nleftright.second);
1279 if (s.delta_time_kick != 0.0) {
1280 timer.StartTiming("ComputeDensityField");
1281 compute_density_field_fourier(density_grid_fourier, s.apos);
1282 timer.EndTiming("ComputeDensityField");
1283 // The potential for the lightcone (from the same density field as the force)
1284 if (lightcone->needs_potential(s.apos, s.apos_new))
1285 compute_lightcone_potential(density_grid_fourier, s.apos);
1286 }
1287
1288 // Compute forces and kick particles (updates velocity)
1289 std::array<FFTWGrid<NDIM>, NDIM> force_real;
1290 if (s.delta_time_kick != 0.0 and not sim.enforce_LPT_trajectories) {
1291 timer.StartTiming("ComputeForce");
1292 grav->compute_force(s.apos,
1293 grav->H0_hmpc * sim.boxsize,
1294 density_grid_fourier,
1295 force.density_assignment_method,
1296 force_real,
1298 timer.EndTiming("ComputeForce");
1299
1300 timer.StartTiming("Kick");
1301 if (force.interpolation_method == "nufft") {
1302 // Exact evaluation of the Fourier series of the force at the particle positions (one species)
1303 auto * p = part.get_particles_ptr();
1304 if (s.velocity_scale != 1.0) {
1305#ifdef USE_OMP
1306#pragma omp parallel for
1307#endif
1308 for (size_t i = 0; i < part.get_npart(); i++) {
1309 auto * vel = FML::PARTICLE::GetVel(p[i]);
1310 for (int idim = 0; idim < NDIM; idim++)
1311 vel[idim] *= s.velocity_scale;
1312 }
1313 }
1314 FML::NUFFT::ESKernel kernel(force.nufft_epsilon);
1315 std::vector<FML::GRID::FloatType> force_particle;
1316 for (int idim = 0; idim < NDIM; idim++) {
1317 force_real[idim].fftw_r2c();
1318 FML::NUFFT::nufft_type2<NDIM>(force_real[idim], p, part.get_npart(), force_particle, kernel);
1319#ifdef USE_OMP
1320#pragma omp parallel for
1321#endif
1322 for (size_t i = 0; i < part.get_npart(); i++)
1323 FML::PARTICLE::GetVel(p[i])[idim] -= force_particle[i] * s.delta_time_kick;
1324 }
1325 } else {
1328 info,
1329 force_real,
1330 s.apos,
1331 s.delta_time_kick,
1332 s.velocity_scale,
1333 force.density_assignment_method,
1334 sim.boxsize);
1335 });
1336 }
1337 // The delta-f weights depend on the momenta
1339 neutrinos.update_weights();
1340 timer.EndTiming("Kick");
1341 }
1343}
The exponential of semicircle (ES) spreading kernel and its Fourier transform.
Definition NUFFT.h:64
void drift_and_lightcone(const StepInfo &s)
The rest of a step after the (PM) kick: COLA kick-drift, lightcone and drift.
void kick_with_interlaced_force(const StepInfo &s)
The kick with force interlacing: the force is computed for force_interlacing_order copies of the part...
void set_force_settings_for_step(double a)
Choose the force settings for a step where the force is evaluated at scale factor a: the early-time s...
double kernel(double x)
Internal method.
void nufft_type2(const FFTWGrid< N > &in, const T *part, size_t NumPart, std::vector< FloatType > &result, const ESKernel &kernel=ESKernel())
NUFFT type 2: compute summing over the modes of the input grid with (the Nyquist planes are ignored...
Definition NUFFT.h:643
void kick_particles(FML::PARTICLE::MPIParticles< P > &part, const SpeciesInfo &info, std::array< FML::GRID::FFTWGrid< NDIM >, NDIM > &force_real, double apos, double delta_time, double velocity_scale, const std::string &interpolation_method, double boxsize)
The kick of a species: v -> velocity_scale v - F dt (times (1 + 2u^2) / sqrt(1 + u^2) at apos for rel...
Definition KickDrift.h:32

◆ store_initial_density_field()

template<int NDIM, class T >
void NBodySimulation< NDIM, T >::store_initial_density_field ( const FFTWGrid< NDIM > & density_grid_fourier,
double a )
protected

Store delta_cb(k,zini) from the density field of the first force evaluation (at zini).

The linear sources are delta_cb(k,zini) times a transfer function ratio and are added to the density field of each step, so delta_cb(k,zini) must have the same window (and aliasing) as that field. With the early-time force (force_early_method: NUFFT, no window, or interlaced with another assignment) the first field is kept for the early steps only, and the field for the later steps is computed again from the particles with the late-time settings (it used to be the early-time one for all steps)

Definition at line 246 of file SimulationDensity.h.

246 {
247 FML::assert_mpi(std::fabs(1.0 / a - 1.0 - params.ic.initial_redshift) < 1e-3,
248 "The initial density field must be stored at the initial redshift");
249 if (not early_force) {
251 initial_density_field_fourier = density_grid_fourier;
253 }
254 return;
255 }
256 initial_density_field_early = density_grid_fourier;
257 initial_density_field_early.add_memory_label("density(k,zini) early-time force");
259 const auto saved_force = current_force;
260 current_force = params.force;
261 const auto nleftright =
263 initial_density_field_fourier = FFTWGrid<NDIM>(current_force.nmesh, nleftright.first, nleftright.second);
264 initial_density_field_fourier.add_memory_label("density(k,zini)");
266 current_force = saved_force;
267 }
268}

◆ time_stepping()

template<int NDIM, class T >
SIMCODE::TimeStepping< NDIM > NBodySimulation< NDIM, T >::time_stepping ( ) const
inline

The time-stepping (where the steps are and their sizes)

Definition at line 278 of file Simulation.h.

278{ return {params.timestep, cosmo, grav}; }

◆ total_shotnoise()

template<int NDIM, class T >
double NBodySimulation< NDIM, T >::total_shotnoise ( double a = -1.0)
inline

The shot noise of the total delta_m = (1 - f_nu) delta_cb + f_nu delta_nu with neutrino particles (with force_neutrino_energy_density and a > 0: of (1 - f_nu) delta_cb + f_nu <E/m>(a) delta_nu, the source of the Poisson equation).

Collective

Definition at line 245 of file Simulation.h.

245 {
246 const double fnu = cosmo->get_fMNu();
247 if (params.force.neutrino_energy_density and a > 0.0) {
249 const double fnu_eff = fnu * neutrino_energy_factor(a);
250 return (1.0 - fnu) * (1.0 - fnu) * cb_shotnoise() + fnu_eff * fnu_eff * neutrinos.shotnoise();
251 }
252 return (1.0 - fnu) * (1.0 - fnu) * cb_shotnoise() + fnu * fnu * neutrinos.shotnoise();
253 }

Field Documentation

◆ cola

template<int NDIM, class T >
ColaState<NDIM, T> NBodySimulation< NDIM, T >::cola
protected

COLA settings and the LPT potentials at the initial time.

Definition at line 140 of file Simulation.h.

◆ cosmo

template<int NDIM, class T >
std::shared_ptr<Cosmology> NBodySimulation< NDIM, T >::cosmo
protected

Everything related to the background evolution.

Definition at line 85 of file Simulation.h.

◆ current_force

template<int NDIM, class T >
SIMCODE::ForceSettings NBodySimulation< NDIM, T >::current_force
protected

Definition at line 131 of file Simulation.h.

◆ density_shift

template<int NDIM, class T >
std::array<double, NDIM> NBodySimulation< NDIM, T >::density_shift {}
protected

Definition at line 129 of file Simulation.h.

129{};

◆ early_force

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::early_force {false}
protected

Definition at line 132 of file Simulation.h.

132{false}; // current_force are the early-time settings

◆ force_options

template<int NDIM, class T >
FML::NBODY::ForceOptions NBodySimulation< NDIM, T >::force_options
protected

Definition at line 133 of file Simulation.h.

◆ grav

template<int NDIM, class T >
std::shared_ptr<GravityModel<NDIM> > NBodySimulation< NDIM, T >::grav
protected

Everything related to gravity: growth factors, computing forces.

Definition at line 88 of file Simulation.h.

◆ grav_ic

template<int NDIM, class T >
std::shared_ptr<GravityModel<NDIM> > NBodySimulation< NDIM, T >::grav_ic
protected

The gravity model used to make the IC (GR if ic_use_gravity_model_GR, otherwise grav)

Definition at line 90 of file Simulation.h.

◆ hybridbias_linear_field_fourier

template<int NDIM, class T >
FFTWGrid<NDIM> NBodySimulation< NDIM, T >::hybridbias_linear_field_fourier
protected

The linear density field delta_cb(zini,k) the particles were displaced with, on a grid of the size of the particle lattice (only if hybridbias)

Definition at line 127 of file Simulation.h.

◆ ic_transfers

template<int NDIM, class T >
std::shared_ptr<FML::INITIALCONDITIONS::TransferProvider> NBodySimulation< NDIM, T >::ic_transfers
protected

Definition at line 95 of file Simulation.h.

◆ ic_velocities_relative_to_cola_frame

template<int NDIM, class T >
bool NBodySimulation< NDIM, T >::ic_velocities_relative_to_cola_frame {false}
protected

Definition at line 143 of file Simulation.h.

143{false};

◆ initial_density_field_early

template<int NDIM, class T >
FFTWGrid<NDIM> NBodySimulation< NDIM, T >::initial_density_field_early
protected

Definition at line 122 of file Simulation.h.

◆ initial_density_field_fourier

template<int NDIM, class T >
FFTWGrid<NDIM> NBodySimulation< NDIM, T >::initial_density_field_fourier
protected

The initial density field delta_cb(zini,k) computed with the same Nmesh as the forces (used for linear massive neutrinos and the N-body gauge - not allocated otherwise)

Definition at line 120 of file Simulation.h.

◆ initial_density_field_shifted

template<int NDIM, class T >
FFTWGrid<NDIM> NBodySimulation< NDIM, T >::initial_density_field_shifted
protected

Definition at line 124 of file Simulation.h.

◆ lightcone

template<int NDIM, class T >
std::shared_ptr<Lightcone<NDIM, T> > NBodySimulation< NDIM, T >::lightcone
protected

The lightcone construction.

Definition at line 146 of file Simulation.h.

◆ lightcone_potential

template<int NDIM, class T >
FFTWGrid<NDIM> NBodySimulation< NDIM, T >::lightcone_potential
protected

Phi/c^2 in real space for the lightcone (plc_relativistic_effects), computed at scale factor lightcone_potential_a from the density field of the step.

Definition at line 114 of file Simulation.h.

◆ lightcone_potential_a

template<int NDIM, class T >
double NBodySimulation< NDIM, T >::lightcone_potential_a {-1.0}
protected

Definition at line 115 of file Simulation.h.

115{-1.0};

◆ nbody_gauge

template<int NDIM, class T >
std::shared_ptr<SIMCODE::NBodyGaugeSource> NBodySimulation< NDIM, T >::nbody_gauge
protected

The linear N-body gauge source (if force_nbody_gauge)

Definition at line 137 of file Simulation.h.

◆ neutrinos

template<int NDIM, class T >
SIMCODE::NeutrinoParticles<NDIM> NBodySimulation< NDIM, T >::neutrinos
protected

The massive neutrino particles (only if particle_neutrinos; delta-f method)

Definition at line 110 of file Simulation.h.

◆ parameters

template<int NDIM, class T >
std::shared_ptr<ParameterMap> NBodySimulation< NDIM, T >::parameters
protected

A copy of the parameterfile (passed on to the models we create)

Definition at line 98 of file Simulation.h.

◆ params

template<int NDIM, class T >
Parameters NBodySimulation< NDIM, T >::params
protected

The parameters of the simulation.

Definition at line 101 of file Simulation.h.

◆ part

template<int NDIM, class T >
MPIParticles NBodySimulation< NDIM, T >::part
protected

All the particles (CDM+baryons as one species "cb", or the CDM particles if particle_baryons)

Definition at line 106 of file Simulation.h.

◆ part_baryon

template<int NDIM, class T >
MPIParticles NBodySimulation< NDIM, T >::part_baryon
protected

The baryon particles (only if particle_baryons)

Definition at line 108 of file Simulation.h.

◆ pofk_cb_every_step

template<int NDIM, class T >
std::vector<std::pair<double, PowerSpectrumBinning> > NBodySimulation< NDIM, T >::pofk_cb_every_step
protected

Definition at line 160 of file Simulation.h.

◆ pofk_every_output

template<int NDIM, class T >
std::vector<std::pair<double, PowerSpectrumBinning> > NBodySimulation< NDIM, T >::pofk_every_output
protected

Definition at line 165 of file Simulation.h.

◆ pofk_multipoles_every_output

template<int NDIM, class T >
std::vector<std::pair<double, std::vector<PowerSpectrumBinning> > > NBodySimulation< NDIM, T >::pofk_multipoles_every_output
protected

Definition at line 167 of file Simulation.h.

◆ pofk_species_every_step

template<int NDIM, class T >
std::map<std::string, std::vector<std::pair<double, PowerSpectrumBinning> > > NBodySimulation< NDIM, T >::pofk_species_every_step
protected

Definition at line 163 of file Simulation.h.

◆ pofk_total_every_step

template<int NDIM, class T >
std::vector<std::pair<double, PowerSpectrumBinning> > NBodySimulation< NDIM, T >::pofk_total_every_step
protected

Definition at line 161 of file Simulation.h.

◆ power_initial_spline

template<int NDIM, class T >
Spline NBodySimulation< NDIM, T >::power_initial_spline {"P(k,zini)"}
protected

Definition at line 153 of file Simulation.h.

153{"P(k,zini)"}; // Spline of baryon-CDM power-spectrum (h/Mpc) vs (Mpc/h)^3

◆ power_primordial_spline

template<int NDIM, class T >
Spline NBodySimulation< NDIM, T >::power_primordial_spline {"P_primordial(k)"}
protected

Definition at line 152 of file Simulation.h.

152{"P_primordial(k)"}; // Spline of primordial power-spectrum (h/Mpc) vs (Mpc/h)^3

◆ species

template<int NDIM, class T >
std::vector<SIMCODE::SpeciesInfo> NBodySimulation< NDIM, T >::species
protected

The particle species (see Species.h): "cb", or "cdm" and "baryon", and "nu".

Definition at line 104 of file Simulation.h.

◆ timer

template<int NDIM, class T >
FML::UTILS::Timings NBodySimulation< NDIM, T >::timer
protected

Timings of the code.

Definition at line 149 of file Simulation.h.

◆ transferdata

template<int NDIM, class T >
std::shared_ptr<LinearTransferData> NBodySimulation< NDIM, T >::transferdata
protected

Linear perturbations, transfer functions, initial pofk This is only used if ic_type_of_input == transferinfofile.

Definition at line 94 of file Simulation.h.


The documentation for this class was generated from the following files: