CLASS (Cosmic Linear Anisotropy Solving System)

repository·master·Indexed 43 days ago

https://github.com/lesgourg/class_public

A code for solving the linear evolution of cosmological perturbations, used to calculate theoretical predictions for various cosmological models. It includes a Python interface (classy), a C++ wrapper, and utilities for plotting outputs via CPU.py and MATLAB. Features include the external_Pk mode for custom primordial spectra and integration with MontePython for MCMC fits.

Tokens
22.1K
Snippets
70
Records
99
Agent score
56%

What's inside CLASS

  1. Module API patterns: init, free, and interpolation

    master

    Each functional module in CLASS (e.g., background.c, thermodynamics.c) follows a consistent API pattern consisting of three types of functions:

    1. module_init(...): Allocates and fills the module's specific structure. This must be called in the order of the seven-module hierarchy (Background $\rightarrow$ Thermodynamics $\rightarrow$ ... $\rightarrow$ Harmonic), as each subsequent module requires the data from the previous one.
    2. module_free(): Deallocates the fields of the structure. Crucial for samplers: If embedding CLASS in a parameter sampler, you must call module_free() between executions and before calling module_init() again with new parameters to prevent memory leaks.
    3. module_something_at_somevalue(...): Provides interpolation for the pre-computed tables. For example, background_at_eta(eta, * values) allows you to retrieve background quantities for any arbitrary conformal time $\eta$ from the tabulated values generated during background_init().
  2. Optimize precision for external_Pk spectra

    master

    When using external spectra, the precision of the results depends on the sampling of $k$ in your output and the CLASS integration parameters.

    To avoid interpolation errors or integration inaccuracies, consider adjusting these CLASS parameters:

    • k_step_trans: Sampling of $k$ in the integral.
    • l_logstep and l_linstep: Sampling of the transfer functions in $l$.

    A good starting point for testing is k_step_trans=0.01 and l_linstep=1. Increase these values slowly until the results change significantly.

  3. How the CLASS module hierarchy works

    master

    CLASS is organized into a ten-module backbone where each module performs a specific task in the cosmological calculation pipeline. The execution follows a strict dependency chain where each module's _init() function takes the results of previous modules as input and populates its own structure with new results.

    Key characteristics of this architecture:

    • Dependency Chain: Modules are initialized sequentially (e.g., background_init $\rightarrow$ thermodynamics_init $\rightarrow$ perturbations_init).
    • Self-Contained Structures: Each module uses a specific structure (e.g., struct perturbations pt) that contains both its input parameters and its computed results (including array sizes for memory management).
    • Memory Management: Each module has a corresponding _free() function (except for precision and output) that deallocates only the arrays owned by that specific module.
    • Reduced Executables: For developers interested in intermediate steps (e.g., only background or only thermodynamics), CLASS provides reduced executables in the test/ directory (e.g., test_perturbations.c) which can be compiled via make test_<module_name>.
    /* Example of the initialization sequence in main.c */
    background_init(&pr, &ba);
    thermodynamics_init(&pr, &ba, &th);
    perturbations_init(&pr, &ba, &th, &pt);
    // ... and so on
  4. Understand CLASS error management and nested error messages

    master

    CLASS uses an integer-based error management system where functions return either _SUCCESS_ or _FAILURE_.

    When a failure occurs, the error message is propagated upwards through a nested structure. Each module has an associated structure containing an error_message field (e.g., background.error_message, thermo.error_message). This allows the user to see the full call stack of errors, including the specific line numbers and the root cause.

    For Developers: Using class_call()

    To ensure errors are correctly propagated and nested, use the class_call() macro when calling module functions. This macro handles appending the local error message to the caller's error message.

    Syntax with pointers to structures:

    class_call(module_i_function(...,pi),
               pi->error_message,
               pj->error_message);

    For Developers: Using class_test()

    You can trigger a formatted error message using class_test(). This is useful for validating input parameters or constraints.

    Example:

    class_test(blabla >= 1,
               px->error_message,
               "your choice of input parameter blabla=%e is not consistent with the constraint blabla<%e",
               blabla, blablamax);
    class_call(module_i_function(...,pi),
               pi->error_message,
               pj->error_message);
  5. Understand specific physics sectors (Recombination, PPF, and Dark Matter)

    master

    CLASS includes specialized formalisms for specific physical sectors:

    • Perturbed Recombination: Detailed equations for perturbed recombination are available (optional since v2.1.0).
    • PPF Formalism: The PPF (Parameterized Post-Friedmann) formalism is used by default for fluid perturbations (since v2.6.0).
    • Dark Matter Interactions:
      • ETHOS Formalism: Models interactions between dark matter (idm) and dark radiation (idr) (introduced in v2.9).
      • Multi-interacting Dark Matter: Since v3.2, the sector supports multi-interacting dark matter with three interaction channels: dark radiation, baryons, and photons.
  6. Configure cosmological parameter bases

    master

    The CLASS input parser is flexible and allows multiple ways to define the same physical quantities. The code 'interprets' the parameters to ensure consistency. For example, you can define the photon density using temperature, mass density, or energy density. The code will automatically convert between them.

    Supported Parameter Equivalents (Examples):

    • Hubble Parameter: h or H0
    • Photon Density: T_cmb (Kelvin), omega_g ($\omega_g \equiv \Omega_g h^2$), or `Omega_g$
    • Baryon Density: omega_b or `Omega_b$
    • Neutrino Density: N_eff or `omega_ur$

    Note: Do not provide more than one parameter for the same physical quantity (e.g., do not provide both T_cmb and Omega_g), as this will cause a conflict error.

  7. Understand the CLASS module architecture and data flow

    master

    CLASS is built on a ten-module backbone where each module is responsible for a specific step in the cosmological computation pipeline.

    The Computation Pipeline

    1. Input: Set parameters (struct precision).
    2. Background: Compute cosmological background (struct background).
    3. Thermodynamics: Compute ionization fractions, etc. (struct thermodynamics).
    4. Perturbations: Compute source functions $S(k, \tau)$ (struct perturbations).
    5. Primordial: Compute primordial spectra (struct primordial).
    6. Fourier: Compute 2-point statistics $P(k)$ (struct fourier).
    7. Transfer: Compute transfer functions $\Delta_l(k)$ (struct transfer).
    8. Harmonic: Compute harmonic power spectra $C_l$ (struct harmonic).
    9. Lensing: Compute lensed CMB spectra (struct lensing).
    10. Distortions: Compute CMB spectral distortions (struct distortions).

    Data Communication

    Communication between modules is handled by passing pointers to specific structures. Each structure contains:

    • An array of tabulated values (e.g., background quantities as a function of time).
    • Metadata regarding array size and physical quantity indices for interpolation.
    • Derived quantities required by subsequent modules.

    Module Interface

    Each module (e.g., background.c, perturbations.c) typically implements three types of functions:

    • module_init(...): Allocates and fills the module's structure. Calling this solves the specific step for the current parameters.
    • module_free(...): Deallocates the structure's fields. Crucial: When interfacing CLASS with a sampler, you must call module_free between executions and before calling module_init again with new parameters.
    • module_something_at_somevalue(...): Interpolates pre-computed tables (e.g., background_at_tau(tau, ...)). These are the only functions intended to be called by other modules.
  8. Use the external_Pk mode to provide a custom primordial spectrum

    master

    The external_Pk mode allows CLASS to use an arbitrary primordial spectrum $P(k)$ generated by an external shell command (e.g., a Python script, C, or Fortran code). This is useful for implementing non-standard inflationary models.

    To enable this mode, set P_k_ini type = external_Pk in your CLASS .ini file. You must then provide a command that executes your script and use custom1 through custom10 to pass up to 10 floating-point parameters to that script.

    P_k_ini type = external_Pk
    command = /path/to/your_script.py
    custom1 = 0.05
    custom2 = 2.2e-9
    custom3 = 1.
  9. Compile CLASS from source

    master

    To compile the CLASS executable and its associated binary files, use the provided Makefile in the root directory. It is recommended to clean the previous build before starting a new one.

    Run the following command in the root directory:

    make clean; make -j

    This will create the class executable and populate the build/ directory.