simple reference
simple.config module
- class config.Config
Bases:
objectConfiguration class to find the installation directory of lognormal_galaxies.
- Parameters:
lognormal_galaxies_path (str) – Installation directory of lognormal_galaxies.
simple.simple module
- class simple.simple.BasicBoxCalculator(redshift, box_size, N_mesh, single_redshift, cosmology)
Bases:
object- property box_volume
Calculates the volume of the simulation box. Cached like a property self.box_volume.
- property delta_redshift
Calculates the redshift difference corresponding to the comoving distance of the LOS length.
- Returns:
Redshift difference corresponding to the comoving distance of the line-of-sight (LOS) length. Cached like a property.
- Return type:
float
- Raises:
ValueError – If the LOS is not aligned with any of the axes [1,0,0], [0,1,0], or [0,0,1].
- get_comoving_distance_per_delta_z(mean_z, delta_z)
Calculates the comoving distance between (z + delta_z) and (z - delta_z).
- Parameters:
mean_z (float) – Mean redshift of the box: mean_z = (z_min + z_max) / 2.
delta_z (float) – Half of the redshift difference: delta_z = (z_max - z_min) / 2.
- Returns:
Comoving distance between (z + delta_z) and (z - delta_z).
- Return type:
Quantity
- get_kspec(dohalf=True, doindep=True)
Compute the power spectrum in Fourier space.
- Parameters:
dohalf (bool, optional) – Flag indicating whether to generate only the half of the Fourier transforms due to symmetry. Default is True.
doindep (bool, optional) – Flag indicating whether to calculate only the independent modes of the Fourier transform. Default is True.
- Returns:
kspec (ndarray) – The norm of the wavevector k in the Fourier transform of our meshes.
muspec (ndarray) – The corresponding values of mu (cosine of the angle between the LOS and the wavevector k).
indep (ndarray (bool)) – Indicates whether the mode is independent or not.
- get_mesh_positions(voxel_length, N_mesh, save_to_self=True)
Returns an array of mesh positions with dimensions (N_mesh, N_mesh, N_mesh, 3), where mesh_position[i, j, k] is the position vector of the center of cell (i, j, k) in Mpc/h.
- Parameters:
voxel_length (Quantity array (3,)) – Length of each voxel in the three spatial dimensions with length units.
N_mesh (array (3,)) – Number of cells in each dimension (dimensionless array).
save_to_self (bool, optional) – Save mesh_position to self.mesh_position. Default: True.
- property k_Nyquist
Calculates the Nyquist frequency (cached).
- property mean_redshift
Calculates the mean of the redshifts of the cells (cached).
- property minimum_distance
Calculates the minimum distance of a cell within the mesh (cached).
- property redshift_mesh_axis
Calculates the redshift coordinates along the LOS axis (cached).
- property voxel_volume
Calculates the volume of a voxel. Cached like a property self.voxel_volume.
- class simple.simple.LognormalIntensityMock(input_dict)
Bases:
BasicBoxCalculatorThe LognormalIntensityMock class takes cosmological and survey parameters as input and produces a intensity and galaxy density meshes from a lognormal galaxy catalog. It can apply a selection function, smoothing, masks, add noise, and model the sky subtraction. Finally, it can calculate the power spectra.
The following parameter list will contain the input parameters in the input_dict. input_dict can be a dictionary or string. As a dictionary, it should contain the following input parameters. If it is a string, it should be the filename of a yaml file version of the dictionary.
Strings as arguments in the dictionary or yaml file can be evaluated in python, e.g. ‘10 * u.Mpc’. Here, ‘u’ is the imported name for ‘astropy.units’. Other possible packages are numpy (‘np’) and astropy.constants (‘const’). If a string contains ‘cosmo’, it will be converted to the class’ astropy cosmology. Therefore expressions such as ‘cosmo.h’ can be evaluated self-consistently.
- Parameters:
verbose (bool, optional) – Flag stating whether to print lots of output. If False, it will only print errors. Default: True.
cosmology (string, dict, or astropy cosmology object) – If astropy cosmology object, it will directly use this. If string, it can either be a named cosmology in astropy.cosmology (see https://docs.astropy.org/en/stable/cosmology/index.html#built-in-cosmologies) or the name of an ecsv-format file generated by saving an astropy.cosmology object (see https://docs.astropy.org/en/stable/cosmology/io.html#cosmology-io). If dict, it will attempt to initiate an astropy.cosmology.FlatwCDM object from the dict (see https://docs.astropy.org/en/stable/api/astropy.cosmology.FlatwCDM.html#astropy.cosmology.FlatwCDM).
n_s (float) – Value of the spectral index \(n_s\) (part of the cosmology).
lnAs (float) – Value of \(\mathrm{ln}(10^{10} A_s)\) (part of the cosmology).
luminosity_function (string or function) – If function, it should take the luminosity as an input (in units of luminosity_unit, but as a float) and return dn/dL as output (in units of 1/luminosity_unit * 1/Mpc**3). If string, it should be the name of the file that contains a table (csv format readable by astropy.table) where ‘L’ is the column containing the luminosity (in units of luminosity_unit, but as a float) and ‘dn/dL’ is the column containing the corresponding dn/dL (in units of 1/luminosity_unit * 1/Mpc**3). Then the class will interpolate between the values and extrapolate at the borders.
luminosity_unit (astropy quantity) – This is the unit of the luminosity in the luminosity function.
Lmin (astropy quantity) – This is the minimum luminosity to consider for the luminosity function. This is necesssary to get a finite number of galaxies to generate.
Lmax (astropy quantity, optional) – This is the maximum luminosity to consider for the luminosity function. Default: infinity.
input_pk_filename (string, optional) –
Name of the file containing a tabulated input matter power spectrum. This power spectrum will be used to generate the lognormal galaxy catalog. The file should be ascii-formatted with
first column: wavenumber in units of [h/Mpc], second column: matter power spectrum in units of [Mpc^3/h^3].
The first column should not contain names for the columns (should be read by lognormal_galaxies code). Default: Use the file generated by lognormal_galaxies from the input cosmological parameters and the Eisenstein & Hu fitting function (see Agrawal et al. 2017 arxiv:1706.09195).
f_growth_filename (string, optional) –
Name of the file containing a tabulated logarithmic growth function. This will be used to generate the lognormal galaxy catalog (lognormal_galaxies: “logarithmic growth rate fnu for massive (massless) neutrinos which varies (does not vary) as a function of k”). The file should be ascii formatted with
1st column: wavenumber [h Mpc^-1], 2nd column: fnu.
Default: Use the file generated by lognormal_galaxies from the input cosmological parameters (see Agrawal et al. 2017 arxiv:1706.09195).
redshift (float) – Central redshift of the box so that z_max - redshift = redshift - z_min where z_min and z_max are the minimum and maximum redshift of the box, respectively. Will be assigned to the entire box if single_redshift == True.
bias (float) – Galaxy bias.
box_size (astropy quantity array) – This should be a list or array containing the three box side lengths in the dimension of length using astropy.units. It will be converted to units of Mpc/h.
N_mesh (array-like, optional) – List containing the mesh size (3 numbers) used to generate the galaxy catalog, meshes, and Fourier transforms. This is optional if voxel_length is given instead.
voxel_length (astropy quantity array, optional) – List containing the side lengths of the voxels (3 astropy quantities). It will be slightly adjusted to make sure than N_mesh is an integer. This is optional if N_mesh is given and will be ignored if N_mesh is given.
single_redshift (bool, optional) – Flag stating whether the ‘redshift’ parameter should be assigned to the entire box. If False, the redshift will evolve along the line of sight (LOS). Default: False.
RSD (bool) – Flag stating whether to calculate the power spectra in redshift space. This is only important when using the run() function, which runs everything automatically. If this class is used in a modular way, you can choose in each function.
min_flux (astropy quantity, array of astropy quantities, function, or string, optional) –
If it is an astropy quantity, it denotes the minimum flux above which a galaxy is detected. If it is an astropy quantity array in the shape of N_mesh, it denotes the minimum flux above which a galaxy is detected in each voxel. If it is a function, it should take the redshift as input and should output the minimum flux (as an astropy quantity in flux units). If it is a string, it should be the name of the file
- either containing a table in ecsv format readable by astropy.table with
’redshift’ column: redshift
’min_flux’ column: min_flux at that redshift,
unit of ‘min_flux’: unit of the ‘min_flux’ column (automatic if saved using astropy.table).
In this case, it will interpolate between redshifts (in case a redshift is out of bounds, the border values are used.)
- or in hdf5 format with
ff[“min_flux”] : min_flux mesh with the same shape as N_mesh
ff[“min_flux”].attrs[“unit”] should be the string of the astropy unit (e.g. “erg / (cm2 s)”).
Default: None. Then all galaxies are detected unless ‘limit_ngal’ is given.
limit_ngal (astropy quantity, function, or string, optional) –
If it is an astropy quantity, it is the desired galaxy number density (in inverse volume dimension) of the detected galaxies. From this, a minimum flux will be calculated for the selection function. If it is a function, it should take the redshift as input and should output the desired galaxy number density (as an astropy quantity in inverse volume dimensions). If it is a string, it should be the name of the file containing a table in ecsv format readable by astropy.table with
’redshift’ column: redshift,
’limit_ngal’ column: limit_ngal at that redshift,
unit of ‘limit_ngal’: unit of the ‘limit_ngal’ column (automatic if saved using astropy.table).
In this case it will interpolate between redshifts (in case a redshift is out of bounds, the border values are used.) Default: None. Then all galaxies are detected unless min_flux is given. Will be ignored if min_flux is given.
galaxy_selection (dict) – Dictionary containing the set of galaxies to be included in the intensity and n_gal meshes. The keys must contain ‘n_gal’ and ‘intensity’. Options for the values are ‘all’, ‘detected’, and ‘undetected’.
sigma_noise (astropy quantity, nd-array of astropy quantities, function, or string, optional) –
If it is an astropy quantity, it denotes the sigma of the Gaussian noise in intensity units. If it is an array of astropy quantities, it denotes the sigma of the Gaussian noise in intensity units at that position in the array. If it is a function, it should take the redshift as input and should output the sigma_noise at that redshift (as an astropy quantity in intensity units). If it is a string, it can be either
- the name of the file in an ecsv format readable by astropy.table, containing
’redshift’ column: redshift,
’sigma_noise’ column: sigma_noise at that redshift,
unit of ‘sigma_noise’ (automatic if saved using astropy.table)
Then it will be interpolated between redshifts (in case a redshift is out of bounds, the border values are used.)
- or the name of the hdf5 file containing the sigma_noise mesh (same shape as N_mesh)
under the name ‘sigma_noise’ with the unit as a string under ff[‘sigma_noise’].attrs[‘unit’].
Default: None. Then the noise is zero.
lambda_restframe (astropy quantity, optional) – Rest-frame wavelength in length units. If lambda_restframe is given, the intensity will be specific intensity dI/dlambda. Optional if ‘nu_restframe’ is given.
nu_restframe (astropy quantity, optional) – Rest-frame frequency in inverse time units. If lambda_restframe is given, the intensity will be specific intensity dI/dnu. Optional if ‘lambda_restframe’ is given.
brightness_temperature (bool, optional) – Flag stating whether to calculate everything in temperature units instead of specific intensity units.
do_spectral_smooth (bool, optional) – Flag stating whether to smooth along the spectral dimension. If ‘do_spectral_smooth’ is True, either ‘dlambda’ or ‘dnu’ must be given, corresponding to whether lambda_restframe or nu_restframe are given. Default: False.
dlambda (astropy quantity, optional) – Smoothing wavelength (in wavelength units) along the spectral direction. If ‘do_spectral_tophat_smooth’ is True, it is the size of the 1d top-hat. Otherwise, it is the Gaussian sigma for a Gaussian smoothing kernel. This will be evaluated at the central redshift (‘redshift’ parameter) of the box for smoothing. Must be given if ‘do_spectral_smooth’ is True and ‘lambda_restframe’ is given. Will be ignored otherwise.
dnu (astropy quantity, optional) – Smoothing frequency (in frequency units) along the spectral direction. If ‘do_spectral_tophat_smooth’ is True, it is the size of the 1d top-hat. Otherwise, it is the Gaussian sigma for a Gaussian smoothing kernel. This will be evaluated at the central redshift (‘redshift’ parameter) of the box for smoothing. Must be given if ‘do_spectral_smooth’ is True and ‘nu_restframe’ is given. Will be ignored otherwise.
do_spectral_tophat_smooth (bool, optional) – Flag stating whether to use a 1d top-hat smoothing kernel in the angular direction. If False, it will use a Gaussian kernel instead. Default: False.
do_angular_smooth (bool, optional) – Flag stating whether to smooth in the directions perpendicular to the LOS. This will be a Gaussian smoothing kernel. If True, ‘sigma_beam’ must be given. Default: False.
sigma_beam (astropy quantity, optional) – Gaussian sigma for the Gaussian smoothing kernel perpendicular to the LOS, in angle units. This will be evaluated at the central redshift (‘redshift’ parameter) of the box for smoothing. Must be given if ‘do_angular_smooth’ is True. Will be ignored otherwise.
footprint_radius (astropy quantity, optional) – Radius of a circular focal plane in angle units. This is necessary if you want to perform a sky subtraction and will be ignored otherwise. Default: None
seed_lognormal (int, optional) – Seed for the (random) generation of the lognormal galaxy catalog and the noise. It it is the same twice, you should get the same results. If None, the code will generate a random positive integer. Default: None
run_pk (dictionary, optional) – Dictionary stating which power spectra to calculate. Keys can include [“intensity”, “n_gal”, “cross”, “sky_subtracted_intensity”, “sky_subtracted_cross”] and the values are either True or False. Default for each key (if not given): False.
dk (astropy quantity, optional) – Size of the linearly spaced wavenumber bins to calculate the power spectra (inverse length units). Default: 2 pi / minimum box size.
kmin (astropy quantity, optional) – Minimum k of the linearly spaced wavenumber bins to calculate the power spectra (inverse length units). Default: 0.
kmax (astropy quantity, optional) – Maximum k of the linearly spaced wavenumber bins to calculate the power spectra (inverse length units). Default: minimum Nyquist frequency.
obs_mask (ndarray (3,) or string) – If it is an ndarray, it should contain the mask (or weights) as floats and should have the same shape as given by N_mesh. If it is a string, it should be the name of the hdf5 file containing the mask array under the name ‘mask’. Default: None (then the mask will be generated as ones).
calc_pk_lognormal (bool, optional) – Flag stating whether to have the galaxy power spectrum calculated by lognormal_galaxies. In this case, it will output the galaxy power spectrum of all galaxies in a file as described in https://bitbucket.org/komatsu5147/lognormal_galaxies/src/master/. Default: False.
Notes
The redshift direction is chosen to be the first axis such that the smallest index is closest to the observer.
- property N_gal
Calculates the number of all galaxies (no selection function) from self.n_bar_gal. Cached like a property self.N_gal
- property N_gal_detected
Outputs the number of detected galaxies in the galaxy catalog (no mask). Cached like a property self.N_gal_detected.
- Pk_multipoles(tracer='intensity', save=False)
Compute the power spectrum monopole and quadrupole of the map.
- Parameters:
tracer (str, optional) – Which power spectrum to compute. Options: ‘intensity’, ‘n_gal’, ‘cross’, ‘sky_subtracted_intensity’, ‘sky_subtracted_cross’. Default: ‘intensity’.
save (bool, optional) – Whether to save the computed power spectrum to a file. Default: False.
- Returns:
mean_k (array_like) – Array of mean wavenumbers.
monopole (array_like) – Array of monopole power spectrum values.
quadrupole (array_like) – Array of quadrupole power spectrum values.
- apply_selection_function()
Assigns whether each galaxy was detected or not given the flux limit (min_flux) of the observation.
- Parameters:
min_flux (astropy quantity, nd-array of floastropy quantities, or function of redshift, optional) – Flux limit of the (mock) observation above which galaxies are detected. If a function, it represents the flux limit as a function of redshift. Units of flux (erg/s/cm**2) required. Either min_flux or limit_ngal must be provided.
limit_ngal (float or function of redshift, optional) – Given number of galaxies per unit comoving volume above which galaxies are detected. If a function, it represents the number density limit as a function of redshift. Either min_flux or limit_ngal must be provided.
- Return type:
None
Notes
This function requires the galaxies to have assigned fluxes. If the fluxes are not assigned, they will be computed using the assign_flux() method. If neither min_flux nor limit_ngal are given, all galaxies will be detected.
- assign_flux(luminosity='luminosity')
Converts luminosity to flux in the galaxy catalog. Accounts for cosmological effects, not for peculiar velocities. Adds the column ‘flux’ to self.cat.
- Parameters:
luminosity (str, optional) – Key name of the luminosity column in the catalog, by default “luminosity”.
- Return type:
None
Notes
This function requires the galaxies to have assigned redshifts. If the redshifts are not assigned, they will be assigned using either a single redshift or redshift along the LOS.
- assign_luminosity()
Randomly assigns luminosities to the galaxies following the luminosity function. Adds the column ‘luminosity’ to self.cat.
- Return type:
None
Notes
This function requires a lognormal galaxy catalog. If the catalog does not exist, it will generate it using lognormal simulations.
- assign_redshift_along_axis()
Assigns redshift along the line-of-sight (LOS) axis (x, y, or z) given the mean/middle redshift. Also assigns the redshift-space distortion (RSD) redshift and inferred positions.
- Return type:
None
- Raises:
ValueError – If the LOS is not aligned with any of the axes [1,0,0], [0,1,0], or [0,0,1].
Notes
This function requires a lognormal galaxy catalog. If the catalog does not exist, it will generate it using lognormal simulations.
- assign_single_redshift()
Assigns a single redshift to the entire box. Adds the columns ‘cosmo_redshift’, ‘RSD_redshift’, ‘RSD_redshift_factor’, ‘RSD_Position’ to self.cat.
- Return type:
None
Notes
This function requires a lognormal galaxy catalog. If the catalog does not exist, it will generate it using lognormal simulations.
- bin_scipy(pkspec, return_nmodes=False)
Perform binning of the power spectrum.
- Parameters:
pkspec (ndarray) – The power spectrum mesh to be binned.
return_nmodes (bool) – Set to true if you want to have the number of modes in each bin returned. Default: False.
- Returns:
mean_k (ndarray) – The mean wavenumber in each bin.
monopole (ndarray) – The monopole component of the power spectrum.
quadrupole (ndarray) – The quadrupole component of the power spectrum.
- copy_info()
Initiates a new LognormalIntensityMock instance with the same input parameters as the original one.
- Returns:
A new instance of LognormalIntensityMock with the same input parameters as the original.
- Return type:
- downsample_all_meshes(new_N_mesh)
Downsamples all meshes to a new grid resolution using NGP: n_gal_mesh, intensity_mesh, obs_mask, sky_intensity_mesh, noise_mesh.
- Parameters:
new_N_mesh (list of int (len 3)) – The new grid resolution for downsampling.
- classmethod from_file(filename, catalog_filename=None, only_params=False, only_meshes=['intensity_mesh', 'noise_mesh', 'n_gal_mesh', 'obs_mask'])
Initialize a LognormalIntensityMock instance from a saved file.
- Parameters:
filename (str) – The filename of the saved file.
catalog_filename (str, optional) – The filename of the galaxy catalog to be read. Default is None.
only_params (bool, optional) – If True, only the parameters are loaded and not the meshes. Default is False.
only_meshes (list of str, optional) – The list of specific meshes to be loaded. Default is [“intensity_mesh”, “noise_mesh”, “n_gal_mesh”, “obs_mask”].
- Returns:
A new instance of LognormalIntensityMock initialized from the saved file.
- Return type:
- get_comoving_distance_per_delta_z(mean_z, delta_z)
Calculates the comoving distance between (z + delta_z) and (z - delta_z).
- Parameters:
mean_z (float) – Mean redshift of the box: mean_z = (z_min + z_max) / 2.
delta_z (float) – Half of the redshift difference: delta_z = (z_max - z_min) / 2.
- Returns:
Comoving distance between (z + delta_z) and (z - delta_z).
- Return type:
Quantity
- get_intensity_noise_cube()
Generate a mock intensity noise cube following a Gaussian distribution with an input sigma.
- Returns:
noise_mesh – The generated intensity noise cube in units of mean intensity.
- Return type:
ndarray
Notes
If sigma_noise is not provided, a zero noise cube is returned.
- get_sky_background(footprint_angle)
Compute the contribution of the intensity map to the measured sky background. It achieves this by smoothing the intensity mesh in the angular directions using a top-hat filter of the specified angular footprint size.
- Parameters:
footprint_angle (astropy.u.Quantity (scalar)) – Angular footprint size as an angular astropy Quantity in angle units.
- Returns:
sky_intensity_mesh – The computed sky background intensity mesh in units of mean intensity.
- Return type:
ndarray
- input_power_spectrum(k)
Calculates the power spectrum corresponding to the given wavenumber values.
- Parameters:
k (array-like) – Wavenumber values in units of [h / Mpc].
- Returns:
Power spectrum values in units of [Mpc^3/h^3].
- Return type:
Quantity
- load_lognormal_catalog_cpp(bin_filename, delete_bin=True)
Loads the lognormal catalog from a binary file.
- Parameters:
bin_filename (str) – Path to the binary file containing the lognormal galaxy catalog (output from lognormal_galaxies).
delete_bin (bool) – Set to False if you want to keep the binary file. Default: True.
- Return type:
None.
- Raises:
AssertionError – If the number of galaxies in the lognormal catalog does not match the number of positions in the loaded catalog.
- log10_luminosity_function(log10_L)
Log_10 of the luminosity function.
- property lognormal_bin_filename
Automatically generates the filename for the binary output file of lognormal_galaxies galaxy catalog.
- luminosity_function_times_L(L)
dn/dL * L
- property mean_intensity
Returns the mean intensity of the mesh in units of mean intensity. As soon as it is calculated once, it is saved.
- mean_intensity_per_redshift(redshifts, galaxy_selection='all', tracer='intensity')
Calculates the mean intensity or the mean galaxy number density that we would expect at a given redshift of a given galaxy population (either all or detected/undetected galaxies). We use the integrals
\[\bar{\rho}_L(z) = \int_{L_\mathrm{min}}^{L_\mathrm{max}} dL\, \frac{\mathrm{d}n}{\mathrm{d}L} L\]\[\bar{I}_\lambda(z) = \frac{c \bar{\rho}_L(z)}{4 \pi \lambda_0 H(z)}\]and
\[\bar{n}_\mathrm{gal}(z) = \int_{L_\mathrm{min}}^{L_\mathrm{max}} dL\, \frac{\mathrm{d}n}{\mathrm{d}L}\]where
Lmin = self.Lminfor all galaxies or undetected galaxies orLmin = self.min_flux(z) * 4 * np.pi * D_L**2for detected galaxies andLmax = self.Lmaxfor all galaxies or detected galaxiesLmax = self.min_flux(z) * 4 * np.pi * D_L**2for undetected galaxies.If min_flux is a mesh with the same size as N_mesh, it will return the mean of the intensity/n_gal mesh depending on the specified tracer.
- Parameters:
redshifts (array (n,)) – List/array of redshifts to be computed.
galaxy_selection (str) – Which galaxies to use: ‘all’, ‘detected’, or ‘undetected’. Default: ‘all’.
tracer (str) – Whether to calculate the mean intensity (‘intensity’) or mean galaxy number density (‘n_gal’). Default: ‘intensity’.
- Returns:
mean_intensity_per_redshift – List/array of the mean intensity per redshift (if tracer==’intensity’) or mean galaxy number density per redshift (if tracer==’n_gal’). Same shape as input redshifts array.
- Return type:
Quantity array (n,)
- property mean_intensity_per_redshift_mesh
Broadcasts the 1D mean_intensity_per_redshift array to the 3D mesh (cached).
- property mean_ngal_per_redshift_mesh
Broadcasts the 1D mean_n_gal_per_redshift array to the 3D mesh (cached).
- property n_bar_gal
Calculates the mean galaxy number density by integrating over the luminosity function from Lmin to Lmax. It does not take the selection function into account. Make sure that the luminosity function output is in units of luminosity_function: dn/dL integral:
\[\int \frac{\mathrm{d}n}{\mathrm{d}L} \mathrm{d}L = \bar{n}_\mathrm{g} [\mathrm{Mpc}^{-3}]\]IMPORTANT: The luminosity function input has to be in units of [Mpc^-3 luminosity_unit^-1] so that int dn/dl dL is in units of [Mpc^-3].
Cached like a property self.n_bar_gal.
- Returns:
The expected mean galaxy number density in units of 1/Mpc**3, not taking into account the selection function.
- Return type:
Quantity
- property n_bar_gal_mesh
Calculates the mean galaxy number density from the mesh self.n_gal_mesh. Cached like a property self.n_bar_gal_mesh.
- property n_gal_detected
Outputs the number density of detected galaxies in the galaxy catalog (no mask). Cached like a property self.n_gal_detected.
- paint_galaxy_mesh(position='RSD_Position')
Calculates the galaxy number density mesh based on the specified position of galaxies. The parameter self.galaxy_selection_function[‘n_gal’] decides whether to use detected, undetected, or all galaxies.
- Parameters:
position (str, optional) – The column name in the catalog representing the position of galaxies. Options: “RSD_Position” (redshift space), “Position” (real space) Default: “RSD_Position”.
- Returns:
field – The generated galaxy number density mesh.
- Return type:
ndarray
- paint_intensity_mesh(position='RSD_Position', redshift='cosmo_redshift', tracer='intensity', luminosity='luminosity')
Generates the mock intensity map obtained from Cartesian coordinates. It does not include noise.
- Parameters:
position (str, optional) – The column name in the catalog representing the position of galaxies. Options: “RSD_Position” (redshift space), “Position” (real space). Default: “RSD_Position”.
redshift (str, optional) – The column name in the catalog representing the redshift of galaxies. This is used to calculate the intensity and irrelevant for tracer “n_gal”. Options: “cosmo_redshift” (without RSD), “RSD_redshift” (which RSD). Default: “cosmo_redshift”.
tracer (str, optional) – The tracer to generate the intensity map for. Options: “intensity”, “n_gal”. Default: “intensity”.
luminosity (str, optional) – The column name in the catalog representing the luminosity of galaxies. Options: “luminosity”. Default: “luminosity”.
- Returns:
field – The generated intensity map.
- Return type:
ndarray
- Raises:
ValueError – If tracer argument is not one of the allowed options.
- prepare_k_values()
Prepares the dimensionless k values for the power spectrum calculations.
- read_galaxy_catalog(catalog_filename)
Initializes the galaxy catalog from a specified file.
- Parameters:
catalog_filename (str) – The filename of the galaxy catalog file.
- Returns:
A dictionary containing the galaxy catalog data.
- Return type:
dict
- run(skip_lognormal=False, save_meshes=False, save_results=True)
Runs the entire simulation and analysis pipeline.
- Parameters:
skip_lognormal (bool, optional) – Skip the lognormal simulation and use a pre-generated catalog. Default: False.
save_meshes (bool, optional) – Save the generated LognormalIntensityMock instance to a file and the galaxy catalog to another file. Default: False.
save_results (bool, optional) – Save the computed power spectra to a file. Default: True.
Notes
This function performs all the necessary steps to run the simulation and analyze the results. It includes
the lognormal simulation,
catalog loading,
redshift assignment,
luminosity and flux assignment,
selection function application,
painting intensity and galaxy meshes,
and computing power spectra.
If skip_lognormal is False (default), the lognormal simulation and catalog loading will be performed. Then, redshift assignment, luminosity assignment, flux assignment, and selection function application will be executed.
The position variable used for painting the intensity and galaxy meshes depends on the RSD (Redshift-Space Distortion) setting self.RSD. If RSD is enabled, “RSD_Position” is used, and if RSD is disabled, “Position” is used.
The intensity and galaxy meshes will be painted if the corresponding power spectra are enabled in the self.run_pk setting.
If save_meshes is True, the generated intensity and galaxy meshes will be saved to file.
If save_results is True (default), the computed power spectra will be saved to file.
- run_lognormal_simulation_cpp()
Calculates the power spectrum from input cosmology and runs lognormal simulation in lognormal_galaxies. Calculates the RSD position given the LOS.
- Parameters:
None. –
- Return type:
None.
- save_galaxy_catalog(cat=None, keys=['Position', 'Velocity'], filename='{}_catalog.h5', galaxy_selection='detected')
Saves the galaxy catalog, either all galaxies or only detected or undetected galaxies, as an h5 file.
- Parameters:
cat (LognormalCatalog object, optional) – Which catalog to save. Default: None. If None, use self.cat.
keys (list of strings, optional) – Which columns to save of the catalog. Options: Position, RSD_Position, Velocity, VelocityOffset, cosmo_redshift, RSD_redshift, luminosity, flux, detected. Default: Position and Velocity.
filename (str, optional) – Name of the output catalog file. If it contains a {}, it will be filled with the galaxy_selection argument. Default: ‘{}_galaxies.h5’.
galaxy_selection (str, optional) – Whether to save all, detected, or undetected galaxies. Options: ‘all’, ‘detected’, ‘undetected’. Default: ‘detected’.
- Raises:
ValueError – If galaxy_selection is not ‘all’, ‘detected’, or ‘undetected’.
- Return type:
None
Notes
This function saves the specified columns of the galaxy catalog as an h5 file. The saved file can be opened using h5py and converted into an astropy Table: >>> import h5py >>> from astropy.table import Table >>> with h5py.File(filename, ‘r’) as F: >>> tab = Table(F)
- save_to_file(filename, catalog_filename=None)
Saves the instance and its attributes to a file.
- Parameters:
filename (str) – The filename of the file to save the instance to.
catalog_filename (str, optional) – The filename of the galaxy catalog file to save (default is None). If None, it does not save the galaxy catalog.
- sigma_par()
Calculate the comoving distance corresponding to the LOS smoothing length.
- Returns:
sigma_par – Comoving distance corresponding to the LOS smoothing length.
- Return type:
Quantity
Notes
This function calculates the comoving distance corresponding to the smoothing length along the line-of-sight (LOS) direction. The calculated value depends on the specified rest frame wavelength (lambda_restframe) or frequency (nu_restframe), the LOS direction, and the cosmological parameters.
- sigma_perp()
Calculate the comoving distance corresponding to the angular smoothing length.
- Returns:
sigma_perp – Comoving distance corresponding to the angular smoothing length.
- Return type:
Quantity
Notes
This function calculates the comoving distance corresponding to the smoothing length perpendicular to the line-of-sight (LOS) direction. The calculated value depends on the specified redshift, angular diameter distance, angular smoothing length, and the cosmological parameters.
- simple.simple.angular_tophat_filter(k, v)
Top-hat filter for k_perp. Applies to an pmesh mesh object as a regular filter.
- Uses globally defined variables:
size_perp - ‘angular’ size of the top-hat filter in the flat sky approximation
- Usage:
mesh.apply(angular_tophat_filter, mode=’complex’, kind=’wavenumber’)
NOTES: k[0] *= modifies the next iteration in the loop. Coordinates are fixed except for the k[1] which are the coordinate that sets what slab is being altered?
- simple.simple.aniso_filter(k, v)
Filter for k_perp and k_par modes separately. Applies to an pmesh mesh object as a regular filter.
- Uses globally defined variables:
sigma_perp - ‘angular’ smoothing in the flat sky approximation sigma_par - ‘radial’ smoothing from number of channels.
- Usage:
mesh.apply(perp_filter, mode=’complex’, kind=’wavenumber’)
NOTES: k[0] *= modifies the next iteration in the loop. Coordinates are fixed except for the k[1] which are the coordinate that sets what slab is being altered?
- simple.simple.aniso_filter_gaussian(k, v)
Filter for k_perp and k_par modes separately. Applies to an pmesh mesh object as a regular filter.
- Uses globally defined variables:
sigma_perp - ‘angular’ smoothing in the flat sky approximation sigma_par - ‘radial’ smoothing from number of channels.
- Usage:
mesh.apply(perp_filter, mode=’complex’, kind=’wavenumber’)
NOTES: k[0] *= modifies the next iteration in the loop. Coordinates are fixed except for the k[1] which are the coordinate that sets what slab is being altered?
simple.pk_3d_model module
- class pk_3d_model.Power_Spectrum_Model(input_dict, do_model_shot_noise=None, out_filename=None)
Bases:
LognormalIntensityMockPower_Spectrum_Model class. Models the intensity/galaxy/cross power spectrum of a LognormalIntensityMock instance with the same input parameters as that.
- Parameters:
input_dict – Input parameters for the LognormalIntensityMock instance, see simple.py.
do_model_shot_noise (bool) – Set to True to model the shot noise by shuffling the galaxy positions perpendicular to the LOS. Default is None/False.
out_filename (str) – Name of the file to save the model power spectra to (hdf5 format).
Notes
The general model is explained in the paper.
- property D_cic_corr
Damping function D for cic resampling evaluated for this instance as a 3D array.
- D_cic_of_k(k, k_N)
Damping function D for cic resampling with the aliasing correction for the shot noise.
- D_sq_par_of_k(k_par, s_par)
Damping function D^2 for LOS-parallel top-hat smoothing with smoothing length s_par.
- D_sq_perp_of_k(k_perp, s_perp)
Damping function D^2 for LOS-perpendicular exponential smoothing with smoothing length s_perp.
- D_sq_tophat_of_k(k_perp, s_perp_sky)
Damping function D^2 for a spherical top-hat smoothing in the directions perpendicular to the LOS.
- property Pm_kspec
Cached property that returns the galaxy power spectrum Pm_kspec. If self.RSD is True, it will return the Kaiser RSD approximation. Otherwise it will be just the bias squared times the matter power spectrum.
- Returns:
The power spectrum Pm_kspec.
- Return type:
astropy quantity array
- classmethod from_file(filename, out_filename, catalog_filename=None, only_params=False, only_meshes=['noise_mesh', 'obs_mask'], do_model_shot_noise=None)
Method to initiate a Power_Spectrum_Model object from a file containing a saved LognormalIntensityMock object.
- Parameters:
filename (str) – Name of the file containing the saved LognormalIntensityMock object.
out_filename (str) – Output filename for the power spectrum results.
catalog_filename (str, optional) – Filename of the catalog associated with the LognormalIntensityMock object.
only_params (bool, optional) – Set to True to load only the parameters and skip loading the meshes.
only_meshes (list of str, optional) – List of specific meshes to load. Default is [“noise_mesh”, “obs_mask”].
do_model_shot_noise (bool, optional) – Set to True to model the shot noise by shuffling the galaxy positions perpendicular to the LOS. Default is None/False.
- Returns:
instance – An instance of the Power_Spectrum_Model class.
- Return type:
- get_3d_pk_model(damping_function, P_shot_smoothed, S_bar, mask_window_function_1, observed_volume, box_volume, Pk_unit, convolve=True, mask_window_function_2=None, save=True, tracer=None, return_3d=False)
Calculates the 3D power spectrum model P(k) by incorporating smoothing, convolution with the window function, and noise, and bins it in linear k bins.
- Parameters:
damping_function (array-like) – The damping function.
P_shot_smoothed (astropy quantity scalar or array) – The shot noise power spectrum that is subject to smoothing (i.e. not pixel noise) in volume units.
S_bar (float) – The value of S_bar.
mask_window_function_1 (array-like) – The window function: mask times mean field as a function of position.
observed_volume (astropy quantity) – The observed volume in volume units.
box_volume (astropy quantity) – The total box volume in volume units.
Pk_unit (astropy unit object) – The unit of the power spectrum (e.g. u.Unit(“u.Mpc**3”))
convolve (bool, optional) – Flag indicating whether to convolve P(k) with the window function squared. If False, just multiply by Q_bar (mean of the window function squared). Default is True.
mask_window_function_2 (array-like, optional) – The window function for the second field in case of a cross power spectrum. Default: None.
save (bool, optional) – Flag indicating whether to save the results. Default is True.
tracer (str, optional) – Options: n_gal, intensity, cross, sky_subtracted_intensity, sky_subtracted_cross. The tracer label in the saved file. Default is None.
return_3d (bool, optional) – Set to True if you want to return the 3D model as well.
Returns –
-------- –
mean_k – Mean k in the k bins.
monopole – Monopole moment of the binned power spectrum.
quadrupole – Quadrupole moment of the binned power spectrum.
- get_Q_bar(weight_mesh, mean_intensity_per_redshift_mesh)
Calculates the Q_bar value given the weight mesh and the mean field as a function of position.
- get_S_bar(weight_mesh, sigma_noise)
Calculates the S_bar value given the weight mesh and the sigma of the Gaussian noise.
- get_cross_model(sky_subtraction=False)
Calculate and save the power spectrum model for the intensity-galaxy number density cross-power spectrum.
- Parameters:
sky_subtraction (bool) – Set to True if you want the sky_subtracted_intensity. Default: False.
- get_cross_shot_noise()
Calculates the shot noise of the cross power spectrum that originates from randomly sampling the number of galaxies and their luminosity from the first moment of the luminosity function that includes only the galaxies overlapping in both fields.
- get_intensity_model(sky_subtraction=False, return_3d=False)
Calculate and save the power spectrum model for the intensity.
- Parameters:
sky_subtraction (bool) – Set to True if you want the sky_subtracted_intensity. Default: False.
- get_intensity_shot_noise()
Calculates the shot noise (from randomly sampling the number of galaxies and the luminosity of each galaxy), which is subject to smoothing from the second moment of the luminosity function.
- get_model(tracer)
Wrapper to calculate and save the model for each tracer.
- Parameters:
tracer (str) – Tracer name to get the power spectrum model for. Options: “intensity”, “n_gal”, “cross”, “sky_subtracted_intensity”, “sky_subtracted_cross”.
- get_models()
Wrapper to calculate and save all specified power spectrum models here self.run_pk[tracer] is True.
- get_n_gal_model()
Calculate and save the power spectrum model for the galaxy number density.
- get_observed_volume()
Returns the observed volume given the mask.
- property k_N
Nyquist frequency in [h/Mpc].
- luminosity_function_times_Lsq(L)
Luminosity function times L**2
- property mean_intensity_per_redshift_mesh
Broadcasts the 1D mean_intensity_per_redshift array to the 3D mesh (cached).
- property mean_ngal_per_redshift_mesh
Broadcasts the 1D mean galaxy number density array to the 3D mesh (cached).
- model_shot_noise(N_real=10)
Model the shot noise in the intensity and galaxy distributions by shuffling the cells in the directions perpendicular to the LOS while keeping the LOS position fixed (to keep directional information that may exist due to redshift differences). After shuffling, calculate the power spectrum. Finally the model shot noise is given by the average of the power spectra of the shuffled meshes.
- Parameters:
N_real (int, optional) – Number of realizations of shuffled meshes. Default is 10.
- own_init(do_model_shot_noise, out_filename)
Step in initializing the Power_Spectrum_Model instance.
- Parameters:
do_model_shot_noise (bool) – Set to True to model the shot noise by shuffling the galaxy positions perpendicular to the LOS.
out_filename (str) – Output filename for the power spectrum results.
- property weight_mesh_im
just 1/mean_intensity.
- Type:
Weights for the intensity mesh
- property weight_mesh_ngal
1/(mean n_gal as a function of position).
- Type:
Weights for the galaxy density mesh
- pk_3d_model.kaiser_pkmu(Plin, k, mu, bias, f_growth)
Returns the Kaiser linear P(k,mu) in redshift space
\[P(k,mu) = (1 + f/b_1 \mu^2)^2 b_1^2 P_\mathrm{lin}(k)\]Copied from nbodykit.
simple.tools_python module
- tools_python.bin_Pk_2d(pkspec, k_bins, k_par, k_perp)
Bins the power spectrum into a grid of given k_bins in the perpendicular and parallel to the LOS directions.
- Parameters:
pkspec (array-like (1D)) – Power spectrum data to be binned. Flattened 3D array.
k_bins (array-like) – Array specifying the bin edges for both k_par and k_perp.
k_par (array-like (1D)) – Array of k_parallel values corresponding to pkspec. Flattened 3D array.
k_perp (array-like (1D)) – Array of k_perpendicular values corresponding to pkspec.
- Returns:
P_k_2d – Binned 2D power spectrum.
- Return type:
array
- tools_python.bin_Pk_mu(pkspec, k_bins, kspec, muspec, mu_bins)
Bins the power spectrum into a grid of given k_bins and mu_bins.
- Parameters:
pkspec (array-like (1D)) – Power spectrum data to be binned. Flattened 3D array.
k_bins (array-like) – Array specifying the bin edges for k values.
kspec (array-like (1D)) – Array of k values corresponding to pkspec. Flattened 3D array.
muspec (array-like (1D)) – Array of mu values corresponding to pkspec. Flattened 3D array.
mu_bins (array-like) – Array specifying the bin edges for mu values.
- Returns:
mean_k_2d (array) – Binned mean k values in the 2D grid.
mean_mu_2d (array) – Binned mean mu values in the 2D grid.
P_k_mu (array) – Binned power spectrum.
- tools_python.bin_scipy(pkspec, k_bins, kspec, muspec, lmax=2, return_nmodes=False)
Calculates the monopole and quadrupole (if lmax==2) power spectrum and mean k in the given k bins.
- Parameters:
pkspec (array-like (1D)) – Array of power spectrum values. Flattened 3D array.
k_bins (array-like (1D)) – Array of bin edges for the k values.
kspec (array-like (1D)) – Array of k values corresponding to pkspec. Flattened 3D array.
muspec (array-like (1D)) – Array of mu values corresponding to pkspec. Flattened 3D array.
lmax (int, optional) – Maximum multipole moment to calculate. Options: 1, 2 Default: 2.
- Returns:
mean_k (ndarray) – Mean k values in each k bin.
monopole (ndarray) – Mean monopole power spectrum in each k bin.
quadrupole (ndarray (or None if lmax==1)) – Mean quadrupole power spectrum in each k bin.
- tools_python.get_checker_mask(N_mesh, N_cells=1)
Generates a checkerboard mask for a 3D grid. The mask is constant along the first axis.
- Parameters:
N_mesh (array-like) – Number of cells in each dimension (3D grid).
N_cells (int, optional) – Number of cells per checkerboard cell (default is 1).
- Returns:
Checkerboard mask for the specified 3D grid.
- Return type:
ndarray
- tools_python.get_cylinder_mask(N_mesh)
Generates a mask for a cylindrical region in a 3D grid. The cylinder is elongated in the first axis.
- Parameters:
N_mesh (array-like) – Number of cells in each dimension (3D grid).
- Returns:
Cylindrical mask indicating the region of interest.
- Return type:
ndarray
- tools_python.jinc(x)
Returns the Jinc function for x!=0 and the limit 0.5 at x==0. The Jinc function is the first Bessel function of x divided by x.
- tools_python.log_interp1d(xx, yy, kind='linear', bounds_error=False, fill_value='extrapolate')
Logarithmic interpolation accepting linear quantities as input (transformed within the function).
- Parameters:
xx (array-like) – Array of x values.
yy (array-like) – Array of y values.
kind (str, optional) – Specifies the kind of interpolation. Default is ‘linear’.
bounds_error (bool, optional) – If True, raise an error when attempting to interpolate outside the bounds of the input data. Default is False.
fill_value (str or numeric, optional) – Specifies the value to use for points outside the bounds of the input data when bounds_error is False. Default is ‘extrapolate’.
- Returns:
A callable function that performs logarithmic interpolation on input values.
- Return type:
callable
- tools_python.make_map(m, Nmesh, BoxSize, type='real')
Returns a pmesh.RealField object from an array ‘m’ as input.
- Parameters:
m (array) – Numpy array to be transformed into a pmesh.RealField object.
Nmesh (array) – Array with dimension (3,) with the number of cells in each dimension.
- tools_python.print_memory_usage()
Prints the current memory usage in GB.
- tools_python.transform_bin_to_h5(bin_filename, h5_filename=None)
Transforms a binary file containing galaxy data from lognormal_galaxies into an HDF5 file.
- Parameters:
bin_filename (str) – Path to the binary output file containing the galaxy catalog from lognormal_galaxies.
h5_filename (str, optional) – Path to the output HDF5 file. If not provided, the output file will be created with the same name as the input file, but with the extension ‘.h5’.
- Returns:
h5_filename – Path to the output HDF5 file
N_gal – Number of galaxies.
- tools_python.yaml_file_to_dictionary(filename)
Opens a yaml file and returns a dictionary from its contents.
- tools_python.yaml_stream_to_dictionary(stream)
Uses an opened yaml file and returns the dicionary.
simple.tools module
Unfortunately, the autodoc does not work for this module because it is written in Cython. Please look at the code itself for the docstrings: https://github.com/mlujnie/simple/blob/main/simple/tools.pyx
simple.run_lognormal_galaxies module
- run_lognormal_galaxies.calc_Pk(i, params, exe)
Calls calculate_pk/calc_pk_const_los_ngp function of lognormal_galaxies.
- Parameters:
i (int) – Number of this realization.
params (dict) – Dictionary containing input parameters for lognormal_galaxies.
exe – Executable object used to run the external commands.
- run_lognormal_galaxies.calc_cPk(i, params, exe)
Calls function calculate_cross/calc_cpk_const_los_v2 of lognormal_galaxies to calculate galaxy-matter power spectrum.
- Parameters:
i (int) – Number of this realization.
params (dict) – Input parameters for lognormal_galaxies.
exe – Executable object used to run the external commands.
- run_lognormal_galaxies.check_dir_im(params)
Creates the necessary directories for saving output files if they do not already exist.
- Parameters:
params (dict) – Dictionary containing the parameters passed to lognormal_galaxies, including “out_dir” specifying the output directory.
- class run_lognormal_galaxies.executable(name)
Bases:
objectClass to execute commands
- run(exename, args, params)
- run_lognormal_galaxies.gen_Poisson(i, params, seed1, seed2, seed3, exe)
Generate galaxy and matter density field and the Poisson-sampled lognormal galaxy catalog using lognormal_galaxies.
- Parameters:
i (int) – Number of this realization.
params (dict) – Dictionary containing the input parameters for lognormal_galaxies.
seed1 (int) – Seed.
seed2 (int) – Seed.
seed3 (int) – Seed.
exe – Executable object used to run the external commands.
- run_lognormal_galaxies.gen_inputs(params, exe)
Generates the necessary input files for generate_Poisson. First, it runs eisensteinhubaonu/compute_pk to calculate the matter power spectrum from the cosmological parameters. Then it runs compute_xi/compute_xi to calculate the corresponding correlation function. Then it runs compute_pkG/calc_pkG to calculate the Gaussian power spectrum for the galaxy field. Then it runs compute_pkG/calc_pkG to calculate the Gaussian power spectrum for the matter field. Finally it runs compute_pkG/calc_pkG to calculate the Gaussian cross-power spectrum of the galaxy and matter fields.
- Parameters:
params (dict) – Dictionary containing the parameters for lognormal_galaxies.
exe (object) – An executable object used to run the external commands.
- run_lognormal_galaxies.wrap_calc_Pk(args)
Wrapper for the function calc_Pk.
- run_lognormal_galaxies.wrap_calc_cPk(args)
Wrapper for function calc_cPk.
- run_lognormal_galaxies.wrap_gen_Poisson(args)
Wrapper for gen_Poisson function.