From 0a653cd36a7bde12a05bdac95b1da9ae0cab82b1 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 19 Nov 2026 21:37:27 +0000 Subject: [PATCH 1/2] fix: LOSSampler raises on a cosmology that mismatches the colossus name cosmology_astropy (deprecated) and LOSSampler(cosmology=...) were silently ignored by the colossus halo mass function and concentration relation, so a WMAP9 caller with the default planck15 colossus name got the Planck15 halo statistics. Both are now checked (H0, Om0) against the colossus cosmology and a mismatch raises a ValueError naming both. Closes #873 Co-Authored-By: Claude Opus 5.5 --- autolens/lens/los.py | 88 +++++++++++++++++++++++++++++----- test_autolens/lens/test_los.py | 84 +++++++++++++++++++++++++++++++- 2 files changed, 158 insertions(+), 14 deletions(-) diff --git a/autolens/lens/los.py b/autolens/lens/los.py index a3123f653..32098090e 100644 --- a/autolens/lens/los.py +++ b/autolens/lens/los.py @@ -131,6 +131,49 @@ 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 + + +def _check_cosmology_matches_colossus(cosmology, col_cosmo, cosmology_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`` and ``Om0``. + 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. + """ + h0 = float(getattr(cosmology.H0, "value", cosmology.H0)) + om0 = float(cosmology.Om0) + + 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 + ): + return + + name = getattr(cosmology, "name", None) or type(cosmology).__name__ + raise ValueError( + f"`{argument}` ({name}: H0={h0:g}, Om0={om0:g}) does not match the colossus cosmology " + f"{cosmology_name!r} (H0={col_cosmo.H0:g}, Om0={col_cosmo.Om0:g}) used for the halo mass " + "function and concentration relation. Pass the matching colossus cosmology name (e.g. " + "`cosmology_name_colossus='WMAP9'` for WMAP9) so both describe the same universe." + ) + + def mass_function_ab_from( redshift, cosmology_astropy=None, @@ -157,9 +200,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 @@ -178,15 +222,20 @@ 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" + ) + from colossus.lss.mass_function import massFunction h = col_cosmo.h @@ -597,11 +646,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. @@ -647,9 +700,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, ) @@ -790,6 +843,17 @@ 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 + ) + if mf_coeffs is None: mf_coeffs = np.zeros((n_planes, 2)) for i in range(n_planes): diff --git a/test_autolens/lens/test_los.py b/test_autolens/lens/test_los.py index 6e7b6ad7d..b713366dc 100644 --- a/test_autolens/lens/test_los.py +++ b/test_autolens/lens/test_los.py @@ -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 @@ -287,7 +287,87 @@ 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 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) + + 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) + + 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 From ebe5a6223caab864b98cc7f212f777498da8f954 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 19 Nov 2026 21:41:48 +0000 Subject: [PATCH 2/2] fix: name the right colossus argument in the hint; also compare curvature (Ok0) Review findings: mass_function_ab_from's hint now names cosmology_name (not cosmology_name_colossus), and a non-flat cosmology no longer passes the check on H0/Om0 alone (LambdaCDM Ode0=0.5 vs planck15 raises, tested). Co-Authored-By: Claude Opus 5.5 --- autolens/lens/los.py | 39 +++++++++++++++++++++++++--------- test_autolens/lens/test_los.py | 10 ++++++++- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/autolens/lens/los.py b/autolens/lens/los.py index 32098090e..749e55b78 100644 --- a/autolens/lens/los.py +++ b/autolens/lens/los.py @@ -136,9 +136,13 @@ def _colossus_cosmology_from(cosmology_name): # 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): +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``. @@ -149,28 +153,35 @@ def _check_cosmology_matches_colossus(cosmology, col_cosmo, cosmology_name, argu Parameters ---------- cosmology - An ``astropy`` cosmology or an autogalaxy ``LensingCosmology``; compared by ``H0`` and ``Om0``. + 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 + 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}) does not match the colossus cosmology " - f"{cosmology_name!r} (H0={col_cosmo.H0:g}, Om0={col_cosmo.Om0:g}) used for the halo mass " - "function and concentration relation. Pass the matching colossus cosmology name (e.g. " - "`cosmology_name_colossus='WMAP9'` for WMAP9) so both describe the same universe." + 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." ) @@ -233,7 +244,11 @@ def mass_function_ab_from( if cosmology_astropy is not None: _check_cosmology_matches_colossus( - cosmology_astropy, col_cosmo, cosmology_name, "cosmology_astropy" + cosmology_astropy, + col_cosmo, + cosmology_name, + "cosmology_astropy", + "cosmology_name", ) from colossus.lss.mass_function import massFunction @@ -851,7 +866,11 @@ def _sample_population(self): ): if supplied is not None: _check_cosmology_matches_colossus( - supplied, col_cosmo, self.cosmology_name_colossus, argument + supplied, + col_cosmo, + self.cosmology_name_colossus, + argument, + "cosmology_name_colossus", ) if mf_coeffs is None: diff --git a/test_autolens/lens/test_los.py b/test_autolens/lens/test_los.py index b713366dc..04d0413c0 100644 --- a/test_autolens/lens/test_los.py +++ b/test_autolens/lens/test_los.py @@ -304,12 +304,19 @@ def test__mass_function_ab_from__mismatched_cosmology_astropy_raises(): ``ValueError`` naming both. A matching colossus name works. """ pytest.importorskip("colossus") - from astropy.cosmology import WMAP9 + 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( @@ -335,6 +342,7 @@ def test__los_sampler__mismatched_cosmology_raises(): 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(