Python CAMB

CAMB (Code for Anisotropies in the Microwave Background), a cosmology code for calculating CMB, lensing, galaxy count, dark-age 21cm power spectra, matter power spectra and transfer functions. There are also general utility function for cosmological calculations. The main code is Python with numerical calculations implemented efficiently in Python-wrapped modern Fortran.

See the CAMB python example notebook for a quick introductory set of examples of how to use the CAMB package.

For a standard non-editable installation use:

pip install camb [--user]

The –user is optional and only required if you don’t have write permission to your main python installation. To install from source, in the project source root directory use:

python setup.py install [--user]

If you want to work on the code, you can also just install in place without copying anything using:

python setup.py make
pip install -e . [--user]

You will need gfortran 6 or higher installed to compile. Binary files for Windows are also provided, so these are used instead if no gfortran installation is found on Windows machines. If you have gfortran installed, “python setup.py make” will build the Fortran library on all systems (including Windows without directly using a Makefile).

After installation the camb python module can be loaded from your scripts using “import camb”. You can also run CAMB from the command line reading parameters from a .ini file, e.g.:

camb inifiles/planck_2018.ini

You may need to check your python scripts directory is in your path for this to work. Alternatively from the source package root directory (after make but without installation) use:

python camb.py inifiles/planck_2018.ini

Main high-level modules:

camb

Python CAMB interface (https://camb.info)

camb.get_results(params)[source]

Calculate results for specified parameters and return CAMBdata instance for getting results.

Parameters:paramsmodel.CAMBparams instance
Returns:CAMBdata instance
camb.get_background(params, no_thermo=False)[source]

Calculate background cosmology for specified parameters and return CAMBdata, ready to get derived parameters and use background functions like angular_diameter_distance().

Parameters:
  • paramsmodel.CAMBparams instance
  • no_thermo – set True if thermal history not required.
Returns:

CAMBdata instance

camb.get_transfer_functions(params)[source]

Calculate transfer functions for specified parameters and return CAMBdata instance for getting results and subsequently calculating power spectra.

Parameters:paramsmodel.CAMBparams instance
Returns:CAMBdata instance
camb.set_params(cp=None, verbose=False, **params)[source]

Set all CAMB parameters at once, including parameters which are part of the CAMBparams structure, as well as global parameters.

E.g.:

cp = camb.set_params(ns=1, H0=67, ombh2=0.022, omch2=0.1, w=-0.95, Alens=1.2, lmax=2000,
                     WantTransfer=True, dark_energy_model='DarkEnergyPPF')

This is equivalent to:

cp = model.CAMBparams()
cp.DarkEnergy = DarkEnergyPPF()
cp.DarkEnergy.set_params(w=-0.95)
cp.set_cosmology(H0=67, omch2=0.1, ombh2=0.022, Alens=1.2)
cp.set_for_lmax(lmax=2000)
cp.InitPower.set_params(ns=1)
cp.WantTransfer = True

The wrapped functions are (in this order):

Parameters:
  • params – the values of the parameters
  • cp – use this CAMBparams instead of creating a new one
  • verbose – print out the equivalent set of commands
Returns:

model.CAMBparams instance

camb.read_ini(ini_filename, no_validate=False)[source]

Get a model.CAMBparams instance using parameter specified in a .ini parameter file.

Parameters:no_validate – do not pre-validate the ini file (faster, but may crash kernel if error)
Returns:model.CAMBparams instance
camb.get_matter_power_interpolator(params, zmin=0, zmax=10, nz_step=100, zs=None, kmax=10, nonlinear=True, var1=None, var2=None, hubble_units=True, k_hunit=True, return_z_k=False, k_per_logint=None, log_interp=True, extrap_kmax=None)[source]

Return a 2D spline interpolation object to evaluate matter power spectrum as function of z and k/h, e.g.

from camb import get_matter_power_interpolator
PK = get_matter_power_interpolator(params);
print('Power spectrum at z=0.5, k/h=0.1/Mpc is %s (Mpc/h)^3 '%(PK.P(0.5, 0.1)))
Parameters:
  • paramsmodel.CAMBparams instance
  • zmin – minimum z (use 0 or smaller than you want for good interpolation)
  • zmax – maximum z (use larger than you want for good interpolation)
  • nz_step – number of steps to sample in z (default max allowed is 100)
  • zs – instead of zmin,zmax, nz_step, can specific explicit array of z values to spline from
  • kmax – maximum k
  • nonlinear – include non-linear correction from halo model
  • var1 – variable i (index, or name of variable; default delta_tot)
  • var2 – variable j (index, or name of variable; default delta_tot)
  • hubble_units – if true, output power spectrum in \(({\rm Mpc}/h)^{3}\) units, otherwise \({\rm Mpc}^{3}\)
  • k_hunit – if true, matter power is a function of k/h, if false, just k (both \({\rm Mpc}^{-1}\) units)
  • return_z_k – if true, return interpolator, z, k where z, k are the grid used
  • k_per_logint – specific uniform sampling over log k (if not set, uses optimized irregular sampling)
  • log_interp – if true, interpolate log of power spectrum (unless any values are negative in which case ignored)
  • extrap_kmax – if set, use power law extrapolation beyond kmax to extrap_kmax (useful for tails of integrals)
Returns:

RectBivariateSpline object PK, that can be called with PK(z,log(kh)) to get log matter power values. if return_z_k=True, instead return interpolator, z, k where z, k are the grid used

camb.get_age(params)[source]

Get age of universe for given set of parameters

Parameters:paramsmodel.CAMBparams instance
Returns:age of universe in gigayears
camb.get_zre_from_tau(params, tau)[source]

Get reionization redshift given optical depth tau

Parameters:
Returns:

reionization redshift (or negative number if error)

camb.set_feedback_level(level=1)[source]

Set the feedback level for internal CAMB calls

Parameters:level – zero for nothing, >1 for more
camb.run_ini(ini_filename, no_validate=False)[source]

Run the command line camb from a .ini file (producing text files as with the command line program). This does the same as the command line program, except global config parameters are not read and set (which does not change results in almost all cases).

Parameters:
  • ini_filename – .ini file to use
  • no_validate – do not pre-validate the ini file (faster, but may crash kernel if error)

camb.model

class camb.model.CAMBparams(**kwargs)[source]

Object storing the parameters for a CAMB calculation, including cosmological parameters and settings for what to calculate. When a new object is instantiated, default parameters are set automatically.

To add a new parameter, add it to the CAMBparams type in model.f90, then edit the _fields_ list in the CAMBparams class in model.py to add the new parameter in the corresponding location of the member list. After rebuilding the python version you can then access the parameter by using params.new_parameter_name where params is a CAMBparams instance. You could also modify the wrapper functions to set the field value less directly.

You can view the set of underlying parameters used by the Fortran code by printing the CAMBparams instance. In python, to set cosmology parameters it is usually best to use set_cosmology() and equivalent methods for most other parameters. Alternatively the convenience function camb.set_params() can construct a complete instance from a dictionary of relevant parameters.

Variables:
  • WantCls – (boolean) Calculate C_L
  • WantTransfer – (boolean) Calculate matter transfer functions and matter power spectrum
  • WantScalars – (boolean) Calculates scalar modes
  • WantTensors – (boolean) Calculate tensor modes
  • WantVectors – (boolean) Calculate vector modes
  • WantDerivedParameters – (boolean) Calculate derived parameters
  • Want_cl_2D_array – (boolean) For the C_L, include NxN matrix of all possible cross-spectra between sources
  • Want_CMB – (boolean) Calculate the temperature and polarization power spectra
  • Want_CMB_lensing – (boolean) Calculate the lensing potential power spectrum
  • DoLensing – (boolean) Include CMB lensing
  • NonLinear – (integer/string, one of: NonLinear_none, NonLinear_pk, NonLinear_lens, NonLinear_both)
  • Transfercamb.model.TransferParams
  • want_zstar – (boolean)
  • want_zdrag – (boolean)
  • min_l – (integer) l_min for the scalar C_L (1 or 2, l=1 dipoles are Newtonian Gauge)
  • max_l – (integer) l_max for the scalar C_L
  • max_l_tensor – (integer) l_max for the tensor C_L
  • max_eta_k – (float64) Maximum k*eta_0 for scalar C_L, where eta_0 is the conformal time today
  • max_eta_k_tensor – (float64) Maximum k*eta_0 for tensor C_L, where eta_0 is the conformal time today
  • ombh2 – (float64) Omega_baryon h^2
  • omch2 – (float64) Omega_cdm h^2
  • omk – (float64) Omega_K
  • omnuh2 – (float64) Omega_massive_neutrino h^2
  • H0 – (float64) Hubble parameter is km/s/Mpc units
  • TCMB – (float64) CMB temperature today in Kelvin
  • YHe – (float64) Helium mass fraction
  • num_nu_massless – (float64) Effective number of massless neutrinos
  • num_nu_massive – (integer) Total physical (integer) number of massive neutrino species
  • nu_mass_eigenstates – (integer) Number of non-degenerate mass eigenstates
  • share_delta_neff – (boolean) Share the non-integer part of num_nu_massless between the eigenstates
  • nu_mass_degeneracies – (float64 array) Degeneracy of each distinct eigenstate
  • nu_mass_fractions – (float64 array) Mass fraction in each distinct eigenstate
  • nu_mass_numbers – (integer array) Number of physical neutrinos per distinct eigenstate
  • InitPowercamb.initialpower.InitialPower
  • Recombcamb.recombination.RecombinationModel
  • Reioncamb.reionization.ReionizationModel
  • DarkEnergycamb.dark_energy.DarkEnergyModel
  • NonLinearModelcamb.nonlinear.NonLinearModel
  • Accuracycamb.model.AccuracyParams
  • SourceTermscamb.model.SourceTermParams
  • z_outputs – (float64 array) redshifts to always calculate BAO output parameters
  • scalar_initial_condition – (integer/string, one of: initial_adiabatic, initial_iso_CDM, initial_iso_baryon, initial_iso_neutrino, initial_iso_neutrino_vel, initial_vector)
  • InitialConditionVector – (float64 array) if scalar_initial_condition is initial_vector, the vector of initial condition amplitudes
  • OutputNormalization – (integer) If non-zero, multipole to normalize the C_L at
  • Alens – (float64) non-physical scaling amplitude for the CMB lensing spectrum power
  • MassiveNuMethod – (integer/string, one of: Nu_int, Nu_trunc, Nu_approx, Nu_best)
  • DoLateRadTruncation – (boolean) If true, use smooth approx to radition perturbations after decoupling on small scales, saving evolution of irrelevant osciallatory multipole equations
  • Evolve_baryon_cs – (boolean) Evolve a separate equation for the baryon sound speed rather than using background approximation
  • Evolve_delta_xe – (boolean) Evolve ionization fraction perturbations
  • Evolve_delta_Ts – (boolean) Evolve the splin temperature perturbation (for 21cm)
  • Do21cm – (boolean) 21cm is not yet implemented via the python wrapper
  • transfer_21cm_cl – (boolean) Get 21cm C_L at a given fixed redshift
  • Log_lvalues – (boolean) Use log spacing for sampling in L
  • use_cl_spline_template – (boolean) When interpolating use a fiducial spectrum shape to define ratio to spline
  • SourceWindows – array of camb.sources.SourceWindow
  • CustomSourcescamb.model.CustomSources
N_eff
Returns:Effective number of degrees of freedom in relativistic species at early times.
copy()

Make independent copy of this object.

Returns:deep copy of self
get_DH(ombh2=None, delta_neff=None)[source]

Get deuterium ration D/H by intepolation using the bbn.BBNPredictor instance passed to set_cosmology() (or the default one, if Y_He has not been set).

Parameters:
  • ombh2\(\Omega_b h^2\) (default: value passed to set_cosmology())
  • delta_neff – additional \(N_{\rm eff}\) relative to standard value (of 3.046) (default: from values passed to set_cosmology())
Returns:

BBN helium nucleon fraction D/H

get_Y_p(ombh2=None, delta_neff=None)[source]

Get BBN helium nucleon fraction (NOT the same as the mass fraction Y_He) by intepolation using the bbn.BBNPredictor instance passed to set_cosmology() (or the default one, if Y_He has not been set).

Parameters:
  • ombh2\(\Omega_b h^2\) (default: value passed to set_cosmology())
  • delta_neff – additional \(N_{\rm eff}\) relative to standard value (of 3.046) (default: from values passed to set_cosmology())
Returns:

\(Y_p^{\rm BBN}\) helium nucleon fraction predicted by BBN.

replace(instance)

Replace the content of this class with another instance, doing a deep copy (in Fortran)

Parameters:instance – instance of the same class to replace this instance with
set_H0_for_theta(theta, cosmomc_approx=False, theta_H0_range=[10, 100], est_H0=67.0, iteration_threshold=8)[source]

Set H0 to give a specified value of the acoustic angular scale parameter theta.

Parameters:
  • theta – value of \(r_s/D_M\) at redshift \(z_\star\)
  • cosmomc_approx – if true, use approximate fitting formula for \(z_\star\), if false do full numerical calculation
  • theta_H0_range – min, max iterval to search for H0 (in km/s/Mpc)
  • est_H0 – an initial guess for H0 in km/s/Mpc, used in the case comsomc_approx=False.
  • iteration_threshold – differnce in H0 from est_H0 for which to iterate, used for cosmomc_approx=False
set_accuracy(AccuracyBoost=1.0, lSampleBoost=1.0, lAccuracyBoost=1.0, DoLateRadTruncation=True)[source]

Set parameters determining overall calculation accuracy (large values may give big slow down). For finer control you can set individual accuracy parameters by changing CAMBParams.Accuracy (model.AccuracyParams) .

Parameters:
  • AccuracyBoost – increase AccuracyBoost to decrease integration step size, increase density of k sampling, etc.
  • lSampleBoost – increase lSampleBoost to increase density of L sampling for CMB
  • lAccuracyBoost – increase lAccuracyBoost to increase the maximum L included in the Boltzmann hierarchies
  • DoLateRadTruncation – If True, use approximation to radiation perturbation evolution at late times
Returns:

self

set_classes(dark_energy_model=None, initial_power_model=None, non_linear_model=None, recombination_model=None)[source]

Change the classes used to implement parts of the model.

Parameters:
  • dark_energy_model – ‘fluid’, ‘ppf’, or name of a DarkEnergyModel class
  • initial_power_model – name of an InitialPower class
  • non_linear_model – name of a NonLinearModel class
  • recombination_model – name of recombination_model class
set_cosmology(H0=None, ombh2=0.022, omch2=0.12, omk=0.0, cosmomc_theta=None, thetastar=None, neutrino_hierarchy='degenerate', num_massive_neutrinos=1, mnu=0.06, nnu=3.046, YHe=None, meffsterile=0.0, standard_neutrino_neff=3.046, TCMB=2.7255, tau=None, deltazrei=None, Alens=1.0, bbn_predictor=None, theta_H0_range=[10, 100])[source]

Sets cosmological parameters in terms of physical densities and parameters (e.g. as used in Planck analyses). Default settings give a single distinct neutrino mass eigenstate, by default one neutrino with mnu = 0.06eV. Set the neutrino_hierarchy parameter to normal or inverted to use a two-eigenstate model that is a good approximation to the known mass splittings seen in oscillation measurements. For more fine-grained control can set the neutrino parameters directly rather than using this function.

Instead of setting the Hubble parameter directly, you can instead set the acoustic scale parameter (cosmomc_theta, which is based on a fitting forumula for simple models, or thetastar, which is numerically calculated more generally). Note that you must have already set the dark energy model, you can’t use set_cosmology with theta and then change the background evolution (which would change theta at the calculated H0 value). Likewise the dark energy model cannot depend explicitly on H0.

Parameters:
  • H0 – Hubble parameter today in km/s/Mpc. Can leave unset and instead set thetastar or cosmomc_theta (which solves for the required H0).
  • ombh2 – physical density in baryons
  • omch2 – physical density in cold dark matter
  • omk – Omega_K curvature parameter
  • cosmomc_theta – The approximate CosmoMC theta parameter \(\theta_{\rm MC}\). The angular diamter distance is calculated numerically, but the redshift \(z_\star\) is calculated using an approximate (quite accurate but non-general) fitting formula. Leave unset to use H0 or thetastar.
  • thetastar – The angular acoustic scale parameter \(\theta_\star = r_s(z_*)/D_M(z_*)\), defined as the ratio of the photon-baryon sound horizon \(r_s\) to the angular diameter distance \(D_M\), where both quantities are evaluated at \(z_*\), the redshift at which the optical depth (excluding reionization) is unity. Leave unset to use H0 or cosmomc_theta.
  • neutrino_hierarchy – ‘degenerate’, ‘normal’, or ‘inverted’ (1 or 2 eigenstate approximation)
  • num_massive_neutrinos – number of massive neutrinos
  • mnu – sum of neutrino masses (in eV, Omega_nu is calculated approximately from this assuming neutrinos non-relativistic today). Set the field values directly if you need finer control or more complex models.
  • nnu – N_eff, effective relativistic degrees of freedom
  • YHe – Helium mass fraction. If None, set from BBN consistency.
  • meffsterile – effective mass of sterile neutrinos
  • standard_neutrino_neff – default value for N_eff in standard cosmology (non-integer to allow for partial heating of neutrinos at electron-positron annihilation and QED effects)
  • TCMB – CMB temperature (in Kelvin)
  • tau – optical depth; if None, current Reion settings are not changed
  • deltazrei – redshift width of reionization; if None, uses default
  • Alens – (non-physical) scaling of the lensing potential compared to prediction
  • bbn_predictorbbn.BBNPredictor instance used to get YHe from BBN consistency if YHe is None
  • theta_H0_range – if thetastar or cosmomc_theta is specified, the min, max interval of H0 values to map to; if H0 is outside this range it will raise an exception.
set_custom_scalar_sources(custom_sources, source_names=None, source_ell_scales=None, frame='CDM', code_path=None)[source]

Set custom sources for angular power spectrum using camb.symbolic sympy expressions.

Parameters:
  • custom_sources – list of sympy expressions for the angular power spectrum sources
  • source_names – optional list of string naes for the sources
  • source_ell_scales – list or dictionary of scalings for each source name, where for integer entry n, the source for multipole \(\ell\) is scalled by \(\sqrt{(\ell+n)!/(\ell-n)!}\), i.e. \(n=2\) for a new polarization-like source.
  • frame – if the source is not gauge invariant, frame in which to interpret result
  • code_path – optional path for output of source code for CAMB f90 source function
set_dark_energy(w=-1.0, cs2=1.0, wa=0, dark_energy_model='fluid')[source]

Set dark energy parameters (use set_dark_energy_w_a to set w(a) from numerical table instead) To use a custom dark energy model, assign the class instance to the DarkEnergy field instead.

Parameters:
  • w\(w\equiv p_{\rm de}/\rho_{\rm de}\), assumed constant
  • wa – evolution of w (for dark_energy_model=ppf)
  • cs2 – rest-frame sound speed squared of dark energy fluid
  • dark_energy_model – model to use (‘fluid’ or ‘ppf’), default is ‘fluid’
Returns:

self

set_dark_energy_w_a(a, w, dark_energy_model='fluid')[source]

Set the dark energy equation of state from tabulated values (which are cubic spline interpolated).

Parameters:
  • a – array of sampled a = 1/(1+z) values
  • w – array of w(a)
  • dark_energy_model – model to use (‘fluid’ or ‘ppf’), default is ‘fluid’
Returns:

self

set_for_lmax(lmax, max_eta_k=None, lens_potential_accuracy=0, lens_margin=150, k_eta_fac=2.5, lens_k_eta_reference=18000.0)[source]

Set parameters to get CMB power spectra accurate to specific a l_lmax. Note this does not fix the actual output L range, spectra may be calculated above l_max (but may not be accurate there). To fix the l_max for output arrays use the optional input argument to results.CAMBdata.get_cmb_power_spectra() etc.

Parameters:
  • lmax\(\ell_{\rm max}\) you want
  • max_eta_k – maximum value of \(k \eta_0\approx k\chi_*\) to use, which indirectly sets k_max. If None, sensible value set automatically.
  • lens_potential_accuracy – Set to 1 or higher if you want to get the lensing potential accurate
  • lens_margin – the \(\Delta \ell_{\rm max}\) to use to ensure lensed \(C_\ell\) are correct at \(\ell_{\rm max}\)
  • k_eta_fac – k_eta_fac default factor for setting max_eta_k = k_eta_fac*lmax if max_eta_k=None
  • lens_k_eta_reference – value of max_eta_k to use when lens_potential_accuracy>0; use k_eta_max = lens_k_eta_reference*lens_potential_accuracy
Returns:

self

set_initial_power(initial_power_params)[source]

Set the InitialPower primordial power spectrum parameters

Parameters:initial_power_paramsinitialpower.InitialPowerLaw or initialpower.SplinedInitialPower instance
Returns:self
set_initial_power_function(P_scalar, P_tensor=None, kmin=1e-06, kmax=100.0, N_min=200, rtol=5e-05, args=())[source]

Set the initial power spectrum from a function P_scalar(k, *args), and optionally also the tensor spectrum. The function is called to make a pre-computed array which is then interpolated inside CAMB. The sampling in k is set automatically so that the spline is accurate, but you may also need to increase other accuracy parameters.

Parameters:
  • P_scalar – function returning normalized initial scalar curvature power as function of k (in Mpc^{-1})
  • P_tensor – optional function returning normalized initial tensor power spectrum
  • kmin – minimum wavenumber to compute
  • kmax – maximum wavenumber to compute
  • N_min – minimum number of spline points for the pre-computation
  • rtol – relative tolerance for deciding how many points are enough
  • args – optional list of arguments passed to P_scalar (and P_tensor)
Returns:

self

set_initial_power_table(k, pk=None, pk_tensor=None)[source]

Set a general intial power spectrum from tabulated values. It’s up to you to ensure the sampling of the k values is high enough that it can be interpolated accurately.

Parameters:
  • k – array of k values (Mpc^{-1})
  • pk – array of primordial curvature perturbation power spectrum values P(k_i)
  • pk_tensor – array of tensor spectrum values
set_matter_power(redshifts=[0.0], kmax=1.2, k_per_logint=None, nonlinear=None, accurate_massive_neutrino_transfers=False, silent=False)[source]

Set parameters for calculating matter power spectra and transfer functions.

Parameters:
  • redshifts – array of redshifts to calculate
  • kmax – maximum k to calculate
  • k_per_logint – number of k steps per log k. Set to zero to use default optimized spacing.
  • nonlinear – if None, uses existing setting, otherwise boolean for whether to use non-linear matter power.
  • accurate_massive_neutrino_transfers – if you want the massive neutrino transfers accurately
  • silent – if True, don’t give warnings about sort order
Returns:

self

set_nonlinear_lensing(nonlinear)[source]

Settings for whether or not to use non-linear corrections for the CMB lensing potential. Note that set_for_lmax also sets lensing to be non-linear if lens_potential_accuracy>0

Parameters:nonlinear – true to use non-linear corrections
validate()[source]

Do some quick tests for sanity

Returns:True if OK
class camb.model.AccuracyParams[source]

Structure with parameters governing numerical accuracy. AccuracyBoost will also scale almost all the other parameters except for lSampleBoost (which is specific to the output interpolation) and lAccuracyBoost (which is specific to the multipole hierarchy evolution), e.g setting AccuracyBoost=2, IntTolBoost=1.5, means that internally the k sampling for integration will be boosed by AccuracyBoost*IntTolBoost = 3.

Variables:
  • AccuracyBoost – (float64) general accuracy setting effecting everything related to step sizes etc. (including separate settings below except the next two)
  • lSampleBoost – (float64) accuracy for sampling in ell for interpolation for the C_l
  • lAccuracyBoost – (float64) Boosts number of multipoles integrated in Boltzman heirarchy
  • AccuratePolarization – (boolean) Do you care about the accuracy of the polarization Cls?
  • AccurateBB – (boolean) Do you care about BB accuracy (e.g. in lensing)
  • AccurateReionization – (boolean) Do you care about pecent level accuracy on EE signal from reionization?
  • TimeStepBoost – (float64) Sampling timesteps
  • BackgroundTimeStepBoost – (float64) Number of time steps for background thermal history and source window interpolation
  • IntTolBoost – (float64) Tolerances for integrating differential equations
  • SourcekAccuracyBoost – (float64) Accuracy of k sampling for source time integration
  • IntkAccuracyBoost – (float64) Accuracy of k sampling for integration
  • TransferkBoost – (float64) Accuracy of k sampling for transfer functions
  • NonFlatIntAccuracyBoost – (float64) Accuracy of non-flat time integration
  • BessIntBoost – (float64) Accuracy of bessel integration truncation
  • LensingBoost – (float64) Accuracy of the lensing of CMB power spectra
  • NonlinSourceBoost – (float64) Accuracy of steps and kmax used for the non-linear correction
  • BesselBoost – (float64) Accuracy of bessel pre-computation sampling
  • LimberBoost – (float64) Accuracy of Limber approximation use
  • KmaxBoost – (float64) Boost max k for source window functions
  • neutrino_q_boost – (float64) Number of momenta integrated for neutrino perturbations
class camb.model.TransferParams[source]

Object storing parameters for the matter power spectrum calculation.

Variables:
  • high_precision – (boolean) True for more accuracy
  • accurate_massive_neutrinos – (boolean) True if you want neutrino transfer functions accurate (false by default)
  • kmax – (float64) k_max to output (no h in units)
  • k_per_logint – (integer) number of points per log k interval. If zero, set an irregular optimized spacing
  • PK_num_redshifts – (integer) number of redshifts to calculate
  • PK_redshifts – (float64 array) redshifts to output for the matter transfer and power
class camb.model.SourceTermParams[source]

Structure with parameters determining how galaxy/lensing/21cm power spectra and transfer functions are calculated.

Variables:
  • limber_windows – (boolean) Use Limber approximation where appropriate. CMB lensing uses Limber even if limber_window is false, but method is changed to be consistent with other sources if limber_windows is true
  • limber_phi_lmin – (integer) When limber_windows=True, the minimum L to use Limber approximation for the lensing potential and other sources (which may use higher but not lower)
  • counts_density – (boolean) Include the density perturbation source
  • counts_redshift – (boolean) Include redshift distortions
  • counts_lensing – (boolean) Include magnification bias for number counts
  • counts_velocity – (boolean) Non-redshift distortion velocity terms
  • counts_radial – (boolean) Radial displacement velocity term; does not include time delay; subset of counts_velocity, just 1 / (chi * H) term
  • counts_timedelay – (boolean) Include time delay terms * 1 / (H * chi)
  • counts_ISW – (boolean) Include tiny ISW terms
  • counts_potential – (boolean) Include tiny terms in potentials at source
  • counts_evolve – (boolean) Accout for source evolution
  • line_phot_dipole – (boolean) Dipole sources for 21cm
  • line_phot_quadrupole – (boolean) Quadrupole sources for 21cm
  • line_basic – (boolean) Include main 21cm monopole density/spin temerature sources
  • line_distortions – (boolean) Redshift distortions for 21cm
  • line_extra – (boolean) Include other sources
  • line_reionization – (boolean) Replace the E modes with 21cm polarization
  • use_21cm_mK – (boolean) Use mK units for 21cm
class camb.model.CustomSources[source]

Structure containing symoblic-compiled custom CMB angular power spectrum source functions. Don’t change this directly, instead call model.CAMBparams.set_custom_scalar_sources().

Variables:
  • num_custom_sources – (integer) number of sources set
  • c_source_func – (pointer) Don’t directly change this
  • custom_source_ell_scales – (integer array) scaling in L for outputs

camb.results

class camb.results.CAMBdata[source]

An object for storing calculational data, parameters and transfer functions. Results for a set of parameters (given in a CAMBparams instance) are returned by the camb.get_background(), camb.get_transfer_functions() or camb.get_results() functions. Exactly which quantities are already calculated depends on which of these functions you use and the input parameters.

To quickly make a fully calculated CAMBdata instance for a set of parameters you can call camb.get_results().

Variables:
  • Paramscamb.model.CAMBparams
  • ThermoDerivedParams – (float64 array) array of derived parameters, see get_derived_params() to get as a dictionary
  • flat – (boolean) flat universe
  • closed – (boolean) closed universe
  • grhocrit – (float64) kappa*a^2*rho_c(0)/c^2 with units of Mpc**(-2)
  • grhog – (float64) kappa/c^2*4*sigma_B/c^3 T_CMB^4
  • grhor – (float64) 7/8*(4/11)^(4/3)*grhog (per massless neutrino species)
  • grhob – (float64) baryon contribution
  • grhoc – (float64) CDM contribution
  • grhov – (float64) Dark energy contribution
  • grhornomass – (float64) grhor*number of massless neutrino species
  • grhok – (float64) curvature contribution to critical density
  • taurst – (float64) time at start of recombination
  • dtaurec – (float64) time step in recombination
  • taurend – (float64) time at end of recombination
  • tau_maxvis – (float64) time at peak visibility
  • adotrad – (float64) da/d tau in early radiation-dominated era
  • omega_de – (float64) Omega for dark energy today
  • curv – (float64) curvature K
  • curvature_radius – (float64) \(1/\sqrt{|K|}\)
  • Ksign – (float64) Ksign = 1,0 or -1
  • tau0 – (float64) conformal time today
  • chi0 – (float64) comoving angular diameter distance of big bang; rofChi(tau0/curvature_radius)
  • scale – (float64) relative to flat. e.g. for scaling l sampling
  • akthom – (float64) sigma_T * (number density of protons now)
  • fHe – (float64) n_He_tot / n_H_tot
  • Nnow – (float64) number density today
  • z_eq – (float64) matter-radiation equality refshift assuming all neutrinos relativistic
  • grhormass – (float64 array)
  • nu_masses – (float64 array)
  • num_transfer_redshifts – (integer) Number of calculated redshift outputs for the matter transfer (including those for CMB lensing)
  • transfer_redshifts – (float64 array) Calculated output redshifts
  • PK_redshifts_index – (integer array) Indices of the requested PK_redshifts
  • OnlyTransfers – (boolean) Only calculating transfer functions, not power spectra
angular_diameter_distance(z)[source]

Get (non-comoving) angular diameter distance to redshift z.

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:z – redshift or array of redshifts
Returns:angular diameter distances, matching rank of z
angular_diameter_distance2(z1, z2)[source]

Get angular diameter distance between two redshifts \(\frac{r}{1+z_2}\text{sin}_K\left(\frac{\chi(z_2) - \chi(z_1)}{r}\right)\) where \(r\) is curvature radius and \(\chi\) is the comoving radial distance.

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:
  • z1 – redshift 1
  • z2 – redshift 2
Returns:

result

calc_background(params)[source]

Calculate the background evolution and thermal history. e.g. call this if you want to get derived parameters and call background functions :param params: CAMBparams instance to use

calc_background_no_thermo(params)[source]

Calculate the background evolution without calculating thermal history. e.g. call this if you want to just use angular_diameter_distance() and similar background functions

Parameters:paramsCAMBparams instance to use
calc_power_spectra(params=None)[source]

Calculates transfer functions and power spectra.

Parameters:params – optional CAMBparams instance with parameters to use
calc_transfers(params, only_transfers=True)[source]

Calculate the transfer functions (for CMB and matter power, as determined by params.WantCls, params.WantTransfer)

Parameters:
  • paramsCAMBparams instance with parameters to use
  • only_transfers – only calculate transfer functions, no power spectra
Returns:

non-zero if error, zero if OK

comoving_radial_distance(z, tol=0.0001)[source]

Get comoving radial distance from us to redshift z in Mpc. This is efficient for arrays.

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:z – redshift
Returns:comoving radial distance (Mpc)
conformal_time(z, presorted=None, tol=None)[source]

Conformal time from hot big bang to redshift z in Megaparsec.

Parameters:
  • z – redshift or array of redshifts
  • presorted – if True, redshifts already sorted to be monotonically increasing, if False decreasing, or if None unsorted. If presorted is True or False no checks are done.
  • tol – integration tolerance
Returns:

eta(z)/Mpc

conformal_time_a1_a2(a1, a2)[source]

Get conformal time between two scale factors (=comoving radial distance travelled by light on light cone)

Parameters:
  • a1 – scale factor 1
  • a2 – scale factor 2
Returns:

eta(a2)-eta(a1) = chi(a1)-chi(a2) in Megaparsec

copy()

Make independent copy of this object.

Returns:deep copy of self
cosmomc_theta()[source]

Get \(\theta_{\rm MC}\), an approximation of the ratio of the sound horizon to the angular diameter distance at recombination.

Returns:\(\theta_{\rm MC}\)
get_BAO(redshifts, params)[source]

Get BAO parameters at given redshifts, using parameters in params

Parameters:
  • redshifts – list of redshifts
  • params – optional CAMBparams instance to use
Returns:

array of rs/DV, H, DA, F_AP for each redshift as 2D array

get_Omega(var, z=0)[source]

Get density relative to critical density of variables var

Parameters:
  • var – one of ‘K’, ‘cdm’, ‘baryon’, ‘photon’, ‘neutrino’ (massless), ‘nu’ (massive neutrinos), ‘de’
  • z – redshift
Returns:

\(\Omega_i(a)\)

get_background_densities(a, vars=['tot', 'K', 'cdm', 'baryon', 'photon', 'neutrino', 'nu', 'de'], format='dict')[source]

Get the individual densities as a function of scale factor. Returns \(8\pi G a^4 \rho_i\) in Mpc units. \(\Omega_i\) can be simply obtained by taking the ratio of the components to tot.

Parameters:
  • z – redshift or array of redshifts
  • vars – list of variables to output (default all)
  • format – ‘dict’ or ‘array’, for either dict of 1D arrays indexed by name, or 2D array
Returns:

n_a x len(vars) 2D numpy array or dict of 1D arrays of \(8\pi G a^4 \rho_i\) in Mpc units.

get_background_outputs()[source]

Get BAO values for redshifts set in Params.z_outputs

Returns:rs/DV, H, DA, F_AP for each requested redshift (as 2D array)
get_background_redshift_evolution(z, vars=['x_e', 'opacity', 'visibility', 'cs2b', 'T_b', 'dopacity', 'ddopacity', 'dvisibility', 'ddvisibility'], format='dict')[source]

Get the evolution of background variables a function of redshift. For the moment a and H are rather perversely only available via get_time_evolution()

Parameters:
  • z – array of requested redshifts to output
  • vars – list of variable names to output
  • format – ‘dict’ or ‘array’, for either dict of 1D arrays indexed by name, or 2D array
Returns:

n_eta x len(vars) 2D numpy array of outputs or dict of 1D arrays

get_background_time_evolution(eta, vars=['x_e', 'opacity', 'visibility', 'cs2b', 'T_b', 'dopacity', 'ddopacity', 'dvisibility', 'ddvisibility'], format='dict')[source]

Get the evolution of background variables a function of conformal time. For the moment a and H are rather perversely only available via get_time_evolution()

Parameters:
  • eta – array of requested conformal times to output
  • vars – list of variable names to output
  • format – ‘dict’ or ‘array’, for either dict of 1D arrays indexed by name, or 2D array
Returns:

n_eta x len(vars) 2D numpy array of outputs or dict of 1D arrays

get_cmb_correlation_functions(params=None, lmax=None, spectrum='lensed_scalar', xvals=None, sampling_factor=1)[source]

Get the CMB correlation functions from the power spectra. By default evaluated at points \(\cos(\theta)\) = xvals that are roots of Legendre polynomials, for accurate back integration with correlations.corr2cl(). If xvals is explicitly given, instead calculates correlations at provided \(\cos(\theta)\) values.

Parameters:
  • params – optional CAMBparams instance with parameters to use. If None, must have previously set parameters and called calc_power_spectra() (e.g. if you got this instance using camb.get_results()),
  • lmax – optional maximum L to use from the cls arrays
  • spectrum – type of CMB power spectrum to get; default ‘lensed_scalar’, one of [‘total’, ‘unlensed_scalar’, ‘unlensed_total’, ‘lensed_scalar’, ‘tensor’]
  • xvals – optional array of \(\cos(\theta)\) values at which to calculate correlation function.
  • sampling_factor – multiple of lmax for the Gauss-Legendre order if xvals not given (default 1)
Returns:

if xvals not given: corrs, xvals, weights; if xvals specified, just corrs. corrs is 2D array corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross, and i indexes xvals

get_cmb_power_spectra(params=None, lmax=None, spectra=['total', 'unlensed_scalar', 'unlensed_total', 'lensed_scalar', 'tensor', 'lens_potential'], CMB_unit=None, raw_cl=False)[source]

Get CMB power spectra, as requested by the ‘spectra’ argument. All power spectra are \(\ell(\ell+1)C_\ell/2\pi\) self-owned numpy arrays (0..lmax, 0..3), where 0..3 index are TT, EE, BB TT, unless raw_cl is True in which case return just \(C_\ell\). For the lens_potential the power spectrum returned is that of the deflection.

Parameters:
  • params – optional CAMBparams instance with parameters to use. If None, must have previously set parameters and called calc_power_spectra (e.g. if you got this instance using camb.get_results()),
  • lmax – maximum l
  • spectra – list of names of spectra to get
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\) and \(\mu K\) units for lensing cross.
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

dictionary of power spectrum arrays, indexed by names of requested spectra

get_cmb_transfer_data(tp='scalar')[source]

Get \(C_\ell\) transfer functions

Returns:ClTransferData instance holding output arrays (copies, not pointers)
get_cmb_unlensed_scalar_array_dict(params=None, lmax=None, CMB_unit=None, raw_cl=False)[source]

Get all unlensed auto and cross power spectra, including any custom source functions set using model.CAMBparams.set_custom_scalar_sources().

Parameters:
  • params – optional CAMBparams instance with parameters to use. If None, must have previously set parameters and called calc_power_spectra() (e.g. if you got this instance using camb.get_results()),
  • lmax – maximum \(\ell\)
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\) and \(\mu K\) units for lensing cross.
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

dictionary of power spectrum arrays, index as TxT, TxE, PxW1, W1xW2, custom_name_1xT… etc. Note that P is the lensing deflection, lensing windows Wx give convergence.

get_dark_energy_rho_w(a)[source]

Get dark energy density in units of the dark energy density today, and w=P/rho

Parameters:a – scalar factor or array of scale factors
Returns:rho, w arrays at redshifts 1/a-1 [or scalars if a is scalar]
get_derived_params()[source]
Returns:dictionary of derived parameter values, indexed by name (‘kd’, ‘age’, etc..)
get_fsigma8()[source]

Get \(f\sigma_8\) growth values (must previously have calculated power spectra). For general models \(f\sigma_8\) is defined as in the Planck 2015 parameter paper in terms of the velocity-density correlation: \(\sigma^2_{vd}/\sigma_{dd}\) for \(8 h^{-1} {\rm Mpc}\) spheres.

Returns:array of f*sigma_8 values, in order of increasing time (decreasing redshift)
get_lens_potential_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get lensing deflection angle potential power spectrum, and cross-correlation with T and E. Must have already calculated power spectra. Power spectra are \([L(L+1)]^2C_L^{\phi\phi}/2\pi\) and corresponding deflection cross-correlations.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K\) units for lensing cross.
  • raw_cl – return lensing potential \(C_L\) rather than \([L(L+1)]^2C_L/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:3], where 0..2 indexes PP, PT, PE.

get_lensed_scalar_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get lensed scalar CMB power spectra. Must have already calculated power spectra.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:4], where 0..3 indexes TT, EE, BB, TE.

get_linear_matter_power_spectrum(var1=None, var2=None, hubble_units=True, have_power_spectra=False, params=None, nonlinear=False)[source]

Calculates \(P_{xy}(k/h)\), where x, y are one of model.Transfer_cdm, model.Transfer_xx etc. The output k values are not regularly spaced, and not interpolated.

Parameters:
  • var1 – variable i (index, or name of variable; default delta_tot)
  • var2 – variable j (index, or name of variable; default delta_tot)
  • hubble_units – if true, output power spectrum in (Mpc/h) units, otherwise Mpc
  • have_power_spectra – set to True if already computed power spectra
  • params – if have_power_spectra=False, optional CAMBparams instance to specify new parameters
  • nonlinear – include non-linear correction from halo model
Returns:

kh, z, PK, where kz an z are arrays of k/h and z respectively, and PK[i,j] is value at z[i], k/h[j]

get_matter_power_interpolator(nonlinear=True, var1=None, var2=None, hubble_units=True, k_hunit=True, return_z_k=False, log_interp=True, extrap_kmax=None)[source]

Assuming transfers have been calculated, return a 2D spline interpolation object to evaluate matter power spectrum as function of z and k/h (or k), e.g.

PK = results.get_matter_power_interpolator();
print('Power spectrum at z=0.5, k/h=0.1 is %s (Mpc/h)^3 '%(PK.P(0.5, 0.1)))
Parameters:
  • nonlinear – include non-linear correction from halo model
  • var1 – variable i (index, or name of variable; default delta_tot)
  • var2 – variable j (index, or name of variable; default delta_tot)
  • hubble_units – if true, output power spectrum in \(({\rm Mpc}/h)^{3}\) units, otherwise \({\rm Mpc}^{3}\)
  • k_hunit – if true, matter power is a function of k/h, if false, just k (both \({\rm Mpc}^{-1}\) units)
  • return_z_k – if true, return interpolator, z, k where z, k are the grid used
  • log_interp – if true, interpolate log of power spectrum (unless any values are negative in which case ignored)
  • extrap_kmax – if set, use power law extrapolation beyond kmax to extrap_kmax (useful for tails of integrals)
Returns:

RectBivariateSpline object PK, that can be called with PK(z,log(kh)) to get log matter power values. If return_z_k=True, instead return interpolator, z, k where z, k are the grid used

get_matter_power_spectrum(minkh=0.0001, maxkh=1.0, npoints=100, var1=None, var2=None, have_power_spectra=False, params=None)[source]

Calculates \(P_{xy}(k/h)\), where x, y are one of Transfer_cdm, Transfer_xx etc. The output k values are regularly log spaced and interpolated. If NonLinear is set, the result is non-linear.

Parameters:
  • minkh – minimum value of k/h for output grid (very low values < 1e-4 may not be calculated)
  • maxkh – maximum value of k/h (check consistent with input params.Transfer.kmax)
  • npoints – number of points equally spaced in log k
  • var1 – variable i (index, or name of variable; default delta_tot)
  • var2 – variable j (index, or name of variable; default delta_tot)
  • have_power_spectra – set to True if already computed power spectra
  • params – if have_power_spectra=False and want to specify new parameters, a CAMBparams instance
Returns:

kh, z, PK, where kz an z are arrays of k/h and z respectively, and PK[i,j] is value at z[i], k/h[j]

get_matter_transfer_data()[source]

Get matter transfer function data and sigma8 for calculated results.

Returns:MatterTransferData instance holding output arrays (copies, not pointers)
get_nonlinear_matter_power_spectrum(**kwargs)[source]

Calculates \(P_{xy}(k/h)\), where x, y are one of model.Transfer_cdm, model.Transfer_xx etc. The output k values are not regularly spaced, and not interpolated.

Parameters:
  • var1 – variable i (index, or name of variable; default delta_tot)
  • var2 – variable j (index, or name of variable; default delta_tot)
  • hubble_units – if true, output power spectrum in \(({\rm Mpc}/h)^{3}\) units, otherwise \({\rm Mpc}^{3}\)
  • have_power_spectra – set to True if already computed power spectra
  • params – if have_power_spectra=False, optional CAMBparams instance to specify new parameters
Returns:

kh, z, PK, where kz an z are arrays of k/h and z respectively, and PK[i,j] is value at z[i], k/h[j]

get_redshift_evolution(q, z, vars=['k/h', 'delta_cdm', 'delta_baryon', 'delta_photon', 'delta_neutrino', 'delta_nu', 'delta_tot', 'delta_nonu', 'delta_tot_de', 'Weyl', 'v_newtonian_cdm', 'v_newtonian_baryon', 'v_baryon_cdm', 'a', 'etak', 'H', 'growth', 'v_photon', 'pi_photon', 'E_2', 'v_neutrino', 'T_source', 'E_source', 'lens_potential_source'], lAccuracyBoost=4)[source]

Get the mode evolution as a function of redshift for some k values.

Parameters:
  • q – wavenumber values to calculate (or array of k values)
  • z – array of redshifts to output
  • vars – list of variable names or camb.symbolic sympy expressions to output
  • lAccuracyBoost – boost factor for ell accuracy (e.g. to get nice smooth curves for plotting)
Returns:

nd array, A_{qti}, size(q) x size(times) x len(vars), or 2d array if q is scalar

get_sigma8()[source]

Get \(\sigma_8\) values (must previously have calculated power spectra)

Returns:array of \(\sigma_8\) values, in order of increasing time (decreasing redshift)
get_source_cls_dict(params=None, lmax=None, raw_cl=False)[source]

Get all source window function and CMB lensing and cross power spectra. Does not include CMB spectra. Note that P is the deflection angle, but lensing windows return the kappa power.

Parameters:
  • params – optional CAMBparams instance with parameters to use. If None, must have previously set parameters and called calc_power_spectra() (e.g. if you got this instance using camb.get_results()),
  • lmax – maximum \(\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

dictionary of power spectrum arrays, index as PXP, PxW1, W1xW2, … etc.

get_tensor_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get tensor CMB power spectra. Must have already calculated power spectra.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:4], where 0..3 indexes TT, EE, BB, TE

get_time_evolution(q, eta, vars=['k/h', 'delta_cdm', 'delta_baryon', 'delta_photon', 'delta_neutrino', 'delta_nu', 'delta_tot', 'delta_nonu', 'delta_tot_de', 'Weyl', 'v_newtonian_cdm', 'v_newtonian_baryon', 'v_baryon_cdm', 'a', 'etak', 'H', 'growth', 'v_photon', 'pi_photon', 'E_2', 'v_neutrino', 'T_source', 'E_source', 'lens_potential_source'], lAccuracyBoost=4, frame='CDM')[source]

Get the mode evolution as a function of conformal time for some k values.

Parameters:
  • q – wavenumber values to calculate (or array of k values)
  • eta – array of requested conformal times to output
  • vars – list of variable names or sympy symbolic expressions to output (using camb.symbolic)
  • lAccuracyBoost – factor by which to increase l_max in hierarchies compared to default - often needed to get nice smooth curves of acoustic oscillations for plotting.
  • frame – for symbolic expressions, can specify frame name if the variable is not gauge invariant. e.g. specifying Delta_g and frame=’Newtonian’ would give the Newtonian gauge photon density perturbation.
Returns:

nd array, A_{qti}, size(q) x size(times) x len(vars), or 2d array if q is scalar

get_total_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get lensed-scalar + tensor CMB power spectra. Must have already calculated power spectra.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:4], where 0..3 indexes TT, EE, BB, TE

get_unlensed_scalar_array_cls(lmax=None)[source]

Get array of all cross power spectra. Must have already calculated power spectra. Results are dimensionless, and not scaled by custom_scaled_ell_fac.

Parameters:lmax – lmax to output to
Returns:numpy array CL[0:, 0:,0:lmax+1], where 0.. index T, E, lensing potential, source window functions
get_unlensed_scalar_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get unlensed scalar CMB power spectra. Must have already calculated power spectra.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:4], where 0..3 indexes TT, EE, BB, TE. CL[:,2] will be zero.

get_unlensed_total_cls(lmax=None, CMB_unit=None, raw_cl=False)[source]

Get unlensed CMB power spectra, including tensors if relevant. Must have already calculated power spectra.

Parameters:
  • lmax – lmax to output to
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\)
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
Returns:

numpy array CL[0:lmax+1,0:4], where 0..3 indexes TT, EE, BB, TE.

h_of_z(z)[source]

Get Hubble rate at redshift z, in \({\rm Mpc}^{-1}\) units, scalar or array

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Use hubble_parameter instead if you want in [km/s/Mpc] units.

Parameters:z – redshift
Returns:H(z)
hubble_parameter(z)[source]

Get Hubble rate at redshift z, in km/s/Mpc units. Scalar or array.

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:z – redshift
Returns:H(z)/[km/s/Mpc]
luminosity_distance(z)[source]

Get luminosity distance from to redshift z.

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:z – redshift or array of redshifts
Returns:luminosity distance (matches rank of z)
physical_time(z)[source]

Get physical time from hot big bang to redshift z in Gigayears.

Parameters:z – redshift
Returns:t(z)/Gigayear
physical_time_a1_a2(a1, a2)[source]

Get physical time between two scalar factors in Gigayears

Must have called calc_background(), calc_background_no_thermo() or calculated transfer functions or power spectra.

Parameters:
  • a1 – scale factor 1
  • a2 – scale factor 2
Returns:

(age(a2)-age(a1))/Gigayear

power_spectra_from_transfer(initial_power_params, silent=False)[source]

Assuming calc_transfers() or calc_power_spectra() have already been used, re-calculate the power spectra using a new set of initial power spectrum parameters with otherwise the same cosmology. This is typically much faster that re-calculating everything, as the transfer functions can be re-used. NOTE: if non-linear lensing is on, the transfer functions have the non-linear correction included when they are calculated, so using this function with a different initial power spectrum will not give quite the same results as doing a full recalculation.

Parameters:
redshift_at_comoving_radial_distance(chi)[source]

Convert comoving radial distance array to redshift array.

Parameters:chi – comoving radial distance (in Mpc), scalar or array
Returns:redshift at chi, scalar or array
redshift_at_conformal_time(eta)[source]

Convert conformal time array to redshift array. Note that this function requires the transfers or background to have been calculated with no_thermo=False (the default).

Parameters:eta – conformal time from bing bang (in Mpc), scalar or array
Returns:redshift at eta, scalar or array
replace(instance)

Replace the content of this class with another instance, doing a deep copy (in Fortran)

Parameters:instance – instance of the same class to replace this instance with
save_cmb_power_spectra(filename, lmax, CMB_unit='muK')[source]

Save CMB power to a plain text file. Output is lensed total \(\ell(\ell+1)C_\ell/2\pi\) then lensing potential and cross: L TT EE BB TE PP PT PE.

Parameters:
  • filename – filename to save
  • lmax – lmax to save
  • CMB_unit – scale results from dimensionless. Use ‘muK’ for \(\mu K^2\) units for CMB \(C_\ell\) and \(\mu K\) units for lensing cross.
set_params(params)[source]

Set parameters from params. Note that this does not recompute anything; you will need to call calc_transfers() if you change any parameters affecting the background cosmology or the transfer function settings.

Parameters:params – a CAMBparams instance
sound_horizon(z)[source]

Get comoving sound horizon as function of redshift in Megaparsecs, the integral of the sound speed up to given redshift.

Parameters:z – redshift or array of redshifts
Returns:r_s(z)
class camb.results.MatterTransferData[source]

MatterTransferData is the base class for storing matter power transfer function data for various q values. In a flat universe q=k, in a closed universe q is quantized.

To get an instance of this data, call results.CAMBdata.get_matter_transfer_data()

Variables:
  • nq – number of q modes calculated
  • q – array of q values calculated
  • sigma_8 – array of \(\sigma_8\) values for each redshift
  • sigma2_vdelta_8 – array of v-delta8 correlation, so sigma2_vdelta_8/sigma_8 can define growth
  • transfer_data

    numpy array T[entry, q_index, z_index] storing transfer functions for each redshift and q; entry+1 can be

    • Transfer_kh = 1 (k/h)
    • Transfer_cdm = 2 (cdm)
    • Transfer_b = 3 (baryons)
    • Transfer_g = 4 (photons)
    • Transfer_r = 5 (massless neutrinos)
    • Transfer_nu = 6 (massive neutrinos)
    • Transfer_tot = 7 (total matter)
    • Transfer_nonu = 8 (total matter excluding neutrinos)
    • Transfer_tot_de = 9 (total including dark energy perturbations)
    • Transfer_Weyl = 10 (Weyl potential)
    • Transfer_Newt_vel_cdm = 11 (Newtonian CDM velocity)
    • Transfer_Newt_vel_baryon = 12 (Newtonian baryon velocity)
    • Transfer_vel_baryon_cdm = 13 (relative baryon-cdm velocity)
transfer_z(name, z_index=0)[source]

Get transfer function (function of q, for each q in self.q_trans) by name for given redshift index

Parameters:
  • name – parameter name
  • z_index – which redshift
Returns:

array of transfer function values for each calculated k

class camb.results.ClTransferData[source]

ClTransferData is the base class for storing CMB power transfer functions, as a function of q and \(\ell\). To get an instance of this data, call results.CAMBdata.get_cmb_transfer_data()

Variables:
  • NumSources – number of sources calculated (size of p index)
  • q – array of q values calculated (=k in flat universe)
  • l – int array of \(\ell\) values calculated
  • delta_p_l_k – transfer functions, indexed by source, l, q
get_transfer(source=0)[source]

Return \(C_\ell\) trasfer functions as a function of \(\ell\) and \(q\) (\(= k\) in a flat universe).

Parameters:source – index of source: e.g. 0 for temperature, 1 for E polarization, 2 for lensing potential
Returns:array of computed l, array of computed q, transfer functions T(l,q)

camb.symbolic

This module defines the scalar linear perturbation equations for standard LCDM cosmology, using sympy. It uses the covariant perturbation notation, but includes functions to project into the Newtonian or synchronous gauge, as well as constructing general gauge invariant quantities. It uses “t” as the conformal time variable (=tau in the fortran code).

For a guide to usage and content see the ScalEqs notebook

As well as defining standard quantities, and how they map to CAMB variables, there are also functions for converting a symbolic expression to CAMB source code, and compiling custom sources for use with CAMB (as used by model.CAMBparams.set_custom_scalar_sources(), results.CAMBdata.get_time_evolution())

A Lewis July 2017

camb.symbolic.LinearPerturbation(name, species=None, camb_var=None, camb_sub=None, frame_dependence=None, description=None)[source]

Returns as linear perturbation variable, a function of conformal time t. Use help(x) to quickly view all quantities defined for the result.

Parameters:
  • name – sympy name for the Function
  • species – tag for the species if relevant (not used)
  • camb_var – relevant CAMB fortran variable
  • camb_sub – if not equal to camb_var, and string giving the expression in CAMB variables
  • frame_dependence – the change in the perturbation when the frame 4-velocity u change from u to u + delta_frame. Should be a sumpy expression involving delta_frame.
  • description – string describing variable
Returns:

sympy Function instance (function of t), with attributes set to the arguments above.

camb.symbolic.camb_fortran(expr, name='camb_function', frame='CDM', expand=False)[source]

Convert symbolic expression to CAMB fortran code, using CAMB variable notation. This is not completely general, but it will handle conversion of Newtonian gauge variables like Psi_N, and most derivatives up to second order.

Parameters:
  • expr – symbolic sympy expression using camb.symbolic variables and functions (plus any standard general functions that CAMB can convert to fortran).
  • name – lhs variable string to assign result to
  • frame – frame in which to interret non gauge-invariant expressions. By default uses CDM frame (synchronous gauge), as used natively by CAMB.
  • expand – do a sympy expand before generating code
Returns:

fortran code snippet

camb.symbolic.cdm_gauge(x)[source]

Evaluates an expression in the CDM frame \((v_c=0, A=0)\). Equivalent to the synchronous gauge but using the covariant variable names.

Parameters:x – expression
Returns:expression evaluated in CDM frame.
camb.symbolic.compile_source_function_code(code_body, file_path='', compiler=None, fflags=None, cache=True)[source]

Compile fortran code into function pointer in compiled shared library. The function is not intended to be called from python, but for passing back to compiled CAMB.

Parameters:
  • code_body – fortran code to do calculation and assign sources(i) output array. Can start with declarations of temporary variables if needed.
  • file_path – optional output path for generated f90 code
  • compiler – compiler, usually on path
  • fflags – options for compiler
  • cache – whether to cache the result
Returns:

function pointer for compiled code

class camb.symbolic.f_K
camb.symbolic.get_hierarchies(lmax=5)[source]

Get Boltzmann hierarchies up to lmax for photons (J), E polarization and massless neutrinos (G).

Parameters:lmax – maxmimum multipole
Returns:list of equations
camb.symbolic.get_scalar_temperature_sources(checks=False)[source]

Derives terms in line of sight source, after integration by parts so that only integrated against a Bessel function (no derivatives).

Parameters:checks – True to do consistency checks on result
Returns:monopole_source, ISW, doppler, quadrupole_source
camb.symbolic.make_frame_invariant(expr, frame='CDM')[source]

Makes the quantity gauge invariant, assuming currently evaluated in frame ‘frame’. frame can either be a string frame name, or a variable that is zero in the current frame,

e.g. frame = Delta_g gives the constant photon density frame. So make_frame_invariant(sigma, frame=Delta_g) will return the combination of sigma and Delta_g that is frame invariant (and equal to just sigma when Delta_g=0).

camb.symbolic.newtonian_gauge(x)[source]

Evaluates an expression in the Newtonian gauge (zero shear, sigma=0). Converts to using conventional metric perturbation variables for metric

\[ds^2 = a^2\left( (1+2\Psi_N)d t^2 - (1-2\Phi_N)\delta_{ij}dx^idx^j\right)\]
Parameters:x – expression
Returns:expression evaluated in the Newtonian gauge
camb.symbolic.synchronous_gauge(x)[source]

evaluates an expression in the synchronous gauge, using conventional synchronous-gauge variables.

Parameters:x – expression
Returns:synchronous gauge variable expression

Other modules:

camb.bbn

class camb.bbn.BBNPredictor[source]

The base class for making BBN predictions for Helium abundance

Y_He(ombh2, delta_neff=0.0)[source]

Get BBN helium mass fraction for CMB code.

Parameters:
  • ombh2\(\Omega_b h^2\)
  • delta_neff – additional N_eff relative to standard value (of 3.046)
Returns:

Y_He helium mass fraction predicted by BBN

Y_p(ombh2, delta_neff=0.0)[source]

Get BBN helium nucleon fraction. Must be implemented by extensions.

Parameters:
  • ombh2\(\Omega_b h^2\)
  • delta_neff – additional N_eff relative to standard value (of 3.046)
Returns:

Y_p helium nucleon fraction predicted by BBN

class camb.bbn.BBN_fitting_parthenope(tau_neutron=None)[source]

Old BBN predictions for Helium abundance using fitting formulae based on Parthenope (pre 2015).

Y_p(ombh2, delta_neff=0.0, tau_neutron=None)[source]

Get BBN helium nucleon fraction. # Parthenope fits, as in Planck 2015 papers

Parameters:
  • ombh2\(\Omega_b h^2\)
  • delta_neff – additional N_eff relative to standard value (of 3.046)
  • tau_neutron – neutron lifetime
Returns:

\(Y_p^{\rm BBN}\) helium nucleon fraction predicted by BBN

class camb.bbn.BBN_table_interpolator(interpolation_table='PArthENoPE_880.2_standard.dat', function_of=['ombh2', 'DeltaN'])[source]

BBN predictor based on interpolation from a numerical table calculated by a BBN code.

Tables are supplied for Parthenope 2017 (PArthENoPE_880.2_standard.dat, default), similar but with Marucci rates (PArthENoPE_880.2_marcucci.dat), and PRIMAT (PRIMAT_Yp_DH_Error.dat).

Parameters:
  • interpolation_table – filename of interpolation table to use.
  • function_of – two variables that determine the interpolation grid (x,y) in the table, matching top column label comment. By default ombh2, DeltaN, and function argument names reflect that, but can also be used more generally.
DH(ombh2, delta_neff=0.0, grid=False)[source]

Get deuterium ratio D/H by interpolation in table

Parameters:
  • ombh2\(\Omega_b h^2\) (or, more generally, value of function_of[0])
  • delta_neff – additional N_eff relative to standard value (of 3.046) (or value of function_of[1])
Returns:

D/H

Y_p(ombh2, delta_neff=0.0, grid=False)[source]

Get BBN helium nucleon fraction by intepolation in table.

Parameters:
  • ombh2\(\Omega_b h^2\) (or, more generally, value of function_of[0])
  • delta_neff – additional N_eff relative to standard value (of 3.046) (or value of function_of[1])
Returns:

Y_p helium nucleon fraction predicted by BBN. Call Y_He() to get mass fraction instead.

get(name, ombh2, delta_neff=0.0, grid=False)[source]

Get value for variable “name” by intepolation from table (where name is given in the column header comment) For example get(‘sig(D/H)’,0.0222,0) to get the error on D/H

Parameters:
  • ombh2\(\Omega_b h^2\) (or, more generally, value of function_of[0])
  • delta_neff – additional N_eff relative to standard value (of 3.046) (or value of function_of[1])
Returns:

Interpolated value

camb.bbn.get_default_predictor()[source]

Get instance of default BBNPredictor class. Currently numerical table interpolation as Planck 2018 analysis.

camb.dark_energy

class camb.dark_energy.DarkEnergyModel[source]

Abstract base class for dark energy model implementations.

class camb.dark_energy.DarkEnergyEqnOfState[source]

Bases: camb.dark_energy.DarkEnergyModel

Abstract base class for models using w and wa parameterization with use w(a) = w + (1-a)*wa parameterization, or call set_w_a_table to set another tabulated w(a). If tabulated w(a) is used, w and wa are set to approximate values at z=0.

See model.CAMBparams.set_initial_power_function() for a convenience constructor function to set a general interpolated P(k) model from a python function.

Variables:
  • w – (float64) w(0)
  • wa – (float64) -dw/da(0)
  • cs2 – (float64) fluid rest-frame sound speed squared
  • use_tabulated_w – (boolean) using an interpolated tabulated w(a) rather than w, wa above
set_params(w=-1.0, wa=0, cs2=1.0)[source]
Set the parameters so that P(a)/rho(a) = w(a) = w + (1-a)*wa
Parameters:
  • w – w(0)
  • wa – -dw/da(0)
  • cs2 – fluid rest-frame sound speed squared
set_w_a_table(a, w)[source]

Set w(a) from numerical values (used as cublic spline). Note this is quite slow.

Parameters:
  • a – array of scale factors
  • w – array of w(a)
Returns:

self

class camb.dark_energy.DarkEnergyFluid[source]

Bases: camb.dark_energy.DarkEnergyEqnOfState

Class implementing the w, wa or splined w(a) parameterization using the constant sound-speed signle fluid model (as for single-field quintessense).

class camb.dark_energy.DarkEnergyPPF[source]

Bases: camb.dark_energy.DarkEnergyEqnOfState

Class implementating the w, wa or splined w(a) parameterization in the PPF perturbation approximation (arXiv:0808.3125) Use inherited methods to set parameters or interpolation table.

class camb.dark_energy.AxionEffectiveFluid[source]

Bases: camb.dark_energy.DarkEnergyModel

Example implementation of a specifc (early) dark energy fluid model (arXiv:1806.10608). Not well tested, but should serve to demonstrate how to make your own custom classes.

Variables:
  • w_n – (float64)
  • om – (float64)
  • a_c – (float64)
  • theta_i – (float64)

camb.initialpower

class camb.initialpower.InitialPower[source]

Abstract base class for initial power spectrum classes

class camb.initialpower.InitialPowerLaw(**kwargs)[source]

Bases: camb.initialpower.InitialPower

Object to store parameters for the primordial power spectrum in the standard power law expansion.

Variables:
  • tensor_parameterization – (integer/string, one of: tensor_param_indeptilt, tensor_param_rpivot, tensor_param_AT)
  • ns – (float64)
  • nrun – (float64)
  • nrunrun – (float64)
  • nt – (float64)
  • ntrun – (float64)
  • r – (float64)
  • pivot_scalar – (float64)
  • pivot_tensor – (float64)
  • As – (float64)
  • At – (float64)
has_tensors()[source]

Do these settings have non-zero tensors?

Returns:True if non-zero tensor amplitude
set_params(As=2e-09, ns=0.96, nrun=0, nrunrun=0.0, r=0.0, nt=None, ntrun=0.0, pivot_scalar=0.05, pivot_tensor=0.05, parameterization='tensor_param_rpivot')[source]

Set parameters using standard power law parameterization. If nt=None, uses inflation consistency relation.

Parameters:
  • As – comoving curvature power at k=pivot_scalar (\(A_s\))
  • ns – scalar spectral index \(n_s\)
  • nrun – running of scalar spectral index \(d n_s/d \log k\)
  • nrunrun – running of running of spectral index, \(d^2 n_s/d (\log k)^2\)
  • r – tensor to scalar ratio at pivot
  • nt – tensor spectral index \(n_t\). If None, set using inflation consistency
  • ntrun – running of tensor spectral index
  • pivot_scalar – pivot scale for scalar spectrum
  • pivot_tensor – pivot scale for tensor spectrum
  • parameterization – See CAMB notes. One of - tensor_param_indeptilt = 1 - tensor_param_rpivot = 2 - tensor_param_AT = 3
Returns:

self

class camb.initialpower.SplinedInitialPower(**kwargs)[source]

Bases: camb.initialpower.InitialPower

Object to store a generic primordial spectrum set from a set of sampled k_i, P(k_i) values

has_tensors()[source]

Is the tensor spectrum set?

Returns:True if tensors
set_scalar_log_regular(kmin, kmax, PK)[source]

Set log-regular cublic spline interpolation for P(k)

Parameters:
  • kmin – minimum k value (not minimum log(k))
  • kmax – maximum k value (inclusive)
  • PK – array of scalar power spectrum values, with PK[0]=P(kmin) and PK[-1]=P(kmax)
set_scalar_table(k, PK)[source]

Set arrays of k and P(k) values for cublic spline interpolation. Note that using set_scalar_log_regular() may be better (faster, and easier to get fine enough spacing a low k)

Parameters:
  • k – array of k values (Mpc^{-1})
  • PK – array of scalar power spectrum values
set_tensor_log_regular(kmin, kmax, PK)[source]

Set log-regular cublic spline interpolation for tensor spectrum P_t(k)

Parameters:
  • kmin – minimum k value (not minimum log(k))
  • kmax – maximum k value (inclusive)
  • PK – array of scalar power spectrum values, with PK[0]=P_t(kmin) and PK[-1]=P_t(kmax)
set_tensor_table(k, PK)[source]

Set arrays of k and P_t(k) values for cublic spline interpolation

Parameters:
  • k – array of k values (Mpc^{-1})
  • PK – array of tensor power spectrum values

camb.nonlinear

class camb.nonlinear.NonLinearModel[source]

Abstract base class for non-linear correction models

Variables:Min_kh_nonlinear – (float64) minimum k/h at which to apply non-linear corrections
class camb.nonlinear.Halofit[source]

Bases: camb.nonlinear.NonLinearModel

Various specific approximate non-linear correction models based on HaloFit.

Variables:halofit_version – (integer/string, one of: original, bird, peacock, takahashi, mead, halomodel, casarini, mead2015)
set_params(halofit_version='takahashi')[source]

Set the halofit model for non-linear corrections.

Parameters:version

One of

class camb.nonlinear.SecondOrderPK[source]

Bases: camb.nonlinear.NonLinearModel

Third-order Newtonian perturbation theory results for the non-linear correction. Only intended for use at very high redshift (z>10) where corrections are perturbative, it will not give sensible results at low redshift.

See Appendix F of astro-ph/0702600 for equations and references.

Not intended for production use, it’s mainly to serve as an example alternative non-linear model implementation.

camb.reionization

class camb.reionization.ReionizationModel[source]

Abstract base class for reionization models.

Variables:Reionization – (boolean) Is there reionization? (can be off for matter power which is independent of it)
class camb.reionization.TanhReionization[source]

Bases: camb.reionization.ReionizationModel

This default (unphysical) tanh x_e parameterization is described in Appendix B of arXiv:0804.3865

Variables:
  • use_optical_depth – (boolean) Whether to use the optical depth or redshift paramters
  • redshift – (float64) Reionization redshift if use_optical_depth-False
  • optical_depth – (float64) Optical depth if use_optical_depth=True
  • delta_redshift – (float64) Duration of reionization
  • fraction – (float64) Reionization fraction when complete, or -1 for full ionization of hydrogen and first ionization of helium.
  • include_helium_fullreion – (boolean) Whether to include second reionization of helium
  • helium_redshift – (float64) Redshift for second reionization of helium
  • helium_delta_redshift – (float64) Width in redshift for second reionization of helium
  • helium_redshiftstart – (float64) Include second helium reionizatio below this redshift
  • tau_solve_accuracy_boost – (float64) Accuracy boosting parameter for solving for z_re from tau
  • timestep_boost – (float64) Accuracy boosting parameter for the minimum number of time sampling steps through reionization
  • max_redshift – (float64) Maxmimum redshift allowed when mapping tau into reionization redshift
get_zre(params, tau=None)[source]

Get the midpoint redshift of reionization.

Parameters:
  • paramsmodel.CAMBparams instance with cosmological parameters
  • tau – if set, calculation the redshift for tau, otherwise uses curently set parameters
Returns:

reionization mid-point redshift

set_tau(tau, delta_redshift=None)[source]

Set the optical depth

Parameters:
  • tau – optical depth
  • delta_redshift – delta z for reionization
Returns:

self

camb.recombination

class camb.recombination.RecombinationModel[source]

Abstract base class for recombination models

Variables:min_a_evolve_Tm – (float64) minimum scale factor at which to solve matter temperature perturbation if evolving sound speed or ionization fraction perturbations
class camb.recombination.Recfast[source]

Bases: camb.recombination.RecombinationModel

RECFAST recombination model (see recfast source for details).

Variables:
  • RECFAST_fudge – (float64)
  • RECFAST_fudge_He – (float64)
  • RECFAST_Heswitch – (integer)
  • RECFAST_Hswitch – (boolean)
  • AGauss1 – (float64)
  • AGauss2 – (float64)
  • zGauss1 – (float64)
  • zGauss2 – (float64)
  • wGauss1 – (float64)
  • wGauss2 – (float64)
class camb.recombination.CosmoRec[source]

Bases: camb.recombination.RecombinationModel

CosmoRec recombination model. To use this, the library must be build with CosmoRec installed and RECOMBINATION_FILES including cosmorec in the Makefile.

CosmoRec must be built with -fPIC added to the compiler flags.

Variables:
  • runmode – (integer) Default 0, with diffusion; 1: without diffusion; 2: RECFAST++, 3: RECFAST++ run with correction
  • fdm – (float64) Dark matter annihilation efficiency
  • accuracy – (float64) 0-normal, 3-most accurate
class camb.recombination.HyRec[source]

Bases: camb.recombination.RecombinationModel

HyRec recombination model. To use this, the library must be build with HyRec installed and RECOMBINATION_FILES including hyrec in the Makefile.

You will need to edit HyRec Makefile to add -fPIC compiler flag to CCFLAG (for gcc), and rename “dtauda_” in history.c to “exported_dtauda”

camb.sources

class camb.sources.SourceWindow[source]

Abstract base class for a number count/lensing/21cm source window function. A list of instances of these classes can be assigned to the SourceWindows field of model.CAMBparams.

Variables:
  • source_type – (integer/string, one of: 21cm, counts, lensing)
  • bias – (float64)
  • dlog10Ndm – (float64)
class camb.sources.GaussianSourceWindow[source]

Bases: camb.sources.SourceWindow

A Gaussian W(z) source window function.

Variables:
  • redshift – (float64)
  • sigma – (float64)
class camb.sources.SplinedSourceWindow(**kwargs)[source]

Bases: camb.sources.SourceWindow

A numerical W(z) source window function constructed by interpolation from a numerical table.

set_table(z, W)[source]

Set arrays of z and W(z) for cublic spline interpolation. Note that W(z) is the total count distribution observed, not a fractional selection function on an underlying distribution.

Parameters:
  • z – array of redshift values (monotonically increasing)
  • W – array of window function values. It must be well enough sampled to smoothly cubic-spline interpolate

camb.correlations

Functions to transform CMB angular power spectra into correlation functions (cl2corr) and vice versa (corr2cl), and calculate lensed power spectra from unlensed ones.

The lensed power spectrum functions are not intended to replace those calculated by default when getting CAMB results, but may be useful for tests, e.g. using different lensing potential power spectra, partially-delensed lensing power spectra, etc.

These functions are all pure python/scipy, and operate and return cls including factors \(\ell(\ell+1)/2\pi\) (for CMB) and \([L(L+1)]^2/2\pi\) (for lensing).

  1. Lewis December 2016
camb.correlations.cl2corr(cls, xvals, lmax=None)[source]

Get the correlation function from the power spectra, evaluated at points cos(theta) = xvals. Use roots of Legendre polynomials (np.polynomial.legendre.leggauss) for accurate back integration with corr2cl. Note currently does not work at xvals=1 (can easily calculate that as special case!).

Parameters:
  • cls – 2D array cls(L,ix), with L (\(\equiv \ell\)) starting at zero and ix-0,1,2,3 in order TT, EE, BB, TE. cls should include \(\ell(\ell+1)/2\pi\) factors.
  • xvals – array of \(\cos(\theta)\) values at which to calculate correlation function.
  • lmax – optional maximum L to use from the cls arrays
Returns:

2D array of corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross

camb.correlations.corr2cl(corrs, xvals, weights, lmax)[source]

Transform from correlation functions to power spectra. Note that using cl2corr followed by corr2cl is generally very accurate (< 1e-5 relative error) if xvals, weights = np.polynomial.legendre.leggauss(lmax+1)

Parameters:
  • corrs – 2D array, corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross
  • xvals – values of \(\cos(\theta)\) at which corrs stores values
  • weights – weights for integrating each point in xvals. Typically from np.polynomial.legendre.leggauss
  • lmax – maximum \(\ell\) to calculate \(C_\ell\)
Returns:

array of power spectra, cl[L, ix], where L starts at zero and ix=0,1,2,3 in order TT, EE, BB, TE. They include \(\ell(\ell+1)/2\pi\) factors.

camb.correlations.gauss_legendre_correlation(cls, lmax=None, sampling_factor=1)[source]

Transform power specturm cls into correlation functions evaluated at the roots of the Legendre polynomials for Gauss-Legendre quadrature. Returns correlation function array, evaluation points and weights. Result can be passed to corr2cl for accurate back transform.

Parameters:
  • cls – 2D array cls(L,ix), with L (\(\equiv \ell\)) starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE. Should include \(\ell(\ell+1)/2\pi\) factors.
  • lmax – optional maximum L to use
  • sampling_factor – uses Gauss-Legendre with degree lmax*sampling_factor+1
Returns:

corrs, xvals, weights; corrs[i, ix] is 2D array where ix=0,1,2,3 are T, Q+U, Q-U and cross

camb.correlations.legendre_funcs(lmax, x, m=[0, 2], lfacs=None, lfacs2=None, lrootfacs=None)[source]

Utility function to return array of Legendre and \(d_{mn}\) functions for all \(\ell\) up to lmax. Note that \(d_{mn}\) arrays start at \(\ell_{\rm min} = \max(m,n)\), so returned arrays are different sizes

Parameters:
  • lmax – maximum \(\ell\)
  • x – scalar value of \(\cos(\theta)\) at which to evaluate
  • m – m values to calculate \(d_{m,n}\), etc as relevant
  • lfacs – optional pre-computed \(\ell(\ell+1)\) float array
  • lfacs2 – optional pre-computed \((\ell+2)*(\ell-1)\) float array
  • lrootfacs – optional pre-computed sqrt(lfacs*lfacs2) array
Returns:

\((P,P'),(d_{11},d_{-1,1}), (d_{20}, d_{22}, d_{2,-2})\) as requested, where P starts at \(\ell=0\), but spin functions start at \(\ell=\ell_{\rm min}\)

camb.correlations.lensed_cl_derivative_unlensed(clpp, lmax=None, theta_max=0.098174771875, apodize_point_width=10, sampling_factor=1.4)[source]

Get derivative dcl of lensed minus unlensed power \(D_\ell \equiv \ell(\ell+1)\Delta C_\ell/2\pi\) with respect to \(\ell(\ell+1)C^{\rm unlens}_\ell/2\pi\)

The difference in power in the lensed spectrum is given by dCL[ix, :, :].dot(cl), where cl is the appropriate \(\ell(\ell+1)C^{\rm unlens}_\ell/2\pi\).

Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in \(C_{{\rm gl},2}\)

Parameters:
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum (zero based)
  • lmax – optional maximum L to use from the clpp array
  • theta_max – maximum angle (in radians) to keep in the correlation functions
  • apodize_point_width – if theta_max is set, apodize around the cut using half Gaussian of approx width apodize_point_width/lmax*pi
  • sampling_factor – npoints = int(sampling_factor*lmax)+1
Returns:

array dCL[ix, ell, L], where ix=0,1,2,3 are TT, EE, BB, TE and result is \(d\left(\Delta D^{\rm ix}_\ell\right) / d D^{{\rm unlens},j}_L\) where j[ix] are TT, EE, EE, TE

camb.correlations.lensed_cl_derivatives(cls, clpp, lmax=None, theta_max=0.098174771875, apodize_point_width=10, sampling_factor=1.4)[source]

Get derivative dcl of lensed \(D_\ell\equiv \ell(\ell+1)C_\ell/2\pi\) with respect to \(\log(C^{\phi}_L)\). To leading order (and hence not actually accurate), the lensed correction to power spectrum ix is given by dcl[ix,:,:].dot(np.ones(clpp.shape)).

Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in \(C_{{\rm gl},2}\)

Parameters:
  • cls – 2D array of unlensed cls(L,ix), with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE. cls should include \(\ell(\ell+1)/2\pi\) factors.
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum (zero based)
  • lmax – optional maximum L to use from the cls arrays
  • theta_max – maximum angle (in radians) to keep in the correlation functions
  • apodize_point_width – if theta_max is set, apodize around the cut using half Gaussian of approx width apodize_point_width/lmax*pi
  • sampling_factor – npoints = int(sampling_factor*lmax)+1
Returns:

array dCL[ix, ell, L], where ix=0,1,2,3 are T, EE, BB, TE and result is \(d[D^{\rm ix}_\ell]/ d (\log C^{\phi}_L)\)

camb.correlations.lensed_cls(cls, clpp, lmax=None, lmax_lensed=None, sampling_factor=1.4, delta_cls=False, theta_max=0.098174771875, apodize_point_width=10, leggaus=True, cache=True)[source]

Get the lensed power spectra from the unlensed power spectra and the lensing potential power. Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in \(C_{{\rm gl},2}\).

Correlations are calculated for Gauss-Legendre integration if leggaus=True; this slows it by several seconds, but will be must faster on subsequent calls with the same lmax*sampling_factor. If Gauss-Legendre is not used, sampling_factor needs to be about 2 times larger for same accuracy.

For a reference implementation with the full integral range and no apodization set theta_max=None.

Note that this function does not pad high \(\ell\) with a smooth fit (like CAMB’s main functions); for accurate results should be called with lmax high enough that input cls are effectively band limited (lmax >= 2500, or higher for accurate BB to small scales). Usually lmax truncation errors are far larger than other numerical errors for lmax<4000.

Parameters:
  • cls – 2D array of unlensed cls(L,ix), with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE. cls should include \(\ell(\ell+1)/2\pi\) factors.
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum (zero based)
  • lmax – optional maximum L to use from the cls arrays
  • lmax_lensed – optional maximum L for the returned cl array (lmax_lensed <= lmax)
  • sampling_factor – npoints = int(sampling_factor*lmax)+1
  • delta_cls – if true, return the difference between lensed and unlensed (optional, default False)
  • theta_max – maximum angle (in radians) to keep in the correlation functions; default: pi/32
  • apodize_point_width – if theta_max is set, apodize around the cut using half Gaussian of approx width apodize_point_width/lmax*pi
  • leggaus – whether to use Gauss-Legendre integration (default True)
  • cache – if leggaus = True, set cache to save the x values and weights between calls (most of the time)
Returns:

2D array of cls[L, ix], with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE. cls include \(\ell(\ell+1)/2\pi\) factors.

camb.correlations.lensed_correlations(cls, clpp, xvals, weights=None, lmax=None, delta=False, theta_max=None, apodize_point_width=10)[source]

Get the lensed correlation function from the unlensed power spectra, evaluated at points \(\cos(\theta)\) = xvals. Use roots of Legendre polynomials (np.polynomial.legendre.leggauss) for accurate back integration with corr2cl. Note currently does not work at xvals=1 (can easily calculate that as special case!).

To get the lensed cls efficiently, set weights to the integral weights for each x value, then function returns lensed correlations and lensed cls.

Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in \(C_{{\rm gl},2}\)

Parameters:
  • cls – 2D array of unlensed cls(L,ix), with L (\(\equiv\ell\)) starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE. cls should include \(\ell(\ell+1)/2\pi\) factors.
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum (zero based)
  • xvals – array of \(\cos(\theta)\) values at which to calculate correlation function.
  • weights – if given also return lensed \(C_\ell\), otherwise just lensed correlations
  • lmax – optional maximum L to use from the cls arrays
  • delta – if true, calculate the difference between lensed and unlensed (default False)
  • theta_max – maximum angle (in radians) to keep in the correlation functions
  • apodize_point_width – smoothing scale for apodization at truncation of correlation function
Returns:

2D array of corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross; if weights is not None, then return corrs, lensed_cls

camb.correlations.lensing_R(clpp, lmax=None)[source]

Get \(R \equiv \frac{1}{2} \langle |\nabla \phi|^2\rangle\)

Parameters:
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum
  • lmax – optional maximum L to use from the cls arrays
Returns:

R

camb.correlations.lensing_correlations(clpp, xvals, lmax=None)[source]

Get the \(\sigma^2(x)\) and \(C_{{\rm gl},2}(x)\) functions from the lensing power spectrum

Parameters:
  • clpp – array of \([L(L+1)]^2 C_L^{\phi\phi}/2\pi\) lensing potential power spectrum (zero based)
  • xvals – array of \(\cos(\theta)\) values at which to calculate correlation function.
  • lmax – optional maximum L to use from the clpp array
Returns:

array of \(\sigma^2(x)\), array of \(C_{{\rm gl},2}(x)\)

camb.postborn

camb.postborn.get_field_rotation_BB(params, lmax=None, acc=1, CMB_unit='muK', raw_cl=False, spline=True)[source]

Get the B-mode power spectrum from field post-born field rotation, based on perturbative and Limber approximations. See arXiv:1605.05662.

Parameters:
  • paramsmodel.CAMBparams instance with cosmological parameters etc.
  • lmax – maximum \(\ell\)
  • acc – accuracy
  • CMB_unit – units for CMB output relative to dimensionless
  • raw_cl – return \(C_\ell\) rather than \(\ell(\ell+1)C_\ell/2\pi\)
  • spline – return InterpolatedUnivariateSpline, otherwise return tuple of lists of \(\ell\) and \(C_\ell\)
Returns:

InterpolatedUnivariateSpline (or arrays of sampled \(\ell\) and) \(\ell^2 C_\ell^{BB}/(2 \pi)\) (unless raw_cl, in which case just \(C_\ell^{BB}\))

camb.postborn.get_field_rotation_power(params, kmax=100, lmax=20000, non_linear=True, z_source=None, k_per_logint=None, acc=1, lsamp=None)[source]

Get field rotation power spectrum, \(C_L^{\omega\omega}\), following arXiv:1605.05662 Uses lowest Limber approximation.

Parameters:
  • paramsmodel.CAMBparams instance with cosmological parameters etc.
  • kmax – maximum k (in \({\rm Mpc}^{-1}\) units)
  • lmax – maximum L
  • non_linear – include non-linear corrections
  • z_source – redshift of source. If None, use peak of CMB visibility for CMB lensing
  • k_per_logint – sampling to use in k
  • acc – accuracy setting, increase to test stability
  • lsamp – array of L values to compute output at. If not set, set to sampling good for interpolation
Returns:

\(L\), \(C_L^{\omega\omega}\): the L sample values and corresponding rotation power

camb.emission_angle

This module calculates the corrections to the standard lensed CMB power spectra results due to time delay and emission angle, following arXiv:1706.02673. This can be combined with the result from the postborn module to estimate the leading corrections to the standard lensing B modes.

Corrections to T and E are negligible, and not calculated. The result for BB includes approximately contributions from reionization, but this can optionally be turned off.

camb.emission_angle.get_emission_angle_powers(camb_background, PK, chi_source, lmax=3000, acc=1, lsamp=None)[source]

Get the power spectrum of \(\psi_d\), the potential for the emission angle, and its cross with standard lensing. Uses the Limber approximation (and assumes flat universe).

Parameters:
  • camb_background – a CAMB results object, used for calling background functions
  • PK – a matter power spectrum interpolator (from camb.get_matter_power_interpolator)
  • chi_source – comoving radial distance of source in Mpc
  • lmax – maximum L
  • acc – accuracy parameter
  • lsamp – L sampling for the result
Returns:

a InterpolatedUnivariateSpline object containing \(L(L+1) C_L\)

camb.emission_angle.get_emission_delay_BB(params, kmax=100, lmax=3000, non_linear=True, CMB_unit='muK', raw_cl=False, acc=1, lsamp=None, return_terms=False, include_reionization=True)[source]

Get B modes from emission angle and time delay effects. Uses full-sky result from appendix of arXiv:1706.02673

Parameters:
  • paramsmodel.CAMBparams instance with cosmological parameters etc.
  • kmax – maximum k (in \({\rm Mpc}^{-1}\) units)
  • lmax – maximum \(\ell\)
  • non_linear – include non-linear corrections
  • CMB_unit – normalization for the result
  • raw_cl – if true return \(C_\ell\), else \(\ell(\ell+1)C_\ell/2\pi\)
  • acc – accuracy setting, increase to test stability
  • lsamp – array of \(\ell\) values to compute output at. If not set, set to sampling good for interpolation
  • return_terms – return the three sub-terms separately rather than the total
  • include_reionization – approximately include reionization terms by second scattering surface
Returns:

InterpolatedUnivariateSpline for \(C_\ell^{BB}\)

camb.emission_angle.get_source_cmb_cl(params, CMB_unit='muK')[source]

Get the angular power spectrum of emission angle and time delay sources \(\psi_t\), \(\psi_\zeta\), as well as the perpendicular velocity and E polarization. All are returned with 1 and 2 versions, for recombination and reionization respectively. Note that this function destroys any custom sources currently configured.

Parameters:
  • paramsmodel.CAMBparams instance with cosmological parameters etc.
  • CMB_unit – scale results from dimensionless, use ‘muK’ for \(\mu K^2\) units
Returns:

dictionary of power spectra, with \(L(L+1)/2\pi\) factors.