diff --git a/docs/reference/index.rst b/docs/reference/index.rst index df26f9692..587b79e35 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -6,6 +6,7 @@ Function reference :maxdepth: 1 shells + spectra fields points shapes diff --git a/docs/reference/spectra.rst b/docs/reference/spectra.rst new file mode 100644 index 000000000..1e696807d --- /dev/null +++ b/docs/reference/spectra.rst @@ -0,0 +1 @@ +.. automodule:: glass.spectra diff --git a/glass/spectra.py b/glass/spectra.py new file mode 100644 index 000000000..439b83971 --- /dev/null +++ b/glass/spectra.py @@ -0,0 +1,604 @@ +""" +Spectra +======= + +.. currentmodule:: glass.spectra + +Angular power spectra of GLASS matter shells without the Limber +approximation, using the Levin method for the Bessel integrals as +implemented by `pylevin `_. + +This module requires the optional ``pylevin`` (2.1.0 or later) and +``scipy`` packages and is not imported by ``import glass``. + +.. autofunction:: nonlimber_cls +.. autofunction:: nonlimber_plan +.. autoclass:: NonLimberPlan + :members: save, load + +""" # noqa: D400 + +from __future__ import annotations + +__lazy_modules__ = [ + "pylevin", + "scipy.interpolate", +] + +import dataclasses +import functools +import importlib.metadata +import itertools +import os +import re +from typing import TYPE_CHECKING + +import numpy as np +import pylevin +from scipy import sparse +from scipy.interpolate import CubicSpline + +# 2.0 exports quadrature rules, 2.0.1 refines unresolved integrands, +# 2.1.0 stores the rules in the first call +_PYLEVIN = re.match(r"(\d+)\.(\d+)\.(\d+)", importlib.metadata.version("pylevin")) +if _PYLEVIN is None or tuple(map(int, _PYLEVIN.groups())) < (2, 1, 0): + msg = "glass.spectra requires pylevin 2.1.0 or later" + raise ImportError(msg) + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from numpy.typing import NDArray + + from glass.cosmology import Cosmology, CosmologyWithInverseComovingDistance + from glass.shells import RadialWindow + + +def _levin( # noqa: PLR0913 + ks: NDArray[np.float64], + ncol: int = 8, + *, + window: tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]], + pk: Callable[..., NDArray[np.float64]], + ell: int, + nthread: int, +) -> NDArray[np.float64]: + """ + Compute the inner integral I(ell, k) of one shell at the given k. + + A new pylevin instance is created per call, since instances cache + their solution. + """ + za, chi, kernel = window + f = np.sqrt(pk(za, ks)) * kernel[:, None] + lp = pylevin.pylevin(0, chi, f, True, True, nthread, True) # noqa: FBT003 + # n_col, n_bisec, rel_acc; gsl Bessel functions abort, tol_abs > 0 stops + # early, and one call needs no stored rules + lp.set_levin( + ncol, + 32, + 1e-4, + super_accurate=True, + verbose=False, + tol_abs_in=0.0, + store_first_call=False, + ) + out = np.zeros(len(ks)) + lp.levin_integrate_bessel_single( + np.full(len(ks), chi[0]), + np.full(len(ks), chi[-1]), + ks, + np.full(len(ks), int(ell)), + out, + ) + return out + + +def _robust( + call: Callable[..., NDArray[np.float64]], + ks: NDArray[np.float64], + tol: float = 1e-4, +) -> NDArray[np.float64]: + """ + Compute I(ell, k) robustly against rare pylevin glitches. + + pylevin returns wrong values at rare isolated k (deterministic, and + flipped by 1e-16 input changes). With 2.1.0 they reach 6e-3 of the + amplitude at n_col 8 and 3e-2 at n_col 6 in tests. Each n_col has + its own glitches, and I(k) is not smooth on the k grid at high l, + so neighbour tests cannot find them. Compute + every k at n_col 8 and 6; where they disagree by more than *tol* + times the 98th percentile amplitude, also compute n_col 10 and take + the median of the three. pylevin pairs n_col (9 == 10, 11 == 12), so + alternates must be even steps apart. + """ + if not len(ks): + return np.zeros(0) + i8, i6 = call(ks, 8), call(ks, 6) + j = np.nonzero(np.abs(i8 - i6) > tol * np.quantile(np.abs(i8), 0.98))[0] + if len(j): + i8[j] = np.median(np.stack([i8[j], i6[j], call(ks[j], 10)]), axis=0) + return i8 + + +def _ell_grid(lmax: int) -> NDArray[np.int_]: + """Multipoles at which the non-Limber integrals are computed.""" + ell_all = np.unique( + np.r_[np.arange(2, 30), np.geomspace(30, lmax, 75).astype(int)], + ) + return np.union1d(np.r_[np.arange(1, 20), ell_all[::2]], [lmax]) + + +def _k_grid(density: float) -> NDArray[np.float64]: + """Shared log wavenumber grid from 1e-4 to 100.""" + return np.geomspace(1e-4, 100.0, int(density * np.log(1e6)) + 1) + + +def _k_mask( + k: NDArray[np.float64], + ell: int, + lo: float, + hi: float, + q: float, +) -> NDArray[np.bool_]: + """K-support [0.3 nu/hi, max(3 nu/lo, q/(hi - lo))] of a shell on [lo, hi].""" + nu = ell + 0.5 + kmax = 3 * nu / lo if lo > 0 else np.inf + return (k >= 0.3 * nu / hi) & (k <= max(kmax, q / (hi - lo))) + + +def _rules( # noqa: PLR0913, PLR0917 + x: NDArray[np.float64], + f: NDArray[np.float64], + lo: NDArray[np.float64], + hi: NDArray[np.float64], + ks: NDArray[np.float64], + ells: NDArray[np.int_], + integrand: NDArray[np.int_], + *, + ncol: int, + nthread: int, +) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.int_], NDArray]: + """ + Compute pylevin quadrature rules for many integrals at once. + + Integral *p* is of column ``integrand[p]`` of *f* times the Bessel + function of order ``ells[p]`` at ``ks[p] x``, from ``lo[p]`` to + ``hi[p]``, as in one diagonal pylevin instance with an integrand + map. The call determines the subintervals and stores the rules. + Returns the nodes, weights and offsets of the rules, and + the integrals. + """ + lp = pylevin.pylevin(0, x, f, False, False, nthread, True) # noqa: FBT003 + lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 + out = np.zeros(len(ks)) + lp.levin_integrate_bessel_single(lo, hi, ks, ells, out, integrand=integrand) + nodes, weights, offsets = lp.get_quadrature() + return np.asarray(nodes), np.asarray(weights), np.asarray(offsets), out + + +def _rule_matrix( + nodes: NDArray[np.float64], + weights: NDArray[np.float64], + offsets: NDArray[np.int_], + knots: NDArray[np.float64], +) -> NDArray[np.float64]: + """ + Combine rules with the not-a-knot cubic spline through *knots*. + + The rules are those of the integrals between *offsets*. Returns the + matrix from integrand values at the knots to integrals. + """ + n = len(offsets) - 1 + s = slice(offsets[0], offsets[-1]) + row = np.repeat(np.arange(n), np.diff(offsets)) + rule = sparse.csr_matrix( + (weights[s], (row, np.arange(len(row)))), shape=(n, len(row)) + ) + return np.asarray(rule @ CubicSpline(knots, np.eye(len(knots)))(nodes[s])) + + +@dataclasses.dataclass(frozen=True) +class NonLimberPlan: + r""" + Precomputed quadrature of :func:`nonlimber_cls`. + + Created by :func:`nonlimber_plan`. The rules are for the half shells + :math:`[b \, \Delta x, (b + 1) \, \Delta x]`. For half *b* and the + *i*-th computed multipole, ``rules[b][i]`` is a tuple + ``(start, stop, w)``: the integrals over the half at the wavenumbers + ``k[start:stop]`` of the grid are ``w @ g``, with ``g`` the integrand + at the knots of the half. + """ + + dx: float + lmax: int + nknot: int + density: float + q: float + rules: list[list[tuple[int, int, NDArray[np.float64]]]] + + @property + def nshells(self) -> int: + """Number of shells the plan is for.""" + return len(self.rules) - 1 + + def save(self, path: str) -> None: + """Save the plan to a ``.npz`` file.""" + arrays = { + f"{b}_{i}": w + for b, rules in enumerate(self.rules) + for i, (_, _, w) in enumerate(rules) + } + starts = np.array([[r[0] for r in rules] for rules in self.rules]) + np.savez( + path, + meta=np.array([self.dx, self.lmax, self.nknot, self.density, self.q]), + starts=starts, + **arrays, + ) + + @classmethod + def load(cls, path: str) -> NonLimberPlan: + """Load a plan saved with :meth:`save`.""" + with np.load(path) as f: + dx, lmax, nknot, density, q = f["meta"] + rules = [] + for b, starts in enumerate(f["starts"]): + rules_b = [] + for i, start in enumerate(starts): + w = f[f"{b}_{i}"] + rules_b.append((int(start), int(start) + len(w), w)) + rules.append(rules_b) + return cls(float(dx), int(lmax), int(nknot), float(density), float(q), rules) + + +def nonlimber_plan( # noqa: PLR0913 + pk: Callable[..., NDArray[np.float64]], + cosmo: CosmologyWithInverseComovingDistance, + lmax: int, + nshells: int, + *, + dx: float = 200.0, + nknot: int = 16, + nthread: int | None = None, + density: float = 217, + q: float = 30.0, + robust: bool = True, + tol: float = 1e-4, +) -> NonLimberPlan: + r""" + Precompute the quadrature of :func:`nonlimber_cls` for many cosmologies. + + With :func:`glass.distance_grid` and :func:`glass.linear_windows`, + shell :math:`a` spans :math:`[a \, \Delta x, (a + 2) \, \Delta x]` in + comoving distance in every cosmology, with the kink of its window at + :math:`(a + 1) \, \Delta x`, since every edge of the grid is a + multiple of :math:`\Delta x`. The inner integrals of each shell are + the sums of integrals over its two halves, each of which is shared + with a neighbouring shell. The adaptive quadrature rules of pylevin + for the halves are therefore computed once, in one diagonal pylevin + instance with one representative integrand per wavenumber: + :math:`\sqrt{P(k, z)}` of the reference cosmology. They are combined + with a cubic spline in comoving distance, with *nknot* knots on each + half, into one matrix per half and multipole. With the plan, + :func:`nonlimber_cls` only evaluates the integrand at the knots, + which is hundreds of times faster than solving the integrals. + + Parameters + ---------- + pk + Matter power spectrum of the reference cosmology, as for + :func:`nonlimber_cls`. It must reach the redshift of comoving + distance :math:`(n + 1) \, \Delta x` for *n* shells. + cosmo + Reference cosmology, with inverse comoving distance. + lmax + Maximum angular mode number. + nshells + Number of shells to plan for: the largest number of shells of + the cosmologies the plan will be used for. + dx + Comoving distance spacing of the shell grid, as given to + :func:`glass.distance_grid`. + nknot + Number of spline knots on each half of a shell. + nthread + Number of threads for pylevin, as for :func:`nonlimber_cls`. + density, q + Wavenumber grid density and k-support cut, as for + :func:`nonlimber_cls`. + robust + Guard the rules against rare isolated pylevin errors, which a + plan would repeat for every cosmology. The rules are computed + with ``n_col`` 8 and 6; where their integrals disagree by more + than *tol* times the 98th percentile amplitude, they are also + computed with ``n_col`` 10, and the rule with the median integral + is kept. + tol + Tolerance of the robust check. + + Returns + ------- + The plan for :func:`nonlimber_cls`. + + """ + nthread = int( + nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 + ) + ell, k = _ell_grid(lmax), _k_grid(density) + nhalf, nell = nshells + 1, len(ell) + + # wavenumbers of half b at ell: those of the shells b - 1 and b + ranges = [] + for b in range(nhalf): + for el in ell: + m = np.zeros(len(k), dtype=bool) + for a in range(max(b - 1, 0), min(b, nshells - 1) + 1): + m |= _k_mask(k, el, a * dx, (a + 2) * dx, q) + idx = np.nonzero(m)[0] + ranges.append((int(idx[0]), int(idx[-1]) + 1)) + counts = [stop - start for start, stop in ranges] + bounds = np.r_[0, np.cumsum(counts)] + kidx = np.concatenate([np.arange(start, stop) for start, stop in ranges]) + half = np.repeat(np.repeat(np.arange(nhalf), nell), counts) + + # one integrand per wavenumber, on all halves + x = np.linspace(0.0, nhalf * dx, 100 * nhalf + 1) + f = np.sqrt(pk(cosmo.inv_comoving_distance(x), k)) + solve = functools.partial(_rules, x, f, nthread=nthread) + args = ( + half * dx, + (half + 1) * dx, + k[kidx], + np.repeat(np.tile(ell, nhalf), counts), + kidx, + ) + rules8 = solve(*args, ncol=8) + + # robust: per integral, the rule of the median of n_col 8, 6, 10 + choice: dict[int, tuple] = {} + if robust: + rules6 = solve(*args, ncol=6) + i8, i6 = rules8[3], rules6[3] + bad = np.concatenate([ + np.abs(i8[v0:v1] - i6[v0:v1]) > tol * np.quantile(np.abs(i8[v0:v1]), 0.98) + for v0, v1 in itertools.pairwise(bounds) + ]) + j = np.nonzero(bad)[0] + if len(j): + rules10 = solve(*(arg[j] for arg in args), ncol=10) + vals = np.stack([i8[j], i6[j], rules10[3]]) + for jj, (v, med) in enumerate( + zip(j, np.argsort(vals, axis=0)[1], strict=True) + ): + if med == 1: + choice[int(v)] = (rules6, v) + elif med == 2: + choice[int(v)] = (rules10, jj) + + rules = [] + for b in range(nhalf): + knots = np.linspace(b * dx, (b + 1) * dx, nknot) + v0, v1 = bounds[b * nell], bounds[(b + 1) * nell] + w = _rule_matrix(*rules8[:2], rules8[2][v0 : v1 + 1], knots) + for v in range(v0, v1): + if v in choice: + (nodes, weights, offsets, _), p = choice[v] + w[v - v0] = _rule_matrix(nodes, weights, offsets[p : p + 2], knots)[0] + rules.append([ + (start, stop, w[bounds[b * nell + i] - v0 : bounds[b * nell + i + 1] - v0]) + for i, (start, stop) in enumerate(ranges[b * nell : (b + 1) * nell]) + ]) + return NonLimberPlan( + float(dx), int(lmax), int(nknot), float(density), float(q), rules + ) + + +def _planned_inner( + plan: NonLimberPlan, + pk: Callable[..., NDArray[np.float64]], + cosmo: CosmologyWithInverseComovingDistance, + ws: Sequence[RadialWindow], + k: NDArray[np.float64], +) -> NDArray[np.float64]: + """Inner integrals I_a(ell, k) of all shells from a plan.""" + if len(ws) > plan.nshells: + msg = f"plan has {plan.nshells} shells, but there are {len(ws)}" + raise ValueError(msg) + dh, dx, nknot = cosmo.hubble_distance, plan.dx, plan.nknot + ell = _ell_grid(plan.lmax) + inner = np.zeros((len(ws), len(ell), len(k))) + for a, w in enumerate(ws): + z_edges = np.array([w.za[0], w.za[np.argmax(w.wa)], w.za[-1]]) + if not np.allclose( + cosmo.comoving_distance(z_edges), + dx * (a + np.arange(3)), + rtol=1e-6, + atol=1e-6 * dx, + ): + msg = ( + f"shell {a} is not on the comoving grid of the plan with " + f"spacing {dx}; use glass.distance_grid with dx={dx}" + " and glass.linear_windows" + ) + raise ValueError(msg) + # knots of the two halves; the middle one is in both + z = cosmo.inv_comoving_distance( + np.r_[ + np.linspace(a * dx, (a + 1) * dx, nknot), + np.linspace((a + 1) * dx, (a + 2) * dx, nknot), + ] + ) + # unit normalisation in comoving distance, on the same grid as without plan + za = np.linspace(w.za[0], w.za[-1], 400) + norm = np.trapezoid( + np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh, + cosmo.comoving_distance(za), + ) + kernel = np.interp(z, w.za, w.wa) * cosmo.H_over_H0(z) / dh / norm + g = kernel[:, None] * np.sqrt(pk(z, k)) + for i, el in enumerate(ell): + idx = np.nonzero(_k_mask(k, el, a * dx, (a + 2) * dx, plan.q))[0] + start, stop = int(idx[0]), int(idx[-1]) + 1 + for b, gb in ((a, g[:nknot]), (a + 1, g[nknot:])): + s, _, wm = plan.rules[b][i] + inner[a, i, start:stop] += np.einsum( + "kj,jk->k", wm[start - s : stop - s], gb[:, start:stop] + ) + return inner + + +def nonlimber_cls( # noqa: PLR0913 + pk: Callable[..., NDArray[np.float64]], + cosmo: Cosmology, + ws: Sequence[RadialWindow], + lmax: int, + *, + nthread: int | None = None, + density: float = 217, + q: float = 30.0, + robust: bool = True, + plan: NonLimberPlan | None = None, +) -> list[NDArray[np.float64]]: + r""" + Compute the angular power spectra of matter shells without Limber. + + For each shell :math:`a` with kernel :math:`K_a(\chi)`, normalised + to unit integral in comoving distance, the inner integral + + .. math:: + + I_a(\ell, k) = \int \! d\chi \, K_a(\chi) \sqrt{P(k, z)} + \, j_\ell(k \chi) + + is computed with the Levin method, and the angular power spectra + are + + .. math:: + + C_{ab}(\ell) = \frac{2}{\pi} \int \! dk \, k^2 \, + I_a(\ell, k) \, I_b(\ell, k) \;. + + The non-Limber integrals are computed at every :math:`\ell < 20`, + at every second value of the combined grid of :math:`\ell \in [20, + 29]` and 75 log-spaced values up to *lmax*, and at *lmax*. In + between, the smooth relative correction :math:`(C - C^{\rm L}) / + \sqrt{C^{\rm L}_{aa} C^{\rm L}_{bb}}` is splined in :math:`\log\ell` + on top of the Limber spectra :math:`C^{\rm L}`, which are computed + at every :math:`\ell`. + + Parameters + ---------- + pk + The matter power spectrum as a function ``pk(z, k)`` of 1-D + arrays of redshift and wavenumber, returning an array of shape + ``(z.size, k.size)``, e.g. the ``P`` method of a CAMB matter + power interpolator. Wavenumbers are in units of the inverse of + the distance units of *cosmo*. + cosmo + Cosmology for comoving distances and the Hubble function. The + integration grid in wavenumber, from 1e-4 to 100, assumes + distances in Mpc. + ws + Radial windows of the matter shells. The power spectrum *pk* + must reach the redshift of the last shell. + lmax + Maximum angular mode number. + nthread + Number of threads for pylevin. Defaults to the + ``SLURM_CPUS_PER_TASK`` environment variable if set, or the + number of CPUs otherwise. + density + Number of wavenumber grid points per e-fold. + q + The k-support of shell :math:`a` is cut to + :math:`[0.3 \, \nu / \chi_{\max}, \max(3 \nu / \chi_{\min}, + q / \Delta\chi)]` with :math:`\nu = \ell + 1/2`. + robust + Guard against rare isolated pylevin errors by solving each + wavenumber twice and taking a median of three where the two + disagree. This doubles the cost. With pylevin 2.1.0, the errors + reach 6e-3 of the amplitude of single shell integrals in tests. + plan + Precomputed quadrature from :func:`nonlimber_plan`. The shells + must then lie on its comoving grid, and *lmax*, *density* and *q* + are taken from the plan; *nthread* and *robust* are not used. + The cosmology needs the inverse comoving distance. + + Returns + ------- + The angular power spectra for :math:`\ell = 0, \ldots, l_{\max}` + in GLASS order (for i in 0..n-1, for j in i..0), with + :math:`C(\ell = 0) = 0`. + + """ + dh = cosmo.hubble_distance + n = len(ws) + if plan is not None: + if lmax != plan.lmax: + msg = f"plan is for lmax={plan.lmax}, not {lmax}" + raise ValueError(msg) + density, q = plan.density, plan.q + + # non-Limber at sparse l on a shared log k grid; shell a only on k in + # [0.3 nu/chi_hi, max(3 nu/chi_lo, q/dchi)] + ell, k = _ell_grid(lmax), _k_grid(density) + if plan is not None: + inner = _planned_inner(plan, pk, cosmo, ws, k) + else: + nthread = int( + nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 + ) + inner = np.zeros((n, len(ell), len(k))) + for a, w in enumerate(ws): + za = np.linspace(w.za[0], w.za[-1], 400) + kernel = np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh + chi = cosmo.comoving_distance(za) + kernel /= np.trapezoid(kernel, chi) + # drop zero endpoints (log spline in pylevin) + za, chi, kernel = za[1:-1], chi[1:-1], kernel[1:-1] + for i, el in enumerate(ell): + m = _k_mask(k, el, chi[0], chi[-1], q) + call = functools.partial( + _levin, + window=(za, chi, kernel), + pk=pk, + ell=el, + nthread=nthread, + ) + inner[a, i, m] = _robust(call, k[m]) if robust else call(k[m]) + cl = np.empty((n, n, len(ell))) + for i in range(len(ell)): # per l keeps the (n, n, nk) temporary small + cl[..., i] = ( + 2 + / np.pi + * np.trapezoid(inner[:, None, i] * inner[None, :, i] * k**2, k, axis=-1) + ) + + # Limber at every l = 1..lmax + zf = np.linspace(1e-4, ws[-1].za[-1], 6000) + chif = cosmo.comoving_distance(zf) + kf = ( + np.array([np.interp(zf, w.za, w.wa, left=0, right=0) for w in ws]) + * cosmo.H_over_H0(zf) + / dh + ) + kf /= np.trapezoid(kf, chif, axis=1)[:, None] + lf = np.arange(1, lmax + 1) + pf = np.array([pk(zf[i : i + 1], (lf + 0.5) / chif[i])[0] for i in range(len(zf))]) + limber = ( + (kf[:, None] * kf[None, :] * (np.gradient(chif) / chif**2)).reshape(n * n, -1) + @ pf + ).reshape(n, n, -1) + + d = np.arange(n) + nrm = np.sqrt(limber[d, d][:, None] * limber[d, d][None, :]) + s = ell - 1 # index of the computed l in lf + full = limber + nrm * CubicSpline( + np.log(ell), + (cl - limber[..., s]) / nrm[..., s], + axis=-1, + )(np.log(lf)) + full[..., s] = cl # exact at the computed l + return [np.r_[0.0, full[i, j]] for i in range(n) for j in range(i, -1, -1)] diff --git a/pyproject.toml b/pyproject.toml index 5c2d57260..9876e25f1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -310,6 +310,9 @@ spaces_indent_inline_array = 4 trailing_comma_inline_array = true [tool.ty] +analysis.allowed-unresolved-imports = [ + "pylevin", # sdist only (needs GSL and Boost), not in the typechecking group +] analysis.respect-type-ignore-comments = false rules = { all = "error", invalid-argument-type = "ignore" } src.include = [ diff --git a/tests/core/test_spectra.py b/tests/core/test_spectra.py new file mode 100644 index 000000000..bc5e90c1b --- /dev/null +++ b/tests/core/test_spectra.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +pytest.importorskip("pylevin", reason="tests require pylevin") +pytest.importorskip("scipy", reason="tests require scipy") + +from scipy.interpolate import RegularGridInterpolator +from scipy.special import spherical_jn + +import glass +import glass.spectra + +if TYPE_CHECKING: + from glass._types import FloatArray + + +class FlatLCDM: + """Flat LCDM cosmology with distances in Mpc.""" + + hubble_distance = 299792.458 / 70.0 + Omega_m0 = 0.3 + + def H_over_H0(self, z: FloatArray) -> FloatArray: # noqa: N802 + """Dimensionless Hubble function.""" + return np.sqrt(self.Omega_m0 * (1 + z) ** 3 + 1 - self.Omega_m0) + + _zg = np.linspace(0.0, 3.0, 6001) + + def _dc(self) -> FloatArray: + f = 1 / self.H_over_H0(self._zg) + dc = np.r_[0.0, np.cumsum((f[1:] + f[:-1]) / 2 * np.diff(self._zg))] + return self.hubble_distance * dc + + def comoving_distance(self, z: FloatArray) -> FloatArray: + """Comoving distance in Mpc.""" + return np.interp(z, self._zg, self._dc()) + + def inv_comoving_distance(self, x: FloatArray) -> FloatArray: + """Redshift of comoving distance in Mpc.""" + return np.interp(x, self._dc(), self._zg) + + +def pk(z: FloatArray, k: FloatArray) -> FloatArray: + """Smooth power spectrum, growing with redshift like D(z)^2 ~ 1/(1+z)^2.""" + return (2e4 * k / (1 + (k / 0.02) ** 2) ** 1.4) / (1 + z[:, None]) ** 2 + + +def test_nonlimber_cls() -> None: + cosmo = FlatLCDM() + ws = glass.linear_windows(np.asarray([0.0, 0.2, 0.4, 0.6])) + lmax = 40 + + # q = 100: the default k-support cut is tuned for ~200 Mpc shells and + # leaves ~1% on the l = 2 cross of these ~1000 Mpc wide shells + cls = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, nthread=1, q=100.0) + + # GLASS order: (0, 0), (1, 1), (1, 0) + assert len(cls) == 3 + for cl in cls: + assert cl.shape == (lmax + 1,) + assert cl[0] == 0.0 + assert np.all(cls[0][1:] > 0) + assert np.all(cls[1][1:] > 0) + assert np.all(cls[2][1:] ** 2 < cls[0][1:] * cls[1][1:]) + + # brute-force non-Limber at a few low l, where Limber is far off + k = np.geomspace(1e-4, 1.0, 4000) + for ell in [2, 5, 12]: + inner = [] + for w in ws: + z = np.linspace(w.za[0], w.za[-1], 2000) + chi = cosmo.comoving_distance(z) + kern = np.interp(z, w.za, w.wa) * cosmo.H_over_H0(z) / cosmo.hubble_distance + kern /= np.trapezoid(kern, chi) + f = kern[:, None] * np.sqrt(pk(z, k)) * spherical_jn(ell, k * chi[:, None]) + inner.append(np.trapezoid(f, chi, axis=0)) + for cl, (a, b) in zip(cls, [(0, 0), (1, 1), (1, 0)], strict=True): + expect = 2 / np.pi * np.trapezoid(k**2 * inner[a] * inner[b], k) + np.testing.assert_allclose(cl[ell], expect, rtol=3e-3) + + +def assert_close_spectra( + cls: list[FloatArray], + ref: list[FloatArray], + tol: float | FloatArray, + lmin: int = 1, +) -> None: + """|cls - ref| <= tol sqrt(ref_aa ref_bb) for every pair in GLASS order.""" + n = int((np.sqrt(8 * len(ref) + 1) - 1) / 2) + pairs = [(i, j) for i in range(n) for j in range(i, -1, -1)] + auto = {i: ref[pairs.index((i, i))][lmin:] for i in range(n)} + tol = np.broadcast_to(tol, ref[0].shape)[lmin:] + for cl, cr, (i, j) in zip(cls, ref, pairs, strict=True): + err = np.abs(cl[lmin:] - cr[lmin:]) + assert np.all(err <= tol * np.sqrt(auto[i] * auto[j])), (i, j) + + +def test_nonlimber_plan(tmp_path) -> None: + cosmo = FlatLCDM() + zgrid = glass.distance_grid(cosmo, 0.0, 0.25, dx=200.0) + ws = glass.linear_windows(zgrid) + lmax = 40 + # a coarse wavenumber grid for speed: plan and direct use the same one + kw = {"nthread": 1, "density": 80} + + plan = glass.spectra.nonlimber_plan(pk, cosmo, lmax, len(ws) + 1, **kw) + assert plan.nshells == len(ws) + 1 + + direct = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, **kw) + planned = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan) + assert len(planned) == len(direct) + assert_close_spectra(planned, direct, 1e-3) + + # the plan is cosmology-independent: a different P(k) still agrees + def pk2(z: FloatArray, k: FloatArray) -> FloatArray: + return 1.5 * pk(z, k) * (1 + 0.3 * np.sin(np.log(k))) / (1 + z[:, None]) + + direct = glass.spectra.nonlimber_cls(pk2, cosmo, ws, lmax, **kw) + planned = glass.spectra.nonlimber_cls(pk2, cosmo, ws, lmax, plan=plan) + assert_close_spectra(planned, direct, 1e-3) + + # save and load + plan.save(tmp_path / "plan.npz") + loaded = glass.spectra.NonLimberPlan.load(tmp_path / "plan.npz") + again = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=loaded) + for cp, ca in zip( + glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan), again, strict=True + ): + np.testing.assert_array_equal(cp, ca) + + # shells off the grid of the plan + with pytest.raises(ValueError, match="not on the comoving grid"): + glass.spectra.nonlimber_cls( + pk, cosmo, glass.linear_windows(zgrid * 1.01), lmax, plan=plan + ) + with pytest.raises(ValueError, match="lmax"): + glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax + 1, plan=plan) + + +def test_nonlimber_cls_camb() -> None: + """Compare with the non-Limber number counts of CAMB at high accuracy.""" + camb = pytest.importorskip("camb", reason="test requires camb") + from camb.sources import SplinedSourceWindow + + pars = camb.set_params( + H0=67.5, + ombh2=0.022, + omch2=0.122, + mnu=0.0, + num_massive_neutrinos=0, + As=2.1e-9, + ns=0.965, + WantCls=False, + ) + pars.Want_CMB = False + pars.NonLinear = camb.model.NonLinear_none + bg = camb.get_background(pars) + + class CambCosmology: + hubble_distance = 299792.458 / pars.H0 + + def H_over_H0(self, z: FloatArray) -> FloatArray: # noqa: N802 + return np.asarray(bg.hubble_parameter(z)) / pars.H0 + + def comoving_distance(self, z: FloatArray) -> FloatArray: + return np.asarray(bg.comoving_radial_distance(z)) + + def inv_comoving_distance(self, x: FloatArray) -> FloatArray: + return np.asarray(bg.redshift_at_comoving_radial_distance(x)) + + cosmo = CambCosmology() + ws = glass.linear_windows(glass.distance_grid(cosmo, 0.0, 0.3, dx=200.0)) + lmax = 100 + + # CAMB's density source is synchronous gauge CDM transformed to + # Newtonian gauge, d_N = d_c + 3 (aH/k)^2 v_N, which changes l = 2 by + # 1%: apply the same transformation to P(k) through the transfers + zmax = ws[-1].za[-1] + 0.1 + p = camb.get_matter_power_interpolator( + pars, + nonlinear=False, + hubble_units=False, + k_hunit=False, + kmax=100.0, + zmax=zmax, + var1="delta_cdm", + var2="delta_cdm", + extrap_kmax=True, + ) + zs = np.linspace(zmax, 0.0, 40) + tp = pars.copy() + tp.set_matter_power(redshifts=list(zs), kmax=10.0) + tr = camb.get_results(tp).get_matter_transfer_data() + dc = tr.transfer_data[camb.model.Transfer_cdm - 1] + vn = tr.transfer_data[camb.model.Transfer_Newt_vel_cdm - 1] + ah = np.asarray(bg.hubble_parameter(zs)) / (1 + zs) / 299792.458 + ratio = 1 + 3 * ah**2 * vn / (tr.q[:, None] ** 2 * dc) + gauge = RegularGridInterpolator((np.log(tr.q), zs[::-1]), ratio[:, ::-1]) + + def pk_newtonian(z: FloatArray, k: FloatArray) -> FloatArray: + lk = np.clip(np.log(k), np.log(tr.q[0]), np.log(tr.q[-1])) + lk_, z_ = np.meshgrid(lk, z) + return p.P(z, k, grid=True) * gauge((lk_, z_)) ** 2 + + cls = glass.spectra.nonlimber_cls(pk_newtonian, cosmo, ws, lmax) + + # number counts of the density term only, without Limber + pars.WantCls = True + pars.set_accuracy(AccuracyBoost=3, lSampleBoost=50, lAccuracyBoost=3) + pars.set_for_lmax(lmax, lens_potential_accuracy=0) + pars.SourceTerms.limber_windows = False + pars.SourceTerms.counts_density = True + for term in ( + "redshift", + "lensing", + "velocity", + "radial", + "timedelay", + "ISW", + "potential", + "evolve", + ): + setattr(pars.SourceTerms, f"counts_{term}", False) + pars.SourceWindows = [ + SplinedSourceWindow( + z=np.maximum(w.za, 1e-5), + W=w.wa / np.trapezoid(w.wa, w.za), + source_type="counts", + ) + for w in ws + ] + cd = camb.get_results(pars).get_source_cls_dict(raw_cl=True, lmax=lmax) + n = len(ws) + ref = [cd[f"W{i + 1}xW{j + 1}"] for i in range(n) for j in range(i, -1, -1)] + + assert_close_spectra(cls, ref, 2e-3, lmin=2)