CLASS (classy)

Synopsis:

Managing the CLASS cosmological code

Author:

Jesus Torrado (import and get_Cl based on MontePython’s CLASS wrapper Benjamin Audren)

This module imports and manages the CLASS cosmological code.

Note

If you use this cosmological code, please cite it as:
D. Blas, J. Lesgourgues, T. Tram, The Cosmic Linear Anisotropy Solving System (CLASS). Part II: Approximation schemes (arXiv:1104.2933)

Note

CLASS is renamed classy for most purposes within cobaya, due to CLASS’s name being a python keyword.

Usage

If you are using a likelihood that requires some observable from CLASS, simply add classy to the theory block.

You can specify any parameter that CLASS understands in the params block:

theory:
  classy:
    extra_args:
      [any param that CLASS understands]

params:
    [any param that CLASS understands, fixed, sampled or derived]

If you want to use your own version of CLASS, you need to specify its location with a path option inside the classy block. If you do not specify a path, CLASS will be loaded from the automatic-install packages_path folder, if specified, or otherwise imported as a globally-installed Python package. If you want to force that the global classy installation is used, pass path='global'. Cobaya will print at initialisation where CLASS was actually loaded from.

Access to CLASS computation products

You can retrieve CLASS computation products within likelihoods (or other pipeline components in general) or manually from a Model as long as you have added them as requisites; see Creating your own cosmological likelihood or Creating your own cosmological likelihood class for the likelihood case, and Using the model wrapper for the manual case.

The products that you can request and later retrieve are listed in must_provide().

For scalar parameters, you can add them as derived parameters in your input file. In principle, you can add most of the parameters that you can retrieve manually in the CLASS Python wrapper (the ones appearing inside the definition of the get_current_derived_parameters() function of the python CLASS interface). If any of them does not work (usually because it has been added to CLASS since Cobaya was last updated), you can still add them as derived parameters in you input as long as you add them also to the classy block as

theory:
  classy:
    [...]
    output_params: ["param1", "param2", ...]

If you would like to access a CLASS result that is not accessible in any of these ways, you can access directly the return value of the python CLASS interface functions get_background(), get_thermodynamics(), get_primordial(), get_perturbations() and get_sources(). To do that add to the requisites {get_CLASS_[...]: None} respectively, and retrieve it with provider.get_CLASS_[...].

In general, the use of these methods for direct access to CLASS results should be avoided in public code, since it breaks compatibility with other Boltzmann codes at the likelihood interface level. If you need a quantity for a public code that is not generally interfaced in must_provide(), let us know if you think it makes sense to add it.

Modifying CLASS

If you modify CLASS and add new variables, make sure that the variables you create are exposed in the Python interface (instructions here). If you follow those instructions you do not need to make any additional modification in Cobaya.

If your modification involves new computed quantities, add the new quantities to the return value of some of the direct-access methods listed in Access to CLASS computation products.

You can use the model wrapper to test your modification by evaluating observables or getting derived quantities at known points in the parameter space (set debug: True to get more detailed information of what exactly is passed to CLASS).

In your CLASS modification, remember that you can raise a CosmoComputationError whenever the computation of any observable would fail, but you do not expect that observable to be compatible with the data (e.g. at the fringes of the parameter space). Whenever such an error is raised during sampling, the likelihood is assumed to be zero, and the run is not interrupted.

Note

If your modified CLASS has a lower version number than the minimum required by Cobaya, you will get an error at initialisation. You may still be able to use it by setting the option ignore_obsolete: True in the classy block (though you would be doing that at your own risk; ideally you should translate your modification to a newer CLASS version, in case there have been important fixes since the release of your baseline version).

Installation

Warning

If the installation folder of CLASS is moved, due to CLASS hard-coding some folders, CLASS needs to be recompiled, either manually or by deleting the CLASS installation and repeating the cobaya-install command in the renamed packages folder.

If you do not recompile CLASS, it causes a memory leak (thanks to Stefan Heimersheim).

Automatic installation

If you do not plan to modify CLASS, the easiest way to install it is using the automatic installation script. Just make sure that theory: classy: appears in one of the files passed as arguments to the installation script.

Manual installation (or using your own version)

You may prefer to install CLASS manually e.g. if you are planning to modify it.

Note

Pre-requisite: CLASS’ Python wrapper needs Cython, which you can install with

$ python -m pip install 'cython'

In particular, if working with a modified CLASS version based on a version previous to v3.2.1, you need to change above 'cython' by 'cython<3' (see this issue).

To download and install CLASS manually in a folder called CLASS under /path/to/cosmo, simply do:

$ cd /path/to/cosmo/
$ git clone https://github.com/lesgourg/class_public.git CLASS --depth=1
$ cd CLASS
$ make

If the second line produces an error (because you don’t have git installed), download the latest snapshot from here, decompress it, rename the resulting class_public-master folder to CLASS (optional) and run the make command from there.

Note

If CLASS seems to compile and install correctly, but you cannot import it from Python manually, or Cobaya fails to import it, it may be that the CLASS installation script is not using the right Python version. To fix that, if your preferred Python command is e.g. python3, re-do the make step as

$ PYTHON=python3 make

If the instructions above failed, follow those in the official CLASS web page.

Finally, in order for Cobaya to use this CLASS installation, you must specify the path to it in the classy input block (otherwise a system-wide CLASS may be used instead):

theory:
  classy:
    path: /path/to/cosmo/CLASS

Documentation of the classy wrapper class

class theories.classy.classy(info=mappingproxy({}), name=None, timing=None, packages_path=None, initialize=True, standalone=True)

CLASS cosmological Boltzmann code cite{Blas:2011rf}.

initialize()

Importing CLASS from the correct path, if given, and if not, globally.

set_cl_reqs(reqs)

Sets some common settings for both lensend and unlensed Cl’s.

must_provide(**requirements)

Specifies the quantities that this Boltzmann code is requested to compute.

Typical requisites in Cosmology (as keywords, case-insensitive):

  • Cl={...}: CMB lensed power spectra, as a dictionary {[spectrum]: l_max}, where the possible spectra are combinations of "t", "e", "b" and "p" (lensing potential). Get with get_Cl().

  • unlensed_Cl={...}: CMB unlensed power spectra, as a dictionary {[spectrum]: l_max}, where the possible spectra are combinations of "t", "e", "b". Get with get_unlensed_Cl().

  • [BETA: CAMB only; notation may change!] source_Cl={...}: \(C_\ell\) of given sources with given windows, e.g.: source_name: {"function": "spline"|"gaussian", [source_args]; for now, [source_args] follows the notation of CAMBSources. It can also take "lmax": [int], "limber": True if Limber approximation desired, and "non_linear": True if non-linear contributions requested. Get with get_source_Cl().

  • Pk_interpolator={...}: Matter power spectrum interpolator in \((z, k)\). Takes "z": [list_of_evaluated_redshifts], "k_max": [k_max], "nonlinear": [True|False], "vars_pairs": [["delta_tot", "delta_tot"], ["Weyl", "Weyl"], [...]]}. Notice that k_min cannot be specified. To reach a lower one, use extra_args in CAMB to increase accuracyboost and TimeStepBoost, or in CLASS to decrease k_min_tau0. The method get_Pk_interpolator() to retrieve the interpolator admits extrapolation limits extrap_[kmax|kmin]. It is recommended to use extrap_kmin to reach the desired k_min, and increase precision parameters only as much as necessary to improve over the interpolation. All \(k\) values should be in units of \(1/\mathrm{Mpc}\).

    Non-linear contributions are included by default. Note that the non-linear setting determines whether non-linear corrections are calculated; the get_Pk_interpolator() method also has a non-linear argument to specify if you want the linear or non-linear spectrum returned (to have both linear and non-linear spectra available request a tuple (False,True) for the non-linear argument).

  • Pk_grid={...}: similar to Pk_interpolator except that rather than returning a bicubic spline object it returns the raw power spectrum grid as a (k, z, P(z,k)) set of arrays. Get with get_Pk_grid().

  • sigma_R={...}: RMS linear fluctuation in spheres of radius \(R\) at redshifts \(z\). Takes "z": [list_of_evaluated_redshifts], "k_max": [k_max], "vars_pairs": [["delta_tot", "delta_tot"],  [...]], "R": [list_of_evaluated_R]. Note that \(R\) is in \(\mathrm{Mpc}\), not \(h^{-1}\,\mathrm{Mpc}\). Get with get_sigma_R().

  • Hubble={'z': [z_1, ...]}: Hubble rates at the requested redshifts. Get it with get_Hubble().

  • Omega_b={'z': [z_1, ...]}: Baryon density parameter at the requested redshifts. Get it with get_Omega_b().

  • Omega_cdm={'z': [z_1, ...]}: Cold dark matter density parameter at the requested redshifts. Get it with get_Omega_cdm().

  • Omega_nu_massive={'z': [z_1, ...]}: Massive neutrinos’ density parameter at the requested redshifts. Get it with get_Omega_nu_massive().

  • angular_diameter_distance={'z': [z_1, ...]}: Physical angular diameter distance to the redshifts requested. Get it with get_angular_diameter_distance().

  • angular_diameter_distance_2={'z_pairs': [(z_1a, z_1b), (z_2a, z_2b)...]}: Physical angular diameter distance between the pairs of redshifts requested. If a 1d array of redshifts is passed as z_pairs, all possible combinations of two are computed and stored (not recommended if only a subset is needed). Get it with get_angular_diameter_distance_2().

  • comoving_radial_distance={'z': [z_1, ...]}: Comoving radial distance from us to the redshifts requested. Get it with get_comoving_radial_distance().

  • sigma8_z={'z': [z_1, ...]}: Amplitude of rms fluctuations \(\sigma_8\) at the redshifts requested. Get it with get_sigma8().

  • fsigma8={'z': [z_1, ...]}: Structure growth rate \(f\sigma_8\) at the redshifts requested. Get it with get_fsigma8().

  • Other derived parameters that are not included in the input but whose value the likelihood may need.

set_collector_with_z_pool(k, zs, method, args=(), args_names=(), kwargs=None, arg_array=None, post=None, d=1)

Creates a collector for a z-dependent quantity, keeping track of the pool of z’s.

If z is an arg, i.e. it is in args_names, then omit it in the args, e.g. args_names=["a", "z", "b"] should be passed together with args=[a_value, b_value].

add_P_k_max(k_max, units)

Unifies treatment of \(k_\mathrm{max}\) for matter power spectrum: P_k_max_[1|h]/Mpc.

Make units="1/Mpc"|"h/Mpc".

calculate(state, want_derived=True, **params_values_dict)

Do the actual calculation and store results in state dict

Parameters:
  • state – dictionary to store results

  • want_derived – whether to set state[‘derived’] derived parameters

  • params_values_dict – parameter values

Returns:

None or True if success, False for fail

get_Cl(ell_factor=False, units='FIRASmuK2')

Returns a dictionary of lensed CMB power spectra and the lensing potential pp power spectrum.

Set the units with the keyword units=number|'muK2'|'K2'|'FIRASmuK2'|'FIRASK2'. The default is FIRASmuK2, which returns CMB \(C_\ell\)’s in FIRAS-calibrated \(\mu K^2\), i.e. scaled by a fixed factor of \((2.7255\cdot 10^6)^2\) (except for the lensing potential power spectrum, which is always unitless). The muK2 and K2 options use the model’s CMB temperature.

If ell_factor=True (default: False), multiplies the spectra by \(\ell(\ell+1)/(2\pi)\) (or by \([\ell(\ell+1)]^2/(2\pi)\) in the case of the lensing potential pp spectrum, and \([\ell(\ell+1)]^{3/2}/(2\pi)\) for the the cross spectra tp and ep).

get_unlensed_Cl(ell_factor=False, units='FIRASmuK2')

Returns a dictionary of unlensed CMB power spectra.

For units options, see get_Cl().

If ell_factor=True (default: False), multiplies the spectra by \(\ell(\ell+1)/(2\pi)\).

get_CLASS_background()

Direct access to get_background from the CLASS python interface.

get_CLASS_thermodynamics()

Direct access to get_thermodynamics from the CLASS python interface.

get_CLASS_primordial()

Direct access to get_primordial from the CLASS python interface.

get_CLASS_perturbations()

Direct access to get_perturbations from the CLASS python interface.

get_CLASS_sources()

Direct access to get_sources from the CLASS python interface.

close()

Finalizes the class, if something needs to be cleaned up.

get_can_provide_params()

Get a list of derived parameters that this component can calculate. The default implementation returns the result based on the params attribute set via the .yaml file or class params (with derived:True for derived parameters).

Returns:

iterable of parameter names

get_can_support_params()

Get a list of parameters supported by this component, can be used to support parameters that don’t explicitly appear in the .yaml or class params attribute or are otherwise explicitly supported (e.g. via requirements)

Returns:

iterable of names of parameters

get_version()

Get version information for this component.

Returns:

string or dict of values or None