Planck 2018 inference#

This notebook samples the flat \(\Lambda\)CDM posterior of Planck 2018’s plik_lite TT,TE,EE and low-\(\ell\) EE likelihoods by nested sampling, and compares it with the Planck 2018 legacy chains of the same data. DISCO-CMB computes the lensed spectra of each batch of proposals on the GPU, clipy evaluates the likelihoods in JAX, and blackjax’s nested slice sampler drives the run. Its settings keep the sampling to about a minute on an NVIDIA 4070 SUPER: enough to land on Planck’s posterior, not production grade.

The model is Planck’s baseline, flat \(\Lambda\)CDM with one neutrino of 0.06 eV beside 2.046 massless ones, as in the legacy chains, with the radiation streaming approximation on. The first run downloads the likelihood files and the chains from the Planck Legacy Archive, about 550 MB, and keeps what it needs (60 MB) in ~/.cache/disco-cmb, or in the folder DISCO_CMB_DATA names.

import contextlib
import io
import os
import re
import tarfile
import urllib.request
import zipfile
from functools import partial
from pathlib import Path

import blackjax
import clipy
import clipy.minicldf
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
from anesthetic import NestedSamples, make_2d_axes, read_chains
from discoeb import LCDM_MNU, solve_eb
from tqdm import tqdm

from discocmb import (
    Grid,
    LineOfSightSources,
    cmb_power_spectrum,
    error_weights,
    lensed_spectra,
    transfer_functions,
)

DATA = Path(os.environ.get("DISCO_CMB_DATA", "~/.cache/disco-cmb")).expanduser()
T_CMB = 2.7255  # K
MODEL = LCDM_MNU.with_settings(
    RSA=1
)  # the radiation streaming approximation, DISCO-EB's default

Data#

Legacy Planck likelihood and posterior chains are available from the ESA archives. We download plik_lite, simall’s EE and the chains of plik TT,TE,EE + lowE:

PLA = "https://pla.esac.esa.int/pla"
PLIK_LITE = DATA / "baseline/plc_3.0/hi_l/plik_lite/plik_lite_v22_TTTEEE.clik"
SIMALL = (
    DATA / "baseline/plc_3.0/low_l/simall/simall_100x143_offlike5_EE_Aplanck_B.clik"
)
CHAINS = DATA / "base/plikHM_TTTEEE_lowE/base_plikHM_TTTEEE_lowE"

if not (PLIK_LITE.exists() and SIMALL.exists()):
    url = "https://pla.esac.esa.int/pla-sl/data-action?COSMOLOGY.COSMOLOGY_OID=151902"
    wanted = (str(PLIK_LITE.relative_to(DATA)), str(SIMALL.relative_to(DATA)))
    with (
        urllib.request.urlopen(url) as response,
        tarfile.open(fileobj=response, mode="r|gz") as tar,
    ):
        for member in tar:
            if member.name.startswith(wanted):
                tar.extract(member, DATA, filter="data")

if not Path(f"{CHAINS}.paramnames").exists():
    archive = DATA / "COM_CosmoParams_base-plikHM_R3.01.zip"
    urllib.request.urlretrieve(
        f"{PLA}/aio/product-action?COSMOLOGY.FILE_ID={archive.name}", archive
    )
    with zipfile.ZipFile(archive) as z:
        root = re.escape(str(CHAINS.relative_to(DATA)))
        for name in z.namelist():
            if re.fullmatch(rf"{root}(_[0-9]+\.txt|\.paramnames)", name):
                z.extract(name, DATA)
    archive.unlink()

Likelihood#

We use likelihoods implemented in clipy, the Python/JAX compatible interface for the Planck likelihood. The plik_lite likelihood consists of TT, TE and EE spectra from \(\ell = 30\) to \(2508\) with the foregrounds marginalised, and simall is EE from \(\ell = 2\) to 29, the low-\(\ell\) data that constrain reionization. Both take the lensed \(C_\ell\) in \(\mu\mathrm{K}^2\) and the calibration \(A_\mathrm{planck}\).

read = clipy.minicldf.File.__getitem__


def native(self, key):
    value = read(self, key)
    if isinstance(value, np.ndarray) and value.dtype.byteorder == ">":
        return value.astype(value.dtype.newbyteorder("="))
    return value


clipy.minicldf.File.__getitem__ = native

with contextlib.redirect_stdout(io.StringIO()):
    plik_lite = clipy.clik(str(PLIK_LITE))
    simall = clipy.clik(str(SIMALL))


def planck_log_like(tt, te, ee, a_planck):
    """plik_lite + simall EE of one cosmology's lensed C_l in muK^2 from l = 0."""

    high = slice(30, 2509)
    cls = jnp.zeros((6, 2509))  # TT, EE, BB, TE, TB, EB
    cls = (
        cls.at[0, high]
        .set(tt[high])
        .at[1, high]
        .set(ee[high])
        .at[3, high]
        .set(te[high])
    )
    low = jnp.zeros((6, 30)).at[1, 2:30].set(ee[2:30] / a_planck**2)
    return plik_lite(cls, {"A_planck": a_planck}) + simall(
        low, {"A_planck": jnp.asarray(1.0)}
    )

Model#

A point \(x\) in the parameter space is defined by \(\omega_b\), \(\omega_c\), \(h\), the reionization redshift \(z_\mathrm{re}\), \(\ln(10^{10} A_s)\), \(n_s\) and \(A_\mathrm{planck}\). DISCO-EB takes \(z_\mathrm{re}\), where Planck sampled the optical depth \(\tau\). The grid comes from the Planck best fit.

def cosmology(x) -> LCDM_MNU:
    omega_b, omega_c, h, z_re, ln10As, n_s = (x[i] for i in range(6))
    return MODEL.from_density_parameters(
        Omega_m=(omega_b + omega_c) / h**2,
        Omega_b=omega_b / h**2,
        H_0=100.0 * h,
        A_s=1.0e-10 * jnp.exp(ln10As),
        n_s=n_s,
        T_cmb=T_CMB,
        Y_He=0.2454,
        N_eff=2.046,  # the massless flavours
        N_mnu=1,
        m_nu=0.06,  # eV
        z_re=z_re,
    )


best_fit = np.array([0.02237, 0.1200, 0.6736, 7.67, 3.044, 0.9649, 1.0])
grid = Grid.from_fiducial(cosmology(best_fit), extrapolate_above=1.2)
weights = error_weights(MODEL)

batch_log_like takes a batch of points in the parameter space (n, 7) through one GPU launch to the lensed spectra and the likelihood. blackjax’s sampler assumes a per-particle likelihood and vmaps over them, whereas our functions are batch-native by design, so we use a custom_vmap rules to tell JAX that the vmap of the one-point likelihood is already our batch function:

def batch_log_like(grid, X):
    cosmologies = [cosmology(x) for x in X]
    values = solve_eb(
        cosmologies,
        grid.k_values,
        grid.a_save,
        extra=[LineOfSightSources],
        keep=[LineOfSightSources.keep],
        error_weights=weights,
    )
    cl, _ = cmb_power_spectrum(transfer_functions(values, grid), cosmologies)
    lensed = lensed_spectra(cl, grid)
    muk2 = (T_CMB * 1.0e6) ** 2
    return jax.vmap(planck_log_like)(
        muk2 * lensed.tt, muk2 * lensed.te, muk2 * lensed.ee, X[:, 6]
    )


@jax.custom_batching.custom_vmap
def log_like(grid, x):
    return batch_log_like(grid, x[None])[0]


@log_like.def_vmap
def _(axis_size, in_batched, grid, x):
    x = x if in_batched[1] else jnp.broadcast_to(x, (axis_size,) + x.shape)
    return batch_log_like(grid, x), True


log_like(grid, jnp.asarray(best_fit))
Array(-491.10219657, dtype=float64)

Nested sampling#

We set up a quick non-production grade nested sampling run as follows: the prior is flat in the six cosmological parameters over a box 20 to 40 posterior widths across, and Gaussian in \(A_\mathrm{planck}\), \(1 \pm 0.0025\), as Planck’s. 128 live points, 64 replaced per iteration by two slice steps each, run until the live points hold less than \(10^{-3}\) of the evidence. The progress bar shows \(\ln Z\) so far and \(\ln(Z_\mathrm{live}/Z)\), which falls to \(\ln 10^{-3} \approx -6.9\). The jitted step takes the grid as an argument, so its tables stay in device buffers.

LOW = jnp.array([0.020, 0.10, 0.60, 4.0, 2.8, 0.92])
HIGH = jnp.array([0.025, 0.14, 0.80, 12.0, 3.3, 1.02])
N_LIVE, N_DELETE, N_INNER = 128, 64, 2


def log_prior(x):
    inside = jnp.all((x[:6] >= LOW) & (x[:6] <= HIGH))
    return jnp.where(inside, -0.5 * ((x[6] - 1.0) / 0.0025) ** 2, -jnp.inf)


def sample_prior(key, n):
    flat, gaussian = jax.random.split(key)
    return jnp.concatenate(
        [
            jax.random.uniform(flat, (n, 6), minval=LOW, maxval=HIGH),
            1.0 + 0.0025 * jax.random.normal(gaussian, (n, 1)),
        ],
        axis=1,
    )


def sampler(grid):
    return blackjax.nss(
        logprior_fn=log_prior,
        loglikelihood_fn=partial(log_like, grid),
        num_inner_steps=N_INNER,
        num_delete=N_DELETE,
    )


init = jax.jit(lambda grid, x: sampler(grid).init(x))
step = jax.jit(lambda grid, state, key: sampler(grid).step(key, state))


def run(key):
    """The dead points of a run, and its final live points."""

    key, prior_key = jax.random.split(key)
    state = init(grid, sample_prior(prior_key, N_LIVE))
    dead = []
    with tqdm(desc="nested sampling", unit=" iterations") as progress:
        while (
            remaining := state.integrator.logZ_live - state.integrator.logZ
        ) > np.log(1.0e-3):
            key, step_key = jax.random.split(key)
            state, info = step(grid, state, step_key)
            dead.append(info.particles)
            progress.update()
            progress.set_postfix(
                lnZ=f"{float(state.integrator.logZ):.2f}",
                remaining=f"{float(remaining):.2f}",
            )
    return jax.block_until_ready(dead + [state.particles])


warm_up_key, key = jax.random.split(jax.random.key(0))
_ = step(grid, init(grid, sample_prior(warm_up_key, N_LIVE)), warm_up_key)  # compile
%time points = run(key)
nested sampling: 36 iterations [01:35,  2.65s/ iterations, lnZ=-508.27, remaining=-6.40]
CPU times: user 1min 35s, sys: 10.3 ms, total: 1min 35s
Wall time: 1min 35s

Comparison with Planck 2018#

We use the anesthetic library to analyse the nested sampling results. The legacy chains of plik TT,TE,EE + lowE sampled \(\tau\) and give \(z_\mathrm{re}\) as a derived parameter, from the same tanh model of reionization.

columns = ["omegabh2", "omegach2", "H0", "zrei", "logA", "ns", "calPlanck"]
position = np.concatenate([np.asarray(p.position) for p in points])
position[:, 2] *= 100.0  # h to H0
ours = NestedSamples(
    data=position,
    columns=columns,
    logL=np.concatenate([np.asarray(p.loglikelihood) for p in points]),
    logL_birth=np.concatenate([np.asarray(p.loglikelihood_birth) for p in points]),
    labels=dict(
        zip(
            columns,
            [
                r"$\Omega_b h^2$",
                r"$\Omega_c h^2$",
                r"$H_0$",
                r"$z_\mathrm{re}$",
                r"$\ln(10^{10} A_s)$",
                r"$n_s$",
                r"$A_\mathrm{planck}$",
            ],
        )
    ),
)
planck = read_chains(str(CHAINS))

parameters = columns[:6]
_, axes = make_2d_axes(parameters, labels=ours.get_labels_map(), figsize=(9, 9))
planck.plot_2d(axes, label="Planck 2018 legacy chains", alpha=0.7)
ours.plot_2d(axes, label="DISCO-CMB, nested sampling", alpha=0.7)
axes.iloc[-1, 0].legend(
    loc="lower center", bbox_to_anchor=(len(parameters) / 2, len(parameters)), ncol=2
)
plt.show()
../_images/7ff10863454bfb13a2530e069dc48d962c730478edd5a8628c0bacb78deb3ef2.png