Source code for hmf.density_field.transfer

"""
Module providing a framework for transfer functions.

This module contains a single class, `Transfer`, which provides methods to
calculate the transfer function, matter power spectrum and several other
related quantities.
"""

from typing import override

import numpy as np

from .._internals._cache import cached_quantity, parameter
from .._internals._framework import get_mdl
from ..cosmology import cosmo
from ..cosmology import growth_factor as gf
from ..density_field import filters
from ..density_field import transfer_models as tm
from .halofit import halofit as _hfit
from .transfer_models import HAVE_CAMB, HAVE_CLASS


[docs] class Transfer(cosmo.Cosmology): """ A transfer function framework. The purpose of this :class:`hmf._frameworks.Framework` is to calculate transfer functions, power spectra and several tightly associated quantities given a basic model for the transfer function. As in all frameworks, to update parameters optimally, use the :meth:`update` method. All output quantities are calculated only when needed (but stored after first calculation for quick access). In addition to the parameters directly passed to this class, others are available which are passed on to its superclass. To read a standard documented list of (all) parameters, use ``Transfer.parameter_info()``. If you want to just see the plain list of available parameters, use ``Transfer.get_all_parameters()``.To see the actual defaults for each parameter, use ``Transfer.get_all_parameter_defaults()``. By default, the `growth_model` is :class:`~growth_factor.GrowthFactor`. However, if using a wCDM cosmology and camb is installed, it will default to :class:`~growth_factor.CambGrowth`. """ def __init__( self, sigma_8=0.8159, sigma_8_species="tot", n=0.9667, z=0.0, lnk_min=np.log(1e-8), # noqa: B008 lnk_max=np.log(2e4), # noqa: B008 dlnk=0.05, transfer_model=tm.CAMB if HAVE_CAMB else tm.EH, transfer_params=None, takahashi=True, growth_model=None, growth_params=None, use_splined_growth=False, **kwargs, ): # Call Cosmology init super().__init__(**kwargs) # Set all given parameters self.n = n self.sigma_8 = sigma_8 self.sigma_8_species = sigma_8_species self.growth_params = growth_params or {} self.use_splined_growth = use_splined_growth self.lnk_min = lnk_min self.lnk_max = lnk_max self.dlnk = dlnk self.z = z self.transfer_model = transfer_model self.transfer_params = transfer_params or {} self.takahashi = takahashi # Growth model has a more complicated default. # We set it here so that "None" is not a relevant option for self.growth_model # (and it can't be explicitly updated to None). if growth_model is None: if hasattr(self.cosmo, "w0") and HAVE_CAMB: self.growth_model = "CambGrowth" else: self.growth_model = "GrowthFactor" else: self.growth_model = growth_model # =========================================================================== # Parameters # ===========================================================================
[docs] @override def validate(self): super().validate() if not self.lnk_min < self.lnk_max: raise ValueError( f"lnk_min must be less than lnk_max, got lnk_min={self.lnk_min}, " f"lnk_max={self.lnk_max}" ) if len(self.k) < 2: raise ValueError( f"The k vector must have at least 2 entries, got {len(self.k)} from " f"lnk_min={self.lnk_min}, lnk_max={self.lnk_max} and dlnk={self.dlnk}." )
@parameter("model") def growth_model(self, val): """ The model to use to calculate the growth function/growth rate. ``"ClassGrowth"`` needs the optional ``classy`` package (``pip install hmf[class]``). :type: `hmf.growth_factor.BaseGrowthFactor` subclass """ if not gf.HAVE_CLASS and val in ["ClassGrowth", gf.ClassGrowth]: raise ValueError( "You cannot use the ClassGrowth growth model since classy isn't installed. " "Install it with `pip install hmf[class]`." ) return get_mdl(val, "BaseGrowthFactor") @parameter("param") def growth_params(self, val): """ Relevant parameters of the :attr:`growth_model`. :type: dict """ return val @parameter("model") def transfer_model(self, val): """ Defines which transfer function model to use. Built-in available models are found in the :mod:`hmf.transfer_models` module. Default is CAMB if installed, otherwise EH. ``"CLASS"`` needs the optional ``classy`` package (``pip install hmf[class]``). :type: str or :class:`hmf.transfer_models.TransferComponent` subclass, optional """ if not HAVE_CAMB and val in ["CAMB", tm.CAMB]: raise ValueError("You cannot use the CAMB transfer since pycamb isn't installed") if not HAVE_CLASS and val in ["CLASS", tm.CLASS]: raise ValueError( "You cannot use the CLASS transfer since classy isn't installed. " "Install it with `pip install hmf[class]`." ) return get_mdl(val, "TransferComponent") @parameter("param") def transfer_params(self, val): """ Relevant parameters of the `transfer_model`. :type: dict """ return val @parameter("param") def sigma_8(self, val): """ RMS linear density fluctuations in spheres of radius 8 Mpc/h. :type: float """ if val < 0.1 or val > 10: raise ValueError(f"sigma_8 out of bounds, {val}") return val @parameter("param") def sigma_8_species(self, val): """ Which matter field :attr:`sigma_8` describes: ``"tot"``, ``"cb"`` or ``None``. The default, ``"tot"``, means :attr:`sigma_8` is the r.m.s. of the *total* matter field (including massive neutrinos), which is how experiments such as Planck quote it, and how the default :attr:`sigma_8` is defined. When the transfer model computes the CDM+baryon field (``matter_species="cb"``, the default), its power spectrum is normalised so that the total matter field from the same model has r.m.s. :attr:`sigma_8`. ``"cb"`` means :attr:`sigma_8` is that of the CDM+baryon field, and ``None`` means whichever field the transfer model computes. This has no effect with massless neutrinos (the fields are then identical) or for transfer models that don't distinguish the two fields (i.e. have no ``matter_species`` parameter, like ``EH`` or ``BBKS``). Otherwise, normalising a field other than the computed one needs that field's transfer function too. With ``CAMB`` or ``CLASS`` this reuses the same run, which gives both fields. See :doc:`/massive_neutrinos`. :type: str or None """ if val not in (None, "tot", "cb"): raise ValueError(f"sigma_8_species must be None, 'tot' or 'cb', got {val!r}") return val @parameter("param") def n(self, val): """ Spectral index of fluctuations. Must be greater than -3 and less than 4. :type: float """ if val < -3 or val > 4: raise ValueError(f"n out of bounds, {val}") return val @parameter("res") def lnk_min(self, val): """ Minimum (natural) log wave-number, :attr:`k` [h/Mpc]. :type: float """ return val @parameter("res") def lnk_max(self, val): """ Maximum (natural) log wave-number, :attr:`k` [h/Mpc]. :type: float """ return val @parameter("res") def dlnk(self, val): """ Step-size of log wave-numbers. :type: float """ return val @parameter("switch") def takahashi(self, val): """ Whether to use updated HALOFIT coefficients from Takahashi+12. If False, use the original coefficients from Smith+2003. :type: bool """ return bool(val) @parameter("param") def z(self, val): """ Redshift. Must be non-negative. :type: float """ try: val = float(val) except ValueError as e: raise ValueError(f"z must be a number, got {val!r}") from e if val < 0: raise ValueError(f"z must be ≥ 0, got {val}") return val # =========================================================================== # DERIVED PROPERTIES AND FUNCTIONS # =========================================================================== @cached_quantity def k(self): """Wavenumbers, [h/Mpc].""" return np.exp(np.arange(self.lnk_min, self.lnk_max, self.dlnk)) @cached_quantity def transfer(self): """The instantiated transfer model.""" return self.transfer_model(self.cosmo, **self.transfer_params) @cached_quantity def _unnormalised_lnT(self): """The un-normalised transfer function.""" return self.transfer.lnt(np.log(self.k)) @cached_quantity def _unnormalised_power(self): """Un-normalised CDM power at :math:`z=0` [units :math:`Mpc^3/h^3`].""" return self.k**self.n * np.exp(self._unnormalised_lnT) ** 2 @cached_quantity def _sigma_8_transfer(self): """The transfer model of the field that :attr:`sigma_8` describes.""" species = self.sigma_8_species if ( species is None or not self.cosmo.has_massive_nu or self.transfer.params.get("matter_species", species) == species ): return self.transfer transfer = self.transfer_model( self.cosmo, **{**self.transfer.params, "matter_species": species} ) # One run of a Boltzmann code (e.g. CAMB) computes every species, so reuse the # run made for self.transfer. if isinstance(self.transfer, tm._BoltzmannTransfer): self.transfer._share_results(transfer) return transfer @cached_quantity def _unn_sig8(self): # Always use a TopHat for sigma_8, and always use full k-range. If the user's # range is narrow, fall back to a grid covering both [-8, 8] and the user's range. transfer = self._sigma_8_transfer if self.lnk_min > -15 or self.lnk_max < 9: lnk = np.arange(min(-8, self.lnk_min), max(8, self.lnk_max), self.dlnk) t = transfer.lnt(lnk) p = np.exp(lnk) ** self.n * np.exp(t) ** 2 filt = filters.TopHat(np.exp(lnk), p) elif transfer is self.transfer: filt = filters.TopHat(self.k, self._unnormalised_power) else: p = self.k**self.n * np.exp(transfer.lnt(np.log(self.k))) ** 2 filt = filters.TopHat(self.k, p) return filt.sigma(8.0)[0] @cached_quantity def _normalisation(self): # Calculate the normalization factor return self.sigma_8 / self._unn_sig8 @cached_quantity def _power0(self): """Normalised power spectrum at z=0 [units :math:`Mpc^3/h^3`].""" return self._normalisation**2 * self._unnormalised_power @cached_quantity def transfer_function(self): """Normalised CDM log transfer function.""" return self._normalisation * np.exp(self._unnormalised_lnT) @cached_quantity def growth(self): """The instantiated growth model.""" return self.growth_model(self.cosmo, **self.growth_params) @cached_quantity def _growth_factor_fn(self): """Function that efficiently returns the growth factor.""" return self.growth.growth_factor_fn() @cached_quantity def growth_factor(self): r"""The growth factor.""" if self.use_splined_growth: return self._growth_factor_fn(self.z) return self.growth.growth_factor(self.z) @cached_quantity def power(self): """Normalised log power spectrum [units :math:`Mpc^3/h^3`].""" return self.growth_factor**2 * self._power0 @cached_quantity def delta_k(self): r"""Dimensionless power spectrum, :math:`\Delta_k = \frac{k^3 P(k)}{2\pi^2}`.""" return self.k**3 * self.power / (2 * np.pi**2) @cached_quantity def nonlinear_power(self): """ Non-linear log power [units :math:`Mpc^3/h^3`]. Non-linear corrections come from HALOFIT. If you use this, please cite HALOFIT: Smith et al. [1]_, and also Takahashi et al. [2]_ when :attr:`takahashi` is True (the default). References ---------- .. [1] Smith, R. E., et al., 2003. MNRAS 341, 1311. arXiv:astro-ph/0207664 .. [2] Takahashi, R., et al., 2012. ApJ 761, 152. arXiv:1208.2701 """ return self.k**-3 * self.nonlinear_delta_k * (2 * np.pi**2) @cached_quantity def nonlinear_delta_k(self): r""" Dimensionless nonlinear power spectrum. .. math:: \Delta_k = \frac{k^3 P_{\rm nl}(k)}{2\pi^2} Non-linear corrections come from HALOFIT. If you use this, please cite HALOFIT: Smith et al. [1]_, and also Takahashi et al. [2]_ when :attr:`takahashi` is True (the default). References ---------- .. [1] Smith, R. E., et al., 2003. MNRAS 341, 1311. arXiv:astro-ph/0207664 .. [2] Takahashi, R., et al., 2012. ApJ 761, 152. arXiv:1208.2701 """ return _hfit(self.k, self.delta_k, z=self.z, cosmo=self.cosmo, takahashi=self.takahashi)