Using automatic differentiation

This tutorial shows how to compute the power spectrum $P(k; \theta)$ and its (logarithmic) derivatives

\[\frac{\partial \lg P}{\partial \lg \theta_i}\]

using automatic differentiation with ForwardDiff.jl. This technique can also differentiate any other quantity.

1. Wrap the evaluation

First, we must decide which parameters $\theta$ the power spectrum $P(k; \theta)$ should be considered a function of. To do so, let us write a small wrapper function that calculates the power spectrum as a function of the parameters $(T_{\gamma 0}, \Omega_{c0}, \Omega_{b0}, N_\textrm{eff}, h, Y_p)$, following the Getting started tutorial:

using SymBoltz
M = ΛCDM(K = nothing)
pars = [M.γ.T₀, M.c.Ω₀, M.b.Ω₀, M.ν.Neff, M.g.h, M.b.YHe, M.h.m_eV, M.I.ln_As1e10, M.I.ns]
prob0 = CosmologyProblem(M, Dict(pars .=> NaN); sparse = false) # dense Jacobian faster for AD

probgen = parameter_updater(prob0, pars)
P(k, θ) = spectrum_matter(probgen(θ), k; ptopts = (reltol = 1e-3, abstol = 1e-3))
P (generic function with 1 method)

It is now easy to evaluate the power spectrum:

using Unitful, UnitfulAstro
θ = [2.7, 0.27, 0.05, 3.0, 0.7, 0.25, 0.02, 3.0, 0.95]
ks = 10 .^ range(0.5, 3.5, length=100)
Ps = P(ks, θ)
100-element view(::Matrix{Float64}, 1, :) with eltype Float64:
 1.463548391131371e-7
 1.5589204334958363e-7
 1.6599266644236235e-7
 1.7668389451959273e-7
 1.879814933503212e-7
 1.9991162919168655e-7
 2.124950754016545e-7
 2.257510977828278e-7
 2.3969578169624e-7
 2.5434537432078477e-7
 ⋮
 5.697774430502692e-9
 4.889069480341221e-9
 4.187437543762829e-9
 3.5835990180170947e-9
 3.0628449413414932e-9
 2.61477068607909e-9
 2.2297896219822974e-9
 1.8994369353066486e-9
 1.6163599153525226e-9

This can be plotted with

using Plots
plot(log10.(ks), log10.(Ps); xlabel = "lg(k / (H₀/c))", ylabel = "lg(P / (c/H₀)³)", label = nothing)
Example block output

2. Calculate the derivatives

To get $\partial \lg P / \partial \lg \theta$, we can simply pass the wrapper function P(k, θ) through ForwardDiff.jacobian:

using ForwardDiff
lgP(lgθ) = log10.(P(ks, 10 .^ lgθ)) # in log-space
dlgP_dlgθs = ForwardDiff.jacobian(lgP, log10.(θ))
100×9 Matrix{Float64}:
 -0.0992245  -1.26057  -0.233447  -0.00633735  …  -0.00488694  3.0  -4.00456
 -0.108589   -1.25653  -0.2327    -0.0070249      -0.00479575  3.0  -3.93827
 -0.118916   -1.25222  -0.231899  -0.00778141     -0.00471149  3.0  -3.87199
 -0.130263   -1.24739  -0.231006  -0.00861062     -0.00463745  3.0  -3.8057
 -0.1427     -1.24213  -0.230031  -0.00951934     -0.00457882  3.0  -3.73941
 -0.156312   -1.23641  -0.22897   -0.0105146   …  -0.00454045  3.0  -3.67313
 -0.171166   -1.23023  -0.227821  -0.0116008      -0.00452744  3.0  -3.60684
 -0.187324   -1.22339  -0.22655   -0.0127843      -0.00454396  3.0  -3.54055
 -0.204868   -1.21606  -0.22519   -0.0140696      -0.00459479  3.0  -3.47427
 -0.223877   -1.20816  -0.223728  -0.015463       -0.00468259  3.0  -3.40798
  ⋮                                            ⋱                    
 -5.86647     1.82779  -0.361222  -0.383036       -0.0253043   3.0   2.02752
 -5.90172     1.84141  -0.365003  -0.386737       -0.0253076   3.0   2.0938
 -5.93563     1.86082  -0.365714  -0.387889       -0.02531     3.0   2.16009
 -5.97163     1.87909  -0.364625  -0.389071       -0.0253121   3.0   2.22638
 -6.00447     1.89528  -0.365696  -0.390893    …  -0.025314    3.0   2.29266
 -6.03631     1.91169  -0.366132  -0.3923         -0.0253157   3.0   2.35895
 -6.06733     1.92767  -0.366319  -0.393587       -0.0253171   3.0   2.42524
 -6.09751     1.94307  -0.366512  -0.394863       -0.0253183   3.0   2.49152
 -6.12695     1.95789  -0.366754  -0.396154       -0.0253194   3.0   2.55781

The matrix element dlgP_dlgθs[i, j] now contains $\partial \lg P(k_i) / \partial \lg \theta_j$. We can plot them all at once:

plot(
    log10.(ks), dlgP_dlgθs;
    xlabel = "lg(k / (H₀/c))", ylabel = "∂ lg(P/(c/H₀)³) / ∂ lg(θᵢ)",
    labels = "θᵢ=" .* ["Tγ0" "Ωc0" "Ωb0" "Neff" "h" "YHe" "mh" "ln(10¹⁰As)" "ns"]
)
Example block output

Get values and derivatives together

The above example showed how to calculate the power spectrum values and their derivatives through two separate calls. If you need both, it is faster to calculate them simultaneously with the package DiffResults.jl:

using DiffResults

# Following DiffResults documentation:
Pres = DiffResults.JacobianResult(ks, θ) # allocate buffer for values+derivatives for a function with θ-sized input and ks-sized output
Pres = ForwardDiff.jacobian!(Pres, lgP, log10.(θ)) # evaluate values+derivatives of lgP(log10.(θ)) and store the results in Pres
lgPs = DiffResults.value(Pres) # extract values
dlgP_dlgθs = DiffResults.jacobian(Pres) # extract derivatives

p1 = plot(
   log10.(ks), lgPs;
   ylabel = "lg(P / (c/H₀)³)", label = nothing
)
p2 = plot(
   log10.(ks), dlgP_dlgθs;
   xlabel = "lg(k / (H₀/c))", ylabel = "∂ lg(P/(c/H₀)³) / ∂ lg(θᵢ)",
   labels = "θᵢ=" .* ["Tγ0" "Ωc0" "Ωb0" "Neff" "h" "YHe" "mh" "ln(10¹⁰As)" "ns"]
)
plot(p1, p2, layout=(2, 1), size = (600, 600))
Example block output

General approach

The technique shown here can be used to calculate the derivative of any SymBoltz.jl output quantity:

  1. Write a wrapper function output(input) that calculates the desired output quantities from the desired input quantities.
  2. Use ForwardDiff.derivative(output, input) (scalar-to-scalar), ForwardDiff.gradient(output, input) (vector-to-scalar) or ForwardDiff.jacobian(output, input) (vector-to-vector) to evaluate the derivative of output at the values input. Or use the similar functions in DiffResults to calculate the value and derivatives simultaneously.