Skip to content

Cosmology model

Dynamic parameter models

class_e.core.cosmo_factory

Dynamic Pydantic model factory for cosmological parameters.

This module creates Pydantic models dynamically from YAML configuration files, allowing for flexible cosmological model definitions with automatic validation.

load_cosmology_from_yaml

load_cosmology_from_yaml(
    yaml_path: str | Path,
    model_name: Optional[str] = None,
    extra_class_params: Optional[Dict[str, Any]] = None,
) -> Type[BaseModel]

Load YAML and create a cosmology model in one step.

Parameters:

Name Type Description Default
yaml_path str or Path

Path to YAML configuration file

required
model_name str

Name for the model (defaults to output.model_name from YAML or filename)

None
extra_class_params dict

Additional CLASS-specific parameters

None

Returns:

Type Description
Type[BaseModel]

Pydantic model class with validation

Examples:

>>> LCDMModel = load_cosmology_from_yaml("configs/lcdm.yaml")
>>> params = LCDMModel(H0=67.4, omega_b=0.022, omega_cdm=0.12)
>>> EDEModel = load_cosmology_from_yaml("configs/ede.yaml", model_name="EDEParams")
>>> params = EDEModel(H0=70.0, omega_b=0.024, f_ede=0.08, log10_z_c=3.5)

create_cosmology

create_cosmology(
    yaml_data: Dict[str, Any],
    base_class: Optional[Type[BaseModel]] = None,
    model_name: str = "DynamicCosmologyParams",
    extra_class_params: Optional[Dict[str, Any]] = None,
) -> Type[BaseModel]

Create a Pydantic model dynamically from YAML parameter specifications.

Parameters:

Name Type Description Default
yaml_data dict

Loaded YAML configuration with 'parameters' section

required
base_class Type[BaseModel]

Base class to inherit from (e.g., for shared methods)

None
model_name str

Name for the generated model class

'DynamicCosmologyParams'
extra_class_params dict

Additional CLASS-specific parameters to add to to_class() output

None

Returns:

Type Description
Type[BaseModel]

Dynamically created Pydantic model class with validation

Examples:

>>> yaml_data = {
...     "parameters": {
...         "H0": [60.0, 80.0],
...         "omega_b": {"min": 0.02, "max": 0.025, "latex": r"\omega_b"},
...         "f_ede": {"min": 0.0, "max": 0.15, "default": 0.0}
...     }
... }
>>> Model = create_cosmology(yaml_data)
>>> params = Model(H0=67.4, omega_b=0.022, f_ede=0.05)
>>> params.H0
67.4

CLASS interface

class_e.core.boltzmann

get_observables

get_observables(
    params: BaseModel,
    extra_args: Optional[Dict[str, Any]] = None,
    *,
    observables: Optional[list[str]] = None,
    lmax: Optional[int] = None,
    lensed: bool = True,
    k_values: Optional[ndarray] = None,
    z_values: Optional[list[float] | ndarray] = None,
    tk_k_values: Optional[ndarray] = None,
    tk_z_values: Optional[list[float] | ndarray] = None,
    bg_z_values: Optional[list[float] | ndarray] = None,
) -> Dict[str, Any]

Compute requested observables (Cls, mPk, Tk, background and/or scalars) in a single CLASS run.

This function replaces the old deprecated get_observables() and serves as a single-pass engine: it configures CLASS once to produce all requested quantities and then extracts them without re-initializing CLASS.

Parameters:

Name Type Description Default
params BaseModel

Cosmology parameters model (must provide to_class()).

required
extra_args dict

Additional CLASS arguments (precision, etc.). Will be merged with the required options for the requested outputs. The 'output' field will be overridden based on the requested observables.

None
observables (list[str], optional(keyword - only))

Any of ["TT", "TE", "EE", "PP", "mPk"]. Defaults to ["TT","TE","EE","mPk"].

None
lmax (int, optional(keyword - only))

Maximum multipole for Cls. Defaults to 2500 if any Cl requested and not provided.

None
lensed bool

Return lensed Cls (tt, te, ee). PP is independent of this flag.

True (keyword-only)
k_values (ndarray, optional(keyword - only))

k grid in h/Mpc for P(k). If None and mPk requested, a default log-space grid is used.

None
z_values (list[float] | ndarray, optional(keyword - only))

Redshift values for P(k). If None and mPk requested, defaults to [0.0].

None
tk_k_values (ndarray, optional(keyword - only))

k grid in 1/Mpc for the matter transfer function ("Tk"). Default: 500 log-spaced points between 1e-4 and 10 1/Mpc.

None
tk_z_values (list[float] | ndarray, optional(keyword - only))

Redshifts of the transfer function. Default: [30.0], before dark energy or modified gravity matter, where late-time growth can take over.

None
bg_z_values (list[float] | ndarray, optional(keyword - only))

Redshifts of the background observables ("Hz", "chi"). Default: default_background_z, 100 points uniform in ln(1+z) from 0 to 1200.

None

Returns:

Type Description
dict

A dictionary possibly containing the following keys depending on the request: - 'ell': (L,) ell grid (2..lmax) - 'tt', 'te', 'ee': (L,) Cl arrays if requested - 'pp': (L,) lensing potential spectrum if requested ("PP") - 'k': (K,) k grid in h/Mpc if mPk requested - 'z': (Z,) redshift grid if mPk requested - 'pk': (Z, K) matter power spectrum if mPk requested - 'tk', 'tk_k', 'tk_z': (Z, K) CDM+baryon transfer function \(-\delta_{cb}(k, z)\) normalized to unit primordial curvature, if "Tk" requested (see Notes) - 'hz': (Z,) expansion rate H(z) in km/s/Mpc, if "Hz" requested - 'chi': (Z,) line-of-sight comoving distance in Mpc, if "chi" requested - 'z_bg': (Z,) their redshift grid - (1,) scalars of the background and thermodynamics, if requested: see BACKGROUND_SCALARS ('rs_drag', 'z_drag', 'rs_star' in Mpc, 'z_star', 'h0' in km/s/Mpc, 'theta_s_100', 'theta_star_100')

Notes

The transfer function is normalized so that, with \(k\) in 1/Mpc,

\[ P_{cb}(k, z) = \frac{2\pi^2}{k^3}\, \mathcal{P}_{\mathcal{R}}(k)\, T_k(k, z)^2 , \]

where \(\mathcal{P}_{\mathcal{R}}\) is the primordial curvature power spectrum and \(T_k\) is the returned tk.

  • This function performs exactly one CLASS compute() call per parameter set.
  • For mPk, the CLASS parameter 'P_k_max_1/Mpc' is set based on the provided k-grid and an estimate of h from the parameters to avoid range errors.
  • If classy is not installed, ImportError is raised with guidance.

compute_cosmology

compute_cosmology(
    params: BaseModel,
    extra_args: Optional[Dict[str, Any]] = None,
    outputs: Optional[str] = None,
) -> Any

Initialize and compute CLASS with given parameters.

Parameters:

Name Type Description Default
params BaseModel

Cosmology parameters (any model with to_class() method)

required
extra_args dict

Additional CLASS parameters (e.g., output types, precision settings)

None
outputs str

Comma-separated list of outputs (e.g., "tCl,pCl,lCl,mPk") Overrides extra_args['output'] if provided; "" computes the background only

None

Returns:

Type Description
Class

Initialized CLASS instance (remember to call struct_cleanup() and empty())

Examples:

>>> from class_e.core.boltzmann import get_default_model, compute_cosmology
>>> LCDM = get_default_model()  # uses configs/lcdm.yaml by default
>>> params = LCDM()
>>> cosmo = compute_cosmology(params, outputs="tCl,pCl,lCl")
>>> try:
...     cls_tt = cosmo.lensed_cl(2500)['tt']
... finally:
...     cosmo.struct_cleanup()
...     cosmo.empty()
>>> # With custom model
>>> EDEModel = load_cosmology_model("configs/ede.yaml")
>>> params = EDEModel(h=0.70, f_ede=0.08, log10_z_c=3.5)
>>> cosmo = compute_cosmology(params, outputs="mPk")

load_cosmology_model

load_cosmology_model(
    config_path: str | Path,
) -> Type[BaseModel]

Load a cosmology model from a YAML configuration file.

This is a convenience function that uses the dynamic model factory to create a Pydantic model class from a YAML configuration.

Parameters:

Name Type Description Default
config_path str or Path

Path to YAML configuration file defining parameters and derived parameters

required

Returns:

Type Description
Type[BaseModel]

Pydantic model class with validation and derived parameters

Examples:

>>> LCDMModel = load_cosmology_model("configs/lcdm.yaml")
>>> params = LCDMModel(h=0.67, omega_b=0.022, omega_cdm=0.12)
>>> class_dict = params.to_class()
>>> # Model with Early Dark Energy
>>> EDEModel = load_cosmology_model("configs/ede.yaml")
>>> params = EDEModel(h=0.70, omega_b=0.024, f_ede=0.08, log10_z_c=3.5)
Notes

The returned model class includes: - Automatic validation of parameter bounds - Support for derived parameters (computed on-the-fly) - to_class() method for CLASS integration - get_bounds() classmethod for sampling - get_latex_names() classmethod for plotting - get_derived_parameters() classmethod for metadata

require_classy

require_classy(raise_if_missing: bool = False) -> bool

Check for classy; optionally raise.

Returns True if classy is available. If not and raise_if_missing is True, raises ImportError.