API Reference

The full list of nbodykit modules is available here. We summarize the most important aspects of the API below.

Cosmology (nbodykit.cosmology)

The main cosmology object relies on the functionality of the classylss package, which provides a binding of the CLASS CMB Boltzmann code. The syntax largely follows that used by CLASS. Below, we list the main cosmology class, as well as its attributes and methods:

Cosmology([h, T0_cmb, Omega0_b, Omega0_cdm, …]) A cosmology calculator based on the CLASS binding in classylss.


A_s The scalar amplitude of the primordial power spectrum at \(k_\mathrm{pivot}\).
C The speed of light in units of km/s.
G The gravitational constant in units of \(10^{-10} \ (M_\odot/h)^{-1} (\mathrm{Mpc}/h) \mathrm{km}^2 \mathrm{s}^{-2}\).
H0 Current Hubble parameter in units of \(\mathrm{km/s} (\mathrm{Mpc}/h)^{-1}.\)
N_ncdm The number of distinguishable ncdm (massive neutrino) species.
N_ur The number of ultra-relativistic species.
Neff Effective number of relativistic species, summed over ultra-relativistic and ncdm species.
Ob0 Returns Omega0_b.
Ode0 Returns the sum of Omega0_lambda and Omega0_fld.
Odm0 Returns Omega0_cdm.
Ogamma0 Returns Omega0_g.
Ok0 Returns Omega0_k.
Om0 Returns Omega0_m.
Omega0_b Current density parameter for photons, \(\Omega_{b,0}\).
Omega0_cb The total density of CDM and Baryon.
Omega0_cdm Current density parameter for cold dark matter, \(\Omega_{cdm,0}\).
Omega0_dcdm Current density parammeter for decaying cold dark matter, \(\Omega_{dcdm,0}\).
Omega0_fld Current density parameter for dark energy (fluid) \(\Omega_{fld, 0}\).
Omega0_g Current density parameter for photons, \(\Omega_{g,0}\).
Omega0_k Current density parameter for curvaturve, \(\Omega_{k,0}\).
Omega0_lambda Current density parameter for cosmological constant, \(\Omega_{\Lambda,0}\).
Omega0_m The sum of density parameters for all non-relativistic components, \(\Omega_{0,m}\).
Omega0_ncdm Current density parameter for distinguishable (massive) neutrinos for each species as an array, \(\Omega_{0, ncdm}\).
Omega0_ncdm_tot Current total density parameter of all distinguishable (massive) neutrinos.
Omega0_pncdm The pressure contribution to the current density parameter for the non-relativatistic part of massive neutrinos (an array holding all species).
Omega0_pncdm_tot The sum of \(\Omega_{0,pncdm}\) for all species.
Omega0_r Current density parameter of radiation, \(\Omega_{0,r}\).
Omega0_ur Current density parameter of ultra-relativistic (massless) neutrinos, \(\Omega_{0,\nu_r}\).
Onu0 Returns the sum of Omega0_ncdm_tot and Omega0_ur.
P_k_max The maximum k value measured for power spectra in \(h \mathrm{Mpc}^{-1}\).
P_k_min The minimum k value for which power spectra have been computed in \(h \mathrm{Mpc}^{-1}\).
P_z_max The input parameter specifying the maximum redshift measured for power spectra.
T0_cmb The current CMB temperature in Kelvins.
T0_ncdm An array holding the current ncdm temperature in Kelvins for each species.
Tcmb0 Returns T0_cmb.
Tnu0 Returns T0_ncdm.
a_max The maximum scale factor for which results can be computed; it can be greater than 1.0.
a_today An arbitrary number that sets the reference scaling factor.
age0 The current age of the universe in gigayears.
gauge The gauge name as a string, either ‘newtonian’ or ‘synchronous’.
h The dimensionless Hubble parameter.
has_massive_nu Returns True if N_ncdm is greater than zero.
has_pk_matter Boolean flag specifying whether matter power spectra have been requested as output.
k_max_for_pk The input parameter specifying the maximum k value to compute spectra for; units of \(h \mathrm{Mpc}^{-1}\).
k_pivot The primordial power spectrum pivot scale, where the primordial power is equal to \(A_s\).
ln_1e10_A_s Return \(\log(10^{10}A_s)\).
m_ncdm The masses of the distinguishable ncdm (massive neutrino) species, in units of eV.
n_s The tilt of the primordial power spectrum.
nonlinear Boolean flag specifying whether the power spectrum is nonlinear.
parameter_file A string holding the parameter names and values as loaded by CLASS.
rs_drag The comoving sound horizon at baryon drag, in \(\mathrm{Mpc}/h\).
rs_rec The comoving sound horizon at recombination, \(z=z_\mathrm{rec}\).
sigma8 The amplitude of matter fluctuations at \(z=0\) in a sphere of radius \(r = 8 \ h^{-1}\mathrm{Mpc}\).
tau_reio The reionization optical depth.
theta_s The sound horizon angle at recombination, equal to \(r_s(z_\mathrm{rec}) / D_a(z_\mathrm{rec})\).
w0 Returns w0_fld.
w0_fld Current fluid equation of state parameter, \(w_{0,fld}\).
wa Returns wa_fld.
wa_fld Fluid equation of state derivative, \(w_{a,fld}\).
z_drag The baryon drag redshift.
z_rec The redshift at which the visibility reaches its maximum; equals the recombination redshift.
z_reio The reionization redshift.


Ob(z) Returns Omega_b().
Ode(z) Returns the sum of Omega_lambda() and Omega_fld().
Odm(z) Returns Omega_cdm().
Ogamma(z) Returns Omega_g().
Ok(z) Returns Omega_k().
Om(z) Returns Omega_m().
Omega_b(self, z) Density parameter of baryons.
Omega_cdm(self, z) Density parameter of cold dark matter.
Omega_fld(self, z) Density parameter of dark energy (fluid).
Omega_g(self, z) Density parameter of photons.
Omega_k(self, z) Density parameter of curvature.
Omega_lambda(self, z) Density of dark energy (cosmological constant).
Omega_m(self, z) Density parameter of non-relativistic (matter-like) component, including non-relativistic part of massive neutrino.
Omega_ncdm(self, z[, species]) Density parameter of massive neutrinos.
Omega_pncdm(self, z[, species]) Return \(\Omega_{pncdm}\) as a function redshift.
Omega_r(self, z) Density parameter of relativistic (radiation-like) component, including relativistic part of massive neutrino and massless neutrino.
Omega_ur(self, z) Density parameter of ultra relativistic neutrinos.
Onu(z) Returns the sum of Omega_ncdm() and Omega_ur().
T_cmb(self, z) The CMB temperature as a function of redshift.
T_ncdm(self, z) The ncdm temperature (massive neutrinos) as a function of redshift.
Tcmb(z) Returns \((1+z)\) T0_cmb.
Tnu(z) Returns \((1+z)\) T0_ncdm.
angular_diameter_distance(self, z) Angular diameter distance in \(\mathrm{Mpc}/h\) at a given redshift.
clone(**kwargs) Create a new cosmology based on modification of self, with the input keyword parameters changed.
comoving_distance(self, z) Comoving line-of-sight distance in \(\mathrm{Mpc}/h\) at a given redshift.
comoving_transverse_distance(self, z) Comoving transverse distance in \(\mathrm{Mpc}/h\) at a given redshift.
compute_for_z(self, z, int column) Internal function to compute the background module at a specific redshift.
efunc(self, z) Function giving \(E(z)\), where the Hubble parameter is defined as \(H(z) = H_0 E(z)\).
efunc_prime(self, z) Function giving \(dE(z) / da\).
from_astropy(cosmo, **kwargs) Initialize and return a Cosmology object from a subclass of astropy.cosmology.FLRW.
from_dict(pars) Creates a Cosmology from a pars dictionary.
from_file(filename, **kwargs) Initialize a Cosmology object from the CLASS parameter file
get_pk(self, k, z) The primary power spectrum result (nonlinear if enabled) on k and z array.
get_pklin(self, k, z) Linear power spectrum result (linear even if nonlinear is enabled) on k and z array.
get_primordial(self) Return the primordial scalar and/or tensor spectrum depending on ‘modes’.
get_transfer(self, z[, output_format]) Return the density and/or velocity transfer functions for all initial conditions today.
hubble_function(self, z) The Hubble function in CLASS units, returning ba.index_bg_H.
hubble_function_prime(self, z) Derivative of Hubble function: \(dH/d\tau\), where \(d\tau/da = 1 / (a^2 H)\) in CLASS units.
luminosity_distance(self, z) Luminosity distance in \(\mathrm{Mpc}/h\) at redshift z.
match([sigma8, Omega0_cb, Omega0_m]) Creates a new cosmology that matches a derived parameter.
nu_relative_density(z) Returns Onu() / Ogamma().
p_ncdm(self, z[, species]) Pressure of non-relative part of massive neutrino.
rho_b(self, z) Density of baryons \(\rho_b\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_cdm(self, z) Density of cold dark matter \(\rho_{cdm}\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_crit(self, z) Critical density excluding curvature \(\rho_c\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_fld(self, z) Density of dark energy fluid \(\rho_{fld}\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_g(self, z) Density of photons \(\rho_g\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_k(self, z) Density of curvature \(\rho_k\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_lambda(self, z) Density of cosmological constant \(\rho_\Lambda\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_m(self, z) Density of matter \(\rho_b\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_ncdm(self, z[, species]) Density of non-relativistic part of massive neutrinos \(\rho_{ncdm}\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_r(self, z) Density of radiation \(\rho_r\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_tot(self, z) Total density \(\rho_\mathrm{tot}\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
rho_ur(self, z) Density of ultra-relativistic radiation (massless neutrinos) \(\rho_{ur}\) as a function of redshift, in units of \(10^{10} (M_\odot/h) (\mathrm{Mpc}/h)^{-3}\).
scale_independent_growth_factor(self, z) Return the scale invariant growth factor \(D(a)\) for CDM perturbations.
scale_independent_growth_rate(self, z) The scale invariant growth rate \(d\mathrm{ln}D/d\mathrm{ln}a\) for CDM perturbations.
sigma8_z(self, z) Return \(\sigma_8(z)\).
tau(self, z) Conformal time, equal to comoving distance when K = 0.0 (flat universe).
time(self, z) Proper time (age of universe) in gigayears.
to_astropy() Initialize and return a subclass of astropy.cosmology.FLRW from the Cosmology class.

There are several transfer functions available to the user:

CLASS(cosmo, redshift) The linear matter transfer function using the CLASS Boltzmann code.
EisensteinHu(cosmo, redshift) The linear matter transfer function using the Eisenstein & Hu (1998) fitting formula with BAO wiggles.
NoWiggleEisensteinHu(cosmo, redshift) Linear power spectrum using the Eisenstein & Hu (1998) fitting formula without BAO wiggles.

There are several power spectrum classes

LinearPower(cosmo, redshift[, transfer]) An object to compute the linear power spectrum and related quantities, using a transfer function from the CLASS code or the analytic Eisenstein & Hu approximation.
HalofitPower(cosmo, redshift) Nonlinear power spectrum computed using HaloFit via CLASS.
ZeldovichPower(cosmo, redshift[, transfer]) The matter power spectrum in the Zel’dovich approximation.

And a correlation function class and functions for transforming between power spectra and correlation functions

CorrelationFunction(power) Evaluate the correlation function by Fourier transforming a power spectrum object, with automatic re-scaling with redshift and sigma8.
xi_to_pk(r, xi[, extrap]) Return a callable function returning the power spectrum, as computed from the Fourier transform of the input \(r\) and \(\xi(r)\) arrays.
pk_to_xi(k, Pk[, extrap]) Return a callable function returning the correlation function, as computed from the Fourier transform of the input \(k\) and \(P(k)\) arrays.

We also have a class for computing LPT background calculations:

PerturbationGrowth(cosmo[, a]) Perturbation Growth coefficients at several orders.

The built-in cosmologies are:

Name Source H0 Om Flat
WMAP5 Komatsu et al. 2009 70.2 0.277 Yes
WMAP7 Komatsu et al. 2011 70.4 0.272 Yes
WMAP9 Hinshaw et al. 2013 69.3 0.287 Yes
Planck13 Planck Collab 2013, Paper XVI 67.8 0.307 Yes
Planck15 Planck Collab 2015, Paper XIII 67.7 0.307 Yes

Transforming Catalog Data (nbodykit.transform)

ConcatenateSources(*sources, **kwargs) Concatenate CatalogSource objects together, optionally including only certain columns in the returned source.
StackColumns(*cols) Stack the input dask arrays vertically, column by column.
ConstantArray(value, size[, chunks]) Return a dask array of the specified size holding a single value.
SkyToUnitSphere(ra, dec[, degrees]) Convert sky coordinates (ra, dec) to Cartesian coordinates on the unit sphere.
SkyToCartesian(ra, dec, redshift, cosmo[, …]) Convert sky coordinates (ra, dec, redshift) to a Cartesian Position column.
HaloConcentration(mass, cosmo, redshift[, mdef]) Return halo concentration from halo mass, based on the analytic fitting formulas presented in Dutton and Maccio 2014.
HaloRadius(mass, cosmo, redshift[, mdef]) Return halo radius from halo mass, based on the specified mass definition.

Data Sources

Discrete Objects

Base class:

CatalogSource(*args, **kwargs) An abstract base class representing a catalog of discrete particles.

And subclasses:

CSVCatalog(*args, **kwargs) A CatalogSource that uses CSVFile to read data from disk.
BinaryCatalog(*args, **kwargs) A CatalogSource that uses BinaryFile to read data from disk.
BigFileCatalog(*args, **kwargs) A CatalogSource that uses BigFile to read data from disk.
TPMBinaryCatalog(*args, **kwargs) A CatalogSource that uses TPMBinaryFile to read data from disk.
HDFCatalog(*args, **kwargs) A CatalogSource that uses HDFFile to read data from disk.
FITSCatalog(*args, **kwargs) A CatalogSource that uses FITSFile to read data from disk.
Gadget1Catalog(*args, **kwargs) A CatalogSource that uses Gadget1File to read data from disk.
ArrayCatalog(data[, comm, use_cache]) A CatalogSource initialized from a dictionary or structured ndarray.
HaloCatalog(source, cosmo, redshift[, mdef, …]) A wrapper CatalogSource of halo objects to interface nicely with halotools.sim_manager.UserSuppliedHaloCatalog.
HODCatalog(halos[, logMmin, sigma_logM, …]) A CatalogSource that uses the HOD prescription of Zheng et al 2007 to populate an input halo catalog with galaxies.
LogNormalCatalog(Plin, nbar, BoxSize, Nmesh) A CatalogSource containing biased particles that have been Poisson-sampled from a log-normal density field.
UniformCatalog(nbar, BoxSize[, seed, comm, …]) A CatalogSource that has uniformly-distributed Position and Velocity columns.
RandomCatalog(csize[, seed, comm, use_cache]) A CatalogSource that can have columns added via a collective random number generator.
FKPCatalog(data, randoms[, BoxSize, BoxPad, …]) An interface for simultaneous modeling of a data CatalogSource and a randoms CatalogSource, in the spirit of Feldman, Kaiser, and Peacock, 1994.
MultipleSpeciesCatalog(names, *species, **kwargs) A CatalogSource interface for handling multiples species of particles.

Interpolating Objects to a Mesh

The base class:

CatalogMesh(*args, **kwargs) A view of a CatalogSource object which knows how to create a MeshSource object from itself.

And subclasses:

MultipleSpeciesCatalogMesh(*args, **kwargs) A subclass of CatalogMesh designed to paint the density field from a sum of multiple types of particles.
FKPCatalogMesh(*args, **kwargs) A subclass of MultipleSpeciesCatalogMesh designed to paint a FKPCatalog to a mesh.

Data Directly on a Mesh

Base class:

MeshSource(comm, Nmesh, BoxSize, dtype) Base class for a source in the form of data on an input grid.

And subclasses:

BigFileMesh(path, dataset[, comm]) A MeshSource object that reads a mesh from disk using bigfile.
LinearMesh(Plin, BoxSize, Nmesh[, seed, …]) A MeshSource object that generates a RealField density mesh from a linear power spectrum function \(P(k)\).
FieldMesh(field) A MeshSource initialized from an in-memory Field object, either a pmesh.pm.RealField or pmesh.pm.ComplexField.
ArrayMesh(array, BoxSize[, comm, root]) A MeshSource initalized from an in-memory numpy array.

Algorithms (nbodykit.algorithms)

Clustering Statistics

FFTPower(first, mode[, Nmesh, BoxSize, …]) Algorithm to compute the 1d or 2d power spectrum and/or multipoles in a periodic box, using a Fast Fourier Transform (FFT).
ProjectedFFTPower(first[, Nmesh, BoxSize, …]) The power spectrum of a field in a periodic box, projected over certain axes.
ConvolvedFFTPower(first, poles[, second, …]) Algorithm to compute power spectrum multipoles using FFTs for a data survey with non-trivial geometry.
Multipoles3PCF(source, poles, edges[, …]) Compute the multipoles of the isotropic, three-point correlation function in configuration space.
SimulationBoxPairCount(mode, first, redges) Count (weighted) pairs of objects in a simulation box using the Corrfunc package.
SurveyDataPairCount(mode, first, redges, cosmo) Count (weighted) pairs of objects from a survey data catalog using the Corrfunc package.
AngularPairCount(first, edges[, second, ra, …]) Count (weighted) angular pairs of objects from a survey data catalog using the Corrfunc package.

Grouping Methods

FOF(source, linking_length, nmin[, …]) A friends-of-friends halo finder that computes the label for each particle, denoting which halo it belongs to.
CylindricalGroups(source, rankby, rperp, rpar) Compute groups of objects using a cylindrical grouping method.
FiberCollisions(ra, dec[, collision_radius, …]) Run an angular FOF algorithm to determine fiber collision groups from an input catalog, and then assign fibers such that the maximum amount of object receive a fiber.


KDDensity(source[, margin]) Estimate a proxy density based on the distance to the nearest neighbor.
RedshiftHistogram(source, fsky, cosmo[, …]) Compute the mean number density as a function of redshift \(n(z)\) from an input CatalogSource of particles.

Managing Multiple Tasks (TaskManager)

TaskManager(cpus_per_task[, comm, debug, …]) An MPI task manager that distributes tasks over a set of MPI processes, using a specified number of independent workers to compute each task.
TaskManager.iterate(tasks) A generator that iterates through a series of tasks in parallel.
TaskManager.map(function, tasks) Like the built-in map() function, apply a function to all of the values in a list and return the list of results.

Analyzing Results (BinnedStatistic)

BinnedStatistic(dims, edges, data[, …]) Lightweight class to hold statistics binned at fixed coordinates.
BinnedStatistic.from_json(filename[, key, …]) Initialize a BinnedStatistic from a JSON file.
BinnedStatistic.to_json(filename) Write a BinnedStatistic from a JSON file.
BinnedStatistic.copy() Returns a copy of the BinnedStatistic
BinnedStatistic.rename_variable(old_name, …) Rename a variable in data from old_name to new_name.
BinnedStatistic.average(dim, **kwargs) Compute the average of each variable over the specified dimension.
BinnedStatistic.reindex(dim, spacing[, …]) Reindex the dimension dim by averaging over multiple coordinate bins, optionally weighting by weights.
BinnedStatistic.sel([method]) Return a new BinnedStatistic indexed by coordinate values along the specified dimension(s).
BinnedStatistic.squeeze([dim]) Squeeze the BinnedStatistic along the specified dimension, which removes that dimension from the BinnedStatistic.

The IO Library (nbodykit.io)

Base class:

FileType An abstract base class representing a file object.

Subclasses available from the nbodykit.io module:

BigFile(path[, exclude, header, dataset]) A file object to handle the reading of columns of data from a bigfile file.
BinaryFile(path, dtype[, offsets, …]) A file object to handle the reading of columns of data from a binary file.
CSVFile(path, names[, blocksize, dtype, …]) A file object to handle the reading of columns of data from a CSV file.
FITSFile(path[, ext]) A file object to handle the reading of FITS data using the fitsio package.
HDFFile(path[, root, exclude]) A file object to handle the reading of columns of data from a h5py HDF5 file.
FileStack(filetype, path, *args, **kwargs) A file object that offers a continuous view of a stack of subclasses of FileType instances.
TPMBinaryFile(path[, precision]) Read snapshot binary files from Martin White’s TPM simulations.
Gadget1File(path[, columndefs, hdtype, ptype]) Read snapshot binary files from Volkers Gadget 1/2/3 simulations.

Internal Nuts and Bolts

MPI Utilities

nbodykit.CurrentMPIComm A class to faciliate getting and setting the current MPI communicator.
nbodykit.CurrentMPIComm.enable(func) Decorator to attach the current MPI communicator to the input keyword arguments of func, via the comm keyword.
nbodykit.CurrentMPIComm.get() Get the current MPI communicator, returning MPI.COMM_WORLD if it has not be explicitly set yet.
nbodykit.CurrentMPIComm.set(comm) Set the current MPI communicator to the input value.
nbodykit.utils.GatherArray(data, comm[, root]) Gather the input data array from all ranks to the specified root.
nbodykit.utils.ScatterArray(data, comm[, …]) Scatter the input data array across all ranks, assuming data is initially only on root (and None on other ranks).

General Utilities

nbodykit.setup_logging([log_level]) Turn on logging, with the specified level.
nbodykit.utils.JSONEncoder(*[, skipkeys, …]) A subclass of json.JSONEncoder that can also handle numpy arrays, complex values, and astropy.units.Quantity objects.
nbodykit.utils.JSONDecoder(*args, **kwargs) A subclass of json.JSONDecoder that can also handle numpy arrays, complex values, and astropy.units.Quantity objects.

Generating Mock Data

nbodykit.mockmaker.gaussian_complex_fields(pm, …) Make a Gaussian realization of a overdensity field, \(\delta(x)\).
nbodykit.mockmaker.gaussian_real_fields(pm, …) Make a Gaussian realization of a overdensity field in real-space \(\delta(x)\).
nbodykit.mockmaker.poisson_sample_to_points(…) Poisson sample the linear delta and displacement fields to points.