Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background, boltzmann, and cls in v3 #1041

Merged
merged 25 commits into from
Mar 24, 2023
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
8 changes: 4 additions & 4 deletions benchmarks/test_cls.py → benchmarks/test_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,8 @@ def read_bm(fname):
('i2', 'i2', 'ii_22', # IA2-IA2
'll_22', 'll_22', 'll_22', 'll_22',
'fl_ll')])
def test_cls(set_up, t1, t2, bm,
a1b1, a1b2, a2b1, a2b2, fl):
def test_cells(set_up, t1, t2, bm,
a1b1, a1b2, a2b1, a2b2, fl):
cosmo, trcs, lfc, bmk = set_up
cl = ccl.angular_cl(cosmo, trcs[t1], trcs[t2], lfc['ells'],
limber_integration_method='qag_quad') * lfc[fl]
Expand All @@ -213,8 +213,8 @@ def test_cls(set_up, t1, t2, bm,
('l2', 'l2', 'll_22', # WL2-WL2
'll_22', 'll_22', 'll_22', 'll_22',
'fl_ll')])
def test_cls_spline(set_up, t1, t2, bm,
a1b1, a1b2, a2b1, a2b2, fl):
def test_cells_spline(set_up, t1, t2, bm,
a1b1, a1b2, a2b1, a2b2, fl):
cosmo, trcs, lfc, bmk = set_up
cl = ccl.angular_cl(cosmo, trcs[t1], trcs[t2], lfc['ells'],
limber_integration_method='spline') * lfc[fl]
Expand Down
12 changes: 8 additions & 4 deletions benchmarks/test_power_nu.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

import pyccl as ccl

# NOTE: We now check up to kmax=23
# because CLASS v3 has a slight mismatch
# (6e-3) at higher k wavenumbers.
KMAX = 23
nikfilippas marked this conversation as resolved.
Show resolved Hide resolved
POWER_NU_TOL = 1.0E-3


Expand Down Expand Up @@ -43,12 +47,12 @@ def test_power_nu(model):
warnings.simplefilter("ignore")
pk_lin_ccl = ccl.linear_matter_power(cosmo, k_lin, a)

err = np.abs(pk_lin_ccl/pk_lin - 1)
assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
assert np.allclose(pk_lin_ccl[k_lin < KMAX],
pk_lin[k_lin < KMAX],
rtol=POWER_NU_TOL)

data_nl = np.loadtxt("./benchmarks/data/model%d_pk_nl_nu.txt" % (model+1))
k_nl = data_nl[:, 0] * cosmo['h']
pk_nl = data_nl[:, 1] / (cosmo['h']**3)
pk_nl_ccl = ccl.nonlin_matter_power(cosmo, k_nl, a)
err = np.abs(pk_nl_ccl/pk_nl - 1)
assert np.allclose(err, 0, rtol=0, atol=POWER_NU_TOL)
assert np.allclose(pk_nl_ccl, pk_nl, rtol=POWER_NU_TOL)
13 changes: 12 additions & 1 deletion pyccl/__init__.py
nikfilippas marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@
)

# Cells & Tracers
from .cls import angular_cl
from .cells import angular_cl
from .tracers import (
Tracer,
NzTracer,
Expand Down Expand Up @@ -150,6 +150,17 @@
from .pyutils import debug_mode, resample_array

# Deprecated & Renamed modules
def __getattr__(name):
rename = {"cls": "cells"}
if name in rename:
from .errors import CCLDeprecationWarning
import warnings
warnings.warn(f"Module {name} has been renamed to {rename[name]}.",
CCLDeprecationWarning)
name = rename[name]
return eval(name)
Comment on lines +156 to +161
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These lines are uncovered, can you add a test at the top of test_cls.py?

Also, can you rename test_cls to test_cells (and all occurrences of the word cls within)?
I found another mention of cls: tests/test_pk2d.py:def test_pk2d_cls().
And in benchmarks/test_cls.py.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

raise AttributeError(f"No module named {name}.")

from .halomodel import (
halomodel_matter_power,
halo_concentration,
Expand Down
11 changes: 7 additions & 4 deletions pyccl/background.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
"""
import numpy as np
from . import ccllib as lib
from .pyutils import _vectorize_fn, _vectorize_fn3
from .pyutils import _vectorize_fn4, _vectorize_fn5
from .pyutils import (_vectorize_fn, _vectorize_fn3,
_vectorize_fn4, _vectorize_fn5)
from .parameters import physical_constants
from .base import warn_api

species_types = {
'critical': lib.species_crit_label,
Expand Down Expand Up @@ -248,7 +249,8 @@ def omega_x(cosmo, a, species):
lib.omega_x_vec, cosmo, a, species_types[species])


def rho_x(cosmo, a, species, is_comoving=False):
@warn_api
def rho_x(cosmo, a, species, *, is_comoving=False):
"""Physical or comoving density as a function of scale factor.

Args:
Expand Down Expand Up @@ -280,7 +282,8 @@ def rho_x(cosmo, a, species, is_comoving=False):
species_types[species], int(is_comoving))


def sigma_critical(cosmo, a_lens, a_source):
@warn_api
def sigma_critical(cosmo, *, a_lens, a_source):
"""Returns the critical surface mass density.

.. math::
Expand Down
17 changes: 9 additions & 8 deletions pyccl/boltzmann.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import numpy as np

try:
import isitgr # noqa: F401
except ModuleNotFoundError:
pass # prevent nans from isitgr

from . import ccllib as lib
from .pyutils import check
from .base import warn_api
from .pk2d import Pk2D
from .errors import CCLError
from .parameters import physical_constants

try:
import isitgr # noqa: F401
except ModuleNotFoundError:
pass # prevent nans from isitgr


def get_camb_pk_lin(cosmo, nonlin=False):
@warn_api
def get_camb_pk_lin(cosmo, *, nonlin=False):
"""Run CAMB and return the linear power spectrum.

Args:
Expand Down Expand Up @@ -289,8 +291,7 @@ def get_isitgr_pk_lin(cosmo):
cp.ombh2 = cosmo['Omega_b'] * h2
cp.omch2 = cosmo['Omega_c'] * h2
cp.omk = cosmo['Omega_k']
# cp.GR = 1 means GR modified!
cp.GR = 1
cp.GR = 1 # means GR modified!
cp.ISiTGR_muSigma = True
cp.mu0 = cosmo['mu_0']
cp.Sigma0 = cosmo['sigma_0']
Expand Down
13 changes: 7 additions & 6 deletions pyccl/cls.py → pyccl/cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@
from .errors import CCLWarning
from . import ccllib as lib
from .pyutils import check, integ_types
from .base import warn_api
from .pk2d import parse_pk2d

# Define symbolic 'None' type for arrays, to allow proper handling by swig
# wrapper
NoneArr = np.array([])


def angular_cl(cosmo, cltracer1, cltracer2, ell, p_of_k_a=None,
@warn_api(pairs=[("cltracer1", "tracer1"), ("cltracer2", "tracer2")])
def angular_cl(cosmo, tracer1, tracer2, ell, *, p_of_k_a=None,
l_limber=-1., limber_integration_method='qag_quad'):
"""Calculate the angular (cross-)power spectrum for a pair of tracers.

Args:
cosmo (:class:`~pyccl.core.Cosmology`): A Cosmology object.
cltracer1 (:class:`~pyccl.tracers.Tracer`): a `Tracer` object,
tracer1 (:class:`~pyccl.tracers.Tracer`): a `Tracer` object,
of any kind.
cltracer2 (:class:`~pyccl.tracers.Tracer`): a second `Tracer` object,
tracer2 (:class:`~pyccl.tracers.Tracer`): a second `Tracer` object,
of any kind.
ell (float or array_like): Angular wavenumber(s) at which to evaluate
the angular power spectrum.
Expand All @@ -46,7 +48,6 @@ def angular_cl(cosmo, cltracer1, cltracer2, ell, p_of_k_a=None,
"CCL does not properly use the hyperspherical Bessel functions "
"when computing angular power spectra in non-flat cosmologies!",
category=CCLWarning)

if limber_integration_method not in ['qag_quad', 'spline']:
raise ValueError("Integration method %s not supported" %
limber_integration_method)
Expand All @@ -64,9 +65,9 @@ def angular_cl(cosmo, cltracer1, cltracer2, ell, p_of_k_a=None,
status = 0
clt1, status = lib.cl_tracer_collection_t_new(status)
clt2, status = lib.cl_tracer_collection_t_new(status)
for t in cltracer1._trc:
for t in tracer1._trc:
status = lib.add_cl_tracer_to_collection(clt1, t, status)
for t in cltracer2._trc:
for t in tracer2._trc:
status = lib.add_cl_tracer_to_collection(clt2, t, status)

ell_use = np.atleast_1d(ell)
Expand Down
6 changes: 3 additions & 3 deletions pyccl/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,10 @@ class Cosmology(CCLObject):
# Go through all functions in the main package and the subpackages
# and make every function that takes `cosmo` as its first argument
# an attribute of this class.
from . import (background, bcm, boltzmann, cls,
from . import (background, bcm, boltzmann, cells,
correlations, covariances, neutrinos,
pk2d, power, pyutils, tk3d, tracers, halos, nl_pt)
subs = [background, boltzmann, bcm, cls, correlations, covariances,
subs = [background, boltzmann, bcm, cells, correlations, covariances,
neutrinos, pk2d, power, pyutils, tk3d, tracers, halos, nl_pt]
funcs = [getmembers(sub, isfunction) for sub in subs]
funcs = [func for sub in funcs for func in sub]
Expand All @@ -214,7 +214,7 @@ class Cosmology(CCLObject):
if pars and pars[0] == "cosmo":
vars()[name] = func
# clear unnecessary locals
del (background, boltzmann, bcm, cls, correlations, covariances,
del (background, boltzmann, bcm, cells, correlations, covariances,
neutrinos, pk2d, power, pyutils, tk3d, tracers, halos, nl_pt,
subs, funcs, func, name, pars)

Expand Down
4 changes: 2 additions & 2 deletions pyccl/halos/profiles/profile_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def convergence(self, cosmo, r, M, a_lens, a_source, mass_def):
:math:`\\kappa`
"""
Sigma = self.projected(cosmo, r, M, a_lens, mass_def) / a_lens**2
Sigma_crit = sigma_critical(cosmo, a_lens, a_source)
Sigma_crit = sigma_critical(cosmo, a_lens=a_lens, a_source=a_source)
return Sigma / Sigma_crit

def shear(self, cosmo, r, M, a_lens, a_source, mass_def):
Expand Down Expand Up @@ -332,7 +332,7 @@ def shear(self, cosmo, r, M, a_lens, a_source, mass_def):
"""
Sigma = self.projected(cosmo, r, M, a_lens, mass_def)
Sigma_bar = self.cumul2d(cosmo, r, M, a_lens, mass_def)
Sigma_crit = sigma_critical(cosmo, a_lens, a_source)
Sigma_crit = sigma_critical(cosmo, a_lens=a_lens, a_source=a_source)
return (Sigma_bar - Sigma) / (Sigma_crit * a_lens**2)

def reduced_shear(self, cosmo, r, M, a_lens, a_source, mass_def):
Expand Down
4 changes: 2 additions & 2 deletions pyccl/tests/test_background.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,14 @@ def test_background_omega_x_raises():
'neutrinos_massive'])
@pytest.mark.parametrize('is_comoving', [True, False])
def test_background_rho_x(a, kind, is_comoving):
val = ccl.rho_x(COSMO_NU, a, kind, is_comoving)
val = ccl.rho_x(COSMO_NU, a, kind, is_comoving=is_comoving)
assert np.all(np.isfinite(val))
assert np.shape(val) == np.shape(a)


def test_background_rho_x_raises():
with pytest.raises(ValueError):
ccl.rho_x(COSMO, 1, 'blah', False)
ccl.rho_x(COSMO, 1, 'blah', is_comoving=False)


def test_input_arrays():
Expand Down
13 changes: 8 additions & 5 deletions pyccl/tests/test_cls.py → pyccl/tests/test_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
NN = np.exp(-((ZZ-0.5)/0.1)**2)
LENS = ccl.WeakLensingTracer(COSMO, dndz=(ZZ, NN))

with pytest.warns(ccl.CCLDeprecationWarning):
ccl.cls


@pytest.mark.parametrize('p_of_k_a', [None, PKA])
def test_cls_smoke(p_of_k_a):
def test_cells_smoke(p_of_k_a):
# make a set of tracers to test with
z = np.linspace(0., 1., 200)
n = np.exp(-((z-0.5)/0.1)**2)
Expand Down Expand Up @@ -69,25 +72,25 @@ def test_cls_smoke(p_of_k_a):


@pytest.mark.parametrize('ells', [[3, 2, 1], [1, 3, 2], [2, 3, 1]])
def test_cls_raise_ell_reversed(ells):
def test_cells_raise_ell_reversed(ells):
with pytest.raises(ValueError):
ccl.angular_cl(COSMO, LENS, LENS, ells)


def test_cls_raise_integ_method():
def test_cells_raise_integ_method():
ells = [10, 11]
with pytest.raises(ValueError):
ccl.angular_cl(COSMO, LENS, LENS, ells,
limber_integration_method='guad')


def test_cls_raise_weird_pk():
def test_cells_raise_weird_pk():
ells = [10, 11]
with pytest.raises(ValueError):
ccl.angular_cl(COSMO, LENS, LENS, ells, p_of_k_a=lambda k, a: 10)


def test_cls_mg():
def test_cells_mg():
# Check that if we feed the non-linear matter power spectrum from a MG
# cosmology into a Calculator and get Cells using MG tracers, we get the
# same results.
Expand Down
4 changes: 2 additions & 2 deletions pyccl/tests/test_cosmology.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ def test_cosmo_methods():
"""
from inspect import getmembers, isfunction, signature
from pyccl import background, bcm, boltzmann, \
cls, correlations, covariances, neutrinos, \
cells, correlations, covariances, neutrinos, \
pk2d, power, tk3d, tracers, halos, nl_pt
cosmo = ccl.CosmologyVanillaLCDM()
subs = [background, boltzmann, bcm, cls, correlations, covariances,
subs = [background, boltzmann, bcm, cells, correlations, covariances,
neutrinos, pk2d, power, tk3d, tracers, halos, nl_pt]
funcs = [getmembers(sub, isfunction) for sub in subs]
funcs = [func for sub in funcs for func in sub]
Expand Down
32 changes: 16 additions & 16 deletions pyccl/tests/test_pk2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def test_pk2d_function():
assert_allclose(dphere, -1.*np.ones_like(dphere), 6)


def test_pk2d_cls():
def test_pk2d_cells():
"""
Test interplay between Pk2D and the Limber integrator
"""
Expand Down Expand Up @@ -234,21 +234,21 @@ def test_pk2d_parsing():
lens1 = ccl.WeakLensingTracer(cosmo, dndz=(z, n))
ells = np.linspace(2, 100, 10)

cls1 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a=None)
cls2 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a='delta_matter:delta_matter')
cls3 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a='a:b')
cls4 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a=psp)
assert all_finite(cls1)
assert all_finite(cls2)
assert all_finite(cls3)
assert all_finite(cls4)
assert np.all(np.fabs(cls2/cls1-1) < 1E-10)
assert np.all(np.fabs(cls3/cls1-1) < 1E-10)
assert np.all(np.fabs(cls4/cls1-1) < 1E-10)
cells1 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a=None)
cells2 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a='delta_matter:delta_matter')
cells3 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a='a:b')
cells4 = ccl.angular_cl(cosmo, lens1, lens1, ells,
p_of_k_a=psp)
assert all_finite(cells1)
assert all_finite(cells2)
assert all_finite(cells3)
assert all_finite(cells4)
assert np.all(np.fabs(cells2/cells1-1) < 1E-10)
assert np.all(np.fabs(cells3/cells1-1) < 1E-10)
assert np.all(np.fabs(cells4/cells1-1) < 1E-10)

# Wrong name
with pytest.raises(KeyError):
Expand Down