UnitContext

class hmf.core.units.UnitContext(H0: Quantity | None = None, *, where: str = 'UnitContext')[source]

Per-instance unit-conversion state: the H0, and cached conversion factors.

Every object with unit_boundary()-decorated methods may provide one, as its _unit_context attribute (see HasUnitContext). The decorator uses it for any argument whose unit is not identical to the canonical unit.

Conversion factors are cached, keyed first by the identity of the units (the fast lookup) and then by their equality, so each distinct unit is converted once per context. The cache is not part of the owning object’s value: it is not compared, hashed or serialised.

Parameters:
  • H0 – The Hubble constant used to convert physical units (e.g. M☉) to h-units (e.g. M☉/h): a scalar Quantity in units of H0_unit (km/s/Mpc), or convertible to it. None if the owner has no cosmology: then only inputs that need no H0 (any unit with the canonical power of littleh) are accepted.

  • where – The name of the owner (e.g. "TabulatedPower"), for error messages.

Raises:

Notes

n_computed counts the conversion factors this context has computed (its cache misses), which tests use to check that the cache is used.

Attributes

H0
n_computed
equivalencies

cu.with_H0(self.H0), built once.

Always built with this context’s H0: cu.with_H0() without an argument silently uses Planck18’s.

Methods

factor(src: UnitBase, dst: UnitBase) → float[source]

Return the factor converting values in src to values in dst.

Parameters:
  • src – The unit of the input.

  • dst – The canonical unit to convert to.

Returns:

value_in_dst = value_in_src * factor.

Return type:

float

Raises:

astropy.units.UnitConversionError – If src has a power of littleh that is neither the canonical one nor zero (e.g. M☉/h² given as a mass), or the wrong dimension.