Computing derivatives

Computing derivatives#

solve_cmb is differentiable in every parameter of the cosmologies, in forward mode (jax.jvp, jax.jacfwd) and reverse mode (jax.grad, jax.vjp). A cosmology is a JAX pytree, so jax.jacfwd of a function of a cosmology returns a cosmology whose fields are the derivatives:

import jax
import jax.numpy as jnp
import numpy as np
from discoeb import LCDM
from discocmb import Grid, solve_cmb

planck = LCDM(
    omega_b=0.02239,
    omega_c=0.1200,
    omega_de=0.3108,
    A_s=2.1e-9,
    n_s=0.966,
    T_cmb=2.7255,
    Y_He=0.2454,
    N_eff=3.046,
    z_re=7.67,
)
ells = np.array([2, 10, 30, 100, 220, 400, 540, 800, 1000, 1200])
grid = Grid.from_fiducial(planck, ells=ells, dtype=jnp.float64)


def tt(cosmology):
    _, _, dl = solve_cmb(cosmology, grid=grid)
    return dl.tt[0, ells]


d = jax.jacfwd(tt)(planck)
d.omega_c  # (10,): dD_l^TT / domega_c at ells

The kernel integrates one sensitivity column beside the state for each parameter. To differentiate fewer, hold the others fixed with replace:

dtt = jax.jacfwd(lambda omega_c: tt(planck.replace(omega_c=omega_c)))(planck.omega_c)

For many directions, split_derivatives=True allows the work to be distributed across multiple GPU threads, with each thread handling a subset of the derivatives.

Parameters derived from others rather than specified upfront work the same way. For example, the physical density of photons \(\omega_\gamma\) is derived from the CMB temperature \(T_\mathrm{CMB}\):

dtt = jax.jacfwd(lambda omega_g: tt(planck.replace(omega_g=omega_g)))(planck.omega_g)

Note that a value set this way stays fixed when the parameters it is derived from change.