Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 95 additions & 12 deletions autolens/lens/los.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,60 @@ def _colossus_cosmology_from(cosmology_name):
return col_cosmology.setCosmology(cosmology_name)


# Relative tolerances for matching a supplied cosmology to the colossus one. Om0 is loose because
# colossus folds massive neutrinos into Om0 (astropy Planck15: 0.3075, colossus planck15: 0.3089);
# a genuinely different cosmology (e.g. WMAP9 vs planck15: 2.3% in H0, 7% in Om0) is far outside.
_H0_RTOL = 1e-3
_OM0_RTOL = 1e-2
# Absolute tolerance on the curvature density Ok0 (colossus and autogalaxy cosmologies are flat).
_OK0_ATOL = 1e-3


def _check_cosmology_matches_colossus(
cosmology, col_cosmo, cosmology_name, argument, name_argument
):
"""
Raise a ``ValueError`` if ``cosmology`` disagrees with the colossus cosmology ``col_cosmo``.

The halo mass function and concentration relation are computed with colossus, whose cosmology
is set by name, so a different cosmology passed alongside it would otherwise be used for the
distances but silently ignored by the halo statistics.

Parameters
----------
cosmology
An ``astropy`` cosmology or an autogalaxy ``LensingCosmology``; compared by ``H0``,
``Om0`` and the curvature ``Ok0`` (taken as 0, flat, when it has none).
col_cosmo
The colossus cosmology set from ``cosmology_name``.
cosmology_name
The colossus cosmology name, quoted in the error.
argument
The name of the argument ``cosmology`` was passed as, quoted in the error.
name_argument
The name of the argument that sets the colossus cosmology name, quoted in the error's hint.
"""
h0 = float(getattr(cosmology.H0, "value", cosmology.H0))
om0 = float(cosmology.Om0)
ok0 = float(getattr(cosmology, "Ok0", 0.0))

if (
np.isclose(h0, col_cosmo.H0, rtol=_H0_RTOL, atol=0.0)
and np.isclose(om0, col_cosmo.Om0, rtol=_OM0_RTOL, atol=0.0)
and abs(ok0 - col_cosmo.Ok0) <= _OK0_ATOL
):
return

name = getattr(cosmology, "name", None) or type(cosmology).__name__
raise ValueError(
f"`{argument}` ({name}: H0={h0:g}, Om0={om0:g}, Ok0={ok0:g}) does not match the colossus "
f"cosmology {cosmology_name!r} (H0={col_cosmo.H0:g}, Om0={col_cosmo.Om0:g}, "
f"Ok0={col_cosmo.Ok0:g}) used for the halo mass function and concentration relation. "
f"Pass the matching colossus cosmology name (e.g. `{name_argument}='WMAP9'` for WMAP9) so "
"both describe the same universe."
)


def mass_function_ab_from(
redshift,
cosmology_astropy=None,
Expand All @@ -157,9 +211,10 @@ def mass_function_ab_from(
redshift
Redshift at which to evaluate the mass function.
cosmology_astropy
Deprecated and ignored. The mass function was formerly computed with ``hmf``, which took an
Deprecated. The mass function was formerly computed with ``hmf``, which took an
``astropy`` cosmology; it is now computed with ``colossus``, which takes
``cosmology_name``. Passing it raises a ``DeprecationWarning``.
``cosmology_name``. Passing it raises a ``DeprecationWarning``, and a ``ValueError`` if it
does not match ``cosmology_name``.
m_min_log10
Lower bound of log10(m / M_sun) for the fit range.
m_max_log10
Expand All @@ -178,15 +233,24 @@ def mass_function_ab_from(
"""
if cosmology_astropy is not None:
warnings.warn(
"mass_function_ab_from: `cosmology_astropy` is deprecated and ignored. The mass "
"function is computed with colossus, whose cosmology is set by `cosmology_name` "
f"(here {cosmology_name!r}).",
"mass_function_ab_from: `cosmology_astropy` is deprecated. The mass function is "
"computed with colossus, whose cosmology is set by `cosmology_name` "
f"(here {cosmology_name!r}); `cosmology_astropy` is only checked against it.",
DeprecationWarning,
stacklevel=2,
)

col_cosmo = _colossus_cosmology_from(cosmology_name)

if cosmology_astropy is not None:
_check_cosmology_matches_colossus(
cosmology_astropy,
col_cosmo,
cosmology_name,
"cosmology_astropy",
"cosmology_name",
)

from colossus.lss.mass_function import massFunction

h = col_cosmo.h
Expand Down Expand Up @@ -597,11 +661,15 @@ class LOSSampler:
truncation_factor
Overdensity factor for truncation radius (e.g. 100 for r_100).
cosmology
A ``LensingCosmology`` instance. Defaults to ``Planck15()``.
A ``LensingCosmology`` instance. Defaults to ``Planck15()``. When the
halo statistics are computed with ``colossus`` it must match
``cosmology_name_colossus`` (H0 and Om0), else sampling raises a
``ValueError``.
cosmology_astropy
Deprecated and ignored: the mass function is now computed with
``colossus`` (see ``cosmology_name_colossus``). Passing it raises a
``DeprecationWarning``.
Deprecated: the mass function is now computed with ``colossus`` (see
``cosmology_name_colossus``). Passing it raises a ``DeprecationWarning``,
and sampling raises a ``ValueError`` if it does not match
``cosmology_name_colossus``.
cosmology_name_colossus
Colossus cosmology name (e.g. ``"planck15"``), used for both the
Sheth-Tormen mass function and the Ludlow+16 concentration relation.
Expand Down Expand Up @@ -647,9 +715,9 @@ def __init__(
self.cosmology = cosmology or Planck15()
if cosmology_astropy is not None:
warnings.warn(
"LOSSampler: `cosmology_astropy` is deprecated and ignored. The mass function is "
"computed with colossus, whose cosmology is set by `cosmology_name_colossus` "
f"(here {cosmology_name_colossus!r}).",
"LOSSampler: `cosmology_astropy` is deprecated. The mass function is computed "
"with colossus, whose cosmology is set by `cosmology_name_colossus` "
f"(here {cosmology_name_colossus!r}); `cosmology_astropy` is only checked against it.",
DeprecationWarning,
stacklevel=2,
)
Expand Down Expand Up @@ -790,6 +858,21 @@ def _sample_population(self):
mf_coeffs = self.mass_function_coefficients
mc_coeffs = self.mass_concentration_coefficients

if mf_coeffs is None or mc_coeffs is None:
col_cosmo = _colossus_cosmology_from(self.cosmology_name_colossus)
for argument, supplied in (
("cosmology", cosmology),
("cosmology_astropy", self.cosmology_astropy),
):
if supplied is not None:
_check_cosmology_matches_colossus(
supplied,
col_cosmo,
self.cosmology_name_colossus,
argument,
"cosmology_name_colossus",
)

if mf_coeffs is None:
mf_coeffs = np.zeros((n_planes, 2))
for i in range(n_planes):
Expand Down
92 changes: 90 additions & 2 deletions test_autolens/lens/test_los.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest

import autolens as al
from autogalaxy.cosmology import Planck15
from autogalaxy.cosmology import FlatLambdaCDM, Planck15
from autolens.lens import los


Expand Down Expand Up @@ -287,7 +287,95 @@ def test__mass_function_ab_from__missing_colossus_raises_clear_import_error(
def test__mass_function_ab_from__cosmology_astropy_is_deprecated():
pytest.importorskip("colossus")

from astropy.cosmology import Planck15 as AstropyPlanck15

with pytest.warns(DeprecationWarning, match="cosmology_astropy"):
A, B = los.mass_function_ab_from(redshift=0.5, cosmology_astropy=object())
A, B = los.mass_function_ab_from(
redshift=0.5, cosmology_astropy=AstropyPlanck15
)

assert A == pytest.approx(-1.907, abs=0.01)


def test__mass_function_ab_from__mismatched_cosmology_astropy_raises():
"""
A ``cosmology_astropy`` that disagrees with the colossus cosmology must not be silently
ignored (it would give the Planck15 mass function for a WMAP9 caller): it raises a
``ValueError`` naming both. A matching colossus name works.
"""
pytest.importorskip("colossus")
from astropy.cosmology import LambdaCDM, WMAP9

with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match="WMAP9") as exc:
los.mass_function_ab_from(redshift=0.5, cosmology_astropy=WMAP9)
assert "planck15" in str(exc.value)
assert "`cosmology_name='WMAP9'`" in str(exc.value)

curved = LambdaCDM(H0=67.74, Om0=0.3089, Ode0=0.5)

with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match="Ok0"):
los.mass_function_ab_from(redshift=0.5, cosmology_astropy=curved)

with pytest.warns(DeprecationWarning):
A, B = los.mass_function_ab_from(
redshift=0.5, cosmology_astropy=WMAP9, cosmology_name="WMAP9"
)
assert B == pytest.approx(8.108, abs=0.002)


def test__los_sampler__mismatched_cosmology_raises():
"""
``LOSSampler`` checks both ``cosmology`` and ``cosmology_astropy`` against
``cosmology_name_colossus`` when it computes the halo statistics with colossus, and raises a
``ValueError`` naming both on a mismatch. Matching pairs, and precomputed coefficients (no
colossus), work unchanged.
"""
pytest.importorskip("colossus")
from astropy.cosmology import WMAP9

wmap9_like = FlatLambdaCDM(H0=69.32, Om0=0.2865)

with pytest.raises(ValueError, match="`cosmology`") as exc:
los.LOSSampler(
z_lens=0.5, z_source=1.0, cosmology=wmap9_like, seed=1
).galaxies_from()
assert "planck15" in str(exc.value)
assert "`cosmology_name_colossus='WMAP9'`" in str(exc.value)

with pytest.warns(DeprecationWarning):
sampler = los.LOSSampler(
z_lens=0.5, z_source=1.0, cosmology_astropy=WMAP9, seed=1
)
with pytest.raises(ValueError, match="WMAP9") as exc:
sampler.galaxies_from()
assert "planck15" in str(exc.value)

mf, mc = _approx_coefficients(n_planes=9)
los.LOSSampler(
z_lens=0.5,
z_source=1.0,
cosmology=wmap9_like,
mass_function_coefficients=mf,
mass_concentration_coefficients=mc,
seed=1,
).galaxies_from()


def test__los_sampler__matching_cosmology_pair_is_accepted(monkeypatch):
pytest.importorskip("colossus")

monkeypatch.setenv("PYAUTO_TEST_MODE", "2")

wmap9_like = FlatLambdaCDM(H0=69.32, Om0=0.2865)

galaxies = los.LOSSampler(
z_lens=0.5,
z_source=1.0,
cosmology=wmap9_like,
cosmology_name_colossus="WMAP9",
seed=1,
).galaxies_from()

assert len(galaxies) > 0
Loading