API Reference¶
cloelib¶
cosmology
¶
Cosmology package of cloelib.
The package provides interface with external Boltzmann solvers or emulators via Python Protocols following the cosmology.API. Core structure enables defining Background & Perturbation models.
Supported External Codes:
- Background:
camb,class - Perturbations:
camb,class,HMCode2020emu,euclidemu2,baccoemu
cosmology
¶
Protocols for Background and Perturbation cosmology classes.
Notes:¶
-
Refactored cosmology.py from the original CLOE to provide a more flexible framework, enabling seamless integration with external cosmological codes while removing dependency on Cobaya.
-
Introduced the use of protocols to standardize external code interfaces, providing a unified and extensible template for interaction.
Background
¶
flowchart TD
cloelib.cosmology.cosmology.Background[Background]
click cloelib.cosmology.cosmology.Background href "" "cloelib.cosmology.cosmology.Background"
Protocol for Background cosmology class.
Omega_cdm0
property
¶
Omega cold dark matter; the cold dark matter density/critical density at z=0.
mnu
property
¶
Total neutrino mass in eV (float) or an array of individual neutrino masses in eV.
Omega_k0
property
¶
Omega curvature; the effective curvature density/critical density at z=0.
interface_args
property
¶
Save internal structure format of possible interface codes.
Omega_m
¶
Compute the matter density as a function of redshift.
A bare Python float is also accepted for a single redshift (e.g.
Omega_m(0.0) to get Omega_m0), matching the convention used
throughout cloelib's observables code; implementations return a
scalar in that case.
Omega_cb
¶
Computes the cold dark matter + baryons (no neutrinos) as a function of redshift.
hubble_parameter
¶
Retrieve the hubble parameter as a function of redshift.
comoving_distance
¶
Calculate the comoving distance for given redshifts.
transverse_comoving_distance
¶
Calculate the transverse comoving distance for given redshifts.
angular_diameter_distance
¶
Calculate the angular diameter distance for given redshifts.
Perturbations
¶
flowchart TD
cloelib.cosmology.cosmology.Perturbations[Perturbations]
click cloelib.cosmology.cosmology.Perturbations href "" "cloelib.cosmology.cosmology.Perturbations"
Protocol for Perturbation cosmology class.
Note: some consumers (e.g. ShearTracer.get_window_IA,
AngularTwoPoint.get_Cl) informally read .k/.z attributes off a
Perturbations instance for the wavenumber/redshift grid it was built
on. These are deliberately not part of this Protocol: not every
backend sets them (e.g. the JAX backends ignore the ks argument to
growth_factor and never set self.k), and several tests assert
isinstance(instance, Perturbations) for those backends. Code reading
.k/.z off an arbitrary Perturbations must use
getattr(perturbations, "k", None) / handle their absence, not assume
they exist.
growth_factor
¶
Evaluate the dimensionless growth factor at redshifts and wavenumbers.
Parameters:
-
(zs¶T) –One-dimensional NumPy or JAX array of redshifts, with shape
(nz,). -
(ks¶T) –One-dimensional NumPy or JAX array of wavenumbers in
1/Mpc, with shape(nk,).
Returns:
-
T(T) –NumPy or JAX array of growth-factor values. Scale-dependent
-
T–backends generally return shape
(nz, nk); scale-independent -
T–backends may return shape
(nz,). The growth factor is -
T–conventionally normalized to unity at redshift zero. Consult the
-
T–concrete backend when relying on a particular shape or
-
T–normalization convention.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[T], default:None) –One-dimensional NumPy or JAX array of redshifts, with shape
(nz,). IfNone, implementations use the redshift grid they were built on; implementations without a default grid may raiseValueError. -
(ks¶Optional[T], default:None) –One-dimensional NumPy or JAX array of wavenumbers in
1/Mpc, with shape(nk,). IfNone, return the growth rate as a function of redshift only.
Returns:
-
T(T) –NumPy or JAX array of growth-rate values. With
ks=None, the -
T–shape is
(nz,); with wavenumbers supplied, the shape is -
T–(nz, nk). Scale-independent growth rates are broadcast along -
T–the wavenumber axis.
matter_power_spectrum
¶
Retrieve the matter power spectrum.
matter_power_spectrum_cb
¶
Retrieves matter power spectrum of cold dark matter + baryons (no neutrinos).
WithWavenumberGrid
¶
flowchart TD
cloelib.cosmology.cosmology.WithWavenumberGrid[WithWavenumberGrid]
click cloelib.cosmology.cosmology.WithWavenumberGrid href "" "cloelib.cosmology.cosmology.WithWavenumberGrid"
Structural protocol for a linearperturbations-like object exposing a k grid.
.k is deliberately not part of the Perturbations protocol (see its
docstring). Boost-style implementations that need the wavenumber grid
their linearperturbations argument was built on (e.g.
EE2NonLinearPerturbations, MGemuNonlinearBoost,
TabulatedNonlinearBoost) type that argument against this narrower
protocol instead of the full Perturbations, since not every
Perturbations implementation sets .k.
WithLinearSpectrumGrid
¶
flowchart TD
cloelib.cosmology.cosmology.WithLinearSpectrumGrid[WithLinearSpectrumGrid]
cloelib.cosmology.cosmology.WithWavenumberGrid[WithWavenumberGrid]
cloelib.cosmology.cosmology.WithWavenumberGrid --> cloelib.cosmology.cosmology.WithLinearSpectrumGrid
click cloelib.cosmology.cosmology.WithLinearSpectrumGrid href "" "cloelib.cosmology.cosmology.WithLinearSpectrumGrid"
click cloelib.cosmology.cosmology.WithWavenumberGrid href "" "cloelib.cosmology.cosmology.WithWavenumberGrid"
Structural protocol for a linearperturbations exposing cached P(k, z) grids.
Used by implementations (e.g. HMemuNonLinearPerturbations) that stitch
a cached low-k linear tail onto a high-k nonlinear/emulated spectrum,
and so need direct array access to the grid linearperturbations was
built on rather than going through matter_power_spectrum/
matter_power_spectrum_cb. .z/.Pk/.Pk_cb are, like .k,
deliberately not part of the Perturbations protocol.
BaryonBoostMixin
¶
flowchart TD
cloelib.cosmology.cosmology.BaryonBoostMixin[BaryonBoostMixin]
click cloelib.cosmology.cosmology.BaryonBoostMixin href "" "cloelib.cosmology.cosmology.BaryonBoostMixin"
Protocol for mixins that add a baryonic suppression factor.
Any class that provides baryonic_suppression satisfies this protocol,
regardless of inheritance. Used for static type-checking only — never
instantiated directly.
Concrete implementations live in backend-specific files and are composed
into Perturbations subclasses to override matter_power_spectrum::
class FlamingoBaryonBoostMixin(BaryonBoostMixin):
def baryonic_suppression(self, zs, ks, k_hunit=False): ...
class CAMBNonLinearFLAMINGOPerturbations(
FlamingoBaryonBoostMixin, CAMBNonLinearPerturbations
):
def matter_power_spectrum(self, zs, ks, ...):
return super().matter_power_spectrum(...) * self.baryonic_suppression(...)
LinearPerturbationsFactory
¶
flowchart TD
cloelib.cosmology.cosmology.LinearPerturbationsFactory[LinearPerturbationsFactory]
click cloelib.cosmology.cosmology.LinearPerturbationsFactory href "" "cloelib.cosmology.cosmology.LinearPerturbationsFactory"
Constructor interface shared by every linear Perturbations class.
A linear perturbations class is built as
cls(background=..., redshifts=...). B_contra is the background type
the implementation needs (e.g. mochiCLASSBackground), so a class that
requires a specific background is only accepted where that background
type is promised.
__call__
¶
__call__(background: B_contra, redshifts: ndarray) -> Perturbations
Build the linear perturbations.
NonLinearPerturbationsFactory
¶
flowchart TD
cloelib.cosmology.cosmology.NonLinearPerturbationsFactory[NonLinearPerturbationsFactory]
click cloelib.cosmology.cosmology.NonLinearPerturbationsFactory href "" "cloelib.cosmology.cosmology.NonLinearPerturbationsFactory"
Constructor interface shared by every nonlinear Perturbations class.
A nonlinear perturbations class is built as
cls(background=..., linearperturbations=..., redshifts=...), followed
by optional, backend-specific keyword arguments (e.g. nonlinear_model,
or log10TAGN for the HMcode-based backends) that are deliberately not
part of this interface.
L_contra is the type of linearperturbations the caller provides, so
implementations that need more than the Perturbations interface from
it (e.g. HMemuNonLinearPerturbations reads the cached Pk/Pk_cb
grid, see WithLinearSpectrumGrid) are only accepted for linear
perturbations that provide it.
__call__
¶
__call__(background: B_contra, linearperturbations: L_contra, redshifts: ndarray) -> Perturbations
Build the nonlinear perturbations.
with_baryon_boost
¶
Compose a nonlinear perturbations class with a baryonic-boost mixin.
Returns a new class that:
- Places
BaryonMixinClassas the left parent (MRO priority). - Wires
__init__to callNonLinearClass.__init__first (so thatself.backgroundandself.zare available) and thenBaryonMixinClass.__init__withbaryon_kwargs. - Overrides
matter_power_spectrumandmatter_power_spectrum_cbto multiply P(k, z) bybaryonic_suppression.
Usage¶
::
from cloelib.cosmology.cosmology import with_baryon_boost
from cloelib.cosmology.baccoemu_cosmology import BACCOemuNonLinearPerturbations
from cloelib.cosmology.FlamingoBaryonResponseEmulator_cosmology import (
FlamingoBaryonBoostMixin,
)
BACCOemuFLAMINGO = with_baryon_boost(
BACCOemuNonLinearPerturbations, FlamingoBaryonBoostMixin
)
pert = BACCOemuFLAMINGO(
background, linear_pert, redshifts,
nonlinear_model_name="Arico2023",
baryon_kwargs=dict(fgas_sigma=0.0, Mstar_sigma=0.0, jet_fraction=0.0),
)
For HMcode2020::
BACCOemuHM = with_baryon_boost(
BACCOemuNonLinearPerturbations, HMcode2020BaryonBoostMixin
)
pert = BACCOemuHM(
background, linear_pert, redshifts,
baryon_kwargs=dict(log10TAGN=7.8),
)
Parameters¶
NonLinearClass:
A concrete nonlinear perturbations class (e.g.
BACCOemuNonLinearPerturbations, CAMBNonLinearPerturbations).
BaryonMixinClass:
A concrete :class:BaryonBoostMixin subclass (e.g.
FlamingoBaryonBoostMixin, BACCOemuBaryonBoostMixin,
HMcode2020BaryonBoostMixin).
Returns¶
type
A new class named
"{NonLinearClass.__name__}With{BaryonMixinClass.__name__}".
Raises¶
TypeError
If NonLinearClass already carries a baryonic mixin, since stacking
two baryonic models would apply baryonic feedback twice.
ValueError
At construction, if the nonlinear options passed already switch on
the backend's own baryonic boost (e.g. log10TAGN or
baryonic_boost), for the same reason.
growth_rate_on_redshifts
¶
growth_rate_on_redshifts(z_grid: ArrayLike, f_grid: ArrayLike, zs: Optional[ArrayLike] = None, ks: Optional[ArrayLike] = None) -> ndarray
Evaluate a tabulated, scale-independent growth rate following Perturbations.growth_rate.
Used by implementations that compute the growth rate on their own redshift grid. Requested redshifts are linearly interpolated on that grid and clamped to its edge values outside of it.
Parameters:
-
(z_grid¶array_like) –Redshifts at which
f_gridis tabulated. -
(f_grid¶array_like) –Growth rate at
z_grid. -
(zs¶Optional[array_like], default:None) –Redshifts at which to evaluate the growth rate. Defaults to
z_grid, returningf_gridunchanged. -
(ks¶Optional[array_like], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–np.ndarray: The growth rate, with shape (nz,) if
ksis None and -
ndarray–(nz, nk) otherwise.
derived_cosmology
¶
Common cosmology derived functions.
rho_crit
¶
rho_crit(background, zs: ndarray) -> ndarray
dV_dzdO
¶
Return the volume element per redshit per solid angle at the redshift requested.
Parameters¶
background: Background Background class containing cosmology zs :np.ndarray Redshifts. hubble_units: (Optional) bool Flag to specify if output in h units, defaults to False
Returns:
-
ndarray–volume element in Mpc^3 h^{-3}
rdrag_fitting_function
¶
rdrag_fitting_function(background, neff=3.046)
camb_cosmology
¶
Implementation of Background and Perturbation cosmology using CAMB.
CAMBBackground
¶
CAMBBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, gamma_MG: float, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0)
A wrapper for CAMB background cosmological calculations.
Parameters:
-
(H0¶float) –Hubble parameter in [km/s/Mpc].
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k).
-
(mnu¶Union[float, Sequence[float]], np.ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the dark energy equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter.
-
(N_mnu¶int) –Number of massive neutrino species.
-
(N_ur¶Optional[float], default:None) –Extra number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
N_ur
property
¶
Effective number of ultra-relativistic species.
If the user gave one, return it; otherwise infer from other parameters such that N_eff = 3.044 for the standard model of cosmology.
N_eff
property
¶
Return the effective number of relativistic species.
Assumes a standard value of T_ncdm = 0.71611 for neutrinos.
hubble_parameter
¶
comoving_distance
¶
comoving_distance(zs: ndarray) -> ndarray
Return the comoving distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Comoving distance values.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Transverse comoving distance values.
angular_diameter_distance
¶
angular_diameter_distance(zs: ndarray) -> ndarray
Return the angular diameter distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Angular diameter distance values.
Omega_cb
¶
Omega_cb(zs: Union[ndarray, float]) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values (no neutrinos).
CAMBLinearPerturbations
¶
CAMBLinearPerturbations(background: Background, redshifts: ndarray)
A wrapper for CAMB linear perturbation calculations.
Parameters:
-
(background¶Background) –A CAMBBackground instance.
-
(redshifts¶ndarray) –Array of redshifts for the calculations.
matter_power_spectrum
¶
matter_power_spectrum(zs: ndarray, ks: ndarray, hubble_units=False, k_hunit=False) -> ndarray
Compute the linear matter power spectrum.
Parameters:
-
(zs¶ndarray) –redshifts
-
(ks¶ndarray) –wavenumber
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_rate
¶
Calculate the scale-independent growth rate f = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate, interpolated on the CAMB redshift grid. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Args zs (numpy.ndarray): redshifts ks (numpy.ndarray): wavenumber
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
growth_factor_cb
¶
Calculate the growth factor for cb for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Args zs (numpy.ndarray): redshifts ks (numpy.ndarray): wavenumber
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
CAMBNonLinearPerturbations
¶
CAMBNonLinearPerturbations(background: Background, linearperturbations: Optional[Perturbations], redshifts: ndarray, nonlinear_model: Optional[str] = None, log10TAGN: Optional[float] = None)
A wrapper for CAMB nonlinear perturbation calculations.
Parameters:
-
(background¶Background) –A CAMBBackground instance.
-
(linearperturbations¶Optional[Perturbations]) –Linear perturbations object (unused by CAMB, which computes nonlinear corrections internally; accepted for interface compatibility with emulator-based NonLinPerturbations classes).
-
(redshifts¶ndarray) –Array of redshifts for the calculations.
-
(nonlinear_model¶Optional[str], default:None) –The nonlinear model to use (e.g., "takahashi"). Defaults to None, which uses the CAMB default model, or "mead2020_feedback" if
log10TAGNis given. -
(log10TAGN¶Optional[float], default:None) –HMcode2020 baryonic feedback parameter log10(T_AGN/K). Only used by the "mead2020_feedback" model. Defaults to None (no baryonic feedback).
Raises:
-
ValueError–If
log10TAGNis given with a nonlinear model that ignores it.
matter_power_spectrum
¶
matter_power_spectrum(zs: ndarray, ks: ndarray, hubble_units=False, k_hunit=False) -> ndarray
Compute the nonlinear matter power spectrum.
Parameters:
-
(zs¶ndarray) –redshifts
-
(ks¶ndarray) –wavenumber
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Nonlinear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Compute the nonlinear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_rate
¶
Calculate the scale-independent growth rate f = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate, interpolated on the CAMB redshift grid. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
growth_factor_cb
¶
Calculate the growth factor for cb for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
class_cosmology
¶
Implementation of Background and Perturbation cosmology using CLASS.
CLASSBackground
¶
CLASSBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, gamma_MG: float, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0, **kwargs)
A wrapper for CLASS background cosmological calculations.
Parameters:
-
(H0¶float) –Hubble parameter at z=0 in km/s/Mpc.
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k).
-
(mnu¶Union[float, Sequence[float], ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter (not directly used in CLASS, but kept for protocol compliance).
-
(N_mnu¶int) –Number of massive neutrino species.
-
(N_ur¶Optional[float], default:None) –Effective number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
N_ur
property
¶
Effective number of ultra-relativistic species.
If the user gave one, return it; otherwise infer from other parameters such that N_eff = 3.044 for the standard model of cosmology.
N_eff
property
¶
Return the effective number of relativistic species.
Assumes a standard value of T_ncdm = 0.71611 K for neutrinos.
hubble_parameter
¶
comoving_distance
¶
comoving_distance(zs: ndarray) -> ndarray
Return the comoving distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Comoving distance values.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Transverse comoving distance values.
angular_diameter_distance
¶
angular_diameter_distance(zs: ndarray) -> ndarray
Return the angular diameter distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Angular diameter distance values.
Omega_cb
¶
Omega_cb(zs: ndarray) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values (no neutrinos).
CLASSLinearPerturbations
¶
CLASSLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using CLASS, inheriting from Perturbations parent class.
matter_power_spectrum
¶
matter_power_spectrum(zs, ks, hubble_units=False, k_hunit=False) -> ndarray
Calculate the CLASS linear matter power spectrum.
Parameters:
-
(zs¶ndarray) –redshifts
-
(ks¶ndarray) –wavenumber
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Linear matter power spectrum at the specified scale
-
ndarray–and redshift
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z).
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–Scale-independent growth rate f(z), with shape (nz,) if ks is None and (nz, nk) otherwise.
CLASSNonLinearPerturbations
¶
CLASSNonLinearPerturbations(background: Background, linearperturbations: Optional[Perturbations], redshifts: ndarray, nonlinear_model: Optional[str] = None, hmcode_version: Optional[str] = None, log10TAGN: Optional[float] = None)
Class for non-linear perturbations cosmology using CLASS, inheriting from Perturbations parent class.
Parameters:
-
(background¶Background) –Background cosmology object.
-
(linearperturbations¶Optional[Perturbations]) –Linear perturbations object (CLASS computes the nonlinear corrections internally). Only needed for the cb x matter cross spectrum, e.g.
CLASSLinearPerturbationson the same background. -
(redshifts¶ndarray) –Array of redshifts for the calculations.
-
(nonlinear_model¶Optional[str], default:None) –The nonlinear model to use. Defaults to None (no nonlinear), or "hmcode" if
log10TAGNis given. -
(hmcode_version¶Optional[str], default:None) –The HMcode version to use. Defaults to None, or "2020_baryonic_feedback" if
log10TAGNis given. -
(log10TAGN¶Optional[float], default:None) –HMcode2020 baryonic feedback parameter log10(T_AGN/K), passed to CLASS as
log10T_heat_hmcode. Defaults to None (no baryonic feedback, or the CLASS default for "2020_baryonic_feedback").
Raises:
-
ValueError–If
log10TAGNis given with a nonlinear model or HMcode version that ignores it.
matter_power_spectrum
¶
matter_power_spectrum(zs, ks, hubble_units=False, k_hunit=False) -> ndarray
Calculate the CLASS non-linear matter power spectrum.
Parameters:
-
(zs¶ndarray) –redshifts
-
(ks¶ndarray) –wavenumber
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Non-linear matter power spectrum at the specified scale
-
ndarray–and redshift
matter_power_spectrum_cb
¶
Calculate the CLASS non-linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z).
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–Scale-independent growth rate f(z), with shape (nz,) if ks is None and (nz, nk) otherwise.
jax_cosmology
¶
Implementation of Background and Perturbation cosmology using JAX.
The module enables automatic differentiation. All of the functions are completely differentiable.
JAXBackground
¶
JAXBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, gamma_MG: float, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0, **kwargs)
Class to define background cosmology using JAX,inheriting from Cosmology parent class.
Parameters:
-
(H0¶float) –Hubble parameter in [km/s/Mpc].
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k). Note: JAXBackground does not use alpha_s (emulator not trained with it).
-
(mnu¶Union[float, Sequence[float], ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the dark energy equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter.
-
(N_mnu¶int) –Number of massive neutrino species. Note that JaxBackground does not support N_mnu != 0.
-
(N_ur¶Optional[float], default:None) –Effective number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
N_ur
property
¶
Effective number of ultra-relativistic species.
This property is not supported in the JAX backend and always returns None. If N_ur was provided during initialization, a ValueError is raised.
Returns¶
None
N_eff
property
¶
Effective number of relativistic species.
This property returns the default value of 3.044, as the JAX backend does not support variations in N_eff.
Returns¶
float The effective number of relativistic species, set to 3.044.
hubble_parameter
¶
comoving_distance
¶
comoving_distance(zs: ndarray) -> ndarray
Calculate the comoving distance for given redshifts.
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the comoving distance.
Returns:
-
ndarray–The comoving distance as a function of redshift.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Transverse comoving distance values.
angular_diameter_distance
¶
angular_diameter_distance(zs: ndarray) -> ndarray
Calculate the angular diameter distance for given redshifts.
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the angular diameter distance.
Returns:
-
ndarray–The angular diameter distance as a function of redshift.
Omega_b
¶
Omega_b(zs: ndarray) -> ndarray
Return the baryon density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–Matter density values.
Omega_m
¶
Omega_m(zs: ndarray) -> ndarray
Return the matter density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts. A bare Python/JAX scalar is also accepted (returns a scalar) -
ShearTracer. get_window_lensing/get_window_IA/get_window_magnificationall call this asOmega_m(0.0).
Returns:
-
ndarray–Matter density values.
Omega_cb
¶
Omega_cb(zs: ndarray) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts. A bare Python/JAX scalar is also accepted (returns a scalar), as for
Omega_m.
Returns:
-
ndarray–jnp.ndarray: Matter density values (no neutrinos).
w_a
¶
Compute the dark energy equation of state parameter w(a).
This function implements the linear equation of state w(a) = w0 + (1 - a) * wa, following the parametrization of Linder (2003).
Parameters¶
a (float or ndarray): Scale factor.
Returns¶
float or ndarray: The equation of state parameter w at scale factor a.
f_de
¶
Compute the logarithmic dark-energy density evolution relative to today.
For the CPL equation of state w(a) = w0 + (1 - a) * wa, this returns
ln(rho_de(a) / rho_de(1)). Its exponential is the dark-energy density
fraction relative to its value at a = 1 and is used in Esqr.
Parameters¶
a (float or ndarray): Scale factor.
Returns¶
float or ndarray
ln(rho_de(a) / rho_de(1)).
Esqr
¶
Compute the dimensionless energy density squared E^2(a).
This function returns the square of the expansion rate normalized by the Hubble constant, E^2(a) = (H(a)/H0)^2.
Parameters¶
a (float or ndarray): Scale factor.
Returns¶
float or ndarray: The dimensionless energy density squared at scale factor a.
Omega_m_a
¶
Compute the matter density parameter as a function of scale factor.
This function returns the fraction of the total energy density contributed by matter at scale factor a.
Parameters¶
a (float or ndarray): Scale factor.
Returns¶
float or ndarray: The matter density parameter Omega_m at scale factor a.
Omega_de_a
¶
Compute the dark energy density parameter as a function of scale factor.
This function returns the fraction of the total energy density contributed by dark energy at scale factor a.
Parameters¶
a (float or ndarray): Scale factor.
Returns¶
float or ndarray: The dark energy density parameter Omega_de at scale factor a.
JAXLinearPerturbations
¶
JAXLinearPerturbations(background: JAXBackground, redshifts: Optional[ndarray] = None)
A wrapper for JAX linear perturbation calculations.
Parameters:
-
(background¶JAXBackground) –A JAX background instance. Must be a
JAXBackground(not just anyBackground) since the growth ODE solved here relies on JAX-specific helpers (Omega_m_a,Omega_de_a,w_a) that aren't part of the generalBackgroundprotocol. -
(redshifts¶Optional[ndarray], default:None) –Default redshifts for
growth_rate. The JAX backend has no internal redshift grid and evaluates every quantity at the requested redshifts, so this is optional and accepted for interface compatibility with the other backends.
D_derivs
¶
Compute the derivatives of the growth factor for numerical integration.
This function implements the second-order linear perturbation equations for the growth factor D and its derivative, used in solving the ODE for the growth factor.
Parameters¶
y (array_like): Current values [D, D'] at scale factor x. x (float or ndarray): Scale factor.
Returns¶
ndarray: Derivatives [D', D''] at scale factor x.
growth_factor
¶
Evaluate the normalized, scale-independent linear growth factor.
The growth equation is integrated over a fixed grid of 128 scale
factors from 1e-3 to 1. The result is normalized to D(z=0)=1
and linearly interpolated in scale factor at the requested redshifts.
Parameters:
-
(zs¶ndarray) –One-dimensional array of redshifts at which to evaluate the growth factor. Values are converted to scale factors with
a = 1 / (1 + z). -
(ks¶Optional[ndarray], default:None) –Wavenumbers, accepted for compatibility with the perturbations interface. Growth is scale-independent in this implementation, so this argument is ignored.
Returns:
-
ndarray–jnp.ndarray: JAX array of growth-factor values, with one value per input redshift and the same shape as
zs.
growth_rate
¶
Compute the scale-independent growth rate.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate. Defaults to the
redshiftsgiven at construction. -
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast the growth rate.
Returns:
-
ndarray–jnp.ndarray: The growth rate, with shape (nz,) if ks is None and
-
ndarray–(nz, nk) otherwise.
transfer_Eisenstein_Hu
¶
transfer_Eisenstein_Hu(ks)
Compute the Eisenstein & Hu matter transfer function.
Parameters:
-
(ks¶array_like) –Wave number in h Mpc^{-1}
Returns:
-
T(array_like) –Value of the transfer function at the requested wave number
Notes
The Eisenstein & Hu transfer functions are computed using the fitting
formulae of :cite:1998:EisensteinHu
sigmasqr
¶
Compute the energy of the fluctuations within a sphere of R h^{-1} Mpc.
where
sigma8sqr
¶
Compute the energy of the fluctuations within a sphere of R h^{-1} Mpc.
where
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: array_like, optional Redshifts
array_like
Wave number in h Mpc^{-1}
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: array_like Linear matter power spectrum at the specified scale and redshift
Notes¶
P_cb = P_mm (D_cb / D_cbnu)^2, with the scale-dependent growth of
cb and of the total matter in the presence of massive neutrinos
from Eisenstein & Hu 1999 (see _cb_to_matter_ratio).
JAXNonLinearPerturbations
¶
JAXNonLinearPerturbations(background: JAXBackground, linearperturbations: Optional[JAXLinearPerturbations] = None, redshifts: Optional[ndarray] = None)
Class for perturbations cosmology using JAX, inheriting from Cosmology parent class.
Parameters:
-
(background¶JAXBackground) –A JAX background instance.
-
(linearperturbations¶Optional[JAXLinearPerturbations], default:None) –The linear perturbations the halofit correction is applied to. Defaults to
JAXLinearPerturbations(background, redshifts). -
(redshifts¶Optional[ndarray], default:None) –Default redshifts for
growth_rate, seeJAXLinearPerturbations. If not given, those oflinearperturbationsare used.
growth_factor
¶
Return the linear growth factor from the wrapped linear backend.
Parameters:
-
(zs¶ndarray) –One-dimensional array of redshifts at which to evaluate the growth factor.
-
(ks¶Optional[ndarray], default:None) –Optional wavenumbers accepted for interface compatibility. The JAX growth factor is scale-independent, so this argument is ignored.
Returns:
-
ndarray–jnp.ndarray: Growth-factor values from
linearperturbations.growth_factor(zs, ks), with one value per input redshift.
growth_rate
¶
Return the linear growth rate, see JAXLinearPerturbations.growth_rate.
Without zs, it is evaluated at the redshifts given at construction,
or else at those of linearperturbations.
halofit
¶
Compute the nonlinear matter power spectrum using the HaloFit model.
This function applies the HaloFit fitting formula to the linear matter power spectrum, providing a fitting model for the nonlinear regime.
Parameters¶
zs : array-like
Redshift or redshifts at which to evaluate the spectrum.
ks : array-like
Wavenumber or wavenumbers. k_hunit controls whether these are
interpreted in h Mpc^-1 or Mpc^-1.
hubble_units : bool, optional
Selects the power-spectrum conversion used by
:meth:JAXLinearPerturbations.matter_power_spectrum: when false,
the result is divided by h**3; when true, that conversion is
omitted. Defaults to false.
k_hunit : bool, optional
If true, ks are in h Mpc^-1; otherwise they are in
Mpc^-1. Defaults to false.
Returns¶
jax.Array
Nonlinear power spectrum. Singleton dimensions are removed by
squeeze; otherwise the result follows the redshift and
wavenumber dimensions.
matter_power_spectrum
¶
Compute the non-linear matter power spectrum.
This function is just a wrapper over several nonlinear power spectra.
nonlinear_matter_power_spectrum_limber_grid
¶
Compute the nonlinear matter power spectrum on a Limber grid.
This function computes the nonlinear matter power spectrum along lines of constant redshift, used for angular correlation function calculations.
Parameters¶
z_l (array_like): Line-of-sight redshifts. ks (array_like): Wavenumbers. zs (array_like): Redshifts for the power spectrum evaluation. ells (array_like): Multipole moments.
Returns¶
ndarray: The nonlinear matter power spectrum on the Limber grid.
matter_power_spectrum_cb
¶
Compute the non-linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Non-linear cb power spectrum at the specified scale and redshift
Notes¶
Writing P_mm = f_cb^2 P_cb + 2 f_cb f_nu P_cbnu + f_nu^2 P_nunu,
the non-linear cb spectrum is obtained by assuming that both spectra
involving neutrinos keep their linear value,
P_nunu^NL = P_nunu^L and P_cbnu^NL = P_cbnu^L, so that all the
non-linear power of the total matter comes from cb,
P_mm^NL - P_mm^L = f_cb^2 (P_cb^NL - P_cb^L):
with f_cb = Omega_cb0 / Omega_m0, P_mm^NL from halofit and
P_cb^L from JAXLinearPerturbations.matter_power_spectrum_cb.
It goes to P_cb^L on linear scales.
simps
¶
Compute the Simpson's rule integral of a function over [a, b].
This function implements Simpson's rule for numerical integration.
Parameters¶
f : callable Function to integrate. a : float Lower limit of integration. b : float Upper limit of integration. N : int, optional Number of subintervals (must be even). Default 128.
Returns¶
float or ndarray: The integral of f over [a, b].
Raises¶
ValueError If N is odd.
odeint
¶
Solve an ordinary differential equation using the Runge-Kutta 4th order method.
This function integrates the ODE dy/dt = fn(y, t) with initial condition y(t0) = y0.
Parameters¶
fn : callable The ODE function f(y, t). y0 : array_like Initial condition for y at t0. t : array_like Time points at which to evaluate the solution.
Returns¶
ndarray The solution y(t) at the specified time points.
interp
¶
Linearly interpolate or extrapolate tabulated one-dimensional data.
For each query value, the nearest tabulated point is selected and the
adjacent segment supplies the slope. Values outside the tabulated range are
linearly extrapolated using the first or last segment. At least three
strictly increasing xp values are required by the index clipping.
jax.vmap vectorizes over the leading dimension of x; xp and
fp are shared across those queries.
Parameters¶
x : array_like
Query points.
xp : array_like
One-dimensional, strictly increasing data coordinates (length at least 3).
fp : array_like
One-dimensional function values corresponding to xp; same length.
Returns¶
jax.Array
Interpolated or extrapolated values, vectorized over the leading axis
of x.
romb
¶
Romberg integration of a callable function or method.
Returns the integral of function (a function of one variable)
over the interval (a, b).
If show is 1, the triangular array of the intermediate results
will be printed. If vec_func is True (default is False), then
function is assumed to support vector arguments.
Parameters:
-
(function¶callable) –Function to be integrated.
-
(a¶float) –Lower limit of integration.
-
(b¶float) –Upper limit of integration.
-
(args¶optional[tuple], default:()) –Extra arguments to pass to function. Each element of
argswill be passed as a single argument tofunc. Default is to pass no extra arguments. -
(divmax¶optional[int], default:6) –Maximum order of extrapolation. Default is 10.
Returns:
-
results(float) –Result of the integration.
See Also¶
fixed_quad : Fixed-order Gaussian quadrature. quad : Adaptive quadrature using QUADPACK. dblquad : Double integrals. tplquad : Triple integrals. romb : Integrators for sampled data. simps : Integrators for sampled data. cumtrapz : Cumulative integration for sampled data. ode : ODE integrator. odeint : ODE integrator. References
.. [1] 'Romberg's method' http://en.wikipedia.org/wiki/Romberg%27s_method Examples
Integrate a gaussian from 0 to 1 and compare to the error function.
from scipy import integrate from scipy.special import erf gaussian = lambda x: 1/np.sqrt(np.pi) * jnp.exp(-x*2) result = integrate.romberg(gaussian, 0, 1, show=True) Romberg integration of
from [0, 1] :: Steps StepSize Results 1 1.000000 0.385872 2 0.500000 0.412631 0.421551 4 0.250000 0.419184 0.421368 0.421356 8 0.125000 0.420810 0.421352 0.421350 0.421350 16 0.062500 0.421215 0.421350 0.421350 0.421350 0.421350 32 0.031250 0.421317 0.421350 0.421350 0.421350 0.421350 0.421350 The final result is 0.421350396475 after 33 function evaluations. print("%g %g" % (2 result, erf(1))) 0.842701 0.842701
Pkl_interp
¶
Interpolate positive power-spectrum values on a two-dimensional grid.
Cubic interpolation is performed in log10(k) and redshift, on
log10(Pk) values, then transformed back to power-spectrum values.
Consequently, all entries of ks and Pk must be positive. The
leading two dimensions of Pk correspond to ks and zs; query
coordinates k_l and z_l are broadcast according to interpax's
two-dimensional interpolation rules.
Parameters¶
k_l : array_like
Line-of-sight wavenumbers.
z_l : array_like
Line-of-sight redshifts.
ks : array_like
Wavenumbers grid.
zs : array_like
Redshifts grid.
Pk : array_like
Strictly positive power-spectrum values on the (ks, zs) grid.
Returns¶
jax.Array Interpolated positive power-spectrum values.
As_to_sigma8_max_precision
¶
Compute the emulated conversion As -> sigma8, using the most accurate expression.
Parameters:
-
(As¶float) –10^9 times the amplitude of the primordial P(k)
-
(Om¶float) –The z=0 total matter density parameter, Om
-
(Ob¶float) –The z=0 baryonic density parameter, Ob
-
(h¶float) –Hubble constant, H0, divided by 100 km/s/Mpc
-
(ns¶float) –Spectral tilt of primordial power spectrum
-
(mnu¶float) –Sum of neutrino masses [eV / c^2]
-
(w0¶float) –Time independent part of the dark energy EoS
-
(wa¶float) –Time dependent part of the dark energy EoS
Returns:
-
sigma8(float) –Root-mean-square density fluctuation when the linearly evolved field is smoothed with a top-hat filter of radius 8 Mpc/h
cosmopower_jax_cosmology
¶
CosmoPower-JAX emulators for the linear and nonlinear matter power spectrum.
Uses cosmopower_jax (rather than the TensorFlow-based cosmopower) for fast
JAX-accelerated predictions. Covers LCDM, wCDM and w0waCDM, plus curvature and
running-spectral-index extensions, each over neutrino configurations N_mnu = 0-3.
Every cosmology exposes Linear and NonLinear inner classes; the baseline
models additionally offer halofit nonlinear variants. Each provides both the
total-matter spectrum (matter_power_spectrum) and the CDM+baryon spectrum
(matter_power_spectrum_cb, built at construction from the paired cb emulator),
along with sigma8, fsigma8, growth_factor, growth_factor_cb and
growth_rate, and validates inputs against CP_EMULATOR_BOUNDS. The classes
share one implementation (the private _CosmoPowerLinear/_CosmoPowerNonLinear
bases), parameterised by a per-cosmology _ModelSpec (emulator file prefix,
supported N_mnu, extra parameters).
CosmoPowerJAXw0waCDMPerturbations
¶
Class for w0waCDM cosmology perturbations using CosmoPower-JAX emulators.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinearHalofit
¶
NonLinearHalofit(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinearHalofit[NonLinearHalofit]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinearHalofit
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinearHalofit href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCDMPerturbations.NonLinearHalofit"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using halofit (Takahashi 2012).
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXwCDMPerturbations
¶
Class for wCDM cosmology perturbations using CosmoPower-JAX emulators.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinearHalofit
¶
NonLinearHalofit(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinearHalofit[NonLinearHalofit]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinearHalofit
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinearHalofit href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXwCDMPerturbations.NonLinearHalofit"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using halofit (Takahashi 2012).
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXLCDMPerturbations
¶
Class for LCDM cosmology perturbations using CosmoPower-JAX emulators.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinearHalofit
¶
NonLinearHalofit(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinearHalofit[NonLinearHalofit]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinearHalofit
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinearHalofit href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMPerturbations.NonLinearHalofit"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using halofit (Takahashi 2012).
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXLCDMCurvaturePerturbations
¶
Class for LCDM+curvature cosmology perturbations using CosmoPower-JAX.
Emulators cover spatial curvature Omega_k0.
Neutrino configuration is selected by background.N_mnu: 0 (massless), 1 (one massive), 3 (three degenerate).
The k-mode grid is read from each emulator (.modes); inputs are
validated against :data:CP_EMULATOR_BOUNDS.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMCurvaturePerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXw0waCurvaturePerturbations
¶
Class for w0waCDM+curvature cosmology perturbations using CosmoPower-JAX.
Emulators cover spatial curvature Omega_k0 together with a w0waCDM dark energy background (free w0, wa).
Neutrino configuration is selected by background.N_mnu: 0 (massless), 1 (one massive), 3 (three degenerate).
The k-mode grid is read from each emulator (.modes); inputs are
validated against :data:CP_EMULATOR_BOUNDS.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waCurvaturePerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXLCDMRunningIndexPerturbations
¶
Class for LCDM+running spectral index cosmology perturbations using CosmoPower-JAX.
Emulators cover running spectral index alpha_s.
Neutrino configuration is selected by background.N_mnu: 0 (massless), 1 (one massive), 3 (three degenerate).
The k-mode grid is read from each emulator (.modes); inputs are
validated against :data:CP_EMULATOR_BOUNDS.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXLCDMRunningIndexPerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
CosmoPowerJAXw0waRunningIndexPerturbations
¶
Class for w0waCDM+running spectral index cosmology perturbations using CosmoPower-JAX.
Emulators cover running spectral index alpha_s together with a w0waCDM dark energy background (free w0, wa).
Neutrino configuration is selected by background.N_mnu: 0 (massless), 1 (one massive), 3 (three degenerate).
The k-mode grid is read from each emulator (.modes); inputs are
validated against :data:CP_EMULATOR_BOUNDS.
Linear
¶
Linear(background: Background, redshifts: ndarray)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.Linear[Linear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear[_CosmoPowerLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.Linear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.Linear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.Linear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Linear matter power spectrum.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
NonLinear
¶
NonLinear(background: Background, linearperturbations: Perturbations, redshifts: ndarray, log10TAGN: Optional[float] = None)
flowchart TD
cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.NonLinear[NonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear[_CosmoPowerNonLinear]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations[_CosmoPowerPerturbations]
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear --> cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.NonLinear
cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations --> cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear
click cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.NonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology.CosmoPowerJAXw0waRunningIndexPerturbations.NonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerNonLinear"
click cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations href "" "cloelib.cosmology.cosmopower_jax_cosmology._CosmoPowerPerturbations"
Nonlinear matter power spectrum using HMcode2020.
log10TAGN controls the HMcode2020 baryonic feedback; the halofit
prescription is dark-matter-only, so there it is accepted for interface
compatibility but ignored.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
growth_factor_cb
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = fsigma8 / sigma8.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts, interpolated on the grid the emulator was evaluated at. Defaults to that grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0.
Returns:
-
float(float) –The rms matter fluctuation sigma8 at z=0.
emulator_data
¶
load_pk_emulator
¶
load_sigma_emulator
¶
check_emulator_bounds
¶
HMcode2020Emu_cosmology
¶
Implementation of Background and Perturbation cosmology using HMcode2020Emu.
HMemuLinearPerturbations
¶
HMemuLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using HMemu, compatibly with the Perturbations protocol.
matter_power_spectrum
¶
matter_power_spectrum(zs, ks, hubble_units=False, k_hunit=False) -> ndarray
Compute the linear matter power spectrum.
Parameters:
-
(ks¶ndarray) –Wave number in h Mpc^{-1}
-
(zs¶ndarray) –redshifts
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
matter_power_spectrum_cb(zs, ks, hubble_units=False, k_hunit=False) -> ndarray
Compute the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters:
-
(ks¶ndarray) –Wave number in h Mpc^{-1}
-
(zs¶ndarray) –redshifts
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_factor_cb
¶
Calculate the growth factor for cb for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[array_like], default:None) –Redshifts at which to calculate the growth rate. Defaults to the redshift grid of this instance.
-
(ks¶Optional[array_like], default:None) –Wavenumbers at which to calculate the growth rate. The HMcode2020Emu growth rate is scale independent, so these only set the shape of the output.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
HMemuNonLinearPerturbations
¶
HMemuNonLinearPerturbations(background: Background, linearperturbations: WithLinearSpectrumGrid, redshifts: ndarray, log10TAGN: Optional[float] = None)
Class for non linear perturbations cosmology using HMemu, compatibly with the Perturbations protocol.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_factor_cb
¶
Calculate the growth factor for cb for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[array_like], default:None) –Redshifts at which to calculate the growth rate. Defaults to the redshift grid of this instance.
-
(ks¶Optional[array_like], default:None) –Wavenumbers at which to calculate the growth rate. The HMcode2020Emu growth rate is scale independent, so these only set the shape of the output.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
HMcode2020BaryonBoostMixin
¶
flowchart TD
cloelib.cosmology.HMcode2020Emu_cosmology.HMcode2020BaryonBoostMixin[HMcode2020BaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin[BaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin --> cloelib.cosmology.HMcode2020Emu_cosmology.HMcode2020BaryonBoostMixin
click cloelib.cosmology.HMcode2020Emu_cosmology.HMcode2020BaryonBoostMixin href "" "cloelib.cosmology.HMcode2020Emu_cosmology.HMcode2020BaryonBoostMixin"
click cloelib.cosmology.cosmology.BaryonBoostMixin href "" "cloelib.cosmology.cosmology.BaryonBoostMixin"
Mixin providing baryonic suppression via an HMcode2020-computed P_baryon/P_dmo ratio.
Can be combined with any nonlinear perturbations class (not just HMcode2020emu)::
class MyPert(HMcode2020BaryonBoostMixin, HMemuNonLinearPerturbations):
def __init__(self, background, linearperturbations, redshifts, log10TAGN=7.8):
HMemuNonLinearPerturbations.__init__(
self, background, linearperturbations, redshifts
)
HMcode2020BaryonBoostMixin.__init__(self, log10TAGN=log10TAGN)
Or use :func:~cloelib.cosmology.cosmology.with_baryon_boost.
.. note::
__init__ must be called after the base NonLinear __init__
because it reads self.background and self.z.
Scales below the nonlinear emulator k range get suppression = 1.
Runs the emulator twice (DMO and baryonic) and stores
B(z, k) as a bivariate spline in self._baryon_ratio_interp.
Call this after the base NonLinear __init__ so that
self.background and self.z are already set. The emulator
parameters are built from self.background rather than taken from
the base class, so the HMcode2020 baryonic boost can be applied on top
of a different nonlinear prescription.
Parameters¶
log10TAGN: log₁₀ of the AGN heating temperature in Kelvin. Typical range: 7.6 (weak) – 8.3 (strong feedback).
baryon_k_range
property
¶
Wavenumbers in 1/Mpc over which baryonic_suppression is emulated.
Below the range the suppression is set to 1; above it the spline holds its boundary value rather than extrapolating.
baryonic_suppression
¶
Return B(z, k) = P_baryon(z, k) / P_dmo(z, k).
Parameters¶
zs : array_like Redshifts. ks : array_like Wavenumbers. By default in 1/Mpc; pass k_hunit=True for h/Mpc. k_hunit : bool If True, convert ks from h/Mpc to 1/Mpc before evaluating.
Returns¶
np.ndarray Baryonic suppression factor, shape (nz, nk). Returns 1.0 for scales below the nonlinear emulator k range.
mochi_class_cosmology
¶
Implementation of Background and Perturbation cosmology using MOCHI_CLASS (https://github.com/mcataneo/mochi_class_public).
mochiCLASSBackground
¶
mochiCLASSBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, mg_stable_basis_on: bool, stable_MG_dict: dict, mg_background_model: str, gamma_MG: float, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0, **kwargs)
A wrapper for MOCHI_CLASS background cosmological calculations.
Parameters:
-
(H0¶float) –Hubble parameter at z=0 in km/s/Mpc.
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k).
-
(mnu¶Union[float, Sequence[float], ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter (not directly used in CLASS, but kept for protocol compliance).
-
(mg_stable_basis_on¶bool) –Flag to indicate if stable basis for modified gravity is used.
-
(stable_MG_dict¶dict) –Dictionary of stable basis parameters lna_smg, Delta_M2, D_kin, cs2 and alpha_B0 for input into mochi_class.
-
(mg_background_model¶str) –Desired background expansion model ('lcdm', 'wowa') for modified gravity in mochi_class.
-
(N_mnu¶int) –Number of massive neutrino species.
-
(N_ur¶Optional[float], default:None) –Effective number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
N_ur
property
¶
Effective number of ultra-relativistic species.
If the user gave one, return it; otherwise infer from other parameters such that N_eff = 3.044 for the standard model of cosmology.
N_eff
property
¶
Return the effective number of relativistic species.
Assumes a standard value of T_ncdm = 0.71611 K for neutrinos.
hubble_parameter
¶
comoving_distance
¶
comoving_distance(zs: ndarray) -> ndarray
Return the comoving distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Comoving distance values.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Transverse comoving distance values.
angular_diameter_distance
¶
angular_diameter_distance(zs: ndarray) -> ndarray
Return the angular diameter distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Angular diameter distance values.
Omega_m
¶
Omega_m(zs: Union[ndarray, float]) -> ndarray
Return the matter density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values.
Omega_cb
¶
Omega_cb(zs: ndarray) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values (no neutrinos).
Omega_b
¶
Omega_b(zs: ndarray) -> ndarray
Return the baryon density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values.
Om_smg
¶
Om_smg(zs: ndarray) -> ndarray
Calculate dark energy density fraction Om_smg(z) (exactly, the ratio of quantities defined by Class as index_bg_rho_smg and index_bg_rho_crit in the background module)
requires mochi_class v3.3.3 - 12/11/2025
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns¶
np.ndarray dark energy density fraction Om_smg(z)
get_background
¶
Return all background quantities
Return a dictionary of background quantities at all times. The name and list of quantities in the returned dictionary are defined in CLASS, in background_output_titles() and background_output_data(). The keys of the dictionary refer to redshift 'z', proper time 'proper time [Gyr]', conformal time 'conf. time [Mpc]', and many quantities such as the Hubble rate, distances, densities, pressures, or growth factors. For each key, the dictionary contains an array of values corresponding to each sampled value of time.
This function works for whatever request in the 'output' field, and even if 'output' was not passed or left blank.
Parameters¶
None
Returns¶
background : dict Dictionary of all background quantities at each time
mochiCLASSLinearPerturbations
¶
mochiCLASSLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using MOCHI_CLASS, inheriting from Perturbations parent class.
matter_power_spectrum
¶
Calculate the CLASS linear matter power spectrum.
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
Returns:¶
np.ndarray The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the scale-dependent growth rate f(z, k).
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers at which to evaluate the growth rate.
Returns:¶
np.ndarray Growth rate f(z) at k = 1 Mpc^-1 with shape (nz,) if ks is None, and f(z, k) with shape (nz, nk) otherwise.
mochiCLASSNonLinearPerturbations
¶
mochiCLASSNonLinearPerturbations(background: mochiCLASSBackground, linearperturbations: Optional[Perturbations], redshifts: ndarray, nonlinear_model: Optional[str] = None, hmcode_version: Optional[str] = None, log10TAGN: Optional[float] = None)
Class for non-linear perturbations cosmology using MOCHI_CLASS, inheriting from Perturbations parent class.
Parameters:
-
(background¶mochiCLASSBackground) –Background cosmology object.
-
(linearperturbations¶Optional[Perturbations]) –Linear perturbations object (CLASS computes the nonlinear corrections internally). Only needed for the cb x matter cross spectrum, e.g.
mochiCLASSLinearPerturbationson the same background. -
(redshifts¶ndarray) –Array of redshifts for the calculations.
-
(nonlinear_model¶Optional[str], default:None) –The nonlinear model to use. Defaults to None (no nonlinear), or "hmcode" if
log10TAGNis given. -
(hmcode_version¶Optional[str], default:None) –The HMcode version to use. Defaults to None, or "2020_baryonic_feedback" if
log10TAGNis given. -
(log10TAGN¶Optional[float], default:None) –HMcode2020 baryonic feedback parameter log10(T_AGN/K), passed to CLASS as
log10T_heat_hmcode. Defaults to None (no baryonic feedback, or the CLASS default for "2020_baryonic_feedback").
Raises:
-
ValueError–If
log10TAGNis given with a nonlinear model or HMcode version that ignores it, or withbackground.mg_stable_basis_on.
matter_power_spectrum
¶
matter_power_spectrum(zs, ks, hubble_units=False, k_hunit=False) -> ndarray
Calculate the CLASS non-linear matter power spectrum.
Parameters:
-
(zs¶ndarray) –redshifts
-
(ks¶ndarray) –wavenumber
-
(hubble_units¶Optional[bool], default:False) –Flag to specify if output in h units
-
(k_hunit¶Optional[bool], default:False) –Flag to specify if wavenumber in h units
Returns:
-
pk(ndarray) –Non-linear matter power spectrum at the specified scale
-
ndarray–and redshift
matter_power_spectrum_cb
¶
Calculate the CLASS non-linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
Returns:
-
ndarray–The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the scale-dependent growth rate f(z, k).
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts at which to evaluate the growth rate. Defaults to
self.z. -
(ks¶Optional[ndarray], default:None) –Wavenumbers at which to evaluate the growth rate.
Returns:¶
np.ndarray Growth rate f(z) at k = 1 Mpc^-1 with shape (nz,) if ks is None, and f(z, k) with shape (nz, nk) otherwise.
EE2_cosmology
¶
Implementation of Background and Perturbation cosmology using EuclidEmulator2.
LinearPerturbationsWithK
¶
flowchart TD
cloelib.cosmology.EE2_cosmology.LinearPerturbationsWithK[LinearPerturbationsWithK]
cloelib.cosmology.cosmology.Perturbations[Perturbations]
cloelib.cosmology.cosmology.WithWavenumberGrid[WithWavenumberGrid]
cloelib.cosmology.cosmology.Perturbations --> cloelib.cosmology.EE2_cosmology.LinearPerturbationsWithK
cloelib.cosmology.cosmology.WithWavenumberGrid --> cloelib.cosmology.EE2_cosmology.LinearPerturbationsWithK
click cloelib.cosmology.EE2_cosmology.LinearPerturbationsWithK href "" "cloelib.cosmology.EE2_cosmology.LinearPerturbationsWithK"
click cloelib.cosmology.cosmology.Perturbations href "" "cloelib.cosmology.cosmology.Perturbations"
click cloelib.cosmology.cosmology.WithWavenumberGrid href "" "cloelib.cosmology.cosmology.WithWavenumberGrid"
A Perturbations implementation that also exposes its .k grid.
EE2NonLinearPerturbations needs both the full Perturbations
interface (to call matter_power_spectrum/growth_factor/etc. on its
linearperturbations) and the wavenumber grid that instance was built
on, which Perturbations deliberately omits.
growth_factor
¶
Evaluate the dimensionless growth factor at redshifts and wavenumbers.
Parameters:
-
(zs¶T) –One-dimensional NumPy or JAX array of redshifts, with shape
(nz,). -
(ks¶T) –One-dimensional NumPy or JAX array of wavenumbers in
1/Mpc, with shape(nk,).
Returns:
-
T(T) –NumPy or JAX array of growth-factor values. Scale-dependent
-
T–backends generally return shape
(nz, nk); scale-independent -
T–backends may return shape
(nz,). The growth factor is -
T–conventionally normalized to unity at redshift zero. Consult the
-
T–concrete backend when relying on a particular shape or
-
T–normalization convention.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[T], default:None) –One-dimensional NumPy or JAX array of redshifts, with shape
(nz,). IfNone, implementations use the redshift grid they were built on; implementations without a default grid may raiseValueError. -
(ks¶Optional[T], default:None) –One-dimensional NumPy or JAX array of wavenumbers in
1/Mpc, with shape(nk,). IfNone, return the growth rate as a function of redshift only.
Returns:
-
T(T) –NumPy or JAX array of growth-rate values. With
ks=None, the -
T–shape is
(nz,); with wavenumbers supplied, the shape is -
T–(nz, nk). Scale-independent growth rates are broadcast along -
T–the wavenumber axis.
matter_power_spectrum
¶
Retrieve the matter power spectrum.
matter_power_spectrum_cb
¶
Retrieves matter power spectrum of cold dark matter + baryons (no neutrinos).
EE2NonLinearPerturbations
¶
EE2NonLinearPerturbations(background: Background, linearperturbations: LinearPerturbationsWithK, redshifts: ndarray)
Class for nonlinear perturbations using EE2, compatible with the Perturbations protocol.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
We use here the growth from the fluctuations without baryons.
Parameters:¶
zs : array_like Redshifts at which to calculate the growth factor. ks : array_like Wavenumbers at which to calculate the growth factor.
Returns:¶
np.ndarray The growth factor as a function of redshift and wavenumber.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
We use here the growth from the fluctuations without baryons.
Parameters:¶
zs : Optional[np.ndarray]
Redshifts at which to evaluate the growth rate. Defaults to self.z.
ks : Optional[np.ndarray]
Wavenumbers at which to evaluate the growth rate.
Returns:¶
np.ndarray The linear growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
baccoemu_cosmology
¶
Implementation of Background and Perturbation cosmology using BACCOemu (similarly to what done with HMcode2020emu).
BACCOemuLinearPerturbations
¶
BACCOemuLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using BACCOemu, compatibly with the Perturbations protocol.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
Calculate the total (dark matter + baryons + neutrinos) growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_rate
¶
Calculate the total (dark matter + baryons + neutrinos) linear growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[array_like], default:None) –Redshifts at which to calculate the growth rate. Defaults to
self.z. -
(ks¶array_like, default:None) –Wavenumbers at which to calculate the growth rate. Required, since the BACCOemu growth rate is scale dependent.
Returns:
-
ndarray–The linear growth rate as a function of redshift and wavenumber.
growth_factor_cb
¶
Calculate the cold (dark matter + baryons) growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The growth factor as a function of redshift and wavenumber.
growth_rate_cb
¶
Calculate the cold (dark matter + baryons) linear growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The linear cold growth rate as a function of redshift and wavenumber.
sigma8_0
¶
Calculate the total (dark matter + baryons + neutrinos) linear sigma8 value for the current cosmology.
Returns:¶
float The sigma8 value.
sigma12_0
¶
Calculate the total (dark matter + baryons + neutrinos) linear sigma12 value for the current cosmology.
Returns:¶
float The sigma8 value.
BACCOemuNonLinearPerturbations
¶
BACCOemuNonLinearPerturbations(background: Background, linearperturbations: Perturbations, redshifts: ndarray, nonlinear_model_name: str = 'Arico2023', baryonic_boost: Optional[str] = None, baryonic_model_name: str = 'Burger2025', M_c: Optional[float] = None, eta: Optional[float] = None, beta: Optional[float] = None, M1_z0_cen: Optional[float] = None, theta_out: Optional[float] = None, theta_inn: Optional[float] = None, M_inn: Optional[float] = None)
Class for non linear perturbations cosmology using BACCOemu, compatibly with the Perturbations protocol.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
growth_factor
¶
Calculate the total (dark matter + baryons + neutrinos) linear growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The linear growth factor as a function of redshift and wavenumber.
growth_rate
¶
Calculate the total (dark matter + baryons + neutrinos) linear growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[array_like], default:None) –Redshifts at which to calculate the growth rate. Defaults to
self.z. -
(ks¶array_like, default:None) –Wavenumbers at which to calculate the growth rate. Required, since the BACCOemu growth rate is scale dependent.
Returns:
-
ndarray–The linear growth rate as a function of redshift and wavenumber.
growth_factor_cb
¶
Calculate the cold (dark matter + baryons) linear growth factor for given redshifts and wavenumbers.
and normalizes as for \(D(z)/D(0)\).
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The linear growth factor as a function of redshift and wavenumber.
growth_rate_cb
¶
Calculate the cold (dark matter + baryons) linear growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶array_like) –Redshifts at which to calculate the growth factor.
-
(ks¶array_like) –Wavenumbers at which to calculate the growth factor.
Returns:
-
ndarray–The linear cold growth rate as a function of redshift and wavenumber.
sigma8_0
¶
Calculate the total (dark matter + baryons + neutrinos) linear sigma8 value for the current cosmology.
Returns:¶
float The sigma8 value.
sigma12_0
¶
Calculate the total (dark matter + baryons + neutrinos) linear sigma12 value for the current cosmology.
Returns:¶
float The sigma8 value.
BACCOemuBaryonBoostMixin
¶
BACCOemuBaryonBoostMixin(M_c: Optional[float], eta: Optional[float], beta: Optional[float], M1_z0_cen: Optional[float], theta_inn: Optional[float], nonlinear_model_name: str = 'Arico2023', baryonic_model_name: str = 'Burger2025', theta_out: Optional[float] = None, M_inn: Optional[float] = None)
flowchart TD
cloelib.cosmology.baccoemu_cosmology.BACCOemuBaryonBoostMixin[BACCOemuBaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin[BaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin --> cloelib.cosmology.baccoemu_cosmology.BACCOemuBaryonBoostMixin
click cloelib.cosmology.baccoemu_cosmology.BACCOemuBaryonBoostMixin href "" "cloelib.cosmology.baccoemu_cosmology.BACCOemuBaryonBoostMixin"
click cloelib.cosmology.cosmology.BaryonBoostMixin href "" "cloelib.cosmology.cosmology.BaryonBoostMixin"
Mixin providing baryonic suppression via a BACCOemu-computed baryonic boost.
Can be combined with any nonlinear perturbations class (not just BACCOemu)
via :func:~cloelib.cosmology.cosmology.with_baryon_boost::
MyPert = with_baryon_boost(SomeNonLinearPerturbations, BACCOemuBaryonBoostMixin)
pert = MyPert(
background, linear_pert, redshifts,
baryon_kwargs=dict(nonlinear_model_name="Arico2023",
baryonic_model_name="Burger2025"),
)
.. note::
__init__ must be called after the base NonLinear __init__
because it reads self.background and self.z which are set there.
.. warning::
BACCOemuNonLinearPerturbations composed with this mixin does not
reproduce BACCOemuNonLinearPerturbations(baryonic_boost=...) exactly.
The two differ outside the baryonic emulator's k range, because this
mixin extends the boost with its own power law (see __init__) while
the native path leaves the extension to BACCOemu. Inside the emulated
range they agree to ~1e-4. Prefer the native argument when the nonlinear
and baryonic backends are both BACCOemu; this mixin exists to put the
BACCOemu boost on top of a different nonlinear backend.
Calls get_baryonic_boost and stores
B(z, k) as a bivariate spline in self._baryon_ratio_interp.
Call this after NonLinearPerturbations.__init__ so
that self.background and self.z are set.
The mixin selects its own BACCOemu instance and builds the emulator
parameters from self.background rather than reusing the base
class's, so the BACCOemu baryonic boost can be applied on top of a
different nonlinear prescription.
The baryonification parameters carry no default values: BACCOemu
provides none, and picking some here would present one arbitrary choice as
"the BACCOemu prediction". theta_out and M_inn are the exception —
they exist only in the Arico2021 model and are ignored by
Burger2025, so they default to None.
Parameters¶
M_c, eta, beta, M1_z0_cen, theta_inn:
Baryonification parameters. Required; BACCOemu has no defaults for them.
nonlinear_model_name:
BACCOemu nonlinear model used to select the emulator instance,
e.g. "Arico2023" or "Angulo2021".
baryonic_model_name:
BACCOemu baryonic model, e.g. "Burger2025" or "Arico2021".
theta_out, M_inn:
Used only by Arico2021; leave at None for Burger2025.
baryon_k_range
property
¶
Wavenumbers in 1/Mpc over which baryonic_suppression is emulated.
Outside this range the returned suppression comes from the power-law extrapolation applied at construction, not from the emulator itself.
baryonic_suppression
¶
Return B(z, k) = P_baryon(z, k) / P_dmo(z, k).
Parameters¶
zs : array_like Redshifts. ks : array_like Wavenumbers. By default in 1/Mpc; pass k_hunit=True for h/Mpc. k_hunit : bool If True, convert ks from h/Mpc to 1/Mpc before evaluating.
Returns¶
np.ndarray Baryonic suppression factor, shape (nz, nk).
emantis_cosmology
¶
Implementation of nonlinear Perturbation cosmology for f(R) gravity using the e-MANTIS emulator.
EmantisFofrNonLinearPerturbations
¶
EmantisFofrNonLinearPerturbations(background: Background, linearperturbations: Perturbations, nonlinearperturbations_lcdm: Perturbations, fR0: float, redshifts: ndarray, verbose: bool = False, emu_version: int = 2, extrapolate_cosmo: bool = True)
Nonlinear perturbations in f(R) gravity.
The nonlinear matter power spectrum boost, i.e. P_f(R)(k) / P_LCDM(k), is computed with the e-MANTIS emulator. The boost is then combined with an external nonlinear LCDM matter power spectrum prediction in order to obtain the full nonlinear matter power spectrum in f(R) gravity.
Parameters¶
background : Background A background cosmology object, providing all the standard cosmological parameters. linearperturbations : Perturbations A linear perturbations object, providing linear perturbations in f(R) gravity. nonlinearperturbations_lcdm : Perturbations A nonlinear perturbations object, providing the nonlinear matter power spectrum in LCDM. fR0 : float The modified gravity parameter fR0. redshifts : np.ndarray An array of redshifts used to compute the matter power spectrum. verbose : float, optional (default=False) Activate or not verbose output from the emantis emulator. emu_version : int, optional (default=2) The version of the emantis emulator to use. Version 2 (the default) has an extended cosmological parameter and redshift range. extrapolate_cosmo : bool optional (default=True) Activate or not constant extrapolation of cosmological parameters. The extrapolation is done only for the LCDM cosmological parameters. There is no extrapolation for fR0.
cb_cross_prescription
property
¶
cb x matter cross spectrum prescription, that of the LCDM baseline.
The same boost rescales the baseline total matter and cb spectra, so
the cross spectrum follows the baseline's prescription (None if the
baseline declares none).
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
Compute the nonlinear CDM+baryons power spectrum.
Parameters¶
zs: numpy.ndarray Redshift values.
numpy.ndarray
Wavenumber values in units of h/Mpc.
Returns¶
pk: numpy.ndarray Nonlinear CDM+baryons power spectrum at the input redshift and wavenumber values.
Raises¶
ValueError If the cosmology has massive neutrinos.
growth_factor
¶
growth_rate
¶
Compute the growth rate f(z, k) for given redshifts and wavenumbers.
Parameters:¶
zs : Optional[array_like]
Redshifts at which to calculate the growth rate. Defaults to self.z.
ks : Optional[array_like]
Wavenumbers at which to calculate the growth rate.
Returns:¶
np.ndarray The linear growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
FlamingoBaryonResponseEmulator_cosmology
¶
Implementation of baryon correction of the matter power spectrum from FlamingoBaryonResponseEmulator on top of CAMB.
Design¶
FlamingoBaryonBoostMixin — concrete subclass of the abstract
BaryonBoostMixin (defined in cosmology.py). Provides
baryonic_suppression and the FLAMINGO-specific
baryonic_suppression_with_variance by calling the external
FlamingoBaryonResponseEmulator. Backend-agnostic: does not import CAMB.
CAMBNonLinearFLAMINGOBaryonicPerturbations inherits from both:
FlamingoBaryonBoostMixin— baryonic correction via FRE.CAMBNonLinearPerturbations— all CAMB setup and methods (matter_power_spectrum,growth_rate,growth_factor,sigma8_0, …).
Notes¶
- Adapted from FlamingoBaryonResponseEmulator/flamingo_response_emulator.py
FlamingoBaryonBoostMixin
¶
flowchart TD
cloelib.cosmology.FlamingoBaryonResponseEmulator_cosmology.FlamingoBaryonBoostMixin[FlamingoBaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin[BaryonBoostMixin]
cloelib.cosmology.cosmology.BaryonBoostMixin --> cloelib.cosmology.FlamingoBaryonResponseEmulator_cosmology.FlamingoBaryonBoostMixin
click cloelib.cosmology.FlamingoBaryonResponseEmulator_cosmology.FlamingoBaryonBoostMixin href "" "cloelib.cosmology.FlamingoBaryonResponseEmulator_cosmology.FlamingoBaryonBoostMixin"
click cloelib.cosmology.cosmology.BaryonBoostMixin href "" "cloelib.cosmology.cosmology.BaryonBoostMixin"
Concrete baryonic-boost mixin for the FlamingoBaryonResponseEmulator.
Implements baryonic_suppression (and the FLAMINGO-specific
baryonic_suppression_with_variance). Can be combined with any
nonlinear perturbations class::
class MyPert(FlamingoBaryonBoostMixin, SomeNonLinearPerturbations):
def __init__(self, background, ..., fgas_sigma=0, Mstar_sigma=0, jet_fraction=0):
SomeNonLinearPerturbations.__init__(self, background, ...)
FlamingoBaryonBoostMixin.__init__(self, fgas_sigma, Mstar_sigma, jet_fraction)
def matter_power_spectrum(self, zs, ks, **kwargs):
return SomeNonLinearPerturbations.matter_power_spectrum(self, zs, ks, **kwargs) * self.baryonic_suppression(zs, ks, k_hunit=kwargs.get("k_hunit", False))
Or use the :func:~cloelib.cosmology.cosmology.with_baryon_boost factory for
zero-boilerplate class creation.
Call this after the base NonLinear perturbations __init__
so that self.background is already set.
The three parameters are required and carry no defaults. Every value is physically valid here, so a default would silently stand in for a real choice instead of raising, and would present one feedback scenario as "the FLAMINGO prediction".
Parameters¶
fgas_sigma:
Offset from calibration gas fraction, in σ. Training range
[-8, +2] for jet_fraction=0; [-4, 0] for jet_fraction=1.
Mstar_sigma:
Offset from stellar mass function calibration, in σ.
Training range [-1, 0].
jet_fraction:
AGN jet energy fraction (0 = pure thermal, 1 = pure jets).
baryon_k_range
property
¶
Wavenumbers in 1/Mpc over which baryonic_suppression is emulated.
Above the upper bound the response is clamped to its value at the maximum trained wavenumber.
baryonic_suppression
¶
Return the FLAMINGO baryonic suppression factor P_hydro/P_DMO.
For z > 3 (outside FRE training range) the correction is 1. For k > 10^1.5 h/Mpc the correction is clamped to its value at the maximum trained wavenumber.
Parameters¶
zs:
Redshifts, shape (nz,).
ks:
Wavenumbers, shape (nk,).
k_hunit:
If True ks are in h/Mpc; otherwise in 1/Mpc.
Returns¶
np.ndarray, shape (nz, nk)
baryonic_suppression_with_variance
¶
baryonic_suppression_with_variance(zs: ndarray, ks: ndarray, k_hunit: bool = False) -> tuple[ndarray, ndarray]
Return the FLAMINGO suppression factor and its emulator variance.
For z > 3 the response is 1 and variance is 0. For k > 10^1.5 h/Mpc the values are clamped to the maximum trained k.
Parameters¶
zs:
Redshifts, shape (nz,).
ks:
Wavenumbers, shape (nk,).
k_hunit:
If True ks are in h/Mpc; otherwise in 1/Mpc.
Returns¶
response : np.ndarray, shape (nz, nk) variance : np.ndarray, shape (nz, nk)
hi_class_cosmology
¶
Implementation of Background and Perturbation cosmology using hi_class.
hi_classBackground
¶
hi_classBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, gamma_MG: float, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0, params_smg: Optional[dict] = None, **kwargs)
A wrapper for hi_class background cosmological calculations.
Parameters:
-
(H0¶float) –Hubble parameter at z=0 in km/s/Mpc.
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k).
-
(mnu¶Union[float, Sequence[float], ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter (not directly used in hi_class, but kept for protocol compliance).
-
(N_mnu¶int) –Number of massive neutrino species.
-
(N_ur¶Optional[float], default:None) –Effective number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
-
(params_smg¶Optional[dict], default:None) –Modified gravity parameters, or other extra parameters not passed by default.
N_ur
property
¶
Effective number of ultra-relativistic species.
If the user gave one, return it; otherwise infer from other parameters such that N_eff = 3.044 for the standard model of cosmology.
N_eff
property
¶
Return the effective number of relativistic species.
Assumes a standard value of T_ncdm = 0.71611 K for neutrinos.
hubble_parameter
¶
comoving_distance
¶
comoving_distance(zs: ndarray) -> ndarray
Return the comoving distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Comoving distance values.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Transverse comoving distance values.
angular_diameter_distance
¶
angular_diameter_distance(zs: ndarray) -> ndarray
Return the angular diameter distance as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Angular diameter distance values.
Omega_cb
¶
Omega_cb(zs: ndarray) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values (no neutrinos).
Omega_m
¶
Omega_m(zs: Union[ndarray, float]) -> ndarray
Return the matter density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values.
Omega_b
¶
Omega_b(zs: ndarray) -> ndarray
Return the baryon density as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values.
get_background
¶
Return all background quantities
Return a dictionary of background quantities at all times. The name and list of quantities in the returned dictionary are defined in hi_class, in background_output_titles() and background_output_data(). The keys of the dictionary refer to redshift 'z', proper time 'proper time [Gyr]', conformal time 'conf. time [Mpc]', and many quantities such as the Hubble rate, distances, densities, pressures, or growth factors. For each key, the dictionary contains an array of values corresponding to each sampled value of time.
This function works for whatever request in the 'output' field, and even if 'output' was not passed or left blank.
Parameters¶
None
Returns¶
background : dict Dictionary of all background quantities at each time
hi_classLinearPerturbations
¶
hi_classLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using hi_class, inheriting from Perturbations parent class.
matter_power_spectrum
¶
Calculate the hi_class linear matter power spectrum.
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
Returns:¶
np.ndarray The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z, k). The standard expression for scale-independent f assumes LCDM and isn't valid in modified gravity. Instead, we use the scale-dependent growth rate, evaluated at large k (1 Mpc^-1) if no wavenumbers are given.
Parameters¶
zs: Optional[np.ndarray]
Redshifts at which to evaluate the growth rate. Defaults to self.z.
ks: Optional[np.ndarray]
Wavenumbers at which to evaluate the growth rate.
Returns¶
np.ndarray Growth rate f(z) at k = 1 Mpc^-1 with shape (nz,) if ks is None, and f(z, k) with shape (nz, nk) otherwise.
hi_classNonLinearPerturbations
¶
hi_classNonLinearPerturbations(background: Background, linearperturbations: Optional[Perturbations], redshifts: ndarray, nonlinear_model: Optional[str] = None)
Class for non-linear perturbations cosmology using hi_class, inheriting from Perturbations parent class.
Parameters:
-
(background¶Background) –Background cosmology object.
-
(linearperturbations¶Optional[Perturbations]) –Linear perturbations object (hi_class computes the nonlinear corrections internally). Only needed for the cb x matter cross spectrum, e.g.
hi_classLinearPerturbationson the same background. -
(redshifts¶ndarray) –Array of redshifts for the calculations.
-
(nonlinear_model¶Optional[str], default:None) –The nonlinear model to use. Defaults to None (no nonlinear).
matter_power_spectrum
¶
Calculate the hi_class non-linear matter power spectrum.
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Non-linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Calculate the hi_class non-linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
Returns:¶
np.ndarray The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z, k). The standard expression for scale-independent f assumes LCDM and isn't valid in modified gravity. Instead, we use the scale-dependent growth rate, evaluated at large k (1 Mpc^-1) if no wavenumbers are given.
Parameters¶
zs: Optional[np.ndarray]
Redshifts at which to evaluate the growth rate. Defaults to self.z.
ks: Optional[np.ndarray]
Wavenumbers at which to evaluate the growth rate.
Returns¶
np.ndarray Growth rate f(z) at k = 1 Mpc^-1 with shape (nz,) if ks is None, and f(z, k) with shape (nz, nk) otherwise.
mgclass_cosmology
¶
Implementation of Background and Perturbation cosmology using MGCLASS, a patch to CLASS for modified gravity models.
MGCLASSBackground
¶
MGCLASSBackground(H0: float, Omega_b0: float, Omega_cdm0: float, Omega_k0: float, As: float, ns: float, Y_He: float, mnu: Union[float, Sequence[float], ndarray], w0: float, wa: float, gamma_MG: float, mg_ansatz: str, mg_z_init: float, mg_params: dict, N_mnu: int, N_ur: Optional[float] = None, alpha_s: float = 0.0, **kwargs)
A wrapper for MGCLASS background cosmological calculations.
Parameters:
-
(H0¶float) –Hubble parameter at z=0 in km/s/Mpc.
-
(Omega_b0¶float) –Baryonic matter density parameter.
-
(Omega_cdm0¶float) –Cold dark matter density parameter.
-
(Omega_k0¶float) –Curvature density parameter.
-
(As¶float) –Scalar amplitude of primordial fluctuations.
-
(ns¶float) –Scalar spectral index.
-
(alpha_s¶float, default:0.0) –Running of the scalar spectral index (d ns / d ln k).
-
(mnu¶Union[float, Sequence[float], ndarray]) –Total neutrino mass in eV. Can be a single float for degenerate masses, an array (or a sequence of floats) for individual species.
-
(w0¶float) –Equation of state parameter for dark energy.
-
(wa¶float) –Time evolution of the equation of state.
-
(gamma_MG¶float) –Modified gravity growth parameter (not directly used in MGCLASS, but kept for protocol compliance).
-
(N_mnu¶int) –Number of massive neutrino species.
-
(N_ur¶Optional[float], default:None) –Effective number of ultra-relativistic species. If not provided, it will be inferred from N_mnu such that N_eff = 3.044.
-
(mg_ansatz¶str) –Modified gravity model name
-
(mg_z_init¶float) –Redshift at which the MG model starts applying
-
(mg_params¶dict) –dictionary for an MGCLASS model parameters
N_ur
property
¶
Effective number of ultra-relativistic species.
If the user gave one, return it; otherwise infer from other parameters such that N_eff = 3.044 for the standard model of cosmology.
N_eff
property
¶
Return the effective number of relativistic species.
Assumes a standard value of T_ncdm = 0.71611 K for neutrinos.
hubble_parameter
¶
Return the Hubble parameter as a function of redshift. Args: zs (np.ndarray): Array of redshifts. units (str): Units for the Hubble parameter ('1/Mpc' or 'km/s/Mpc').
Returns:
-
ndarray–np.ndarray: Hubble parameter values at specified redshifts.
comoving_distance
¶
Return the comoving distance as a function of redshift. Args: zs (np.ndarray): Array of redshifts.
Returns:
-
ndarray–np.ndarray: Comoving distance values.
transverse_comoving_distance
¶
transverse_comoving_distance(zs: ndarray) -> ndarray
Return the transverse comoving distance between two redshifts.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Return
np.ndarray: Transverse comoving distance values.
angular_diameter_distance
¶
Returns the angular diameter distance as a function of redshift. Args: zs (np.ndarray): Array of redshifts.
Returns:
-
ndarray–np.ndarray: Angular diameter distance values.
Omega_cb
¶
Omega_cb(zs: Union[ndarray, float]) -> ndarray
Return the cold dark matter + baryons (no neutrinos) as a function of redshift.
Parameters:
-
(zs¶ndarray) –Array of redshifts.
Returns:
-
ndarray–np.ndarray: Matter density values (no neutrinos).
MGCLASSLinearPerturbations
¶
MGCLASSLinearPerturbations(background: Background, redshifts: ndarray)
Class for perturbations cosmology using MGCLASS, inheriting from Perturbations parent class.
matter_power_spectrum
¶
Calculate the MGCLASS linear matter power spectrum.
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Computes the linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
Returns:¶
np.ndarray The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z).
Parameters¶
zs: Optional[np.ndarray]
Redshifts at which to evaluate the growth rate, interpolated on
self.z. Defaults to self.z.
ks: Optional[np.ndarray]
Wavenumbers used to broadcast the growth rate.
Returns¶
np.ndarray Scale-independent growth rate f(z), with shape (nz,) if ks is None and (nz, nk) otherwise.
Raises¶
ValueError If the instance was built on fewer than 3 redshifts.
MGCLASSNonLinearPerturbations
¶
MGCLASSNonLinearPerturbations(background: Background, linearperturbations: Optional[Perturbations], redshifts: ndarray, nonlinear_model: Optional[str] = None)
Class for non-linear perturbations cosmology using MGCLASS, inheriting from Perturbations parent class.
Parameters:
-
(background¶Background) –Background cosmology object.
-
(linearperturbations¶Optional[Perturbations]) –Linear perturbations object (MGCLASS computes the nonlinear corrections internally). Only needed for the cb x matter cross spectrum, e.g.
MGCLASSLinearPerturbationson the same background. -
(redshifts¶ndarray) –Array of redshifts for the calculations.
-
(nonlinear_model¶Optional[str], default:None) –The nonlinear model to use. Defaults to None (no nonlinear).
matter_power_spectrum
¶
Calculate the MGCLASS non-linear matter power spectrum.
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Non-linear matter power spectrum at the specified scale and redshift
matter_power_spectrum_cb
¶
Calculate the CLASS non-linear matter power spectrum of cold dark matter + baryons (no neutrinos).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
(Optional) bool
Flag to specify if output in h units, defaults to False
(Optional) bool
Flag to specify if wavenumber in h units, defaults to False
Returns¶
pk: numpy.ndarray Linear matter power spectrum at the specified scale and redshift
growth_factor
¶
Calculate the growth factor for given redshifts and wavenumbers.
.. math:: D(z, k) =\sqrt{P_{\rm \delta\delta}(z, k)\ /P_{\rm \delta\delta}(z=0, k)}\
and normalizes as for :math:D(z)/D(0).
Parameters¶
zs: numpy.ndarray redshifts
numpy.ndarray
wavenumber
Returns:¶
np.ndarray The growth factor at the specified redshift and wavenumber.
growth_rate
¶
Calculate the growth rate f(z).
Parameters¶
zs: Optional[np.ndarray]
Redshifts at which to evaluate the growth rate, interpolated on
self.z. Defaults to self.z.
ks: Optional[np.ndarray]
Wavenumbers used to broadcast the growth rate.
Returns¶
np.ndarray Scale-independent growth rate f(z), with shape (nz,) if ks is None and (nz, nk) otherwise.
Raises¶
ValueError If the instance was built on fewer than 3 redshifts.
ReACTEmu_cosmology
¶
MGemuNonlinearBoost
¶
MGemuNonlinearBoost(background: Background, linearperturbations: WithWavenumberGrid, zs: ndarray, gravity_model: str, mgpars: dict, high_z_policy: str = 'taper', z_decay: float = 0.75)
Build a redshift- and wavenumber-dependent nonlinear power boost.
The MGEmu backend supplies the boost relative to its GR baseline. This
class interpolates that boost as B(z, k) and resamples it onto the
supplied linear perturbation wavenumber grid. Wavenumbers are represented
internally in 1/Mpc. Supported gravity_model tags are fr,
dgp, gamma, mu, wCDM, w0waCDM, and ide; the first
four map to matching MGEmu backends, while the last three use its ds
The mgpars keys read by the adapter are fr0, omega_rc,
gamma0, mu0, sigma0, c1, lam, q1, q2,
q3, and xi; omitted values use the defaults in the implementation.
The input redshifts and linearperturbations.k must be suitable for
spline construction and extrapolation; the constructor does not validate
their ordering or sampling. Emulator training bounds are clipped in the
parameter dictionary, and the emulator neutrino density is fixed to
1e-10. For models other than wCDM, w0waCDM, ide, and
mu, the background is required by an assertion to have w0=-1 and
wa=0. The boost is extended toward unity at low k, extrapolated to
high k (up to the extension grid used by extend_spectra), and given
one of the power_law, freeze, one, or taper high-redshift
continuations. The latter policies return to a boost of unity according
to the selected rule and z_decay.
Raises:
-
ImportError–If MGEmu cannot be imported.
-
ValueError–If the gravity model or high-redshift policy is unknown.
-
AssertionError–If a model's assumed background equation of state is not satisfied.
These emulators were created based on training data produced using ReACT (https://arxiv.org/abs/2005.12184)
This class allows for f(R), DGP, IDE and other parameterized gravity models
See https://github.com/nebblu/MGEmus/tree/main for more details
Parameters¶
background : Background A cosmological background instance containing parameters such as Omega_b0, Omega_cdm0, H0, ns, mnu, w0, and wa. Note w0 and wa are assumed to be LCDM values for some modified gravity models.
WithWavenumberGrid
A standard linear perturbation object (e.g. from CAMB) used as the LCDM baseline;
only its .k wavenumber grid is used here.
np.ndarray
Array of redshifts at which to compute the MG corrections.
str, optional
Name of the gravity model or dark energy model to use. Examples: 'fr', 'dgp', 'ide', 'wCDM', 'w0waCDM', 'gamma', 'mu' etc.
dict
Dictionary of the extended MG parameters. Examples: fR0 for f(R), omegarc for DGP, gamma0/gamma1 for Linder models, mu0/Sigma0 or binned values for mu-Sigma, xi for IDE, etc.
string (default taper)
Gives the high redshift extrapolation policy. Can choose from the following: options: "power_law", "freeze", "one", "taper"
float
Gives the decay rate after emulator max redshift going back to LCDM (boost=1)
mg_spectrum_boost
¶
Evaluate the dimensionless nonlinear power-spectrum boost.
Parameters¶
zs : array_like
Redshifts at which to evaluate the boost.
ks : array_like
Wavenumbers in 1/Mpc.
Returns¶
numpy.ndarray
Boost values. With array inputs, RectBivariateSpline uses
grid semantics and returns shape (len(zs), len(ks)).
Notes¶
Values outside the constructed interpolation grid use the spline's
extrapolation behavior. For paired-point rather than grid evaluation,
call MGboost_interp(zs, ks, grid=False) directly.
BoostedPerturbations
¶
Adapt a baseline perturbation backend by multiplying its nonlinear P(k,z).
base_perturbations supplies background, matter_power_spectrum
and sigma8_0; base_lin_perturbations supplies growth_rate and
may supply sigma_lensing. boost_interp is a callable B(z, k);
grid-shaped spectra require a callable accepting the grid=False
keyword for paired-point evaluation. The wrapper exposes k and z
from the nonlinear base when present. It asserts a flat background, but
does not check that the linear and nonlinear bases share one.
Parameters¶
Parameters¶
base_lin_perturbations : object
An object representing the linear perturbations, which may include methods
like sigma_lensing for lensing calculations.
object
An object with a matter_power_spectrum(z, k) method that provides the
nonlinear matter power spectrum for the ΛCDM model.
callable
A function or interpolator B(z, k) that returns the nonlinear boost to be applied to the ΛCDM
matter_power_spectrum
¶
Return the boosted nonlinear matter power spectrum.
Parameters¶
zs : float or np.ndarray Redshift value or array of redshifts. ks : float or np.ndarray Wavenumber value or array of wavenumbers in 1/Mpc.
Returns¶
float or np.ndarray
Boosted spectrum in the units returned by the base backend.
Inputs are promoted to 1D arrays; a base result shaped
(len(zs), len(ks)) is multiplied by a pointwise boost, and
other shapes use the boost callable's ordinary argument handling.
The result is squeezed, removing all singleton axes.
growth_factor
¶
Estimate the growth factor from the boosted spectrum.
If ks is provided:
D(z,k) = sqrt( P(z,k) / P(0,k) )
If ks is None, use the boost-only large-scale estimate
sqrt(B(z,k_lin) / B(0,k_lin)). Here k_lin is the smallest
available self.k, or 0.02 1/Mpc if no grid is exposed. This
branch does not use the base linear growth factor. Denominators are
floored at 1e-300 and the result is squeezed.
Parameters¶
zs : array_like Redshifts. ks : array_like or None Wavenumbers. If None, returns linear-growth estimate from the boost at k_lin.
Returns¶
np.ndarray If ks is None or scalar -> shape (len(zs),) If z and k arrays -> shape (len(zs), len(ks))
growth_rate
¶
Return the linear growth rate of base_lin_perturbations.
The boost only modifies the nonlinear matter power spectrum, so the
growth rate is that of the underlying linear perturbations, see
Perturbations.growth_rate. Without zs, it is evaluated on self.z,
the redshift grid of base_perturbations, if that has one.
sigma8_0
¶
Approximate the boosted sigma8(0) from one low-k boost value.
Returns base.sigma8_0() * sqrt(B(0, 0.02 1/Mpc)). This is a
single-wavenumber approximation, not a re-integration of the boosted
power spectrum. The boost callable can make the result array-valued
(typically length one), despite the scalar return annotation.
Returns:¶
float or np.ndarray The base value multiplied by the square root of the boost.
TabulatedBoost_cosmology
¶
Tabulated nonlinear boost module.
This module provides a lightweight interface for using simulation-based nonlinear matter power spectrum boosts B(k, z). It reads a text file containing a common k-grid and boost values for a set of snapshot redshifts, constructs a 2D spline interpolator B(z, k), and exposes it in the required format.
TabulatedNonlinearBoost
¶
TabulatedNonlinearBoost(background: Background, linearperturbations: WithWavenumberGrid, zs: ndarray, boost_file: str, z_cols: Sequence[float], high_z_policy: str = 'taper', z_decay: float = 0.75)
Nonlinear matter power spectrum boost from a tabulated file B(k; z).
The boost file is expected to have
- column 1: k values in
h/Mpc(same k-grid at every redshift) - columns 2..N: dimensionless boost values
B(k; z_i)
Parameters¶
background : Background A cosmological background instance containing parameters such as Omega_b0, Omega_cdm0, H0, ns, mnu, w0, and wa. Note w0 and wa are assumed to be LCDM values for some modified gravity models.
WithWavenumberGrid
A standard linear perturbation object (e.g. from CAMB) used as the LCDM baseline;
only its .k wavenumber grid is used here.
np.ndarray
Array of redshifts at which to compute the MG corrections.
str
Path to the text file containing [k, B(z1), B(z2), ..., B(zN)]. Commented header lines starting with '#' are allowed.
Sequence[float]
1D array or list of redshifts corresponding to columns 2..N in the boost file (same order). Length must match the number of boost columns; values and corresponding columns are sorted by redshift internally.
string (default taper)
Gives the high redshift extrapolation policy. Can choose from the following: options: "power_law", "freeze", "one", "taper"
float
Gives the decay rate after emulator max redshift going back to LCDM (boost=1)
Notes¶
The first column is converted from h/Mpc to 1/Mpc using
background.h. The input k grid and sorted snapshot redshifts must be
strictly increasing and sufficiently sampled for a linear
RectBivariateSpline; the requested zs grid must also be suitable
for interpolation and extrapolation. Only the column count is explicitly
validated, so file parsing, ordering, and spline errors otherwise
propagate from NumPy/SciPy. The boost is resampled onto
linearperturbations.k and extended at low and high k.
high_z_policy accepts "power_law", "freeze", "one", or
"taper". z_decay sets the taper scale. Non-power-law policies are
applied to requested redshifts outside the tabulated interval on either
side; the implementation currently does not enforce a high-z floor at
unity.
Raises¶
ValueError If the file has fewer than two columns, the number of redshift labels does not match the boost columns, or the policy is unsupported.
mg_spectrum_boost
¶
Evaluate the dimensionless nonlinear power-spectrum boost.
Parameters¶
zs : array_like
Redshifts at which to evaluate the boost.
ks : array_like
Wavenumbers in 1/Mpc.
Returns¶
numpy.ndarray
Boost values. With array inputs, RectBivariateSpline uses
grid semantics and returns shape (len(zs), len(ks)).
Notes¶
Values outside the constructed interpolation grid use the spline's
extrapolation behavior. For paired-point rather than grid evaluation,
call MGboost_interp(zs, ks, grid=False) directly.
TabulatedBoostedPerturbations
¶
Apply a tabulated nonlinear boost through the Perturbations interface.
The wrapper multiplies the nonlinear base's matter power spectrum by
boost_interp(z, k). The nonlinear base must provide
matter_power_spectrum and sigma8_0; the linear base must provide
background and growth_rate and may provide sigma_lensing.
k and z are exposed from the nonlinear base when available. This
class takes its background from the linear base and asserts flatness,
but does not verify that the two bases use consistent backgrounds. For
grid-shaped spectra the boost callable must accept grid=False for
paired-point evaluation.
Parameters¶
base_lin_perturbations : object
An object representing the linear perturbations, which may include methods
like sigma_lensing for lensing calculations. Must have the same background
as in the modified theory of gravity or dark energy (not ΛCDM for CPL-backgrounds!).
object
An object with a matter_power_spectrum(z, k) method that provides the
nonlinear matter power spectrum for the ΛCDM model.
callable
A function or interpolator B(z, k) that returns the nonlinear boost to be applied to the ΛCDM spectrum.
matter_power_spectrum
¶
Return the boosted nonlinear matter power spectrum.
Parameters¶
zs : float or np.ndarray Redshift value or array of redshifts. ks : float or np.ndarray Wavenumber value or array of wavenumbers in 1/Mpc.
Returns¶
float or np.ndarray
Boosted spectrum in the units returned by the base backend.
Inputs are promoted to 1D arrays; a base result shaped
(len(zs), len(ks)) is multiplied by a pointwise boost, and
other shapes use the boost callable's ordinary argument handling.
The result is squeezed, removing all singleton axes.
growth_factor
¶
Calculate the growth factor.
If ks is provided:
D(z,k) = sqrt( P(z,k) / P(0,k) )
If ks is None, use the boost-only large-scale estimate
sqrt(B(z, k_lin) / B(0, k_lin)). Here k_lin is the smallest
available self.k, or 0.02 1/Mpc if no grid is exposed. This
branch does not use the base linear growth factor. Denominators are
floored at 1e-300 and the result is squeezed.
Parameters¶
zs : array_like Redshifts. ks : array_like or None Wavenumbers. If None, returns linear-growth estimate from the boost at k_lin.
Returns¶
np.ndarray If ks is None or scalar -> shape (len(zs),) If z and k arrays -> shape (len(zs), len(ks))
growth_rate
¶
Return the linear growth rate of base_lin_perturbations.
The boost only modifies the nonlinear matter power spectrum, so the
growth rate is that of the underlying linear perturbations, see
Perturbations.growth_rate. Without zs, it is evaluated on self.z,
the redshift grid of base_perturbations, if that has one.
sigma8_0
¶
Approximate boosted sigma8(0) from the boost at 0.02 1/Mpc.
Returns base.sigma8_0() * sqrt(B(0, 0.02 1/Mpc)); this does not
re-integrate the boosted spectrum. The callable may make the result
array-valued (typically length one), despite the scalar annotation.
mg_cosmopower_jax_cosmology
¶
Implementation of modified-gravity Perturbation cosmology using CosmoPower-JAX emulators.
The emulators predict the modified-gravity boost B(k, z) = P_MG(k, z) / P_LCDM(k, z), applied on top of an external LCDM baseline (another cloelib Perturbations object) as P_MG = B * P_LCDM on the baseline k-grid (no regridding), so that mu = eta = 1 recovers the baseline up to the boost emulators' own residual at GR (|B - 1| below 3e-4 for k <= 1 h/Mpc, up to 2.5e-3 at k ~ 10 h/Mpc for the nonlinear multi-bin emulator). mu and eta are read from a mutable MGParams holder and either modify a single redshift bin (bin_index an int) or all bins at once (bin_index None); the matching emulators are downloaded on first use. eta has no nonlinear effect and enters only through the lensing parameter Sigma = mu(1 + eta)/2, which every lensing kernel (cosmic shear, magnification bias, CMB lensing) applies.
The implementation lives in the module-level MGLinearPerturbations and
MGNonLinearPerturbations classes, which are checked statically against the
Perturbations protocol; mg_perturbations returns subclasses with the MG
parameters and the LCDM baseline classes bound as class attributes.
MGParams
¶
Mutable holder for the per-call modified-gravity parameters mu and eta.
Single-bin mode (bin_index an int) stores scalar mu/eta for
that bin; multi-bin mode (bin_index=None) stores length-N_BINS
arrays. Unset mu/eta default to the GR value of one.
MGLinearPerturbations
¶
Linear modified-gravity perturbations: linear boost times LCDM baseline.
The sampled parameters and the LCDM baseline are bound through the class
attributes mg_params and baseline_linear; mg_perturbations returns
a subclass with them set. Defined at module level so the Perturbations
protocol is checked statically (tests/typing/perturbations_conformance.py).
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
Compute the linear CDM+baryon matter power spectrum.
The boost is applied to the baseline CDM+baryon spectrum, matching the COLA spectra the boost emulators were trained on.
Parameters:
Returns:
-
pk(ndarray) –Linear CDM+baryon power spectrum (boost times LCDM baseline).
growth_factor
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = -(1 + z) dlnD/dz.
f is computed on self.z from the linear modified-gravity power
spectrum, then interpolated to zs and broadcast over ks.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts. Defaults to the instance grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0 from the linear modified-gravity power spectrum.
Returns:
-
float(float) –The rms matter fluctuation sigma8.
MGNonLinearPerturbations
¶
Nonlinear modified-gravity perturbations: nonlinear boost times LCDM baseline.
Bound through the class attributes mg_params, baseline_linear and
baseline_nonlinear; see MGLinearPerturbations.
cb_cross_prescription
property
¶
cb x matter cross spectrum prescription, that of the LCDM baseline.
The same boost rescales the baseline total matter and cb spectra, so the cross spectrum follows the baseline's prescription.
matter_power_spectrum
¶
matter_power_spectrum_cb
¶
Compute the nonlinear CDM+baryon matter power spectrum.
The boost is applied to the baseline CDM+baryon spectrum, matching the COLA spectra the boost emulators were trained on.
Parameters:
Returns:
-
pk(ndarray) –Nonlinear CDM+baryon power spectrum (boost times LCDM baseline).
growth_factor
¶
growth_rate
¶
Compute the scale-independent growth rate f(z) = -(1 + z) dlnD/dz.
f is computed on self.z from the linear modified-gravity power
spectrum, then interpolated to zs and broadcast over ks.
Parameters:
-
(zs¶Optional[ndarray], default:None) –Redshifts. Defaults to the instance grid.
-
(ks¶Optional[ndarray], default:None) –Wavenumbers used to broadcast f.
Returns:
-
ndarray–The growth rate, with shape (nz,) if ks is None and (nz, nk) otherwise.
sigma8_0
¶
Compute sigma8 at z=0 from the linear modified-gravity power spectrum.
Returns:
-
float(float) –The rms matter fluctuation sigma8.
mg_perturbations
¶
mg_perturbations(mg_params, baseline_linear, baseline_nonlinear) -> tuple
Build the modified-gravity Linear and NonLinear perturbation classes.
The single-bin or multi-bin mode is selected by mg_params.bin_index
(an int or None). The returned classes follow the cloelike LinPerturbations
and NonLinPerturbations protocols.
Parameters:
-
(mg_params¶MGParams) –Holder read at each instantiation for the sampled mu and eta.
-
(baseline_linear¶type) –LCDM linear perturbation class, e.g.
CosmoPowerJAXLCDMPerturbations.Linear. -
(baseline_nonlinear¶type) –LCDM nonlinear perturbation class, e.g.
CosmoPowerJAXLCDMPerturbations.NonLinear.
Returns:
-
tuple(tuple) –The
(Linear, NonLinear)modified-gravity perturbation classes, subclasses ofMGLinearPerturbations/MGNonLinearPerturbationswith the arguments bound as class attributes.
options: show_root_toc_entry: true show_root_heading: true show_submodules: false heading_level: 3
observables
¶
Observable package of cloelib.
The package provides photometric, gravitational-wave, and spectroscopic observables. The Tracer protocol is used to define photometric and gravitational-wave observables. The SpectroPower protocol is used to define Spectroscopic observables.
Supported External Codes:
- SpectroPower: comet-emu, PBJ
- Tracers: ShearTracer, PositionsTracer, GWNumberCountsTracer,
GWWeakLensingTracer
photo
¶
Photometric probe tracers: cosmic shear and angular galaxy clustering.
ShearTracer and everything related to its intrinsic-alignment models
(LensingContribution, NLAContribution,
TATTContribution, PBJTATTLoopComputer) live together in photo.shear.
PositionsTracer and its Contributions
(GalaxyBiasContribution, MagnificationContribution,
NonLinearGalaxyBiasContribution, PBJNonlinearBiasLoopComputer) live
together in photo.positions. The generic, tracer-agnostic pieces both of
those (and
AngularTwoPoint) build on - the Tracer protocol, the Contribution
protocol/IntrinsicAlignmentContribution base, and the generalized
per-contribution-pair spectrum engine - live here too, in photo.tracer,
photo.contributions, photo.spectrum_engine respectively; moved from the
old flat cloelib/observables/tracer.py/contributions.py/
spectrum_engine.py (imports updated at every call site - no back-compat
shims left at the old paths).
ShearTracer and PositionsTracer are re-exported here too, for
from cloelib.observables.photo import ShearTracer, PositionsTracer.
shear
¶
Cosmic shear tracer: ShearTracer, its Contributions, and its
intrinsic-alignment models.
Compatible with the Tracer protocol. Counterpart to photo.positions,
which holds PositionsTracer.
Everything needed to build and use a shear tracer - including its intrinsic-alignment options - lives in this one module:
ShearTraceritself. By default (ia_model=None) it has no intrinsic-alignment contribution at all - onlyLensingContribution. Passia_model="NLA"explicitly forNLAContribution(the nonlinear alignment model), oria_model="TATT"forTATTContributionbelow.LensingContribution,NLAContribution: two of theContributions aShearTracercan be built from.TATTContribution(Eqs. 9-16 of Navarro-Gironés et al. 2026, arXiv:2602.16448, "Euclid preparation. CIV. Impact of galaxy intrinsic alignment modelling choices on Euclid 3x2pt cosmology"): an alternative IA model, selected viaShearTracer(..., ia_model="TATT", tatt_loop_computer=...). Its ten one-loop kernels come from a requiredloop_computer-PBJTATTLoopComputer: real physics, viafastpt.FASTPT.IA_ta/.IA_tt/.IA_mix(thefast-ptPyPI package - an optional dependency,pip install cloelib[fastpt]) on the linear matter power spectrum. The same three FAST-PT calls, kernel names, andc1**2*Pdd + 2*c1*c1d*D**4*(a00e+c00e) + ...assembly production CLOE used (github.com/cloe-org/CLOE,cloe/non_linear/miscellanous.py/pLL_phot.py) - verified directly against that source.cloelib's ownpbjcosmo-based PBJ interface (spectro/PBJ_spectro.py) has no IA/TATT support of its own (verified against pbjcosmo 1.6.1's published source: its own PT wrapper class subclasses afastptvariant withoutIA_*methods), butpbjcosmoitself depends on this samefast-ptpackage as its PT engine - so this goes straight tofast-pt, independent of whetherpbjcosmois installed.loop_computeris a required argument (not defaulted to anything illustrative):TATTContributiononly ever reports kernel values it can stand behind as real physics - passing any other object exposing the same.compute(name) -> callable(matter_pk, ks, zs)interface is also supported, for a different PT backend.
Pass loop_computer=PBJTATTLoopComputer(perturbations) directly to
ShearTracer(..., ia_model="TATT", tatt_loop_computer=...) - one
constructor call, not build-then-replace .ia.
See CONTRIBUTION_ARCHITECTURE.md for the design this all
follows.
LensingContribution
¶
LensingContribution(tracer: ShearTracer)
Weak-lensing shear kernel term of ShearTracer.get_window().
NLAContribution
¶
NLAContribution(tracer: ShearTracer)
flowchart TD
cloelib.observables.photo.shear.NLAContribution[NLAContribution]
cloelib.observables.photo.contributions.IntrinsicAlignmentContribution[IntrinsicAlignmentContribution]
cloelib.observables.photo.contributions.IntrinsicAlignmentContribution --> cloelib.observables.photo.shear.NLAContribution
click cloelib.observables.photo.shear.NLAContribution href "" "cloelib.observables.photo.shear.NLAContribution"
click cloelib.observables.photo.contributions.IntrinsicAlignmentContribution href "" "cloelib.observables.photo.contributions.IntrinsicAlignmentContribution"
NLA (nonlinear alignment model) intrinsic-alignment kernel term of
ShearTracer.get_window().
Implemented by ShearTracer.get_window_IA - selected via
ia_model="NLA" on ShearTracer (the default, ia_model=None, has no
IA contribution at all). ia_model="TATT" swaps in TATTContribution
here instead - a different intrinsic-alignment model, hence the
distinct name; get_window() and AngularTwoPoint don't need to
change either way.
TATTLoopComputer
¶
flowchart TD
cloelib.observables.photo.shear.TATTLoopComputer[TATTLoopComputer]
click cloelib.observables.photo.shear.TATTLoopComputer href "" "cloelib.observables.photo.shear.TATTLoopComputer"
Interface TATTContribution needs from its one-loop kernel backend.
PBJTATTLoopComputer is the production implementation; any other
object with these two members can be passed as tatt_loop_computer.
linear_perturbations
property
¶
linear_perturbations: Perturbations
Linear perturbations used for the D(z) factors in C1/C2/D**4.
compute
¶
Return a SpectrumRequest.compute callable for kernel name.
PBJTATTLoopComputer
¶
PBJTATTLoopComputer(perturbations: Perturbations)
FAST-PT-backed computer for the ten TATT one-loop kernels.
Calls fastpt.FASTPT.IA_ta/.IA_tt/.IA_mix on the linear matter
power spectrum at z=0, with the same extrapolation settings and
C_window production CLOE uses (see module docstring). The ten
outputs are pure functions of k (no z-dependence - TATTContribution
supplies that separately via D(z)**4 and its C1/C1delta/C2
amplitudes, exactly matching Eqs. 13-15's own separation of scales), so
they're computed once per k-grid, cached, and reused across the ten
named SpectrumRequests (and across get_Cl calls, as long as the
k-grid doesn't change) instead of re-running FAST-PT per kernel name.
Takes the same perturbations object you'd pass to ShearTracer -
typically nonlinear (a halo model/emulator backend, for the tree-level
P_dd term), but FAST-PT's one-loop integrals are only valid starting
from the linear power spectrum (the same distinction production CLOE
draws between Pk_delta and Pk_halomodel_recipe), so this class
resolves the actual linear source itself: perturbations.
linearperturbations if that attribute exists (every nonlinear backend
that's built from a separate linear one sets it -
HMemuNonLinearPerturbations, EE2NonLinearPerturbations,
BACCOemuNonLinearPerturbations, EmantisFofrNonLinearPerturbations,
JAXNonLinearPerturbations), else perturbations itself if and only
if it's itself a recognized *LinearPerturbations backend (see
_is_known_linear_perturbations) - raises ValueError otherwise (PR
569 review): the absence of a .linearperturbations attribute does¶
not by itself mean the object passed in is linear, and silently
treating an unrecognized nonlinear backend as linear would be a
physical error, not a numerical one (FAST-PT would still return
finite-looking, wrong spectra) - the kind that shouldn't fail silently.
CAMBNonLinearPerturbations is the concrete case this currently
excludes: it does not set .linearperturbations (its own
matter_power_spectrum is always nonlinear), so it now raises here
instead of being misused - pass CAMBLinearPerturbations directly
instead.
TODO (PR #569 review): standardize access to the corresponding linear
perturbations object across nonlinear cosmology backends (e.g. also
wiring it up for CAMBNonLinearPerturbations), so PT-based observables
can retrieve a linear P(k,z) through one common interface instead of
this getattr-plus-name-check fallback.
FAST-PT requires its input k-grid to be evenly log-spaced (an FFTLog
requirement); TATTContribution's own ks (whatever grid the calling
AngularTwoPoint.get_Cl was invoked with, e.g. perturbations.k from
an emulator's extended, non-uniform grid) generally isn't. Production
CLOE handles this by running FAST-PT on its own dedicated log-uniform
k_win grid and interpolating the results onto whatever wavenumber
is actually needed (Misc.ia_tatt_terms's interp1d(..., kind=
'linear', fill_value='extrapolate')); this class does the same -
builds a log-uniform grid spanning the requested ks' own range,
runs FAST-PT there, and linearly interpolates (extrapolating past the
edges, matching production CLOE) back onto ks.
Requires the optional fast-pt dependency (pip install
cloelib[fastpt]); raises ImportError with install instructions at
construction time.
compute
¶
Return the FAST-PT callable for one named TATT kernel.
name must be present in _ALL_KERNELS. The returned
SpectrumRequest.compute(matter_pk, ks, zs) ignores matter_pk
and zs because the cached kernel depends only on k, and returns
shape (len(ks),).
TATTContribution
¶
TATTContribution(tracer: ShearTracer, A1: float, A2: float, b_TA: float, loop_computer: TATTLoopComputer, eta1: float = 0.0, eta2: float = 0.0, z0: float = 0.62, C_IA: float = 0.0134)
flowchart TD
cloelib.observables.photo.shear.TATTContribution[TATTContribution]
cloelib.observables.photo.contributions.IntrinsicAlignmentContribution[IntrinsicAlignmentContribution]
cloelib.observables.photo.contributions.IntrinsicAlignmentContribution --> cloelib.observables.photo.shear.TATTContribution
click cloelib.observables.photo.shear.TATTContribution href "" "cloelib.observables.photo.shear.TATTContribution"
click cloelib.observables.photo.contributions.IntrinsicAlignmentContribution href "" "cloelib.observables.photo.contributions.IntrinsicAlignmentContribution"
TATT intrinsic-alignment contribution (Eqs. 9-16 of Navarro-Gironés et al. 2026, arXiv:2602.16448), see module docstring.
C1(z) = -A1 * C_IA * Omega_m0 * ((1+z)/(1+z0))**eta1 / D(z)
C1delta(z) = b_TA * C1(z)
C2(z) = 5*A2 * C_IA * Omega_m0 / D(z)**2 * ((1+z)/(1+z0))**eta2
P_II^EE(z,k) = C1(z)**2 * P_dd(z,k)
+ 2*C1(z)*C1delta(z)*D(z)**4 * [A_0_0E(k) + C_0_0E(k)]
+ C1delta(z)**2 * D(z)**4 * A_0E_0E(k)
+ C2(z)**2 * D(z)**4 * A_E2_E2(k)
+ 2*C1(z)*C2(z)*D(z)**4 * [A_0_E2(k) + B_0_E2(k)]
+ 2*C1delta(z)*C2(z)*D(z)**4 * D_0E_E2(k)
P_deltaI(z,k) = C1(z)*P_dd(z,k)
+ C1delta(z)*D(z)**4 * [A_0_0E(k) + C_0_0E(k)]
+ C2(z)*D(z)**4 * [A_0_E2(k) + B_0_E2(k)]
C_IA bundles the paper's C_bar_1 * rho_crit product (the standard
IA literature convention; ShearTracer.get_window_IA's NLA
implementation already uses one constant this way with the same
default value, 0.0134 - see Brown et al. 2002).
Parameters:
-
(tracer¶ShearTracer) –the owning
ShearTracer. -
(A1¶float) –tidal-alignment amplitude (Table 2 of the reference paper).
-
(A2¶float) –tidal-torquing amplitude (Table 2).
-
(b_TA¶float) –tidal-alignment-of-galaxy-bias-tracers amplitude (Table 2).
-
(eta1¶float, default:0.0) –redshift-evolution index for
A1's (1+z)/(1+z0) scaling (Table 2; the fullzTATTmodel uses all five of these). -
(eta2¶float, default:0.0) –redshift-evolution index for
A2's (1+z)/(1+z0) scaling (Table 2). -
(z0¶float, default:0.62) –pivot redshift for the (1+z)/(1+z0) scaling. Fixed at 0.62 in the reference paper's fiducial setup (their Table 3).
-
(C_IA¶float, default:0.0134) –the
C_bar_1 * rho_critnormalisation constant (see above); same convention and default (0.0134) asShearTracer's NLA model. -
(loop_computer¶TATTLoopComputer) –object exposing
.compute(name) -> callable(matter_pk, ks, zs)for each of the ten kernel names in_ALL_KERNELS- the "SpectrumComputer" for the one-loop terms. Required: passPBJTATTLoopComputer(perturbations)(or build aShearTracerdirectly withia_model="TATT", tatt_loop_computer=PBJTATTLoopComputer(...), which does this for you), or any other object with the same interface. No default -TATTContributiononly ever reports kernel values it can stand behind as real physics.
compute_kernel
¶
Amplitude-free IA weighting kernel: n_i(z) * H(z)/c.
Unlike NLA (where a single scalar C1(z) factor can be baked
straight into the window because P_II = C1(z)2 * P_dd(z,k) shares
P_dd's k-shape), TATT's extra terms have k-shapes (the one-loop
kernels) that differ from P_dd - so the amplitude weighting
(C1/C1delta/C2) has to move into get_effective_pk's P(k,z)
assembly instead of living in this kernel.
The H(z)/c factor is not part of the TATT amplitude functions
themselves - it's the same "per unit z to per unit comoving
distance" Jacobian ShearTracer.get_window_IA's NLA implementation
already folds into its own window (factor = -Hz/c_0 * ...).
Leaving it out here isn't just a simplification: without it, this
contribution's effective normalisation differs from NLA's by
(Hz/c_0) per side. Keeping the Jacobian in the kernel (applied
identically to every contribution pairing) rather than folding it
into C1/C1delta/C2 separately keeps get_effective_pk matching the
paper's equations exactly, unencumbered by this pipeline-specific
normalisation detail.
get_spectrum_requests
¶
Return requests for the ten TATT kernels.
get_requirements_for_interaction retains only the GI kernels when
paired with a non-IA contribution; an IA-IA pairing needs all ten.
get_requirements_for_interaction
¶
Drop the II-only (EE and BB) kernels unless other is IA too.
Mirrors toy_cloelib.contributions.TATTModel.get_requirements_for_
interaction, which drops its analogous pk_beta term for the same
reason: those terms only enter the II auto/cross correlation, never
the matter-intrinsic GI cross-correlation - computing them for a
GI-only analysis would be wasted one-loop-integral cost for terms
that get multiplied into a total no GI computation ever reads.
get_effective_pk
¶
get_effective_pk(other, bank: SpectraBank)
P_II^EE(k,z) or P_deltaI(k,z), as appropriate.
Bilinear in self's and other's own amplitude functions: reduces
exactly to the II form when other is self (or another
TATTContribution with identical parameters), and is the natural
generalisation for a genuine cross-population II term otherwise.
other's C1/C1delta/C2 are used when it exposes them (i.e. it's
also a TATTContribution); a plain NLAContribution
(NLA) has no C1delta/C2 of its own, so it's treated as
C1delta=C2=0 - the correct NLA limit, just cross-correlated against
this contribution's full TATT terms rather than assuming both sides
are identical.
The P_dd(z,k) terms use the base spectrum of the fields the two
sides trace (bank.base): P_mm against IA or lensing, the cb x
matter cross spectrum against the galaxy-bias term of a
PositionsTracer(use_Pcb=True).
Returns None (defers to the plain matter Pk) only if this call is
somehow reached with neither side being IA-like, which shouldn't
happen given get_requirements_for_interaction.
ShearTracer
¶
ShearTracer(perturbations: Perturbations, dndz: ndarray, z: ndarray, nuisance_params: dict, ia_model: str | Contribution | None = None, tatt_loop_computer: Optional[TATTLoopComputer] = None)
Class for the kernel for Cosmic Shear.
dndz is expected to have shape (n_bin, len(z)) with
normalized distributions. Per-bin width transformations are applied
before redshift shifts. z must not contain zero.
Parameters:
-
(perturbations¶Perturbations) –Backend supplying background and perturbation quantities used by the kernels.
-
(dndz¶ndarray) –Normalized tomographic distributions, shape
(n_bin, len(z)). -
(z¶ndarray) –One-dimensional redshift grid corresponding to the second axis of
dndz. -
(nuisance_params¶dict) –Mapping requiring one-based keys
multiplicative_bias_{i+1},dz_shear_{i+1}, andwidth_shear_{i+1}for each bin. -
(ia_model¶str | Contribution | None, default:None) –Which intrinsic-alignment contribution to use.
None(default) means no intrinsic-alignment contribution at all -get_window()/get_Cluse only the lensing term."NLA"buildsNLAContribution(get_window_IA, readingnuisance_params["AIA"/"CIA"/"EtaIA"])."TATT"builds aTATTContributionfromnuisance_params["AIA"](=A1),nuisance_params["A2IA"],nuisance_params["bTA"], and optionallynuisance_params["Eta2IA"]/["z0IA"](default 0.0/0.62). Advanced use: pass aContributioninstance directly to use any other model. -
(tatt_loop_computer¶Optional[TATTLoopComputer], default:None) –required when
ia_model="TATT"(raisesValueErrorif omitted) - theTATTContribution's one-loop kernel backend (seeTATTContribution's docstring). PassPBJTATTLoopComputer(perturbations)for real FAST-PT-computed kernels, or any other object with the same.compute(name)interface. Passing this with anyia_modelother than"TATT"raisesValueError.
Raises:
-
ValueError–If
zcontains zero,ia_modelis unknown, or the TATT loop-computer argument is inconsistent withia_model.
get_contributions
¶
Return this tracer's window as its separable Contribution terms.
Returns:
-
contributions(tuple) –(self.lensing,)ifia_model=None(the default - no intrinsic-alignment contribution), otherwise(self.lensing, self.ia).
get_ia_effective_spectra
¶
get_ia_effective_spectra(ks: Optional[ndarray] = None, zs: Optional[ndarray] = None) -> Dict[str, ndarray]
The IA model's own effective power spectra - P_II(k,z) and
P_deltaI(k,z) - the same grids AngularTwoPoint._compute_cl_
generalized integrates internally, exposed directly for
inspection/plotting/validation (e.g. against an external code's own
tabulated TATT spectra) without building a SpectraBank by hand.
Only meaningful for an IA model that defines its own effective
spectra (currently TATTContribution) - raises ValueError for
ia_model=None (no IA contribution) or ia_model="NLA" (whose
P_II/P_deltaI share the matter Pk's k-shape by construction: the
amplitude is applied directly inside get_window_IA, not exposed
as a separate grid).
Parameters:
-
(ks¶Optional[ndarray], default:None) –wavenumber grid to evaluate on. Defaults to
self.perturbations.k. -
(zs¶Optional[ndarray], default:None) –redshift grid to evaluate on. Defaults to
self.perturbations.z.
Returns:
-
dict(Dict[str, ndarray]) –{"II": P_II(k,z), "deltaI": P_deltaI(k,z)}, each shape(len(zs), len(ks)).
get_window_IA
¶
get_window_IA(z)
Return the NLA intrinsic-alignment kernel on z.
The per-bin kernel is -H(z)/c * AIA * CIA * Omega_m0 *
(1+z)**EtaIA / D(z) * dndz_shifted. If the backend returns a
scale-dependent growth factor, the second tabulated k column is used;
otherwise its scale-independent result is used. TATT amplitudes are
represented in effective spectra rather than by this NLA window.
Parameters:
-
(z¶array_like) –Redshift evaluation grid.
Returns a two-dimensional NLA kernel with one row per tomographic bin and one column per redshift.
get_lensing_efficiency_bin
¶
Compute the legacy single-bin lensing efficiency.
Uses Akima interpolation of the shifted bin distribution and a fixed
integration grid from redshift 0 to 4. The vectorized production
window path uses :meth:get_lensing_efficiency instead.
get_lensing_efficiency
¶
get_lensing_efficiency(z)
Compute the discretized lensing efficiency for every bin.
The efficiency uses dndz_shifted and the grid distance-ratio
factor 1 - chi(z_lens) / chi(z_source), contracted with cached
stacked Simpson weights. The supplied redshift grid is used as both
the lens and source grid; this implementation assumes uniform spacing.
Parameters:
-
(z¶ndarray) –1D, evenly spaced redshift evaluation grid.
Returns a two-dimensional lensing efficiency with one row per tomographic bin and one column per redshift.
Notes¶
- Assumes
zis evenly spaced; spacing is inferred asz[1] - z[0]. - Uses a precomputed Simpson rule weight matrix (
cached_stacked_simpson) for integration. self.dndz_shiftedhas shape(n_bin, len(z)).- Efficiency is evaluated using
np.einsum.
get_window_lensing
¶
get_window_lensing(z)
Return the radial weak-lensing kernel for the supplied redshifts.
It multiplies the discretized efficiency from
:meth:get_lensing_efficiency by
3/2 * (H0/c)**2 * Omega_m0 * (1+z) * chi(z). The harmonic shear
response is applied by AngularTwoPoint.
Parameters:
-
(z¶ndarray) –Redshift evaluation grid.
Returns a two-dimensional kernel with one row per bin and one column per redshift.
positions
¶
Angular (galaxy) clustering tracer: PositionsTracer and its Contributions.
Compatible with the Tracer protocol. Counterpart to photo.shear, which
holds ShearTracer.
NonLinearGalaxyBiasContribution (McDonald & Roy 2009, arXiv:0902.0991,
"Clustering of Dark Matter Tracers: Generalizing Bias for the Coming Era of
Precision LSS", Eqs. 39-40, extended with a bk2 non-local/counterterm
bias - see the class docstring): an alternative to the three purely-linear
galaxy_bias_model options GalaxyBiasContribution implements, selected
via PositionsTracer(..., galaxy_bias_model="nonlinear",
nl_bias_loop_computer=...). Its one-loop kernels come from a required
loop_computer - PBJNonlinearBiasLoopComputer: real physics, via
fastpt.FASTPT.one_loop_dd_bias_b3nl (the fast-pt PyPI package - an
optional dependency, pip install cloelib[fastpt]) on the linear matter
power spectrum. This is the same "closest available real physics via the
public fast-pt package" choice TATTContribution (photo/shear.py)
makes for intrinsic alignments.
Grounded in production CLOE (github.com/cloe-org/CLOE) where CLOE itself
provides the relevant recipe, and flagged plainly where it doesn't:
- The photometric galaxy-bias module cloe/non_linear/pgg_phot.py/
pgL_phot.py computes an equivalent set of terms, but in a different
basis - the Lagrangian bG2/bG3 "Gamma"-operator basis, via CLOE's own
non-public FASTPTPlus subclass (cloe/non_linear/eft.py::EFTofLSS) -
and has no bk2/counterterm bias at all. NonLinearGalaxyBiasContribution
uses the public-fast-pt-native Eulerian basis (b1, b2, bs2,
b3nl) instead, the same basis-choice tradeoff TATTContribution already
makes for IA (real physics via the public package's own API, rather than
reimplementing CLOE's private engine).
- CLOE's own "1-loop perturbation theory" counterterms (Euclid
Collaboration: Joudaki et al. 2026, "CLOE. 2. Code implementation",
arXiv:2603.22475, Sect. 3.7 - "linear, quadratic, and two non-local
galaxy biases, along with four counter-terms based on 1-loop
perturbation theory") are part of the spectroscopic (redshift-space)
power spectrum module instead, a distinct RSD-specific counterterm set,
not a photometric bk2. bk2's own k^2 P_{\delta\delta}(k,z) form
here follows the standard EFT-of-LSS treatment that same CLOE paper cites
for its own counterterms (Baumann et al. 2012, arXiv:1004.2488; Carrasco,
Hertzberg & Senatore 2012, arXiv:1206.2926) - see the class docstring.
See CONTRIBUTION_ARCHITECTURE.md for the design this all follows.
GalaxyBiasContribution
¶
GalaxyBiasContribution(tracer: PositionsTracer)
Galaxy-bias-weighted positions kernel term of PositionsTracer.get_window().
One of the three linear-bias models selected by galaxy_bias_model
(PositionsTracer.get_window_positions). galaxy_bias_model="nonlinear"
swaps in NonLinearGalaxyBiasContribution here instead - a different
galaxy-bias model, hence the distinct name; get_window()/
AngularTwoPoint don't need to change either way.
MagnificationContribution
¶
MagnificationContribution(tracer: PositionsTracer)
Magnification-bias kernel term of PositionsTracer.get_window().
Lensing by the total matter, so it traces MATTER even with
use_Pcb=True (the default field).
NonlinearBiasLoopComputer
¶
flowchart TD
cloelib.observables.photo.positions.NonlinearBiasLoopComputer[NonlinearBiasLoopComputer]
click cloelib.observables.photo.positions.NonlinearBiasLoopComputer href "" "cloelib.observables.photo.positions.NonlinearBiasLoopComputer"
Interface NonLinearGalaxyBiasContribution needs from its one-loop
kernel backend.
PBJNonlinearBiasLoopComputer is the production implementation; any
other object with this member can be passed as nl_bias_loop_computer.
compute
¶
Return a SpectrumRequest.compute callable for kernel name.
PBJNonlinearBiasLoopComputer
¶
PBJNonlinearBiasLoopComputer(perturbations: Perturbations)
FAST-PT-backed computer for the seven McDonald & Roy (2009) one-loop
galaxy-bias kernels used by NonLinearGalaxyBiasContribution.
Calls fastpt.FASTPT.one_loop_dd_bias_b3nl on the linear matter power
spectrum at z=0, with the same extrapolation settings and C_window
production CLOE's own FAST-PT-backed code uses (see module docstring).
The seven outputs are pure functions of k (no z-dependence -
NonLinearGalaxyBiasContribution supplies that separately via its
constant-in-z b1/b2/bs2/b3nl amplitudes), so they're computed once per
k-grid, cached, and reused across the seven named SpectrumRequests
(and across get_Cl calls, as long as the k-grid doesn't change)
instead of re-running FAST-PT per kernel name - the same caching
PBJTATTLoopComputer (photo/shear.py) uses, which this class mirrors
closely; see that class's docstring for the rationale behind each of
the shared choices below (linear-source resolution, log-uniform k-grid
construction, edge interpolation). One difference: the FAST-PT grid here
has at least _MIN_POINTS_PER_DECADE points per decade rather than
just len(ks) points, since sig3nl in particular needs the resolution.
Takes the same perturbations object you'd pass to PositionsTracer -
typically nonlinear, so this class resolves the actual linear source
itself: perturbations.linearperturbations if that attribute exists,
else perturbations itself (assumed already linear). Same known gap as
PBJTATTLoopComputer: CAMBNonLinearPerturbations does not (yet) set
.linearperturbations.
sig4 (FAST-PT's _get_sig4) is a single k-independent normalisation
constant (a UV-sensitive loop integral, not itself a function of k),
broadcast to a constant array shaped like the requested ks so it fits
the same compute(name) -> array(len(ks)) contract as every other
kernel.
Requires the optional fast-pt dependency (pip install
cloelib[fastpt]); raises ImportError with install instructions at
construction time.
compute
¶
Return the cached FAST-PT callable for a nonlinear-bias kernel.
name must be one of the kernel names in _NLBIAS_KERNELS.
The returned SpectrumRequest.compute(matter_pk, ks, zs) callable
ignores matter_pk and zs because these kernels depend only on
k, and returns shape (len(ks),). Kernels are cached while the
requested k grid is unchanged.
NonLinearGalaxyBiasContribution
¶
NonLinearGalaxyBiasContribution(tracer: PositionsTracer, b1: ndarray, loop_computer: NonlinearBiasLoopComputer, b2: ndarray, bs2: ndarray, b3nl: ndarray, bk2: ndarray)
Non-linear galaxy-bias kernel term of PositionsTracer.get_window(),
see module docstring for basis/citation notes.
Standard McDonald & Roy (2009, arXiv:0902.0991) Eulerian one-loop
expansion in (b1, b2, bs2, b3nl), extended with a bk2 non-local
("higher-derivative") counterterm bias in the standard EFT-of-LSS form
bk2 * k^2 * P_{\delta\delta}(k,z) (Baumann et al. 2012, Carrasco,
Hertzberg & Senatore 2012 - see module docstring). For two (possibly
different) instances self/other - the same tomographic bin's own
auto-spectrum when other is self, a genuine cross-population term
otherwise:
P_gg(z, k) = b1_a b1_b P_dd(z, k)
+ (1/2)(b1_a b2_b + b1_b b2_a) Pd1d2(k,z)
+ (1/4) b2_a b2_b [Pd2d2(k,z) - 2 sig4(z)]
+ (1/2)(b1_a bs2_b + b1_b bs2_a) Pd1s2(k,z)
+ (1/4)(b2_a bs2_b + b2_b bs2_a) [Pd2s2(k,z) - (4/3) sig4(z)]
+ (1/4) bs2_a bs2_b [Ps2s2(k,z) - (8/9) sig4(z)]
+ (1/2)(b1_a b3nl_b + b1_b b3nl_a) sig3nl(k,z)
+ (1/2)(b1_a bk2_b + b1_b bk2_a) k^2 P_dd(k,z)
P_g,delta(z, k) = b1 P_dd(z, k)
+ (1/2) b2 Pd1d2(k,z)
+ (1/2) bs2 Pd1s2(k,z)
+ (1/2) b3nl sig3nl(k,z)
+ (1/2) bk2 k^2 P_dd(k,z)
where Pd1d2/Pd2d2/Pd1s2/Pd2s2/Ps2s2/sig3nl are FAST-PT's
one_loop_dd_bias_b3nl kernels (pure functions of k, computed once at
z=0 by PBJNonlinearBiasLoopComputer) scaled to redshift z via the
growth factor D(z)^4 (_growth4) - the same z-scaling
TATTContribution._D4 applies to its own one-loop kernels, and for the
same reason: FAST-PT's one-loop integrals are only valid from the
linear Pk, so the z-dependence of a term quadratic in the linear
density field has to be supplied separately as D(z)^4, not read off
matter_pk (which is P_dd itself, i.e. D(z)^2 for the linear
part but includes nonlinear corrections beyond that). k^2 P_dd(k,z)
instead uses matter_pk directly (already fully z- and k-dependent, no
separate growth-factor scaling needed).
At b2=bs2=b3nl=bk2=0, P_gg/P_g,delta collapse exactly to
b1_a*b1_b * matter_pk/b1 * matter_pk - every other term is
multiplied by a zero amplitude - independent of the (real, but
then-irrelevant) kernel values this class's own tests check this
against.
P_g,delta is used for every pairing with a non-density contribution
(LensingContribution, MagnificationContribution, a CMB-lensing
kernel, ...) except an IntrinsicAlignmentContribution (NLA or TATT):
there, only the linear-bias term b1 P_dd is used (get_pk_terms
returns a single b1 * matter_pk term, deferring the rest of the
amplitude to the IA side's own kernel) - matching production CLOE's
Pgi_phot_halo_nla/_tatt (cloe/non_linear/pgL_phot.py,
github.com/cloe-org/CLOE), which likewise never applies its own
_add_NLbias_contributions_gL to the galaxy-intrinsic cross (a
documented CLOE limitation, not something specific to this class): the
higher-order bias corrections aren't modelled for that cross yet.
Unlike TATTContribution's global C1/C1delta/C2 amplitudes, b1/b2/
bs2/b3nl/bk2 here are genuinely per tomographic bin (arrays of
length tracer.n_z_bins, matching GalaxyBiasContribution's per-bin
b1_photo_bin{i}) - achieved via get_pk_terms (spectrum_engine.
PkTerm), which lets this class hand the generalized Limber engine
several per-bin-weighted-kernel pairs per contribution pairing
instead of the single shared-kernel/shared-Pk pair get_effective_pk
assumes (see PkTerm's docstring for why the ordinary get_effective_pk
mechanism can't express a per-bin amplitude). Redshift dependence
within a bin is not supported (each bias parameter is one constant
per bin, matching GalaxyBiasContribution's "per_bin" model, not its
"per_bin_int"/"poly" ones) - a real, deliberate scope limit.
Every term is built from the total matter power spectrum (P_dd =
P_mm, one-loop kernels from the linear P_mm), so this class traces
MATTER only: PositionsTracer(use_Pcb=True) raises
NotImplementedError for galaxy_bias_model="nonlinear".
Parameters:
-
(tracer¶PositionsTracer) –the owning
PositionsTracer. -
(b1¶ndarray) –linear bias (McDonald & Roy 2009 convention), shape
(n_z_bins,). -
(loop_computer¶NonlinearBiasLoopComputer) –object exposing
.compute(name) -> callable(matter_pk, ks, zs)for each of the seven kernel names in_NLBIAS_KERNELS- the "SpectrumComputer" for the one-loop terms. Required: passPBJNonlinearBiasLoopComputer(perturbations)(or build aPositionsTracerdirectly withgalaxy_bias_model="nonlinear", nl_bias_loop_computer=PBJNonlinearBiasLoopComputer(...), which does this for you), or any other object with the same interface. No default - likeTATTContribution, this only ever reports kernel values it can stand behind as real physics. -
(b2¶ndarray) –quadratic bias, shape
(n_z_bins,). -
(bs2¶ndarray) –tidal (
s^2) bias, shape(n_z_bins,). -
(b3nl¶ndarray) –third-order non-local bias, shape
(n_z_bins,). -
(bk2¶ndarray) –non-local/counterterm bias, shape
(n_z_bins,).
compute_kernel
¶
The b1 (linear-bias) part of the window only - diagnostic/
get_window() use (e.g. plotting), not what the generalized
engine uses for get_Cl (that goes through get_pk_terms, which
needs the b2/bs2/b3nl/bk2-weighted kernels too, each paired with
its own k-shape - see class docstring). Matches
GalaxyBiasContribution.compute_kernel's per-bin convention.
get_spectrum_requests
¶
Return one spectrum request per FAST-PT bias kernel.
Interaction-specific requirements may prune these requests when the other contribution is intrinsic alignment.
get_requirements_for_interaction
¶
Drop every one-loop kernel when paired with an IA contribution.
Paired with IntrinsicAlignmentContribution, get_pk_terms uses
only b1 * matter_pk (see class docstring) - no one-loop kernel is
needed for that pairing at all. Mirrors TATTContribution.
get_requirements_for_interaction's pairing-aware pruning, in the
opposite direction (fewer terms for the IA pairing here, rather
than for the non-IA one there).
get_pk_terms
¶
get_pk_terms(other, zs, bank: SpectraBank)
The PkTerms for P_gg(k,z) or P_g,delta(k,z), as
appropriate - see class docstring for both formulas and when each
applies. Returned in (self, other) order, per spectrum_engine.
get_pk_terms's contract.
zs (the tracer's own window/dndz z-grid, zs_calc in
AngularTwoPoint._compute_cl_generalized) is used only for the
window kernels (_bias_kernel/compute_kernel) - the returned
PkTerm.pk grids are built on bank.zs instead (see _loop_pk's
docstring for why these must be two different z-grids).
PositionsTracer
¶
PositionsTracer(perturbations: Perturbations, dndz: ndarray, z: ndarray, galaxy_bias_model: str, nuisance_params: dict, include_rsd: bool = False, nl_bias_loop_computer: NonlinearBiasLoopComputer | None = None, *, use_Pcb: bool = False)
Class to define the kernel for angular (galaxy) clustering.
dndz is expected to have shape (n_bin, len(z)). Per-bin
width transformations are applied before redshift shifts. The redshift
grid must not contain zero; the window integrations assume a suitably
sampled grid.
Parameters:
-
(perturbations¶Perturbations) –Backend providing the background and perturbation quantities required by this tracer.
-
(dndz¶ndarray) –Normalized tomographic redshift distributions, shape
(n_bin, len(z)). -
(z¶ndarray) –One-dimensional redshift grid matching the second axis of
dndz. -
(galaxy_bias_model¶str) –"per_bin"uses constant per-binb1_photo_bin{i};"per_bin_int"interpolates those values between each distribution's peak;"poly"usesb1_photo_poly0throughb1_photo_poly3;"nonlinear"selects the one-loop bias contribution and requiresnl_bias_loop_computer. Linear bias defaults to 1.0; nonlinearb1defaults to 1.0 andb2,bs2,b3nl, andbk2default to 0.0. Bias nuisance bin indices are zero-based. -
(nuisance_params¶dict) –Mapping containing required one-based
dz_pos_{i+1},width_pos_{i+1}, andmagnification_bias_{i+1}values, plus optional bias parameters described above. -
(include_rsd¶bool, default:False) –Whether to include the linear photo-RSD window in legacy
AngularTwoPointcalculations. The generalized contribution engine does not support RSD. -
(nl_bias_loop_computer¶NonlinearBiasLoopComputer | None, default:None) –Required for
galaxy_bias_model="nonlinear"and must implementcompute(name). Supplying it for another model, or omitting it for nonlinear bias, raisesValueError. -
(use_Pcb¶bool, default:False) –Keyword-only. A flag indicating whether to use the power spectrum of cold dark matter + baryons (no neutrinos). Must be a Python
bool(raisesTypeErrorotherwise). Not supported withgalaxy_bias_model="nonlinear"(raisesNotImplementedError).
Raises:
-
ValueError–If the redshift grid contains zero or the nonlinear loop-computer argument is inconsistent with the bias model.
get_contributions
¶
Return this tracer's window as its separable Contribution terms.
Returns:
-
contributions(tuple) –(self.bias, self.magnification)-self.biasis aGalaxyBiasContributionfor the three lineargalaxy_bias_models, or aNonLinearGalaxyBiasContributionforgalaxy_bias_model="nonlinear".
get_window_positions
¶
get_window_positions(z) -> ndarray
Return the bias-weighted positions kernel at redshifts z.
For each bin the kernel is b_i(z) * dndz_shifted_i(z) * H(z)/c.
The bias is constant per bin for per_bin and redshift-dependent
for per_bin_int and poly. In nonlinear mode this window is a
diagnostic using the linear b1 component; the full spectrum is
formed by the generalized contribution engine.
Parameters:
-
(z¶array_like) –Redshift evaluation grid compatible with the tracer's distributions.
Returns an array with one row per tomographic bin and one column per redshift.
get_window_rsd
¶
Linear photo-RSD window :math:W^{\rm RSD}_i(\ell,z) tabulated on the internal z-grid.
We use the shifted-distance (extended Limber) approximation, where the RSD contribution is written as a linear combination of the source term evaluated at shifted redshifts:
with $$ S_i(z)=\frac{H(z)\,f(z)}{c}\,n_i(z), $$
and shifted distances defined by the _alpha_coeffs factors:
$$
\chi_{-}=\frac{2\ell-3}{2\ell+1}\chi(z),\qquad
\chi_{+}=\frac{2\ell+5}{2\ell+1}\chi(z).
$$
The coefficients match _L_coeffs. Multipoles below 2 are set to
zero, and shifted-distance queries outside the tabulated chi grid
contribute zero.
$$
A_\ell=\frac{2\ell^2+2\ell-1}{(2\ell-1)(2\ell+3)},\quad
B_\ell=-\frac{\ell(\ell-1)}{(2\ell-1)\sqrt{(2\ell-3)(2\ell+1)}},\quad
C_\ell=-\frac{(\ell+1)(\ell+2)}{(2\ell+3)\sqrt{(2\ell+1)(2\ell+5)}}.
$$
Notes¶
chiis used purely as an interpolation coordinate soget_photo_rsdcan evaluate the shifted arguments efficiently.
Parameters¶
ells : array_like
Multipoles ell.
H, f : array_like
H(z) and growth rate f(z), sampled on the same z-grid as self.dndz_shifted.
chi : array_like
Comoving distance χ(z)=r(z), sampled on the same z-grid.
Returns¶
ndarray
The RSD window with shape (len(ells), n_bin, len(chi)).
get_magnification_efficiency
¶
get_magnification_efficiency(z)
Compute magnification efficiency for each bin from shifted dndz.
Parameters:
-
(z¶ndarray) –1D array of redshift values (must be evenly spaced). Used to compute comoving distances and define integration domain.
Returns:
-
ndarray–2D array of shape (N_bins, len(z)) representing the lensing efficiency kernel W(z) for each redshift bin over the evaluation grid.
Notes¶
- Assumes
zis evenly spaced; spacing is inferred asz[1] - z[0]. - Uses a precomputed Simpson rule weight matrix (
cached_stacked_simpson) for integration. self.dndz_shiftedhas shape(n_bin, len(z)).- Efficiency is evaluated using
np.einsum.
get_window_magnification
¶
get_window_magnification(z)
Return the magnification-bias contribution to the positions window.
The geometric efficiency is evaluated on the supplied redshift grid
using the shifted source distribution and Simpson weights; its
distance-ratio factor is 1 - chi(z_lens) / chi(z_source). The
resulting efficiency is multiplied by the usual matter-lensing
prefactor and the per-bin magnification_bias value.
Parameters:
-
(z¶array_like) –One-dimensional, evenly spaced redshift evaluation grid.
The returned two-dimensional kernel has one row per bin and one
column per redshift; each bin is multiplied by its
magnification_bias_{i+1} nuisance parameter.
get_window
¶
get_window(z) -> ndarray
Sum the bias and magnification contribution kernels.
Parameters:
-
(z¶array_like) –Redshift evaluation grid.
Returns an array with one row per bin and one column per redshift. In nonlinear-bias mode this is diagnostic; the generalized engine forms the full bias spectrum from contribution terms.
get_photo_rsd
¶
Evaluate the shifted-distance approximation to the photo-RSD kernel.
Parameters:
-
(ells¶array_like) –Multipoles, shape
(n_ell,). -
(chi¶array_like) –Comoving-distance grid, shape
(n_z), used as the interpolation coordinate. -
(S_bin_z¶array_like) –Source term sampled on
chi, shape(n_bin, n_z).
The returned RSD kernel is indexed by multipole, tomographic bin, and redshift. Shifted queries outside the supplied distance grid contribute zero; multipoles below two also have zero contribution.
tracer
¶
Tracer protocol for different window functions.
Tracer
¶
flowchart TD
cloelib.observables.photo.tracer.Tracer[Tracer]
click cloelib.observables.photo.tracer.Tracer href "" "cloelib.observables.photo.tracer.Tracer"
Tracer protocol to implement window functions.
n_z_bins
property
¶
Number of tomographic redshift bins carried by this tracer.
Not used by the tracer itself, but required by
AngularTwoPoint.get_Cl to size its output. Declared here so it is
part of the documented contract rather than an implicit assumption.
z
property
¶
Redshift grid this tracer was built on.
Required by AngularTwoPoint.get_Cl, which reads tracer1.z as the
integration grid for the Limber integral.
prefact_toggle
property
¶
Whether the spin-2-to-convergence Limber prefactor applies (1) or not (0).
Required by AngularTwoPoint.get_Cl. ShearTracer sets this to 1,
PositionsTracer/CMBLensingTracer to 0.
contributions
¶
Contribution
¶
flowchart TD
cloelib.observables.photo.contributions.Contribution[Contribution]
click cloelib.observables.photo.contributions.Contribution href "" "cloelib.observables.photo.contributions.Contribution"
A single additive term of a tracer's window function.
spectrum_engine.py and photo.shear's TATTContribution extend this
with three optional methods, deliberately left out of this Protocol
so every simpler Contribution is unaffected:
get_spectrum_requests() -> Sequence[SpectrumRequest]: derived power spectra this contribution needs beyond the plain matter Pk (default, for anything not defining it: none).get_requirements_for_interaction(other) -> Sequence[SpectrumRequest]: context-aware version of the above - e.g. TATT needs fewer terms when paired with a non-IA contribution than with another IA one (default:get_spectrum_requests(), unconditionally).get_effective_pk(other, bank) -> Optional[Array]: the effective P(k,z) this contribution's pairing withothershould be integrated against, shape(len(bank.zs), len(bank.ks))(default:None, meaning "use the plain matter Pk", today's behavior for everything).
spectrum_engine.py looks these up via getattr(obj, name, None)
rather than requiring them here, so nothing below needs to change.
An optional field attribute (MATTER or CB, read through
contribution_field) states which density field the contribution
traces; it selects the base power spectrum of each contribution pair
in AngularTwoPoint (default: MATTER).
compute_kernel
¶
Return this contribution's kernel, shape (n_bins, len(z)).
IntrinsicAlignmentContribution
¶
Base class for every intrinsic-alignment model - the general "this is
an IA contribution" type. NLAContribution and TATTContribution
(photo/shear.py) are its two concrete models today; a future IA model
would be a third subclass here, not a fourth unrelated name.
Lets a contribution ask "is the other side of this pairing also IA?" -
e.g. TATT needs its II-only one-loop terms (Eq. 14 of Navarro-Gironés
et al. 2026) only when paired with another IA contribution, not with a
density/lensing one - via isinstance(other,
IntrinsicAlignmentContribution). Mirrors toy_cloelib.contributions.
AbstractIAContribution, which the same TATT pruning logic there relies
on. Carries no behavior of its own: a plain base class, not a
typing.Protocol - an empty @runtime_checkable Protocol matches
any object under isinstance (nothing to structurally check for),
which would silently break the II-vs-GI pruning this class exists for.
NLAContribution and LensingContribution both satisfy the same
Contribution Protocol (compute_kernel(z)), so "is this IA" is a
nominal question with no structural feature to key a Protocol off.
The concrete photometric-probe Contributions (LensingContribution,
NLAContribution, TATTContribution, ... for shear;
GalaxyBiasContribution, MagnificationContribution for positions)
live alongside their owning tracer in cloelib.observables.photo.shear
/ .positions - this module holds only the generic, tracer-agnostic
base types spectrum_engine.py and both submodules share.
unit_sigma
¶
Default MG lensing parameter Sigma(z) = 1 for GR / LCDM perturbations.
Every lensing kernel (shear, magnification bias, CMB lensing) multiplies by
perturbations.Sigma(z) when the perturbations provide it, and by this
otherwise.
contribution_field
¶
contribution.field if defined, else MATTER.
Only contributions that can trace the cold dark matter + baryons field
(e.g. GalaxyBiasContribution of a PositionsTracer(use_Pcb=True))
define field; everything else (lensing, magnification, intrinsic
alignments, ...) traces the total matter and needs no change.
spectrum_engine
¶
Generalized per-contribution-pair spectrum engine.
contributions.py gives each tracer's window terms their own Contribution
object. Most of them only ever need the plain matter power spectrum P(k,z),
so AngularTwoPoint.get_Cl can pair one shared Pk grid against the
tracer-level window sum. TATT breaks that assumption: its II (and GI)
power spectra are sums of several distinct k-dependent terms (Eqs. 13-15
of Navarro-Gironés et al. 2026, arXiv:2602.16448, following Blazek et al.
2019), each needing its own one-loop kernel, not just P(k,z). This module
is the minimal machinery that lets a Contribution declare "I need these
extra derived spectra" and get them computed once (and only if actually
needed for the pairing at hand) before the Limber integral runs - the same
principle toy_cloelib demonstrates (see its engine.py /
ARCHITECTURE_REVIEW.md Sect. 1.2), adapted here without adding new
dependencies (no equinox/plum): plain dataclasses and a
getattr(..., default) lookup, matching how AngularTwoPoint already
dispatches on tracer type (tracer_rules, angular_two_point.py).
Nothing here changes behavior for any Contribution that doesn't declare
extra requests: needs_generalized_engine returns False for them, and
AngularTwoPoint.get_Cl keeps using its original, untouched fast path in
that case.
SpectrumRequest
dataclass
¶
One derived power-spectrum grid a Contribution needs beyond P(k,z).
Attributes:
-
name(str) –unique key this grid is stored/looked up under in a
SpectraBank. Two contributions declaring the samenameshare one computation (memoized bySpectraBank). -
compute(Callable[..., ndarray]) –compute(matter_pk, ks, zs) -> Array, shape(len(zs), len(ks))or(len(ks),)for a pure k-kernel - whatever shape the requesting Contribution'sget_effective_pkexpects back. This is the "SpectrumComputer": the math that turns the base matter power spectrum into the derived one. Swapping the physics (e.g. a PBJ-backed computer instead of a placeholder) means passing a differentcomputecallable, not touching the Contribution.
SpectraBank
¶
Memoized store of the power-spectrum grids for one get_Cl call.
Holds two kinds of grids on the (zs, ks) grid, each computed at most
once and only when first asked for:
- base spectra,
base(field1, field2):P_mm,P_cband the cb x matter cross spectrum, combined from the backend'sP_mmandP_cb(and their linear counterparts when the cross spectrum needs them); - derived spectra,
get(request): e.g. TATT's one-loop kernels, computed frommatter_pk(P_mm).
Not shared across calls - AngularTwoPoint builds one per get_Cl with
from_perturbations. Built directly from an already evaluated
matter_pk instead (SpectraBank(matter_pk, ks, zs)), only the total
matter is available: base raises for any pair involving cb.
matter_pk
property
¶
The total matter power spectrum P_mm, shape (len(zs), len(ks)).
from_perturbations
classmethod
¶
from_perturbations(perturbations, ks, zs) -> SpectraBank
Bank evaluating every spectrum lazily from perturbations.
base
¶
Base power spectrum for a pair of traced fields.
P_mm for (MATTER, MATTER), P_cb for (CB, CB) and the cb x
matter cross spectrum for a mixed pair, with the fields given by
contributions.contribution_field. The fields are static Python
strings, so the choice is resolved at trace time and is safe under
jax.jit/jax.grad.
Returns:
-
Array(ndarray) –shape
(len(zs), len(ks)).
get
¶
get(request: SpectrumRequest) -> ndarray
Return the named derived grid, computing and caching it on first use.
PkTerm
dataclass
¶
One additive term of a contribution-pair's Limber integrand:
Cl += Cl_integration(kernel1, kernel2, pk, ...).
Generalizes get_effective_pk (a single (compute_kernel, compute_
kernel, effective_pk) triple per pairing) to a sum of triples with
their own, different kernels - needed whenever a contribution's bias
amplitudes vary per tomographic bin (e.g.
NonLinearGalaxyBiasContribution's per-bin b1/b2/bs2/b3nl/bk2): its
P_gg(k,z) is a sum of terms like 0.5*(b1_i*b2_j + b1_j*b2_i)*Pd1d2(k),
which isn't expressible as one shared kernel pair times one shared
effective Pk (the standard get_effective_pk contract) because the
bin-dependence lives in different bias-weighted kernels per term, not
in one amplitude-free kernel times one Pk. Contributions whose
amplitudes are global (not per-bin), e.g. TATTContribution, have no
need for this and keep using get_effective_pk.
Attributes:
-
kernel1(ndarray) –window kernel for the first tracer, shape
(n_bin1, len(zs))- not necessarily this term's own contribution'scompute_kernel(z)output. -
kernel2(ndarray) –window kernel for the second tracer, shape
(n_bin2, len(zs))- same caveat askernel1. -
pk(ndarray) –the power spectrum this term should be integrated against, shape
(len(bank.zs), len(bank.ks))- asget_effective_pkreturns, but scoped to just this one additive term.
needs_generalized_engine
¶
Whether any contribution-pair in this tracer pair needs extra spectra.
Pure Python over Contribution types/declared requests, evaluated
before any Limber integration - safe to call from plain (non-jitted)
get_Cl code, and cheap enough to call on every get_Cl invocation.
get_effective_pk
¶
get_effective_pk(c1, c2, bank: SpectraBank)
The effective P(k,z) for the pairing (c1, c2), or None.
Tries c1.get_effective_pk(c2, bank) first, then c2.get_effective_pk(
c1, bank) - the P(k,z) two contributions should be integrated against
is a property of the pairing, not of either side alone (e.g. a plain
LensingContribution never defines this, but a TATTContribution it's
paired with does, regardless of argument order: P_deltaI(k,z) is the
same scalar grid whichever contribution is asked). None means neither
side has anything special to say - use the pair's base spectrum
(SpectraBank.base), i.e. every non-TATT pairing.
compute_effective_pk
¶
One-call convenience wrapper: get_effective_pk for a pairing that
doesn't already have a SpectraBank lying around.
AngularTwoPoint._compute_cl_generalized builds a SpectraBank and
calls get_effective_pk per contribution pair as part of computing a
full Cl, but that bank is a local variable, not something callers can
get at directly - anyone who wants just the effective P(k,z) itself
(e.g. to plot or validate it, without integrating a full Cl) would
otherwise have to reconstruct a SpectraBank by hand. This does that
reconstruction for you, in one call:
P_II = compute_effective_pk(tracer.ia, tracer.ia, matter_pk, ks, zs)
P_deltaI = compute_effective_pk(tracer.ia, tracer.lensing, matter_pk, ks, zs)
matter_pk must already be evaluated on (zs, ks) (e.g.
perturbations.matter_power_spectrum(zs, ks)) - this doesn't compute
it for you, since which perturbations object to use is caller
context this function has no way to guess. Returns None for any
pairing with nothing special to say (e.g. two plain, non-IA
contributions) - same as get_effective_pk.
get_pk_terms
¶
get_pk_terms(c1, c2, zs, bank: SpectraBank)
The PkTerms for the pairing (c1, c2), or None.
Tries c1.get_pk_terms(c2, zs, bank) first, then c2.get_pk_terms(c1,
zs, bank) - mirrors get_effective_pk's own order-dependent
resolution (see its docstring), generalized to a list of terms instead
of one. A Contribution.get_pk_terms(other, zs, bank) implementation
must return its terms in (self, other) order regardless of which
tracer position it's called from - this resolver swaps kernel1/
kernel2 back into (c1, c2) order when c2 is the side that
actually defined the terms, so callers never need to know which side
supplied them.
None means neither side needs this - callers should fall back to
get_effective_pk (still None for a pairing needing neither).
cmb
¶
Module implementing CMB lensing.
This class is compatible with the Tracer protocol.
CMBLensingContribution
¶
CMBLensingContribution(tracer: CMBLensingTracer)
CMB-lensing convergence kernel term of CMBLensingTracer.get_window().
Lets CMBLensingTracer participate in the generalized
per-contribution-pair spectrum engine
(cloelib.observables.photo.spectrum_engine) whenever it's paired with
a contribution that itself declares extra SpectrumRequests (e.g.
NonLinearGalaxyBiasContribution, TATTContribution). Without this,
getattr(tracer, "get_contributions", lambda: ())() returns an empty
tuple for CMBLensingTracer, which silently disables the generalized
engine for any pairing involving CMB lensing (an empty
contributions2 means spectrum_engine.needs_generalized_engine's
for c2 in contributions2 loop never runs) - falling back to the
legacy path's plain get_window/matter-Pk integral even when the other
side needs its own effective P(k,z) (e.g. NonLinearGalaxyBiasContribution's
amplitude-free kernel, which relies on get_effective_pk to supply the
bias amplitude at all). Carries no get_spectrum_requests of its own -
CMB lensing needs nothing beyond the plain matter Pk (or, paired with a
density contribution, that contribution's own galaxy-matter cross
spectrum) - so pairing CMB lensing with anything that itself declares
no extra requests still takes the untouched legacy path, exactly as
before this class existed.
CMBLensingTracer
¶
CMBLensingTracer(perturbations: Perturbations, z: ndarray)
Class for the kernel for CMB Lensing convergence.
Parameters¶
perturbations : object An object from NonLinearPerturbations class z : np.ndarray A 1-dimensional array used to perform line-of-sight integration.
get_contributions
¶
Return this tracer's window as its separable Contribution terms.
Returns:
-
contributions(tuple) –(self.convergence,).
get_window
¶
Computes CMB lensing window function
Parameters¶
z: float Redshift at which window kernel is being evaluated
Returns¶
window: np.ndarray
gw
¶
Gravitational-wave number-count and weak-lensing tracers.
GWNumberCountsTracer lives in gw.number_counts, and
GWWeakLensingTracer lives in gw.weak_lensing. Both implement the tracer
interface consumed by AngularTwoPoint and are re-exported here for concise
imports.
number_counts
¶
GW number-count tracer: GWNumberCountsTracer and its Contributions.
Compatible with the Tracer protocol. Counterpart to gw.weak_lensing, which
holds GWWeakLensingTracer.
GWSourceBiasContribution
¶
GWSourceBiasContribution(tracer: GWNumberCountsTracer)
Source-bias-weighted kernel term of GWNumberCountsTracer.get_window().
Currently one of the three linear-bias models selected by
gw_bias_model (GWNumberCountsTracer.get_window_number_counts).
GWNumberCountsTracer
¶
GWNumberCountsTracer(perturbations: Perturbations, dndz: ndarray, z: ndarray, gw_bias_model: str, nuisance_params: dict)
Tracer for the angular number density of GW sources.
Parameters:
-
(perturbations¶Perturbations) –Perturbation backend providing a compatible background cosmology.
-
(dndz¶ndarray) –A n-dimensional array representing the number density distribution of GW sources as a function of redshift, with shape
(n_bins, n_z). It is expected to be normalised. -
(z¶ndarray) –Evenly sampled, non-zero redshift grid with shape
(n_z,)corresponding to the last axis ofdndz. -
(gw_bias_model¶str) –A string specifying the model used to describe the GW source bias.
-
(nuisance_params¶dict) –Redshift-shift and width parameters for every bin, plus parameters for the selected GW bias model.
get_contributions
¶
Return this tracer's window as its separable Contribution terms.
The contribution currently delegates to get_window_number_counts.
Returns:
-
contributions(tuple) –(self.bias,).
get_window_number_counts
¶
get_window_number_counts(z) -> ndarray
GW number-count window function.
Implements the GW number-count source-density window, analogous to
PositionsTracer.get_window_positions, with the galaxy bias replaced
by the GW source bias.
Parameters:
-
(z¶ndarray) –Redshift grid at which to evaluate the window.
Returns:
-
window_number_counts(ndarray) –Angular GW number-count windows with shape
(n_bins, n_z).
weak_lensing
¶
GW weak-lensing tracer: GWWeakLensingTracer and its Contributions.
Compatible with the Tracer protocol. Counterpart to gw.number_counts, which
holds GWNumberCountsTracer.
GWWeakLensingContribution
¶
GWWeakLensingContribution(tracer: GWWeakLensingTracer)
Weak-lensing convergence kernel term of GWWeakLensingTracer.get_window().
GWWeakLensingTracer
¶
GWWeakLensingTracer(perturbations: Perturbations, dndz: ndarray, z: ndarray, nuisance_params: dict)
Tracer for weak-lensing convergence inferred from GW sources.
Parameters:
-
(perturbations¶Perturbations) –Perturbation backend providing a compatible background cosmology.
-
(dndz¶ndarray) –A n-dimensional array representing the number density distribution of GW sources as a function of redshift, with shape
(n_bins, n_z). It is expected to be normalised. -
(z¶ndarray) –A 1 dimensional array representing the evenly sampled, non-zero redshift grid with shape
(n_z,)corresponding to thedndzarray. -
(nuisance_params¶dict) –Redshift-shift and width parameters for every bin.
get_contributions
¶
Return this tracer's window as its separable Contribution terms.
Returns:
-
contributions(tuple) –(self.lensing,).
get_lensing_efficiency_bin
¶
Compute the GW lensing efficiency in a redshift bin.
get_lensing_efficiency
¶
get_lensing_efficiency(z) -> ndarray
Compute the GW lensing efficiency kernel for each redshift bin.
This function calculates the geometric lensing kernel W(χ), which weights the contribution
of matter at different redshifts to the weak lensing signal, for a given redshift grid z.
Parameters:
-
(z¶ndarray) –1D array of redshift values (must be evenly spaced). Used to compute comoving distances and define integration domain.
Returns:
-
ndarray–2D array of shape (N_bins, len(z)) representing the lensing efficiency kernel W(z) for each redshift bin over the evaluation grid.
Notes¶
- Assumes
zis evenly spaced; spacing is inferred asz[1] - z[0]. - Uses a precomputed Simpson rule weight matrix (
cached_stacked_simpson) for integration. self.dndz_shiftedis expected to have shape (N_bins, len(z)) and be normalized.- Efficiency is evaluated using
np.einsum.
get_window_lensing
¶
get_window_lensing(z) -> ndarray
GW weak-lensing convergence kernel.
Calculates the GW weak-lensing kernel for a given tomographic bin
distribution. The underlying geometry is the scalar convergence
kernel. The observable-dependent harmonic response is applied in
AngularTwoPoint. There is no magnification bias,
intrinsic alignment, or multiplicative shear factor in this tracer.
Parameters:
-
(z¶ndarray) –One-dimensional redshift grid matching the source distributions.
Returns:
-
ndarray–Numpy array of convergence kernel values of shape (n_bins, n_z)
spectro
¶
Spectroscopic-probe interfaces: the SpectroPower protocol and its
PT/emulator backends (PBJ, Comet).
spectro.spectro holds the SpectroPower protocol itself;
spectro.PBJ_spectro, spectro.CometEFT_spectro, spectro.CometVDG_spectro
each hold one backend implementing it. Grouped together here for file-tree
organization; moved from the old flat cloelib/observables/PBJ_spectro.py/
CometEFT_spectro.py/CometVDG_spectro.py (imports updated at every call
site - no back-compat shims left at the old paths).
CometEFT_spectro
¶
Interface of Legendre Multiples with Comet.
CometEFT_SpectroPower
¶
CometEFT_SpectroPower(background: Background, RSD_parameters: dict, redshift: float)
Class to retrieve \(P(k,\mu)\) (including RSD) with the EFT model from COMET.
Parameters:
-
(background¶Background) –Background class containing cosmology and background distances
-
(RSD_parameters¶dict) –Dictionary containing bias and counterterm parameters
-
(redshift¶float) –Redshift at which to evaluate \(P(k,\mu)\)
CometVDG_spectro
¶
Interface of Legendre Multiples with Comet.
CometVDG_SpectroPower
¶
CometVDG_SpectroPower(background: Background, RSD_parameters: dict, redshift: float)
Class to retrieve \(P(k,\mu)\) (including RSD) with the VDG model from COMET.
Parameters:
-
(background¶Background) –Background class containing cosmology and background distances
-
(RSD_parameters¶dict) –Dictionary containing bias and counterterm parameters
-
(redshift¶float) –Redshift at which to evaluate \(P(k,\mu)\)
PBJ_spectro
¶
Interface of Legendre Multipoles with PBJ.
PBJLinearPerturbations
¶
flowchart TD
cloelib.observables.spectro.PBJ_spectro.PBJLinearPerturbations[PBJLinearPerturbations]
cloelib.cosmology.cosmology.Perturbations[Perturbations]
cloelib.cosmology.cosmology.Perturbations --> cloelib.observables.spectro.PBJ_spectro.PBJLinearPerturbations
click cloelib.observables.spectro.PBJ_spectro.PBJLinearPerturbations href "" "cloelib.observables.spectro.PBJ_spectro.PBJLinearPerturbations"
click cloelib.cosmology.cosmology.Perturbations href "" "cloelib.cosmology.cosmology.Perturbations"
The Perturbations interface plus the extras PBJSpectroPower uses.
.z, growth_factor_cb and the hubble_units/k_hunit keywords of
matter_power_spectrum(_cb) are not part of Perturbations (not every
backend provides them), but the Boltzmann-code backends PBJ is used
with (CAMB, CLASS and variants) do.
matter_power_spectrum
¶
Linear total-matter power spectrum.
matter_power_spectrum_cb
¶
Linear cdm+baryon power spectrum.
growth_factor
¶
Growth factor, also for a scalar redshift/wavenumber.
growth_rate
¶
Calculate the growth rate for given redshifts and wavenumbers.
Parameters:
-
(zs¶Optional[T], default:None) –One-dimensional NumPy or JAX array of redshifts, with shape
(nz,). IfNone, implementations use the redshift grid they were built on; implementations without a default grid may raiseValueError. -
(ks¶Optional[T], default:None) –One-dimensional NumPy or JAX array of wavenumbers in
1/Mpc, with shape(nk,). IfNone, return the growth rate as a function of redshift only.
Returns:
-
T(T) –NumPy or JAX array of growth-rate values. With
ks=None, the -
T–shape is
(nz,); with wavenumbers supplied, the shape is -
T–(nz, nk). Scale-independent growth rates are broadcast along -
T–the wavenumber axis.
PBJSpectroPower
¶
PBJSpectroPower(linear_perturbations: PBJLinearPerturbations, nuisance_parameters: dict, redshift: float)
Class to retrieve \(P(k,\mu)\) with the EFT model from PBJ.
Parameters:
-
(linear_perturbations¶PBJLinearPerturbations) –Perturbations object containing cosmology, linear power spectrum, and growth functions
-
(nuisance_parameters¶dict) –Dictionary containing bias and counterterm parameters
-
(redshift¶float) –single redshift in which to evaluate PBJ
Pk2d_rsd
¶
Pk2d_term_rsd
¶
2D power spectrum for a subset of specific diagrams of the loop expansion, corresponding to linear parameters that can be analytically marginalised over.
Parameters¶
k: np.ndarray Wavenumber mu: np.ndarray Angle (cosinus) to the line of sight term_list: list Identifiers of loop diagrams. Available options: 'bG3', 'c0', 'c2', 'c4', 'ck4'
Returns¶
Pk2d: np.ndarray 2D power spectrum of specific terms
spectro
¶
SpectroPower protocol.
SpectroPower
¶
flowchart TD
cloelib.observables.spectro.spectro.SpectroPower[SpectroPower]
click cloelib.observables.spectro.spectro.SpectroPower href "" "cloelib.observables.spectro.spectro.SpectroPower"
Protocol to define the \(P(k,\mu)\) interface.
Pk2d_rsd
¶
2D power spectrum from couplings of density and velocity fields.
Parameters:
-
(k¶ndarray) –Wavenumber. Can be NumPy (
numpy.ndarray) or JAX (jax.numpy.ndarray) ndarray. -
(mu¶ndarray | ndarray) –Angle (cosinus) to the line of sight. Can be NumPy (
numpy.ndarray) or JAX (jax.numpy.ndarray) ndarray.
Returns:
-
Pk2d_rsd(ndarray | ndarray) –2D power spectrum from couplings of density and velocity fields
Pk2d_term_rsd
¶
2D power spectrum for a subset of specific term of the loop expansion.
Parameters:
-
(k¶ndarray | ndarray) –Wavenumber. Can be NumPy (
numpy.ndarray) or JAX (jax.numpy.ndarray) ndarray. -
(mu¶ndarray | ndarray) –Angle (cosinus) to the line of sight. Can be NumPy (
numpy.ndarray) or JAX (jax.numpy.ndarray) ndarray.
Returns:
-
Pk2d_term_rsd(ndarray | ndarray) –2D power spectrum of specific terms. Can be NumPy (
numpy.ndarray) or JAX (jax.numpy.ndarray) ndarray.
halos
¶
Modules relative to galaxy clusters
halo_model_properties
¶
HaloModelProperties
¶
HaloModelProperties(perturbations: Perturbations, interpolate_pk: bool = True, interpolate_da: bool = True, z=linspace(1e-05, 2.0 - 1e-05, 100), k=geomspace(0.0001, 10, 500))
Initialize the class with given perturbations and overdensity definition. If requested, cosmological functions (e.g., the matter power spectrum) are interpolated.
Parameters¶
perturbations : Perturbations
An object from the LinearPerturbations class containing cosmological
perturbation data (e.g., power spectrum, growth function).
interpolate_pk : bool, optional
If true, the class interpolates the matter power spectrum.
A default interpolation is set when class is instanciated with
interpolate_pk=True. For a more customized interpolation, check
the set_matter_power_spectrum_interpolation function.
interpolate_da : bool, optional
If true, the class interpolates the angular diameter distance.
A default interpolation is set when class is instanciated with
interpolate_da=True. For a more customized interpolation, check
the set_angular_diameter_distance_interpolation function.
Notes¶
In the current implementation, the matter power spectrum never includes the contribution of massive neutrinos. Halo mass function, halo bias, and 2-halo profile models implemented in this subpackage require cold dark matter + baryons (no neutrinos) power spectra.
angular_diameter_distance
¶
matter_power_spectrum_cb
¶
Computes the non interpolated matter power spectrum.
This function computes the cold dark matter + baryons power spectrum, not including the massive neutrino contribution.
Parameters¶
z: float or np.ndarray Redshift. k: float or np.ndarray Wavenumber where W(kR) is evaluated. Units: h Mpc^{-1}
Returns¶
float or np.ndarray Matter power spectrum.
set_matter_power_spectrum_interpolation
¶
Create internal interpolation of matter power spectrum.
This function interpolates the cold dark matter + baryons power spectrum, not including the massive neutrino contribution.
Parameters¶
z: float or np.ndarray Redshift. k: float or np.ndarray Wavenumber where W(kR) is evaluated. Units: h Mpc^{-1}
set_angular_diameter_distance_interpolation
¶
Create internal interpolation of angular diameter distance.
Parameters¶
z: float or np.ndarray Redshift.
surface_mass_density_2h
¶
Surface 2-halo matter density profile.
Computes the cosmological unbiased surface 2-halo density profile at radius R.
Parameters¶
R: np.ndarray Radial points (units : Mpc / h) z: np.ndarray Redshift. radius_units: str Unit for the input radius. Accepted values are: "Mpc/h", "radians", "degrees", "arcmin", "arcsec".
Returns¶
Sigma: np.ndarray 2-halo surface mass density profile (units : h * Msun / pc**2). Shape: (z.size, R.size).
excess_surface_mass_density_2h
¶
Excess surface 2-halo matter density profile.
Computes the cosmological unbiased excess surface 2-halo density profile at radius R.
Parameters¶
R: np.ndarray Radial points (units : Mpc / h) z: np.ndarray Redshift. radius_units: str Unit for the input radius. Accepted values are: "Mpc/h", "radians", "degrees", "arcmin", "arcsec".
Returns¶
DeltaSigma: np.ndarray 2-halo surface mass density profile (units : h * Msun / pc**2). Shape: (z.size, R.size).
halo_abundance
¶
castro_halo_abundance
¶
CastroHaloAbundance
¶
CastroHaloAbundance(halo_model_properties: HaloModelProperties)
flowchart TD
cloelib.observables.halos.halo_abundance.castro_halo_abundance.CastroHaloAbundance[CastroHaloAbundance]
cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase[HaloAbundanceBase]
cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase --> cloelib.observables.halos.halo_abundance.castro_halo_abundance.CastroHaloAbundance
click cloelib.observables.halos.halo_abundance.castro_halo_abundance.CastroHaloAbundance href "" "cloelib.observables.halos.halo_abundance.castro_halo_abundance.CastroHaloAbundance"
click cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase href "" "cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase"
Class implementing the Castro et al. mass abundance models.
Castro et al. followed the cold dark matter prescription by Costanzi+13 (https://arxiv.org/abs/1311.1514) and Castorina+13 (https://arxiv.org/pdf/1311.1212). That is, the halo mass function and halo bias do not include the massive neutrino contribution in the computation of mass variance, power spectrum, and overdensity.
Initialize the class with given perturbations and overdensity definition.
Parameters¶
halo_model_properties : HaloModelProperties
An object from the HaloModelProperties class.
sigma8_0
property
¶Returns the sigma_8 value at redshift z=0. If sigma_8
is not set as a base parameter, it is computed from the power spectrum.
The contribution from massive neutrinos is not included in the power
spectrum.
f_sigma_nu
¶Computation of the multiplicity function.
Computes the Castro et al. (2023) multiplicity function at the requested redshift and mass points. Valid only for virial overdensities.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
f_sigma_nu: numpy.ndarray f_sigma_nu[i,j], where i is the redshift axis and j the mass axis
bias
¶Computation of the halo bias.
Computes the Castro et al. (2024) halo bias at the requested redshift and mass points. Valid only for virial overdensities.
Parameters¶
z: numpy.ndarray Redshift points M: numpy.ndarray Mass points in h^{-1} Msun
Returns¶
bias: numpy.ndarray bias[i,j], where i is the redshift axis and j the mass axis
Notes¶
If the mass array has less than 4 entries, this causes problem with the derivative
dn_dm_fsigmanu
¶Derivative of the number density with pre-computed halo mass function.
Computes the derivative of the number density at the requested redshift and mass points. This implementation follows the cold dark matter prescription by Costanzi+13 (https://arxiv.org/abs/1311.1514).
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun. fsigmanu: numpy.ndarray Multiplicity function.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
window
¶Top-hat window and its derivative.
Computes the top-hat window function and its derivative.
Parameters¶
k: numpy.ndarray Wavenumber where W(kR) is evaluated. Units: h Mpc^{-1} R: numpy.ndarray Radius where W(kR) is evaluated. Units: h^{-1} Mpc
Returns¶
W: numpy.ndarray W[i,j], where i is the wavenumber axis and j the radius axis dWdx: numpy.ndarray dWdx[i,j], where i is the wavenumber axis and j the radius axis
radius_M
¶ sigma_z_R
¶Standard deviation of perturbations given a redshift and radius.
Computes the rms at the radii requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. R: numpy.ndarray Radius points in h^{-1} Mpc.
Returns¶
sigma_z_R: numpy.ndarray sigma_z_R[i,j], where i is the redshift axis and j the radius axis.
sigma_z_M
¶Standard deviation of perturbations given a redshift and mass.
Computes the rms at the masses requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
sigma_z_M: numpy.ndarray sigma_z_M[i,j], where i is the redshift axis and j the mass axis.
delta_c
¶Critical overdensity.
Computes the critical overdensity at a given redshift following an approximation from Kitayama & Suto (1999). The contribution from massive neutrinos is not included in the matter density parameter.
Parameters¶
z: float or np.ndarray Redshift at which to evaluate the delta_c
Returns¶
delta_c: float or numpy.ndarray Value of the critical overdensity a given redshift.
nu_z_M
¶Peak height.
Computes the critical overdensity over the rms, delta_c/sigma, at a given redshift and mass. The contribution from massive neutrinos is not included in the power spectrum and in the matter density parameter.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points.
Returns¶
nu_z_M: numpy.ndarray nu_z_M[i,j], where i is the redshift axis and j the mass axis.
dlns_dlnM
¶Derivative of the logarithmic rms.
Computes the derivative of the ln rms with respect to the ln of mass at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dlns_dlnM: numpy.ndarray dlns_dlnM[i,j], where i is the redshift axis and j the mass axis.
dn_dm
¶Derivative of the number density.
Computes the derivative of the number density at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
halo_abundance_base
¶
HaloAbundanceBase
¶
HaloAbundanceBase(halo_model_properties: HaloModelProperties)
Initialize the class with given perturbations and overdensity definition.
Parameters¶
halo_model_properties : HaloModelProperties
An object from the HaloModelProperties class.
sigma8_0
property
¶Returns the sigma_8 value at redshift z=0. If sigma_8
is not set as a base parameter, it is computed from the power spectrum.
The contribution from massive neutrinos is not included in the power
spectrum.
dn_dm_fsigmanu
¶Derivative of the number density with pre-computed halo mass function.
Computes the derivative of the number density at the requested redshift and mass points. This implementation follows the cold dark matter prescription by Costanzi+13 (https://arxiv.org/abs/1311.1514).
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun. fsigmanu: numpy.ndarray Multiplicity function.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
window
¶Top-hat window and its derivative.
Computes the top-hat window function and its derivative.
Parameters¶
k: numpy.ndarray Wavenumber where W(kR) is evaluated. Units: h Mpc^{-1} R: numpy.ndarray Radius where W(kR) is evaluated. Units: h^{-1} Mpc
Returns¶
W: numpy.ndarray W[i,j], where i is the wavenumber axis and j the radius axis dWdx: numpy.ndarray dWdx[i,j], where i is the wavenumber axis and j the radius axis
radius_M
¶ sigma_z_R
¶Standard deviation of perturbations given a redshift and radius.
Computes the rms at the radii requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. R: numpy.ndarray Radius points in h^{-1} Mpc.
Returns¶
sigma_z_R: numpy.ndarray sigma_z_R[i,j], where i is the redshift axis and j the radius axis.
sigma_z_M
¶Standard deviation of perturbations given a redshift and mass.
Computes the rms at the masses requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
sigma_z_M: numpy.ndarray sigma_z_M[i,j], where i is the redshift axis and j the mass axis.
delta_c
¶Critical overdensity.
Computes the critical overdensity at a given redshift following an approximation from Kitayama & Suto (1999). The contribution from massive neutrinos is not included in the matter density parameter.
Parameters¶
z: float or np.ndarray Redshift at which to evaluate the delta_c
Returns¶
delta_c: float or numpy.ndarray Value of the critical overdensity a given redshift.
nu_z_M
¶Peak height.
Computes the critical overdensity over the rms, delta_c/sigma, at a given redshift and mass. The contribution from massive neutrinos is not included in the power spectrum and in the matter density parameter.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points.
Returns¶
nu_z_M: numpy.ndarray nu_z_M[i,j], where i is the redshift axis and j the mass axis.
dlns_dlnM
¶Derivative of the logarithmic rms.
Computes the derivative of the ln rms with respect to the ln of mass at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dlns_dlnM: numpy.ndarray dlns_dlnM[i,j], where i is the redshift axis and j the mass axis.
dn_dm
¶Derivative of the number density.
Computes the derivative of the number density at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
halo_abundance
¶
- Introducing a protocol for the halo statistics part that we might have many versions of it.
HaloAbundance
¶
flowchart TD
cloelib.observables.halos.halo_abundance.halo_abundance.HaloAbundance[HaloAbundance]
click cloelib.observables.halos.halo_abundance.halo_abundance.HaloAbundance href "" "cloelib.observables.halos.halo_abundance.halo_abundance.HaloAbundance"
tinker_halo_abundance
¶
TinkerHaloAbundance
¶
TinkerHaloAbundance(halo_model_properties: HaloModelProperties, overdensity_type: str = 'vir', overdensity: int = 200)
flowchart TD
cloelib.observables.halos.halo_abundance.tinker_halo_abundance.TinkerHaloAbundance[TinkerHaloAbundance]
cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase[HaloAbundanceBase]
cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase --> cloelib.observables.halos.halo_abundance.tinker_halo_abundance.TinkerHaloAbundance
click cloelib.observables.halos.halo_abundance.tinker_halo_abundance.TinkerHaloAbundance href "" "cloelib.observables.halos.halo_abundance.tinker_halo_abundance.TinkerHaloAbundance"
click cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase href "" "cloelib.observables.halos.halo_abundance.halo_abundance_base.HaloAbundanceBase"
Class implementing the Tinker et al. mass abundance models.
Following the cold dark matter prescription by Costanzi+13 (https://arxiv.org/abs/1311.1514) and Castorina+13 (https://arxiv.org/pdf/1311.1212), the halo mass function and halo bias do not include the massive neutrino contribution in the computation of mass variance, power spectrum, and overdensity.
sigma8_0
property
¶Returns the sigma_8 value at redshift z=0. If sigma_8
is not set as a base parameter, it is computed from the power spectrum.
The contribution from massive neutrinos is not included in the power
spectrum.
f_sigma_nu
¶Computation of the multiplicity function.
Computes the Tinker et al. (2008) multiplicity function at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
f_sigma_nu: numpy.ndarray f_sigma_nu[i,j], where i is the redshift axis and j the mass axis
bias
¶ dn_dm_fsigmanu
¶Derivative of the number density with pre-computed halo mass function.
Computes the derivative of the number density at the requested redshift and mass points. This implementation follows the cold dark matter prescription by Costanzi+13 (https://arxiv.org/abs/1311.1514).
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun. fsigmanu: numpy.ndarray Multiplicity function.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
window
¶Top-hat window and its derivative.
Computes the top-hat window function and its derivative.
Parameters¶
k: numpy.ndarray Wavenumber where W(kR) is evaluated. Units: h Mpc^{-1} R: numpy.ndarray Radius where W(kR) is evaluated. Units: h^{-1} Mpc
Returns¶
W: numpy.ndarray W[i,j], where i is the wavenumber axis and j the radius axis dWdx: numpy.ndarray dWdx[i,j], where i is the wavenumber axis and j the radius axis
radius_M
¶ sigma_z_R
¶Standard deviation of perturbations given a redshift and radius.
Computes the rms at the radii requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. R: numpy.ndarray Radius points in h^{-1} Mpc.
Returns¶
sigma_z_R: numpy.ndarray sigma_z_R[i,j], where i is the redshift axis and j the radius axis.
sigma_z_M
¶Standard deviation of perturbations given a redshift and mass.
Computes the rms at the masses requested from the table given by the Boltzman code. The contribution from massive neutrinos is not included in the power spectrum.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
sigma_z_M: numpy.ndarray sigma_z_M[i,j], where i is the redshift axis and j the mass axis.
delta_c
¶Critical overdensity.
Computes the critical overdensity at a given redshift following an approximation from Kitayama & Suto (1999). The contribution from massive neutrinos is not included in the matter density parameter.
Parameters¶
z: float or np.ndarray Redshift at which to evaluate the delta_c
Returns¶
delta_c: float or numpy.ndarray Value of the critical overdensity a given redshift.
nu_z_M
¶Peak height.
Computes the critical overdensity over the rms, delta_c/sigma, at a given redshift and mass. The contribution from massive neutrinos is not included in the power spectrum and in the matter density parameter.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points.
Returns¶
nu_z_M: numpy.ndarray nu_z_M[i,j], where i is the redshift axis and j the mass axis.
dlns_dlnM
¶Derivative of the logarithmic rms.
Computes the derivative of the ln rms with respect to the ln of mass at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dlns_dlnM: numpy.ndarray dlns_dlnM[i,j], where i is the redshift axis and j the mass axis.
dn_dm
¶Derivative of the number density.
Computes the derivative of the number density at the requested redshift and mass points.
Parameters¶
z: numpy.ndarray Redshift points. M: numpy.ndarray Mass points in h^{-1} Msun.
Returns¶
dn_dm: numpy.ndarray dn_dm[i,j], where i is the redshift axis and j the mass axis. Units: h^4 Mpc^{-3} Ms^{-1}.
profiling
¶
Time profiling package of cloelib.
The package provides modules to time profile the library functions
profiling
¶
Profiling utilities for cloelib.
Provides decorators and helpers for runtime profiling using pyinstrument.
profile_function
¶
Define the decorator to profile a function's runtime using pyinstrument.
summary_statistics
¶
Summary Statistics package of cloelib.
The package provides modules to compute the final summary statistics, such as angular power spectra or Legendre multipoles.
angular_correlation_function_wigner
¶
AngularCorrelationFunctionWigner
¶
AngularCorrelationFunctionWigner(angular_two_point, ells, ks)
flowchart TD
cloelib.summary_statistics.angular_correlation_function_wigner.AngularCorrelationFunctionWigner[AngularCorrelationFunctionWigner]
cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction[AngularCorrelationFunction]
cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction --> cloelib.summary_statistics.angular_correlation_function_wigner.AngularCorrelationFunctionWigner
click cloelib.summary_statistics.angular_correlation_function_wigner.AngularCorrelationFunctionWigner href "" "cloelib.summary_statistics.angular_correlation_function_wigner.AngularCorrelationFunctionWigner"
click cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction href "" "cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction"
Correlation function implementation using Wigner small-d matrices.
The real-space angular correlation functions are computed from angular power spectra Cl via spherical harmonic projection. The spin configuration is inferred from the types of tracers in the provided AngularTwoPoint object.
Parameters:
-
(angular_two_point¶AngularTwoPoint) –Object providing Cl evaluation and tracers.
-
(ells¶ndarray) –Multipole moments at which the Cl spectrum is evaluated.
-
(ks¶ndarray) –Wavenumber grid (only needed for computing Cl via angular_two_point).
build_xi_dict
¶
Return a dictionary of TwoPointCorrelationFunction objects.
get_xi
¶
get_xi(theta)
Compute the angular correlation function xi(theta) using the Wigner d-matrices.
TODO: Also implement FFTLog which is likely faster WARNING: Currently assumes B-modes are zero, as they are not passed on from AngularTwoPoint
Parameters:
-
(theta¶ndarray) –Angles in radians. Should be JAX (
jax.numpy.ndarray) ndarray.
Returns:
-
ndarray | (ndarray, ndarray)–Computed xi(theta) if at least one tracer is spin 0 (clustering or GGL) (
jax.numpy.ndarray) or Computed xi_+(theta) and xi_-(theta) (jax.numpy.ndarray,jax.numpy.ndarray) if both tracers are spin 2 (cosmic shear)
angular_correlation_function
¶
Protocol for angular correlation function classes.
This protocol defines a standard interface for computing real-space two-point correlation functions xi(theta). Implementing classes are expected to encapsulate any internal information needed to evaluate the correlation function, such as multipole grids (ells), wavenumber grids (ks), and angular power spectra (Cl).
Notes¶
Implementations may return a single correlation function xi(theta) (e.g., galaxy clustering or galaxy-galaxy lensing) or a tuple (xi_plus, xi_minus) for spin-2 tracers (e.g., cosmic shear).
AngularCorrelationFunction
¶
flowchart TD
cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction[AngularCorrelationFunction]
click cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction href "" "cloelib.summary_statistics.angular_correlation_function.AngularCorrelationFunction"
angular_two_point
¶
Module for angular two-point functions.
AngularTwoPoint
¶
Two point asbtract class to compute two point functions.
Checks if the tracers are compatible and sets the two tracers as instance attributes.
Parameters:
-
(tracer1¶Tracer, default:None) –The first tracer for the two-point function. Defaults to None.
-
(tracer2¶Tracer, default:None) –The second tracer for the two-point function. Defaults to None.
get_Cl_tensor
¶
Compute the angular power spectrum Cl using Limber approximation,
as a plain jax.numpy.ndarray - the exact same computation
get_Cl runs, without the final packaging step.
get_Cl itself is now also differentiable via jax.grad/
jax.jacobian (as of cosmolib's
26-fix-jax-clash-with-cloelib-photo-classes fix: its
AngularPowerSpectrum.__post_init__ used to unconditionally do
np.asarray(self.array, dtype=float) - a plain NumPy cast that
severs any jax.grad trace passing through it
(TracerArrayConversionError) - it now branches on jax.Array
and uses jax.numpy.asarray instead when the input is JAX's, so
it no longer breaks the trace). Prefer get_Cl_tensor over
get_Cl anyway when you don't need the packaged, per-pair-type
dict: it skips building that dict and the AngularPowerSpectrum
wrapper objects entirely, which is the more meaningful saving for
anything running under jax.jit/jax.vmap. The physics itself
(Limber integral, window functions, and - with the JAX-native
cosmology backend - the growth-factor ODE solve and halofit) was
always fully differentiable; confirmed against finite differences
in playground/tutorials/observables/photo_autodiff.ipynb and
validation/photo_autodiff.ipynb.
Parameters:
-
(ells¶ndarray) –Multipole moments for the angular power spectrum.
-
(nl¶ndarray) –Noise power spectrum (not used yet, reserved for future use).
-
(ks¶ndarray) –Wavenumber grid of the matter power spectrum.
Returns:
-
ndarray–Angular power spectrum Cl for the given multipoles,
-
ndarray–shape
(len(ells), n_bins1, n_bins2)-get_Cl's packaging -
ndarray–(
_package_cl) builds its per-pair-type output (e.g. SHE-SHE's -
ndarray–2x2 E/B-mode block) from these same values, not a plain
-
ndarray–reshape of this tensor; e.g. for a SHE-SHE pair,
-
ndarray–get_Cl(...)[("SHE","SHE",i,j)].array[0, 0](the EE block) -
ndarray–equals
get_Cl_tensor(...)[:, i-1, j-1]exactly.
get_Cl
¶
Compute the angular power spectrum Cl using Limber approximation.
Combines the window functions of the tracers, interpolated matter power spectrum, Hubble parameter, and comoving distances to calculate the two-point angular statistics.
Differentiable via jax.grad (requires cosmolib's
26-fix-jax-clash-with-cloelib-photo-classes fix; see
get_Cl_tensor's docstring). get_Cl_tensor returns the same
computation without the packaging step, which is still cheaper for
code that doesn't need the packaged dict.
Parameters:
-
(ells¶ndarray) –Multipole moments for the angular power spectrum.
-
(nl¶ndarray) –Noise power spectrum (not used yet, reserved for future use).
-
(ks¶ndarray) –Wavenumber grid of the matter power spectrum.
Returns:
-
ndarray–Angular power spectrum Cl for the given multipoles.
get_pseudo_Cl
¶
Compute the pseudo angular power spectrum Cl convolved with the mixing matrices.
Parameters: - nl (jax.numpy.ndarray): Noise power spectrum (not used yet). - ks (jax.numpy.ndarray): Wavenumber grid of the matter power spectrum. - mixing_matrix (dict): Mixing matrices in the euclidlib internal format.
Returns: - dict: Pseudo angular power spectrum Cl for the multipoles specified by the mixing matrix.
get_cosebis
¶
Compute EE and BB COSEBIs from angular power spectra.
Delegates to the module-level :func:get_cosebis_from_cl. See that
function for full parameter documentation.
Cl_integration
¶
Perform the integration to compute the angular power spectrum Cl.
The integration is done using the unnormalized trapezoidal rule, utilizing the window functions, power spectrum, Hubble parameter, and comoving distance squared.
Parameters:
-
(WT1¶ndarray) –Window function for the first tracer.
-
(WT2¶ndarray) –Window function for the second tracer.
-
(Pkl¶ndarray) –Matter power spectrum interpolated on Limber grid.
-
(H¶ndarray) –Hubble parameter evaluated at redshifts.
-
(chi2¶ndarray) –Square of comoving distances at redshifts.
-
(weights¶ndarray) –Array of weights used for the fixed nodes integration.
Returns:
-
ndarray–Angular power spectrum Cl with shape (len(ells), len(ells), len(ells)).
Cl_integration_batched
¶
Same as Cl_integration, batched (and summed) over an extra leading
"term" axis on WT1/WT2/Pkl.
Lets a caller with several different (kernel1, kernel2, Pk) triples
to sum into one Cl (e.g. NonLinearGalaxyBiasContribution's several
PkTerms per contribution pairing - see spectrum_engine.PkTerm)
fuse the whole sum into one einsum call instead of a Python loop over
Cl_integration - the sum over the term axis t falls out of
einsum for free (it appears in every input but not the output
subscripts, so it's contracted/summed exactly like z already is).
Parameters:
-
(WT1¶ndarray) –Window function for the first tracer, shape (n_terms, n_bin1, len(z)).
-
(WT2¶ndarray) –Window function for the second tracer, shape (n_terms, n_bin2, len(z)).
-
(Pkl¶ndarray) –Power spectrum interpolated on Limber grid, shape (n_terms, len(ells), len(z)).
-
(H¶ndarray) –Hubble parameter evaluated at redshifts.
-
(chi2¶ndarray) –Square of comoving distances at redshifts.
-
(weights¶ndarray) –Array of weights used for the fixed nodes integration.
Returns:
-
ndarray–Angular power spectrum Cl with shape (len(ells), n_bin1, n_bin2), summed over the term axis.
Pkl_interp
¶
Interpolate the matter power spectrum on a Limber grid.
Utilizes interpax's 2D interpolation with Akima method to handle non-uniform grids in logarithmic space. Extrapolation is enabled for values outside the given grid.
Parameters:
-
(k_l¶ndarray) –Wavenumbers corresponding to (ells + 0.5) / chi.
-
(z_l¶ndarray) –Redshift grid for Limber integration.
-
(ks¶ndarray) –Original wavenumber grid of the matter power spectrum.
-
(zs¶ndarray) –Original redshift grid of the matter power spectrum.
-
(Pk¶ndarray) –Matter power spectrum values on (ks, zs) grid.
Returns:
-
ndarray–Interpolated power spectrum on the Limber grid.
Pkl_interp_signed
¶
Interpolate a possibly-negative effective power spectrum on a Limber grid.
Pkl_interp interpolates log10(P) in log-log (log10(k), z) space,
which assumes P > 0 everywhere - true for the plain matter power
spectrum, but not for e.g. a matter-intrinsic (GI) effective spectrum,
which is generically signed (C1(z) in the TATT/NLA model carries a
minus sign - see tatt.py).
A first attempt at this interpolated P itself (not log10(P))
linearly to sidestep log10 of a negative number; that turned out to
be a real bug, not just a simplification - P(k,z) spans many orders
of magnitude across a log-spaced k grid, and interpax's akima
interpolation of the raw values across that range was wildly
inaccurate (verified: it produced results independent of the actual
effective-Pk terms, off by 5-6 orders of magnitude from the correct
C12 * P_dd limit). This keeps log-log accuracy for the magnitude
(log10(|P|)) and interpolates the sign separately, recombining
sign(interpolated sign) * 10**(interpolated log10|P|) - standard
practice for interpolating a signed, log-scale quantity.
Used by the generalized engine (AngularTwoPoint._compute_cl_
generalized) instead of Pkl_interp, which stays log-log (and
untouched) for the always-positive legacy path.
Parameters/Returns: as Pkl_interp.
TODO (PR #569 review): add dedicated tests for this function's
gradient behavior specifically (not just its forward values) - the
sign(...)/clip(...) machinery here is exactly the kind of
piecewise construct that can produce zero or discontinuous gradients
at a sign change or a clip boundary, and that risk hasn't been
checked directly yet (only indirectly, via the end-to-end TATT
differentiability tests in test_get_cl_tensor.py, which don't
target this function's own zero-crossing/edge behavior).
Cl_int_liz_jz
¶
Contract an RSD window for tracer 1 with an ordinary window for 2.
WT1l has shape (n_ell, n_bin1, n_z), WT2 has shape
(n_bin2, n_z), Pkl has shape (n_ell, n_z), and each of
invH, invchi2, and weights has shape (n_z,).
The returned three-dimensional array is indexed by multipole and the two tracer-bin axes. This helper performs the weighted contraction only; the legacy integration path supplies physical prefactors and grid-spacing factors.
Cl_int_iz_ljz
¶
Contract an ordinary window for tracer 1 with tracer 2's RSD window.
WT1 has shape (n_bin1, n_z), WT2l has shape
(n_ell, n_bin2, n_z), Pkl has shape (n_ell, n_z), and each
of invH, invchi2, and weights has shape (n_z,).
The returned three-dimensional array is indexed by multipole and the two tracer-bin axes. This helper performs the weighted contraction only; the legacy integration path supplies physical prefactors and grid-spacing factors.
Cl_int_liz_ljz
¶
Contract RSD windows for both tracers.
Each RSD window has shape (n_ell, n_bin, n_z); Pkl has shape
(n_ell, n_z), and each of invH, invchi2, and weights has
shape (n_z,).
The returned three-dimensional array is indexed by multipole and the two tracer-bin axes. This helper performs the weighted contraction only; the legacy integration path supplies physical prefactors and grid-spacing factors.
get_cosebis_from_cl
¶
Compute EE and BB COSEBIs for all SHE-SHE keys in cells.
Can be used as a standalone function without instantiating AngularTwoPoint
if angular power spectra are already available.
Parameters¶
cells : dict
Angular power spectra in cosmolib format. All SHE-SHE bin pairs
present in the dict are processed automatically.
ells : jax.numpy.ndarray
Multipoles at which the integration is performed. Any strictly
increasing grid is accepted (see quadrature_weights); it must be
fine enough to resolve the oscillations of the kernels.
w_ell : dict
Harmonic-space COSEBIs kernels. Two layouts are accepted:
* **Global** — a single dict ``{n: array, ..., "metadata": {...}}``
(as returned by ``get_W_ell``). The same kernels are used for
every bin pair.
* **Per-bin** — a dict ``{(i, j): {n: array, ..., "metadata": {...}},
...}`` supplying independent kernels per bin pair. A ``None`` key
may be included as a global fallback for pairs without an explicit
entry.
ns : array-like
Mode indices selecting kernels from w_ell.
software : str, optional
Software provenance tag stored in the output COSEBI objects.
Defaults to 'get_cosebis_from_cl (cloelib)'.
Returns¶
dict
Dictionary keyed like the SHE-SHE entries of cells with COSEBI
values of shape (2, 2, n_modes). thmin/thmax are in
arcmin, as in the Euclid LE3 products read by euclidlib.
get_cosebis_from_2pcf
¶
Compute EE and BB COSEBIs for all SHE-SHE keys in twopcf.
Can be used as a standalone function without instantiating AngularTwoPoint
if two-point correlation functions are already available.
Following Schneider, Eifler & Krause (2010),
.. math::
E_n = \frac{1}{2} \int d\theta\, \theta
[T_{+n}(\theta) \xi_+(\theta) + T_{-n}(\theta) \xi_-(\theta)],
B_n = \frac{1}{2} \int d\theta\, \theta
[T_{+n}(\theta) \xi_+(\theta) - T_{-n}(\theta) \xi_-(\theta)].
Parameters¶
twopcf : dict
Two-point correlation functions in cosmolib format.
Keys should be tuples like ('SHE', 'SHE', i, j).
theta : jax.numpy.ndarray
Angular scales in radians, spanning the COSEBI range
[theta_min, theta_max].
T_plus : array-like
Real-space T_+ kernel functions evaluated on theta (without the
extra factor of theta), shape (n_rows, len(theta)).
T_minus : array-like
Real-space T_- kernel functions evaluated on theta, same layout as
T_plus.
ns : jax.numpy.ndarray
Row indices selecting kernels from T_plus/T_minus.
software : str, optional
Software provenance tag stored in the output COSEBI objects.
Defaults to 'get_cosebis_from_2pcf (cloelib)'.
Returns¶
dict
COSEBIs with EE and BB modes, keyed like twopcf. thmin/thmax
are in arcmin, as in the Euclid LE3 products read by euclidlib.
bao_alphas
¶
Module to compute alpha parameters for the BAO analysis.
BaryonAcousticOscillations
¶
BaryonAcousticOscillations(background: Background, background_fiducial: Background, redshifts: ndarray)
Class to compute alpha parameters for the BAO analysis.
Parameters:
-
(background¶Background) –Object following the Background protocol; used to compute background quantities needed for the alphas in a given cosmology
-
(background_fiducial¶Background) –Object following the Background protocol; used to compute background quantities in the fiducial cosmology
-
(redshifts¶ndarray) –Array of redshifts at which the alphas are output
alpha_par
¶
alpha_par(zs: T) -> T
Alpha_parallel.
Dilation parameter along the line of sight
Parameters:
-
(zs¶array) –redshift
Returns:
-
alpha_par(array) –alpha_parallel at requested redshifts
alpha_perp
¶
alpha_perp(zs: T) -> T
Alpha_perpendicular.
Dilation parameter perpendicular to the line of sight
Parameters:
-
(zs¶array) –redshift
Returns:
-
alpha_perp(array) –alpha_perpendicular at requested redshifts
alpha_iso
¶
alpha_iso(alpha_par: T, alpha_perp: T) -> T
Alpha_iso.
Geometrical mean of alpha_parallel and alpha_perpendicular
Parameters:
Returns:
-
alpha_iso(array) –alpha_iso computed from alpha_par, alpha_perp
alpha_AP
¶
alpha_AP(alpha_par: ndarray, alpha_perp: ndarray) -> ndarray
Alpha_AP.
Ratio of alpha_parallel and alpha_perpendicular
Parameters:
Returns:
-
alpha_AP(array) –alpha_AP computed from alpha_par, alpha_perp
set_alphas
¶
Construct a dictionary with values for the BAO alphas.
The alphas are alpha_par, alpha_perp, alpha_iso and alpha_AP. The alphas are evaluated at the redshifts requested at initialisation.
Returns:
-
alphas(dict) –Dictionary containing values for the BAO alphas
legendre_multipoles
¶
Module to compute Legendre multipoles.
LegendreMultipoles
¶
LegendreMultipoles(spectro_power: SpectroPower, background_fiducial: Background, parameters: dict, nbar: float)
Class to compute spectroscopic Legendre multipoles of the galaxy power spectrum.
Parameters:
-
(spectro_power¶SpectroPower) –Class returning the anisotropic power spectrum (only density and velocity field couplings; noise and systematics are included directly here)
-
(background_fiducial¶Background) –Background class for computing fiducial background distances
-
(parameters¶dict) –Dictionary containing shot noise and parameters related to observational systematics
-
(nbar¶float) –Mean number denisty of the sample
power_multipoles
¶
power_multipoles(k: ndarray, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True, format_type: Optional[str] = None) -> dict
Power spectrum Legendre multipoles.
Parameters:
-
(k¶ndarray) –Wavenumber
-
(ells¶ndarray, default:None) –Legendre multipole order
-
(use_AP¶bool, default:True) –Flag to switch between with and without AP corrections
-
(format_type¶str, default:None) –Type of output format
Returns: multipoles (dict): Power spectrum Legendre multipoles
power_term_multipoles
¶
power_term_multipoles(k: ndarray, term_list: list, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True) -> dict
Power spectrum Legendre multipoles of specified terms.
Parameters:
-
(k¶ndarray) –Wavenumber
-
(term_list¶list) –List of terms to compute
-
(ells¶ndarray, default:None) –Legendre multipole order
-
(use_AP¶bool, default:True) –Flag to switch between with and without AP corrections
Returns:
-
multipoles(dict) –Power spectrum Legendre multipoles of specified terms
convolved_power_multipoles
¶
convolved_power_multipoles(mixing_matrix: PowerSpectrumMultipolesMixingMatrix, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True, format_type: Optional[str] = None, k_center: Optional[ndarray] = None) -> dict
Power spectrum Legendre multipoles convolved with the mixing matrix.
Parameters:
-
(mixing_matrix¶PowerSpectrumMultipolesMixingMatrix) –Dicitonary containing the mixing matrix
-
(ells¶ndarray, default:None) –Legendre multipole order
-
(use_AP¶bool, default:True) –Flag to switch between with and without AP corrections
-
(format_type¶str, default:None) –Type of output format
Returns:
-
multipoles_out(dict) –Convolved power spectrum Legendre multipoles
convolved_power_term_multipoles
¶
convolved_power_term_multipoles(mixing_matrix: PowerSpectrumMultipolesMixingMatrix, term_list: list, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True) -> dict
Convolved power spectrum multipoles of specified terms.
Parameters:
-
(mixing_matrix¶PowerSpectrumMultipolesMixingMatrix) –Dicitonary containing the mixing matrix
-
(term_list¶list) –List of terms to compute
-
(ells¶ndarray, default:None) –Legendre multipole order
-
(use_AP¶bool, default:True) –Flag to switch between with and without AP corrections
Returns:
-
multipoles_out(dict) –Convolved power spectrum Legendre multipoles of specified terms
two_point_correlation_multipoles
¶
two_point_correlation_multipoles(s: ndarray, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True, logkmin: Optional[float] = -6.0, logkmax: Optional[float] = 2.0, nk: Optional[int] = 2048, kcut: Optional[float] = 2.0, pow: Optional[float] = 2.0, format_type: Optional[str] = None) -> dict
Two-point correlation function Legendre multipoles.
Parameters¶
s: np.ndarray Comoving separations ells: np.ndarray Legendre multipole order use_AP: bool Flag to switch between with and without AP corrections logkmin: float Left logarithmic edge of input wave mode array logkmax: float Right logarithmic edge of input wave mode array nk: int Number of logarithmic wave mode bins kcut: float Cutoff scale for exponential damping pow: float Power index for exponential damping format_type: str Type of output format Returns
multipoles: dict Two-point correlation function Legendre multipoles
two_point_correlation_polar
¶
two_point_correlation_polar(s: ndarray, mu: ndarray, use_AP: Optional[bool] = True, logkmin: Optional[float] = -6.0, logkmax: Optional[float] = 2.0, nk: Optional[int] = 2048, kcut: Optional[float] = 2.0, pow: Optional[float] = 2.0, format_type: Optional[str] = None) -> dict
Polar two-point correlation function.
Parameters¶
s: np.ndarray Comoving separations mu: np.ndarray Cosinus of the angle between the pair separation and the line of sight use_AP: bool Flag to switch between with and without AP corrections logkmin: float Left logarithmic edge of input wave mode array logkmax: float Right logarithmic edge of input wave mode array nk: int Number of logarithmic wave mode bins kcut: float Cutoff scale for exponential damping pow: float Power index for exponential damping format_type: str Type of output format Returns
xi_polar: np.ndarray Polar two-point correlation function
two_point_correlation_term_multipoles
¶
two_point_correlation_term_multipoles(s: ndarray, term_list: list, ells: Optional[ndarray] = None, use_AP: Optional[bool] = True, logkmin: Optional[float] = -6.0, logkmax: Optional[float] = 2.0, nk: Optional[int] = 2048, kcut: Optional[float] = 2.0, pow: Optional[float] = 2.0) -> dict
Two-point correlation function Legendre multipoles of specified terms.
Parameters¶
s: np.ndarray Comoving separations term_list: list List of terms to compute ells: np.ndarray Legendre multipole order use_AP: bool Flag to switch between with and without AP corrections logkmin: float Left logarithmic edge of input wave mode array logkmax: float Right logarithmic edge of input wave mode array nk: int Number of logarithmic wave mode bins kcut: float Cutoff scale for exponential damping pow: float Power index for exponential damping Returns
multipoles: dict Two-point correlation function Legendre multipoles of specified terms
APDistortion
¶
Module to compute Alcock-Paczynski (AP) distortions parameters.
APDistortion
¶
APDistortion(background: Background, background_fiducial: Background)
Class to compute AP distortion parameters from cosmological background quantities.
Parameters:
-
(background¶Background) –Background class for computing background distances
-
(background_fiducial¶Background) –Background class for computing fiducial background distances
auxiliary
¶
Auxiliary package of cloelib.
The package provides numerical helpers and utilities used across cloelib.
akima
¶
Module to implement Akima interpolation using JAX.
akima_interpolation
module-attribute
¶
akima_interpolation = jax.jit(akima_interpolation, static_argnames=['axis'])
Performs Akima 1D interpolation along the specified axis.
Parameters¶
u : jnp.ndarray
Function values, shape (..., n, ...), interpolation along axis.
t : jnp.ndarray, shape (n,)
x-coordinates of the data points.
tq : jnp.ndarray, shape (k,)
Points where interpolation is to be evaluated.
axis : int
Axis along which to interpolate.
Returns¶
jnp.ndarray
Interpolated values of shape (..., k, ...) along axis.
bnt
¶
Module with one class to compute the BNT matrix.
BNTMatrixCalculator
¶
BNTMatrixCalculator(dndz_list: List[T], z: T, background: Background)
Class to compute the BNT matrix.
Parameters¶
dndz_list : List[np.ndarray or jnp.ndarray]
A list of 1d-arrays representing the number density distribution of galaxies as a function of redshift.
Each list member is expected to be normalised.
z : np.ndarray or jnp.ndarray
A 1-dimensional array representing the redshift values corresponding to the dndz array.
background : Background
Cosmological background instance.
get_bnt_matrix
¶
Compute the BNT matrix.
The BNT matrix is a lower–triangular linear transformation acting on tomographic weak-lensing kernels, designed to construct linear combinations of shear kernels that are localised in comoving distance.
Returns¶
np.ndarray
The BNT transformation matrix with shape (nbins, nbins), always
lower triangular with ones on the diagonal.
cache
¶
Caching utilities for functions that accept JAX arrays.
This module exposes memoize_jax, a decorator that adds hash-based
memoization to any Python function whose positional or keyword
arguments include JAX DeviceArray objects.
Background¶
JAX arrays are mutable and therefore unhashable, so they cannot be
passed directly to functools.lru_cache. memoize_jax solves
this by turning every array into a fully hashable key composed of its
raw bytes, shape and dtype. The wrapped function receives the original
arrays, while cache lookup happens on the hashable representation.
Internally the cache is maintained by functools.lru_cache with
maxsize=None (an unbounded cache).
cosebi_helpers
¶
get_roots_and_norms
¶
Calculates the roots,norms and matrix elements given a min and max theta up to a certain Nmax.
Parameters:¶
tmax: float maximum seperation tmin: float minimum seperation Nmax: integer maximum COSEBI
Returns¶
rn (mp.math) the roots nn (mp.math) the normalizations coeff_j (mp.math matrix) Matrix elements
Notes¶
Based on the the implementation from OneCovariance by Robert Reischke, https://github.com/rreischke/OneCovariance.
tp
¶
tm
¶
get_T_plus_minus
¶
Real-space COSEBI kernels T_n^+(theta) and T_n^-(theta) for n = 1..Nmax.
The output layout is the one expected by
cloelib.summary_statistics.angular_two_point.get_cosebis_from_2pcf.
Parameters¶
thetagrid : np.ndarray
Angular separation grid in radians; its first and last values set the
COSEBI range [theta_min, theta_max].
Nmax : int
Maximum COSEBI mode index.
Returns¶
T_plus, T_minus : np.ndarray
Arrays of shape (Nmax + 1, len(thetagrid)); row n holds mode
n and row 0 is zero, so T_plus[ns] selects modes ns.
get_W_ell
¶
Compute harmonic-space COSEBI kernels W_n(ell) for n = 1..Nmax.
The T_n^- real-space kernels are expanded in Chebyshev series computed at
mpmath precision (150 decimal digits) and evaluated in float64 via
_tm_fast, so their cost does not grow with the size of thetagrid.
All Nmax kernels are then stacked into a single (N_theta, Nmax)
integrand matrix and passed to pylevin in one batched Levin call.
The Levin integration dominates the run time and scales linearly with
len(ells). Since the COSEBI integrals account for the grid spacing
(see cloelib.auxiliary.math_utils.quadrature_weights), ells does not
need to be unit-spaced: a uniform grid only has to resolve the oscillations
of W_n(ell), whose period is roughly 2 pi / theta_max. For example,
for theta in [0.5, 300] arcmin, np.arange(2, 60000, 5) reproduces the
unit-spaced result to ~1e-5 at one fifth of the cost.
Parameters¶
thetagrid : np.ndarray
Angular separation grid in radians (log-spaced).
Nmax : int
Maximum COSEBI mode index.
ells : np.ndarray
Multipoles at which W_n(ell) is evaluated. Pass the same grid to
get_cosebis_from_cl/AngularTwoPoint.get_cosebis.
N_thread : int
Number of threads passed to pylevin.
Returns¶
dict
Keys 1..Nmax map to 1-D arrays of length len(ells);
key "metadata" holds {"THMIN": tmin, "THMAX": tmax} in radians
(the unit of thetagrid). The COSEBI outputs built from these kernels
store thmin/thmax in arcmin.
extrapolator
¶
Extrapolator module.
extend_spectra
¶
extend_spectra(wavenumber_in, redshift_in, boost_in, flag_range, norm_dist=0, option_wavenumber='hm_simple', option_redshift='hm_simple', option_cosmo='hm_simple', extrap_func=None, extrap_kmax=500.0, extrap_kmin=0.0001, extrap_z=4.0, wavenumber_tanh_slope=10.0, wavenumber_tanh_scale=1.15, ns=0.96)
Calculate extrapolation of the spectrum/boost outside its given range.
Return spectrum/boost array and corresponding scales in 1/Mpc.
Options for redshift extrapolation:
- const, power_law, hm_simple
Options for cosmo extrapolation:
- const, hm_simple, hm_smooth
Both hm_simple and hm_smooth extrapolate with HMcode, but the smooth case uses a tanh to interpolate between another extrapolation and HMcode, making it a continuous extrapolation. Any of this cases requires a function computing the HMcode prediction to be passed
Parameters¶
wavenumber_in: numpy.ndarray
Scales used by emulator in units of 1/Mpc
redshift_in: float
Max redshift of emulator
boost_in: numpy.ndarray
Array with boost at z_win redshifts and scales wavenumber_in
flag_range: bool
Flag for cosmo params range of emulator
option_wavenumber: string
Option for wavenumber extrapolation
option_redshift: str
Option for redshift extrapolation
option_cosmo: str
Option for cosmology extrapolation
extrap_func: callable
function to call to get prediciton from HMcode (ignored if not using
HMcode extrapolation)
extrap_kmax: float
max wavenumber for extrapolation in 1/Mpc
extrap_kmin: float
min wavenumber for extrapolation in 1/Mpc
extrap_z: float or np.ndarray
max redshift to extrapolate or array with redshifts to evaluate
Returns¶
wavenumber_out: numpy.ndarray
Concatenation of scales used by emulator with extended ones, in units
of 1/Mpc
redshift_out: numpy.ndarray
Concatenation of redshifts used by emulator with extended ones
boost_out: numpy.ndarray
Array with extrapolated boost at extended redshifts
and scales wavenumber_out
fftlog
¶
FFTLOG MODULE
Class to perform integrals with the FFTLog algorithm.
Class to implement the Fast Fourier Transform in logarithmic space (FFTLog)
algorithm to perform the Fourier transform of a periodic sequence of
logarithmically spaced points. This is based on the work published in
Hamilton (2000) <https://arxiv.org/abs/astro-ph/9905191v4> and
Fang et al. (2020) <https://arxiv.org/abs/1911.11947>
fftlog
¶
flowchart TD
cloelib.auxiliary.fftlog.fftlog[fftlog]
click cloelib.auxiliary.fftlog.fftlog href "" "cloelib.auxiliary.fftlog.fftlog"
Class for the FFTLog algorithm.
It computes integrals involving a Bessel function with the algorithm
described in
Hamilton (2000) <https://arxiv.org/abs/astro-ph/9905191v4>__ .
It decomposes the integrand function using the Fast Fourier Transform;
after this decomposition, each term can be integrated analytically.
Parameters¶
x: numpy.ndarray
Original logarithmically sampled domain of the input function. If
not even, the algorithmic implementation modifies it accordingly
fx: numpy.ndarray
Original sampled input function
nu: float
Bias index, used to have a more stable fast Fourier transform
N_extrap_begin: int
Number of extrapolated points at the beginning of input arrays
N_extrap_end: int
Number of extrapolated points at the end of input arrays
c_window_width: float
Fraction of the c_m coefficients smoothed by the window
N_pad: int
Number of zero-padded points at the beginning and end of fx
array
fftlog
¶
Performs the fftlog.
Calculates
.. math:: F(y) = \int_0^\infty \frac{dx}{x} f(x) j_{\rm \ell}(xy)
where :math:j_\ell is the spherical Bessel function of order
:math:\ell.
Parameters¶
ell: int Order of the Bessel function present in the integral
Returns¶
y, Fy: numpy.ndarray, numpy.ndarray
Logarithmically spaced array, set as
y[:] = (ell+1)/x[::-1], FFTlog transform evaluated
over the y array
halo_helpers
¶
Module implementing auxiliary functions
convert_to_Delta_crit
¶
Critical overdensity factor.
Converts the input overdensity factor into a critical one. The contribution from massive neutrinos is not included in the matter density parameter.
Parameters¶
overdensity_type : str
Overdensity definition for halo mass calculation. Must be one of:
- "crit": Relative to critical density of the universe.
- "mean": Relative to mean matter density.
- "vir": Virial overdensity from spherical collapse.
overdensity : int, optional
Value of the overdensity. Effective for non-virial overdensities.
Example: If it equals 200, halos are defined as regions with density
200 times the chosen reference (crit or mean).
background : Background
Background object.
z: float or np.ndarray
Redshift.
Returns¶
overdensity: float or np.ndarray The overdensity factor which needs to be multiplied to the critical density in order to define an overdensity.
Notes¶
The function is returned for :math:\rm \rho_c in a density definition
at a given redshift. The function returns :math:\rm \Delta for the
critical density of the universe, :math:\rm \Delta \Omega_{m} for
the mean matter density of the universe, :math:\rm \Delta determined
by Bryan & Norman 1998
<http://adsabs.harvard.edu/abs/1998ApJ...495...80B>_ Equation 6 for
the virial density.
convert_distance
¶
Convert distances
Parameters¶
distance: np.ndarray Input projected distances units_in: str Unit for the input projected distance. Accepted values are: "Mpc/h", "radians", "degrees", "arcmin", "arcsec". units_out: str Unit for the output projected distance. Accepted values are: "Mpc/h", "radians", "degrees", "arcmin", "arcsec". angular_diameter_distance: float, np.ndarray Angular diameter distance (units: Mpc/h) to be used for converting between angular and physical units. If array, it should be in the shape (z.size, 1).
Returns¶
np.ndarray Distance in output units. If z is array and physical to angular conversion used, output shape is (z.size, distance.size).
photoz_rsd_correction
¶
photoz_rsd_correction(background, z: ndarray, k: ndarray, z_obs_scatter: ndarray) -> tuple[ndarray, ndarray, ndarray]
Compute the correction that accounts for photo-z uncertainty and RSD (Kaiser effect),
from (Kaiser (1987)) <(https://doi.org/10.1093/mnras/227.1.1>_.
Parameters¶
background: Background Background class containing cosmology k: np.ndarray wavenumber z: np.ndarray redshift z_obs_scatter: float, numpy.ndarray Observed redshift scatter. If array, first dimension must be z.
Returns¶
corr0, corr1, corr2: np.ndarray Correction terms to the power spectrum monopole Shape (z.size, k.size, other dimensions of z_obs_scatter)
tophat_window
¶
tophat_window_derivative
¶
isotropic_volume_distance
¶
tabulated_return
¶
Check if arguments given are the same from the reference table. If true, returns the tabulated value. Otherwise, recomputes the output value and stores it (and inputs) back in reference table.
Parameters¶
reference_table: dict
Dictionary with the tabulated function. It must contain a inputs
key with the dictionary of arguments or function and a values
key with the computed value of said function with those arguments.
func: function
Function to be tabulated
func_kwargs: dict
Dictionary with named arguments for the function.
Returns¶
Output of func(**func_kwargs)
math_utils
¶
Module for mathematical functions.
ensure_z_zero_included
¶
Ensure z=0 is in redshift array for sigma8(z=0) computation.
This utility function checks if z=0 is present in the redshift array, and adds it if missing. This is necessary for computing sigma8(z=0) which is required for cosmological analyses.
Parameters¶
redshifts : np.ndarray Array of redshift values
Returns¶
np.ndarray Redshift array with z=0 included (sorted)
simpsons_weights_odd
¶
Simpson's rule weights when num_el is odd.
simpsons_weights_even
¶
Simpson's rule weights when num_el is even.
simpsons_weights_jax
¶
JAX-compatible Simpson's weights computation.
simpsons_weights_avg
¶
simpsons_weights_avg(num_el: int) -> ndarray
Simpson-type quadrature weights (unit spacing) without the alternating 4/3, 2/3 pattern, for any number of nodes.
The composite Simpson rule (simpsons_weights_odd) alternates 4/3, 2/3 in the
interior. For an integrand that is under-resolved by the grid - e.g. the
Limber integrand of a narrow tomographic bin, which goes as n(z)^2 - that
makes the result depend on where a peak falls between nodes, and the error
oscillates with the number of nodes. simpsons_weights_even already avoids
this by averaging two shifted Simpson rules: its weights are 1 except at the
first and last two nodes (5/12, 13/12). This function uses that rule for even
num_el (unchanged) and, for odd num_el, the analogous average of two
shifted even-N rules, whose weights are 1 except at the first and last three
nodes (11/24, 1, 25/24). One node gives weight 0, two nodes the trapezoid rule.
Parameters:
-
(num_el¶int) –number of nodes (a static Python int).
Returns:
-
ndarray–jnp.ndarray: weights of length
num_el; multiply by the grid spacing.
quadrature_weights
¶
Quadrature weights w on the grid x such that sum(w * f(x))
approximates the integral of f over x.
Simpson's rule is used for linearly spaced grids (w = s * dx) and for
logarithmically spaced grids (integrating in ln x, w = s * dlnx * x);
any other grid falls back to the trapezoidal rule.
Parameters¶
x : array-like Strictly increasing integration grid (not traced by JAX).
Returns¶
jnp.ndarray
Weights with the same length as x.
stack_zeros_and_simpson
¶
Row of stacked_simpson: num_zeros zeros followed by the
simpsons_weights_avg weights for num_weights nodes.
stacked_simpson
¶
Matrix of quadrature weights (unit spacing) for cumulative integrals to the
end of the grid: row i integrates over nodes i, ..., n-1 with
simpsons_weights_avg (zero weights before node i).
Row i therefore sums to the number of remaining intervals, n - 1 - i: the
last row (a single node) is zero and the one before it is the trapezoid rule.
cached_stacked_simpson
¶
Cached stacked_simpson(n). n must be a static Python int (e.g. len(z));
safe to call inside jitted code.
legendre
¶
Evaluate the Legendre polynomial of degree n at x.
The polynomial is evaluated with the three-term recurrence relation. x may
be a scalar or an array; the result is a JAX value with the corresponding shape.
Parameters¶
n : int Non-negative degree of the polynomial. x : array-like Point or points at which to evaluate the polynomial.
Returns¶
jax.Array
Values of the degree-n Legendre polynomial at x.
simps
¶
Compute Simpson's-rule integrals of f over [a, b].
f is evaluated at N + 1 equally spaced points, and composite
Simpson's rule is applied along the leading axis of its result.
Parameters¶
f : callable
Function evaluated at the integration points. Its result must have a
leading dimension of length N + 1.
a, b : float
Lower and upper integration limits.
N : int, optional
Number of equal subintervals; must be even. Defaults to 128.
Returns¶
scalar or array-like
Integral value(s), with the shape of f's result after reducing its
leading dimension. The concrete array type follows the value returned by
f and numpy.sum's dispatch.
Raises¶
ValueError
If N is odd.
safe_sqrt
¶
sqrt with a finite gradient at (and below) zero.
jax.grad of sqrt(x) is inf at x = 0, which turns into NaNs once
multiplied by a zero cotangent. The double-where keeps both the value
and the gradient finite where x <= 0 (value and gradient set to 0).
check_nonzero_redshifts
¶
Raise ValueError if the redshift grid z contains zero.
A zero redshift breaks the Limber integration. The check runs in plain
NumPy on a concrete grid, so a tracer constructor holding it can still be
traced by jax.jit, where even a constant jnp array would otherwise be
compared as a tracer. A traced z is not checked.
systematics
¶
Module for auxiliary functions related to systematics effects.
shift_dndz_jax
¶
Shift redshift distributions by a bin-specific offset using JAX-compatible interpolation.
This function interpolates each redshift distribution in dndz from a shifted redshift grid
z - dz[i] back onto the original z grid, allowing redshift bin shifts in auto-diff pipelines.
Parameters¶
dndz : Union[jnp.ndarray, np.ndarray]
Array of shape (N_bins, N_z), representing redshift distributions for each bin.
z : Union[jnp.ndarray, np.ndarray]
1D array of redshift values corresponding to the columns of dndz.
dz : Union[jnp.ndarray, np.ndarray]
1D array of length N_bins specifying redshift shift per bin.
Returns¶
Union[jnp.ndarray, np.ndarray]
Shifted redshift distributions, same shape as dndz, interpolated and zero-padded where needed.
Notes¶
- Interpolation outside bounds is filled with zero.
dndzis being normalized by this function .- JAX-compatible and JIT-compiled for use in differentiable models.
stretch_dndz_jax
¶
Stretch redshift distributions by a bin-specific stretch parameter using JAX-compatible interpolation.
This function interpolates each redshift distribution in dndz from a stretched redshift grid
widths[i]*(z-zmean) + zmean back onto the original z grid, allowing redshift bin stretches in auto-diff pipelines.
Parameters¶
dndz : Union[jnp.ndarray, np.ndarray]
Array of shape (N_bins, N_z), representing redshift distributions for each bin.
z : Union[jnp.ndarray, np.ndarray]
1D array of redshift values corresponding to the columns of dndz.
width : Union[jnp.ndarray, np.ndarray]
1D array of length N_bins specifying redshift stretches per bin.
Returns¶
Union[jnp.ndarray, np.ndarray]
Stretched redshift distributions, same shape as dndz, interpolated and zero-padded where needed.
Notes¶
- Interpolation outside bounds is filled with zero.
dndzis being normalized by this function .- JAX-compatible and JIT-compiled for use in differentiable models.
units
¶
The constants used across the code are defined in this module.