Source code for discocmb.grids._grids

"""The wave-number, time and multipole grids, and :class:`Grid`, which holds them with their operators."""

from __future__ import annotations

import dataclasses
import glob
import hashlib
import importlib.util
import os
import pickle
from pathlib import Path
from typing import NamedTuple

import jax
import jax.numpy as jnp
import numpy as np
from discoeb import A_START
from jax.tree_util import register_pytree_node_class

from .._cosmology import as_cosmologies, fiducial
from .._numerics import curvature_band, trapezoid_weights
from ..sources._component import K_MAX_CMB
from ._operators import (
    LimberWeights,
    every_ell_matrix,
    exact_lensing_operator,
    k_band,
    late_taper,
    limber_k,
    limber_spline,
    projection_tables,
    spans,
)
from ._summary import _grid_summary, _kernel_thermal_history
from ._wigner import LensingTables, lensing_tables


def _resample_from_density(x, density, n):
    """Return ``n`` points drawn from ``x`` in proportion to ``density``."""

    cdf = np.cumsum(density) * (x[1] - x[0])
    cdf -= cdf[0]
    cdf /= cdf[-1]
    return np.interp(np.linspace(0.0, 1.0, n), cdf, x)


def k_grid(
    cosmology,
    *,
    n: int = 200,
    mode: str = "ode",
    k_min: float = 1.0e-5,
    k_max: float = 0.5,
    ell_min: int = 2,
    ell_max: int = 2500,
    n_ell_samples: int = 30,
    n_eval: int = 5000,
) -> np.ndarray:
    """Return a nonuniform wavenumber grid, densest where the sources vary.

    ``mode="ode"`` resolves the sources' acoustic oscillations (period from
    ``r_s``, envelope from ``k_D``). The perturbation solve runs on it.
    ``mode="cl"`` also weights each ``k`` by how many multipoles project onto
    it, ``k ~ l / chi_star``. The ``C_l`` quadrature uses this finer grid.
    ``cosmology`` is one DISCO-EB cosmology, ``discoeb.LCDM(omega_b=..., ...)``,
    whose thermal history shapes the grid.
    """

    cosmology, model = fiducial(cosmology)
    summary = _grid_summary(cosmology, model)
    x = np.linspace(np.log(k_min), np.log(k_max), n_eval)
    k = np.exp(x)
    primordial = k ** (dict(cosmology)["n_s"] + 2.0)
    acoustic_curv = (1.0 / summary["r_s"]) ** 2
    damped = primordial * np.exp(-((k / summary["k_D"]) ** 2))

    if mode == "cl":
        sigma_k = 1.0 / summary["delta_tau_rec"]
        chi_star = summary["tau0"] - summary["tau_star"]
        ell_samples = np.unique(
            np.geomspace(ell_min, ell_max, n_ell_samples).astype(int)
        )
        raw_weight = np.zeros_like(k)
        for ell in ell_samples:
            envelope = np.exp(-0.5 * ((k - ell / chi_star) / (3.0 * sigma_k)) ** 2)
            raw_weight += np.maximum(acoustic_curv, sigma_k**2) * envelope * damped
        floor = 1.0e-6 * np.max(raw_weight)
    else:
        smooth_curv = (k * summary["r_s"]) ** 2 / summary["tau_eq"] ** 2
        raw_weight = np.maximum(acoustic_curv, smooth_curv) * damped
        floor = 0.005 * np.max(raw_weight)

    grid = np.exp(_resample_from_density(x, (raw_weight + floor) ** (1.0 / 3.0), n))
    grid[0], grid[-1] = k_min, k_max
    return grid


def tau_grid(
    cosmology,
    k_values,
    n: int,
    *,
    n_eval: int = 10000,
) -> np.ndarray:
    """Return a nonuniform conformal-time grid for saving the sources.

    The sources peak sharply at recombination (width ``delta_tau_rec``), vary
    on the sound-horizon scale and may bump at reionization. The sampling
    density is the cube root of the sum of those three weights. The grid
    runs from this cosmology's conformal time at ``A_START``, where the solve
    starts, to its conformal age. ``cosmology`` is one DISCO-EB cosmology
    (``discoeb.LCDM(omega_b=..., ...)``).
    """

    k_arr = np.asarray(k_values, dtype=np.float64)
    s = _grid_summary(*fiducial(cosmology))
    tau0 = s["tau0"]

    tau = np.linspace(s["tau_start"], tau0, n_eval, dtype=np.float64)
    weight = (
        np.exp(-0.5 * ((tau - s["tau_star"]) / s["delta_tau_rec"]) ** 2)
        / s["delta_tau_rec"] ** 2
    )
    weight += (
        np.exp(-0.5 * ((tau - s["tau_star"]) / s["r_s"]) ** 2)
        * (float(k_arr[-1]) / np.sqrt(3.0)) ** 2
    )
    weight += (
        0.3
        * np.exp(-0.5 * ((tau - s["tau_reion"]) / s["delta_tau_reion"]) ** 2)
        / s["delta_tau_reion"] ** 2
    )

    tau_save = _resample_from_density(
        tau, (weight + 0.005 * np.max(weight)) ** (1.0 / 3.0), n
    )
    tau_save[0], tau_save[-1] = s["tau_start"], tau0
    return tau_save


def scale_factors(cosmology, tau) -> np.ndarray:
    """Return the scale factors at which ``cosmology`` has the conformal times ``tau``.

    From the conformal time the grid summary's trajectory kept, by a cubic
    spline of ``ln a`` in ``ln tau``. The ends are ``A_START`` and 1 exactly.
    """

    from scipy.interpolate import CubicSpline

    tau_grid, a_grid, _ = _kernel_thermal_history(*fiducial(cosmology))
    tau = np.asarray(tau, dtype=np.float64)
    a = np.exp(CubicSpline(np.log(tau_grid), np.log(a_grid))(np.log(tau)))
    a = np.clip(a, A_START, 1.0)
    if tau[0] <= tau_grid[0]:
        a[0] = A_START
    if tau[-1] >= tau_grid[-1]:
        a[-1] = 1.0
    return a


K_LOW = 0.01
"""Wave number (Mpc^-1) below which :func:`solve_modes` spaces the solved modes uniformly."""

LOW_STEP = 2.0e-4
"""Spacing (Mpc^-1) of the solved modes below :data:`K_LOW`.

The polarization source at reionization oscillates in ``k`` with period
``2 pi / (tau_reio - tau_rec)``, about 1.5e-3 / Mpc, which the logarithmic
modes of :func:`k_grid` sample once there: EE at ``l < 30`` came out 1.5
percent off."""


def solve_modes(k_own) -> np.ndarray:
    """Return the modes ``k_own`` with uniform steps of :data:`LOW_STEP` up to :data:`K_LOW` where they are wider apart."""

    k_own = np.asarray(k_own, dtype=np.float64)
    wide = np.flatnonzero((np.diff(k_own) > LOW_STEP) & (k_own[:-1] < K_LOW))
    if not len(wide):
        return k_own
    start = k_own[wide[0]]
    return np.concatenate(
        [k_own[k_own < start], np.arange(start, K_LOW, LOW_STEP), k_own[k_own >= K_LOW]]
    )


def quadrature_modes(
    k_min: float, k_max: float, step: float, k_turn: float = 0.01
) -> np.ndarray:
    """Return wave modes for the ``C_l`` quadrature, uniform in ``u = (k + k_turn ln k) / step``.

    ``Theta_l(k)^2`` oscillates in ``k`` with period ``pi / chi_star``, about
    2.3e-4 / Mpc, at every multipole. A trapezoid on modes spaced ``step`` in
    ``k`` integrates that oscillation to zero as long as ``step`` stays off
    the period, where it aliases to a constant. Below ``k_turn`` the modes
    go over to a spacing of ``step / k_turn`` in ``ln k`` for the low
    multipoles. The map from ``u`` is smooth, so no kink spoils the
    trapezoid's cancellation.
    """

    k = np.geomspace(k_min, k_max, 200_000)
    u = (k + k_turn * np.log(k)) / step
    return np.interp(np.linspace(u[0], u[-1], int(np.ceil(u[-1] - u[0])) + 1), u, k)


L_MAX = 3400
"""Last multipole of the default grid. The lensed spectra are good to ~2500."""

ELL_NODES = np.unique(
    np.concatenate(
        [
            np.arange(2, 30),
            np.arange(30, 40, 2),
            np.arange(40, 260, 10),
            np.arange(260, 2620, 40),
            np.arange(2620, L_MAX, 80),
            [L_MAX],
        ]
    )
).astype(np.int64)
"""Multipoles of the default grid.

Every multipole through the reionization bump, where EE and TE turn from one
``l`` to the next, steps of 10 across the first EE trough (``l ~ 217``, which
steps of 40 miss by 1.3 percent), then the acoustic peaks at CLASS's own
spacing, and coarser past ``l = 2620``, where the spectra only feed the
lensing sums."""

K_MIN, K_MAX_LENSING = 1.0e-5, 3.0
"""Wave numbers (Mpc^-1) of the first mode and of the last mode of the lensing potential."""

LENSING_MODES = np.geomspace(K_MAX_CMB, K_MAX_LENSING, 17)[1:]
"""Modes beyond :data:`~discocmb.sources.K_MAX_CMB` that the lensing potential needs.

The Limber integral reads the Weyl potential at ``k = (l + 1/2) / chi`` and
drops what lies beyond the solved modes: with modes to 1.2 / Mpc that is
everything nearer than ``z ~ 0.5`` at ``l = 2300``, and ``C_l^pp`` comes
out 1.3 percent low there (0.3 percent with modes to 3 / Mpc)."""

LIMBER_L_MIN = 30
"""First multipole of the lensing potential's Limber integral.

The exact projection integrates ``j_l(k chi)`` on the save grid, coarse at
late times, and degrades with ``l``. The Limber approximation is good to
``(l + 1/2)^-2``."""

K_MAX_EXACT = 1.2
"""Last mode (Mpc^-1) of the lensing potential's exact projection.

The exact projection integrates ``j_l(k chi)`` on the save grid, which the
modes added for the Limber multipoles alias on. They carry nothing at the
exact multipoles, so the operator leaves them out."""

LENSING_BETA_MAX = np.pi / 16.0
"""Largest angle of the lensing sums (:func:`lensing_tables`'s default is ``pi / 8``)."""


@dataclasses.dataclass(frozen=True, eq=False)
class Layout:
    """The NumPy arrays of a :class:`Grid`, static under ``jit``.

    It compares by identity, so a jitted function traces once for each
    :class:`Grid` it is passed.
    """

    k_values: np.ndarray  # the modes to solve, ascending
    k_lensing: (
        np.ndarray
    )  # those and the modes extrapolated beyond, for the lensing potential
    k_fine: np.ndarray  # the quadrature modes of C_l
    ells: np.ndarray  # the multipoles of the projection
    ells_pp: np.ndarray  # the multipoles of the lensing potential
    tau_save: np.ndarray  # the fiducial's conformal times at the saves
    a_save: np.ndarray  # the scale factors of the saves
    i_star: int  # the save nearest the fiducial's visibility peak
    chi_star: float  # the fiducial's distance to it
    spans: tuple  # the chunks of the Bessel tables (:func:`~discocmb.grids.spans`)


class Operators(NamedTuple):
    """The device arrays of a :class:`Grid`."""

    lnk_knots: jax.Array  # ln k of the solved modes
    lnk_curvature: jax.Array  # the band of the ln k spline's second-derivative operator
    lnk_weights: jax.Array  # trapezoid weights of the C_l quadrature in ln k
    band: jax.Array  # (n_ell, n_k_fine) the modes each multipole reads
    keep: jax.Array  # (n_k_fine, n_save) the late-time taper of the sources
    bessel: tuple  # chunks of the (n_k_fine, n_ell, 3, n_save) Bessel table
    bessel_e: tuple  # chunks of the (n_k_fine, n_ell, n_save) E-mode table
    lensing_exact: jax.Array  # the exact multipoles' j_l(k chi) table
    limber_weights: LimberWeights  # the Limber multipoles' banded spline weights
    k_chi: jax.Array  # the Limber multipoles' wave numbers
    tables: LensingTables  # the Wigner d-functions of the lensing sums
    every_ell: jax.Array  # (n_ell, lmax + 1) spline onto every multipole, in dtype
    every_ell_pp: jax.Array  # (n_ell_pp, lmax + 1) the same for the lensing potential


def _sources_digest(*settings) -> str:
    """Return a digest of ``settings`` and of the sources of DISCO-CMB, DISCO-EB and modax."""

    h = hashlib.sha256(repr(settings).encode())
    folders = [str(Path(__file__).resolve().parents[1])]
    for name in ("discoeb", "modax"):
        spec = importlib.util.find_spec(name)
        if spec is not None and spec.submodule_search_locations:
            folders.extend(spec.submodule_search_locations)
    for folder in folders:
        for path in sorted(
            glob.glob(os.path.join(folder, "**", "*.py"), recursive=True)
        ):
            with open(path, "rb") as f:
                h.update(f.read())
    return h.hexdigest()[:20]


[docs] @register_pytree_node_class class Grid: """The grid of a CMB computation and the operators on it, shaped by a fiducial cosmology. :meth:`from_fiducial` builds them. :func:`discoeb.solve_eb` solves the modes ``k_values`` at the scale factors ``a_save``, and :func:`~discocmb.transfer_functions` projects the sources onto the multipoles ``ells`` with the operators, gigabytes of Bessel and Wigner tables. Spectra come out at every multipole to ``lmax = ells[-1]``. A grid is a JAX pytree whose leaves are the operators and whose NumPy arrays are static. A jitted function that takes it as an argument reads the tables in place as device buffers. One that closed over them would carry them as constants of its program. """ def __init__(self, layout: Layout, operators: Operators): self.layout = layout self.operators = operators def tree_flatten(self): return (self.operators,), self.layout @classmethod def tree_unflatten(cls, layout, children): return cls(layout, *children) @property def k_values(self) -> np.ndarray: """The wave modes (1/Mpc) to solve, ascending.""" return self.layout.k_values @property def a_save(self) -> np.ndarray: """The scale factors at which to save, from ``discoeb.A_START`` to 1.""" return self.layout.a_save @property def tau_save(self) -> np.ndarray: """The fiducial's conformal times (Mpc) at ``a_save``.""" return self.layout.tau_save @property def k_fine(self) -> np.ndarray: """The quadrature modes of the ``C_l`` integral.""" return self.layout.k_fine @property def ells(self) -> np.ndarray: """The multipoles the projection computes, from which a spline gives every one.""" return self.layout.ells @property def lmax(self) -> int: """The last multipole of the spectra.""" return int(self.layout.ells[-1]) @property def tau_end(self) -> float: """The fiducial's conformal age, where the shared ``chi`` grid starts.""" return float(self.layout.tau_save[-1])
[docs] @classmethod def from_fiducial( cls, cosmology, *, k_values=None, ells=None, n_k: int = 128, n_save: int = 600, k_fine_step: float = 1.9e-4, extrapolate_above: float | None = None, dtype=jnp.float32, cache_dir: str | None = None, ) -> Grid: """Return the grid and operators appropriate for the given ``cosmology``. Nearby cosmologies share where their sources vary, so one fiducial's grid serves a batch, and every batch of an inference loop. ``k_values`` are the wave modes (1/Mpc) of the temperature and polarization, up to :data:`~discocmb.sources.K_MAX_CMB`, and the grid adds :data:`LENSING_MODES` past the last one for the lensing potential. Without them the modes are :func:`k_grid`'s ``n_k`` with uniform steps at low ``k`` (:func:`solve_modes`). The ``C_l`` quadrature runs on :func:`quadrature_modes` of step ``k_fine_step``, and the solve saves at ``n_save`` scale factors (:func:`tau_grid`). ``ells`` are the multipoles to project, :data:`ELL_NODES` by default, and the spectra come out at every multipole to ``ells[-1]``. ``extrapolate_above`` leaves the modes past it unsolved and continues the last two solved ones in the lensing potential (5e-5 at 1.2 / Mpc). ``dtype`` is the precision of the tables, of the spline onto every multipole and of the Limber tilt. Single precision costs 2.6e-4 in ``D_l``, too much for a derivative, which needs ``jnp.float64`` and a short list of ``ells``: the tables grow with the multipoles. The building takes about 13 s, mostly the Bessel tables on the host. ``cache_dir`` keeps the result on disk under a digest of the arguments, the fiducial and the installed sources of DISCO-CMB, DISCO-EB and modax. """ parameters, model = fiducial(cosmology) (fid,) = as_cosmologies(cosmology) ells = ELL_NODES if ells is None else np.unique(np.asarray(ells, np.int64)) lmax = int(ells[-1]) cached = None if cache_dir is not None: described = ( parameters, model.name, sorted(dict(model.settings).items()), None if k_values is None else np.asarray(k_values).tolist(), ells.tolist(), n_k, n_save, k_fine_step, extrapolate_above, jnp.dtype(dtype).name, ) cached = os.path.join(cache_dir, _sources_digest(*described) + ".pkl") if os.path.exists(cached): with open(cached, "rb") as f: layout, operators = pickle.load(f) return cls(layout, jax.tree.map(jnp.asarray, operators)) if k_values is None: k_cmb = solve_modes( k_grid(fid, n=n_k, mode="ode", k_min=K_MIN, k_max=K_MAX_CMB) ) k_lensing = np.sort(np.concatenate([k_cmb, LENSING_MODES])) else: k_lensing = np.unique(np.asarray(k_values, dtype=np.float64)) k_lensing = k_lensing[k_lensing <= K_MAX_LENSING] k_lensing = np.concatenate( [k_lensing, LENSING_MODES[LENSING_MODES > 1.05 * k_lensing[-1]]] ) k_cmb = k_lensing[k_lensing <= K_MAX_CMB] # The CMB modes shape the quadrature and the saves. The lensing modes # only extend the range of the solve. k_fine = quadrature_modes(k_cmb[0], k_cmb[-1], k_fine_step) tau_save = tau_grid(fid, k_cmb, n_save) a_save = scale_factors(fid, tau_save) tau0 = float(tau_save[-1]) n_solved = ( len(k_lensing) if extrapolate_above is None else int(np.sum(k_lensing <= extrapolate_above)) ) k_solved = k_lensing[:n_solved] i_star = int(np.argmin(np.diff(tau_save))) chi_star = float(tau0 - tau_save[i_star]) chi_max = float(tau0 - tau_save[0]) chunks = spans(ells, k_fine, a_save, chi_max, chi_star) # The Bessel tables in chunks of modes, each a device buffer of its # own: a compiled program copies a slice of an argument, and a copy # of half the table does not fit beside it. full, full_e = projection_tables(ells, k_fine, tau_save, tau0, dtype) bessel = tuple( jnp.array(full[f0:f1, l0:l1, :, t0:t1]) for f0, f1, t0, t1, l0, l1 in chunks ) bessel_e = tuple( jnp.array(full_e[f0:f1, l0:l1, t0:t1]) for f0, f1, t0, t1, l0, l1 in chunks ) del full, full_e chi = tau0 - tau_save ells_pp = np.unique(np.round(np.geomspace(2, lmax, 40)).astype(np.int64)) exact, limber = ells_pp < LIMBER_L_MIN, ells_pp >= LIMBER_L_MIN lensing_exact = ( exact_lensing_operator(ells_pp[exact], k_lensing, tau_save, tau0, dtype) * jnp.asarray(k_lensing <= K_MAX_EXACT, dtype)[None, :, None] ) layout = Layout( k_values=k_solved, k_lensing=k_lensing, k_fine=k_fine, ells=ells, ells_pp=ells_pp, tau_save=tau_save, a_save=a_save, i_star=i_star, chi_star=chi_star, spans=chunks, ) operators = Operators( lnk_knots=jnp.log(jnp.asarray(k_solved)), lnk_curvature=jnp.asarray(curvature_band(np.log(k_solved))), lnk_weights=jnp.asarray(trapezoid_weights(np.log(k_fine))), band=k_band( jnp.asarray(ells, dtype=jnp.float64), jnp.asarray(k_fine), chi_max, chi_star, ), keep=late_taper(k_fine, a_save, dtype), bessel=bessel, bessel_e=bessel_e, lensing_exact=lensing_exact, limber_weights=limber_spline(ells_pp[limber], k_lensing, chi, dtype), k_chi=jnp.asarray(limber_k(ells_pp[limber], chi)), tables=lensing_tables(lmax, dtype=dtype, beta_max=LENSING_BETA_MAX), every_ell=every_ell_matrix(ells, lmax).astype(dtype), every_ell_pp=every_ell_matrix(ells_pp, lmax, power=2), ) if cached is not None: os.makedirs(os.path.dirname(cached), exist_ok=True) with open(cached + ".tmp", "wb") as f: pickle.dump( (layout, jax.tree.map(np.asarray, operators)), f, protocol=5 ) os.replace(cached + ".tmp", cached) return cls(layout, operators)