Skip to contents

Sensitivity analysis asks how the solution of a model changes when its inputs change. For a differential equation u′=f(u,p,t)u' = f(u, p, t) with initial value u0u_0 and parameters pp, the local sensitivities are the derivatives ∂u(t)/∂p\partial u(t) / \partial p and ∂u(t)/∂u0\partial u(t) / \partial u_0; for a scalar cost G(u,p)G(u, p) of the solution they combine into the gradient dG/dpdG/dp. Gradients drive parameter estimation, optimal control, experimental design and uncertainty propagation.

modelcompR ports the local sensitivity methods of SciMLSensitivity.jl. This article covers

A model to differentiate

Most examples use the Lotka Volterra predator prey model, written symbolically. When a problem comes from a System, the sensitivity methods use the symbolic Jacobians ∂f/∂u\partial f / \partial u and ∂f/∂p\partial f / \partial p of the compiled model, so every vector Jacobian product is exact.

t <- t_nounits
D <- D_nounits
variables("x(t)", "y(t)")
parameters("r", "k", "m", "e")
eqs <- list(D(x) ~ r * x - k * x * y,
            D(y) ~ -m * y + e * x * y)
lv <- mtkcompile(System(eqs, t, name = "lv"))
prob <- ODEProblem(lv, list(x ~ 1, y ~ 1, r ~ 1.5, k ~ 1, m ~ 3, e ~ 1), c(0, 3))
prob$u0
#> y(t) x(t) 
#>    1    1
prob$p
#>   r   k   e   m 
#> 1.5 1.0 1.0 3.0

The order of the unknowns and parameters is chosen by the compiler, so the results below are always read by name.

Forward sensitivities

The forward method differentiates the ODE with respect to the parameters and integrates the sensitivity matrix S=∂u/∂pS = \partial u / \partial p alongside the state: S′=∂f∂uS+∂f∂p,S(0)=∂u0∂p. S' = \frac{\partial f}{\partial u} S + \frac{\partial f}{\partial p}, \qquad S(0) = \frac{\partial u_0}{\partial p}. The augmented system has n(1+np)n (1 + n_p) equations, so the cost grows with the number of parameters. It is the method of choice for few parameters, or when the sensitivities of the whole trajectory are wanted. ODEForwardSensitivityProblem() mirrors the Julia constructor of the same name; it accepts an ODEProblem, a compiled System or a plain R function.

fprob <- ODEForwardSensitivityProblem(prob)
fsol <- solve(fprob, Tsit5(), reltol = 1e-8, abstol = 1e-8)

extract_local_sensitivities() splits the augmented solution into the state u and the sensitivities du, one entry per parameter. With an index it returns one saved time; with t it interpolates; with asmatrix = TRUE the sensitivities form one n×npn \times n_p matrix.

last <- extract_local_sensitivities(fsol, length(fsol$t))
last$u
#>      y(t)      x(t) 
#> 1.9098538 0.9703305
last$du$r
#>       y(t)       x(t) 
#> -4.4126744 -0.7620413
extract_local_sensitivities(fsol, t = 1.5, asmatrix = TRUE)
#> $u
#>      y(t)      x(t) 
#> 0.3914541 5.0742539 
#> 
#> $du
#>             r          k         e          m
#> y(t) 1.168993 -0.5353709  1.048283 -0.3494798
#> x(t) 5.803967 -2.2201502 -2.704768  1.5521777

Without an index the function returns the whole trajectory: u is a matrix with one row per saved time, and each element of du is a matrix of the same shape.

traj <- extract_local_sensitivities(fsol)
dim(traj$u)
#> [1] 110   2
matplot(fsol$t, cbind(traj$du$r, traj$du$m), type = "l", lty = c(1, 1, 2, 2),
        col = c(1, 2, 1, 2), xlab = "t", ylab = "sensitivity")
legend("bottomleft", c("dx/dr", "dy/dr", "dx/dm", "dy/dm"), lty = c(1, 1, 2, 2),
       col = c(1, 2, 1, 2), bty = "n")

The sensitivities grow along the oscillation: a small change in the growth rate shifts the phase of the cycle, and the phase error accumulates.

Derivatives with respect to the initial values

ForwardSensitivity() (the default) differentiates with respect to the parameters. ForwardDiffSensitivity(), Julia’s dual number method, can also differentiate with respect to the initial values; the seed matrices du0 and dp choose the directions. Each column of the seeds is one direction (δu0,δp)(\delta u_0, \delta p). For u′=−puu' = -p u, u(0)=1u(0) = 1, p=2p = 2, the derivatives of u(1)=e−2u(1) = e^{-2} are e−2e^{-2} with respect to u0u_0 and −e−2-e^{-2} with respect to pp:

dprob <- ODEForwardSensitivityProblem(function(u, p, t) -p[1] * u, 1, c(0, 1), 2,
                                      sensealg = ForwardDiffSensitivity(),
                                      du0 = cbind(1, 0), dp = cbind(0, 1))
dsol <- solve(dprob, Tsit5(), reltol = 1e-10, abstol = 1e-12)
extract_local_sensitivities(dsol, t = 1, asmatrix = TRUE)$du
#>       theta1     theta2
#> u1 0.1353353 -0.1353353
c(exp(-2), -exp(-2))
#> [1]  0.1353353 -0.1353353

ODEForwardSensitivityFunction() returns the right-hand side of the augmented system itself, for use with other tools.

ODEForwardSensitivityFunction(prob)
#> ODEForwardSensitivityFunction(numindvar = 2, numparams = 4)

Adjoint sensitivities

When there are many parameters and one scalar cost, the adjoint method is cheaper. For a cost G(p)=∫t0Tg(u,p,t)dt+∑igi(u(ti)) G(p) = \int_{t_0}^{T} g(u, p, t)\, dt + \sum_i g_i(u(t_i)) it solves the adjoint equation backward in time, λ′=−(∂f∂u)Tλ−(∂g∂u)T,dGdp=λ(t0)T∂u0∂p+∫t0T(λT∂f∂p+∂g∂p)dt, \lambda' = -\left(\frac{\partial f}{\partial u}\right)^{\!T} \lambda - \left(\frac{\partial g}{\partial u}\right)^{\!T}, \qquad \frac{dG}{dp} = \lambda(t_0)^T \frac{\partial u_0}{\partial p} + \int_{t_0}^{T} \left(\lambda^T \frac{\partial f}{\partial p} + \frac{\partial g}{\partial p}\right) dt, with jumps λ+=∂gi/∂u\lambda \mathrel{+}= \partial g_i / \partial u at the discrete cost times. One backward solve of nn equations (plus a quadrature of npn_p) gives the whole gradient, whatever the number of parameters.

adjoint_sensitivities(sol, alg, ...) takes a forward solution and returns du0 and dp. A discrete cost is given by its gradient dgdu_discrete(u, p, t, i) at the times t; a continuous cost by g(u, p, t) (its gradients are then taken by finite differences) or by dgdu_continuous and dgdp_continuous. The forward solution must be dense, so it is solved without saveat.

sol <- solve(prob, Tsit5(), reltol = 1e-10, abstol = 1e-10)
ts <- seq(0.5, 3, by = 0.5)
# G = sum_i x(t_i): the gradient of the cost at each time is the unit vector of x
ix <- match("x(t)", names(prob$u0))
ex <- replace(numeric(2), ix, 1)
adj <- adjoint_sensitivities(sol, Tsit5(), t = ts, dgdu_discrete = function(u, p, t, i) ex,
                             abstol = 1e-10, reltol = 1e-10)
adj$du0
#>       y(t)       x(t) 
#> -0.8804078 -2.2959192
adj$dp
#>           r           k           e           m 
#>  -3.3989981  -0.8804078 -21.6001198   5.5081056

The adjoint methods

The methods differ in how they obtain the forward state during the backward solve and how they integrate the parameter gradient:

Method Forward state Parameter gradient
InterpolatingAdjoint() interpolated from the dense forward solution (or re-solved between checkpoints) integrated with λ\lambda
BacksolveAdjoint() integrated backward with λ\lambda (reset at the saved points with checkpointing = TRUE) integrated with λ\lambda
QuadratureAdjoint() interpolated adaptive Gauss Kronrod quadrature after the backward solve
GaussAdjoint() interpolated (or checkpointed) Gauss Legendre rule on each backward step
GaussKronrodAdjoint() interpolated (or checkpointed) Gauss Kronrod rule on each backward step

BacksolveAdjoint() needs the least memory but can be unstable when the backward integration of the state is ill conditioned. GaussAdjoint() is the default of solve_gradient() for larger problems, as in Julia. All methods give the same gradient to the solver tolerances:

methods <- list(InterpolatingAdjoint = InterpolatingAdjoint(),
                Interpolating_checkpointed = InterpolatingAdjoint(checkpointing = TRUE),
                BacksolveAdjoint = BacksolveAdjoint(),
                QuadratureAdjoint = QuadratureAdjoint(abstol = 1e-10, reltol = 1e-10),
                GaussAdjoint = GaussAdjoint(),
                GaussKronrodAdjoint = GaussKronrodAdjoint())
grads <- t(vapply(methods, function(sa) {
  r <- adjoint_sensitivities(sol, Tsit5(), t = ts, dgdu_discrete = function(u, p, t, i) ex,
                             sensealg = sa, abstol = 1e-10, reltol = 1e-10)
  c(r$du0, r$dp)
}, numeric(6)))
signif(grads, 8)
#>                                  y(t)      x(t)         r          k         e
#> InterpolatingAdjoint       -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#> Interpolating_checkpointed -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#> BacksolveAdjoint           -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#> QuadratureAdjoint          -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#> GaussAdjoint               -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#> GaussKronrodAdjoint        -0.8804078 -2.295919 -3.398998 -0.8804078 -21.60012
#>                                   m
#> InterpolatingAdjoint       5.508106
#> Interpolating_checkpointed 5.508106
#> BacksolveAdjoint           5.508106
#> QuadratureAdjoint          5.508106
#> GaussAdjoint               5.508106
#> GaussKronrodAdjoint        5.508106

The forward sensitivities give the same numbers: dG/dp=∑i∂x(ti)/∂pdG/dp = \sum_i \partial x(t_i) / \partial p.

fs <- extract_local_sensitivities(fsol, t = ts, asmatrix = TRUE)
Reduce(`+`, lapply(fs, function(s) s$du["x(t)", ]))
#>           r           k           e           m 
#>  -3.3989982  -0.8804078 -21.6001198   5.5081055

A continuous cost works the same way. Here G=∫03x(t)2dtG = \int_0^3 x(t)^2\, dt:

adjoint_sensitivities(sol, Tsit5(), g = function(u, p, t) u[ix]^2,
                      sensealg = GaussAdjoint(), abstol = 1e-10, reltol = 1e-10)$dp
#>           r           k           e           m 
#>   -9.977070   -6.133288 -110.214385   30.451914

The adjoint problem

ODEAdjointProblem() builds the backward problem without solving it. It is an ordinary ODEProblem with a reversed time span; its finish element turns the backward solution into the gradients.

ap <- ODEAdjointProblem(sol, GaussAdjoint(), Tsit5(), t = ts,
                        dgdu_discrete = function(u, p, t, i) ex)
ap$tspan
#> [1] 3 0
asol <- solve(ap, Tsit5(), abstol = 1e-10, reltol = 1e-10)
ap$finish(asol)$dp
#>           r           k           e           m 
#>  -3.3989981  -0.8804078 -21.6001198   5.5081056

Vector Jacobian products

In Julia, autojacvec selects the automatic differentiation backend that computes the products λT∂f/∂u\lambda^T \partial f / \partial u and λT∂f/∂p\lambda^T \partial f / \partial p: ZygoteVJP(), EnzymeVJP(), ReverseDiffVJP(), TrackerVJP(), MooncakeVJP() or ReactantVJP(). R has no automatic differentiation, so in modelcompR

  • autojacvec = NULL or TRUE (and every backend object above) uses the symbolic derivatives of the System, compiled to R code, or the problem’s jac when it was built from an R function;
  • autojacvec = FALSE uses central finite differences.

The backend names are accepted so that code translated from Julia runs unchanged:

ZygoteVJP()
#> ZygoteVJP()
sa_list <- list(symbolic = GaussAdjoint(autojacvec = TRUE),
                zygote = GaussAdjoint(autojacvec = ZygoteVJP()),
                enzyme = InterpolatingAdjoint(autojacvec = EnzymeVJP()),
                reversediff = InterpolatingAdjoint(autojacvec = ReverseDiffVJP(compile = TRUE)),
                finite_differences = GaussAdjoint(autojacvec = FALSE))
vapply(sa_list, function(sa) {
  adjoint_sensitivities(sol, Tsit5(), t = ts, dgdu_discrete = function(u, p, t, i) ex,
                        sensealg = sa, abstol = 1e-10, reltol = 1e-10)$dp[["r"]]
}, 0)
#>           symbolic             zygote             enzyme        reversediff 
#>          -3.398998          -3.398998          -3.398998          -3.398998 
#> finite_differences 
#>          -3.398998

The discretize then optimize methods ZygoteAdjoint(), EnzymeAdjoint(), ReverseDiffAdjoint(), TrackerAdjoint() and MooncakeAdjoint(), which differentiate through the solver in Julia, run the forward sensitivities of the discretized solve in R (ForwardDiffSensitivity()), and so give the derivative of the computed solution.

ZygoteAdjoint()
#> ZygoteAdjoint()

Gradients of a loss through solve

solve_gradient(loss, prob, alg, ...) is the R counterpart of calling Zygote.gradient on a function that solves an ODE in Julia. loss is any R function of the solution that returns a number; the options in ... go to solve() (saveat, tolerances, callbacks), and sensealg picks the method. The result holds the gradients u0 and p, the loss value and the forward solution sol.

The loss below compares the predator prey trajectory at saved times with a target. Only the saved values may enter the loss: the adjoint knows the cotangent of the loss at the saveat points.

ts <- seq(0, 3, by = 0.25)
loss <- function(sol) sum((sol[x] - 1)^2) + sum(sol[y])
g_fwd <- solve_gradient(loss, prob, Tsit5(), saveat = ts, reltol = 1e-9, abstol = 1e-10,
                        sensealg = ForwardDiffSensitivity())
g_adj <- solve_gradient(loss, prob, Tsit5(), saveat = ts, reltol = 1e-9, abstol = 1e-10,
                        sensealg = GaussAdjoint())
g_fwd$value
#> [1] 125.4767
rbind(forward = c(g_fwd$u0, g_fwd$p), adjoint = c(g_adj$u0, g_adj$p))
#>              y(t)      x(t)         r         k         e        m
#> forward -22.48912 -87.49685 -7.764659 -42.02611 -352.4844 100.1787
#> adjoint -22.48912 -87.49685 -7.764659 -42.02611 -352.4844 100.1787

A central finite difference check:

F <- function(th) loss(solve(remake(prob, u0 = th[1:2], p = th[3:6]), Tsit5(),
                             reltol = 1e-10, abstol = 1e-10, saveat = ts))
th <- c(prob$u0, prob$p)
fd <- vapply(seq_along(th), function(j) {
  h <- replace(numeric(6), j, 1e-5)
  (F(th + h) - F(th - h)) / 2e-5
}, 0)
max(abs(fd - c(g_adj$u0, g_adj$p)))
#> [1] 1.047363e-06

When sensealg is not given, solve_gradient() picks one from the problem: forward sensitivities for small ODEs, GaussAdjoint() for larger ones, SteadyStateAdjoint() for nonlinear and steady state problems.

How the loss is differentiated

The sensitivity methods need the derivative of the loss with respect to each saved value. By default solve_gradient() takes it by finite differences in every saved value: correct for any loss, but one or two loss evaluations per saved value. Two options make it cheaper without guessing which values the loss reads:

  • loss_rows declares the saved rows the loss depends on, for example loss_rows = "last" for a terminal loss; the other rows get a zero cotangent. A wrong declaration gives a wrong gradient, so declare only what the loss is known to read.
  • loss_grad = function(sol) returns the cotangent directly, as a matrix of the shape of as.matrix(sol) (or a list with u and p). It sees the same view of the solution as the loss, save_idxs included. Values the loss reads through sol(t) at unsaved times are still differenced.
p2 <- ODEProblem(function(u, p, t) -p[1] * u, c(1, 2), c(0, 1), 1)
terminal <- function(sol) sum(tail(as.matrix(sol), 1)^2)
a <- solve_gradient(terminal, p2, Tsit5(), saveat = 0.01, reltol = 1e-10, abstol = 1e-12)
b <- solve_gradient(terminal, p2, Tsit5(), saveat = 0.01, reltol = 1e-10, abstol = 1e-12,
                    loss_rows = "last")
c(all_rows = a$p, last_row = b$p, exact = -10 * exp(-2))
#>  all_rows  last_row     exact 
#> -1.353353 -1.353353 -1.353353

Every numerical stage of a gradient is checked: a forward solve, an adjoint solve or a checkpoint replay that does not reach the end of its interval raises a condition of class sens_stage_failure with the stage, its retcode and the time it reached. g$execution records the sensitivity method, the arithmetic, how the loss was differentiated and the saved view.

Events

Events are differentiated too, including the dependence of the event time on the parameters. A ball dropped from height x0x_0 bounces at x=0x = 0 with restitution ee; the loss is the height at t=0.8t = 0.8, after the bounce.

variables("h(t)", "v(t)")
parameters("grav", "rest")
ball <- mtkcompile(System(list(D(h) ~ v, D(v) ~ -grav), t, name = "ball",
                          continuous_events = list(list(h ~ 0), list(v ~ -rest * Pre(v)))))
bprob <- ODEProblem(ball, list(h ~ 1, v ~ 0, grav ~ 9.81, rest ~ 0.9), c(0, 0.8))
height <- function(sol) tail(sol[h], 1)
gb <- solve_gradient(height, bprob, Tsit5(), saveat = 0.8, reltol = 1e-10, abstol = 1e-12,
                     sensealg = InterpolatingAdjoint())
gb$value
#> [1] 0.7935593
gb$p
#>       grav       rest 
#> 0.02315797 1.54355753

The exact height after the bounce is −evτ(T−τ)−g(T−τ)2/2-e\, v_\tau (T - \tau) - g (T - \tau)^2 / 2 with τ=2x0/g\tau = \sqrt{2 x_0 / g} and vτ=−gτv_\tau = -g \tau, so ∂x(T)/∂e=gτ(T−τ)\partial x(T) / \partial e = g \tau (T - \tau):

tau <- sqrt(2 / 9.81)
9.81 * tau * (0.8 - tau)
#> [1] 1.543558

To use adjoint_sensitivities() directly on a problem with events, solve it with solve(prob, alg, sensealg = ...), which records the events for the backward pass.

Parameter estimation with a gradient

A gradient makes local optimizers converge in a few iterations. The logistic growth model N′=ρN(1−N/K)N' = \rho N (1 - N / K) is fitted to noisy observations with stats::optim() and the bounded quasi Newton method L-BFGS-B; solve_gradient() supplies both the loss and its gradient. The parameters are optimized on the log scale to keep them positive.

variables("N(t)")
parameters("rho", "K")
logistic <- mtkcompile(System(list(D(N) ~ rho * N * (1 - N / K)), t, name = "logistic"))
lprob <- ODEProblem(logistic, list(N ~ 0.1, rho ~ 1.2, K ~ 2), c(0, 8))
tobs <- seq(0, 8, by = 0.5)
set.seed(1)
truth <- solve(lprob, Tsit5(), saveat = tobs, reltol = 1e-10, abstol = 1e-10)[N]
Nobs <- truth + rnorm(length(tobs), sd = 0.05)

pnames <- names(lprob$p)
sse <- function(sol) sum((sol[N] - Nobs)^2)
cache <- new.env()
objective <- function(logp) {
  if (!identical(cache$logp, logp)) {   # optim asks for fn and gr at the same point
    pr <- remake(lprob, p = setNames(exp(logp), pnames))
    cache$res <- solve_gradient(sse, pr, Tsit5(), saveat = tobs, reltol = 1e-8, abstol = 1e-10)
    cache$logp <- logp
  }
  cache$res
}
fn <- function(logp) objective(logp)$value
gr <- function(logp) objective(logp)$p * exp(logp)   # chain rule for log parameters

start <- log(c(rho = 0.5, K = 1))[pnames]
fit <- optim(start, fn, gr, method = "L-BFGS-B", lower = log(0.05), upper = log(20))
exp(fit$par)
#>        K      rho 
#> 1.996440 1.217135
fit$counts
#> function gradient 
#>       10       10

The bounds keep the line search away from growth rates so large that the ODE becomes extremely stiff; an unbounded BFGS search on the log scale can try ρ=e30\rho = e^{30} in its first step.

The estimates are close to the true values ρ=1.2\rho = 1.2 and K=2K = 2.

fitted <- solve(remake(lprob, p = setNames(exp(fit$par), pnames)), Tsit5())
plot(tobs, Nobs, xlab = "t", ylab = "N", pch = 19)
tt <- seq(0, 8, length.out = 200)
lines(tt, vapply(tt, function(s) fitted(s)[[1]], 0), col = 2)

Differential algebraic equations

Semi-explicit DAEs compiled from a System become mass matrix ODEs with zero rows for the algebraic equations. The interpolating, quadrature and Gauss adjoints handle them, as do the forward methods; the algebraic initial values are recomputed from the constraint, so their gradient is zero.

variables("w(t)", "z(t)")
parameters("kd", "ad")
dsys <- mtkcompile(System(list(D(w) ~ -kd * z, 0 ~ z^3 + z - ad * w), t, name = "dae"))
daeprob <- ODEProblem(dsys, list(w ~ 1, kd ~ 0.7, ad ~ 0.5), c(0, 2), jac = TRUE,
                      guesses = list(z ~ 0.5))
dloss <- function(sol) sum(sol[w]^2) + 3 * sum(sol[z])
dts <- seq(0, 2, by = 0.5)
gd <- solve_gradient(dloss, daeprob, Rodas5P(), saveat = dts, reltol = 1e-9, abstol = 1e-10,
                     sensealg = GaussAdjoint())
gd$u0
#>     w(t)     z(t) 
#> 10.52531  0.00000
gd$p
#>        kd        ad 
#> -3.617351  4.148709

Fully implicit DAEs F(u′,u,p,t)=0F(u', u, p, t) = 0 (a DAEProblem) have their own adjoint, DAEAdjointProblem(), used by adjoint_sensitivities(). The residual below couples u1′=−p1u1+u2u_1' = -p_1 u_1 + u_2 with the algebraic equation u2=p2u1u_2 = p_2 u_1, so u1′=−(p1−p2)u1u_1' = -(p_1 - p_2) u_1. With u1(0)=1u_1(0) = 1, p=(1,0.5)p = (1, 0.5), the cost G=u1(1)=e−(p1−p2)G = u_1(1) = e^{-(p_1 - p_2)} has gradient (−1,1)e−0.5(-1, 1)\, e^{-0.5} in pp:

res <- function(du, u, p, t) c(du[1] + p[1] * u[1] - u[2], u[2] - p[2] * u[1])
iprob <- DAEProblem(res, c(-0.5, 0), c(1, 0.5), c(0, 1), c(1, 0.5),
                    differential_vars = c(TRUE, FALSE))
isol <- solve(iprob, DFBDF(), abstol = 1e-10, reltol = 1e-10)
ir <- adjoint_sensitivities(isol, DFBDF(), t = 1, dgdu_discrete = function(u, p, t, i) c(1, 0),
                            abstol = 1e-10, reltol = 1e-10)
ir$dp
#> [1] -0.6065307  0.6065307
c(-1, 1) * exp(-0.5)
#> [1] -0.6065307  0.6065307

Steady states and nonlinear solutions

For a steady state f(u*,p)=0f(u^*, p) = 0, the implicit function theorem gives ∂u*/∂p=−(∂f/∂u)−1∂f/∂p\partial u^* / \partial p = -(\partial f / \partial u)^{-1} \partial f / \partial p without differentiating the iterations of the solver. The adjoint form needs one linear solve with the transposed Jacobian; SteadyStateAdjoint() implements it.

The steady state of x′=s−kx2x' = s - k x^2 is x*=s/kx^* = \sqrt{s / k}, so G=x*2=s/kG = x^{*2} = s / k has ∂G/∂k=−s/k2=−3/4\partial G / \partial k = -s / k^2 = -3/4 and ∂G/∂s=1/k=1/2\partial G / \partial s = 1 / k = 1/2 at k=2k = 2, s=3s = 3.

variables("q(t)")
parameters("kq", "sq")
ss <- mtkcompile(System(list(D(q) ~ sq - kq * q^2), t, name = "ss"))
ssprob <- SteadyStateProblem(ss, list(q ~ 1, kq ~ 2, sq ~ 3))
sssol <- solve(ssprob, SSRootfind())
adjoint_sensitivities(sssol, NULL, sensealg = SteadyStateAdjoint(), g = function(u, p) u[1]^2)$dp
#>    kq    sq 
#> -0.75  0.50
solve_gradient(function(sol) sol$u[[1]]^2, ssprob, SSRootfind())$p
#>    kq    sq 
#> -0.75  0.50

Nonlinear problems work the same way. For the system u12=p1u_1^2 = p_1, u2=p2u1u_2 = p_2 u_1, the loss u1+u2u_1 + u_2 has gradient (1+p2)/(2p1)(1 + p_2) / (2 \sqrt{p_1}) in p1p_1 and p1\sqrt{p_1} in p2p_2:

nprob <- NonlinearProblem(function(u, p) c(u[1]^2 - p[1], u[2] - p[2] * u[1]), c(1, 1),
                          p = c(2, 3))
solve_gradient(function(sol) sum(sol$u), nprob, NewtonRaphson())$p
#> [1] 1.414214 1.414214
c(4 / (2 * sqrt(2)), sqrt(2))
#> [1] 1.414214 1.414214

The optimum of an OptimizationProblem is differentiated through its optimality conditions: UnconstrainedOptimizationAdjoint() without constraints, OptimizationAdjoint() (the KKT conditions) with them. The minimizer of (x1−p1)2+(x2−p2x1)2(x_1 - p_1)^2 + (x_2 - p_2 x_1)^2 is x1=p1x_1 = p_1, x2=p1p2x_2 = p_1 p_2, so the loss x1+x2x_1 + x_2 has gradient (1+p2,p1)(1 + p_2, p_1):

fq <- function(x, p) (x[1] - p[1])^2 + (x[2] - p[2] * x[1])^2
oprob <- OptimizationProblem(fq, c(0, 0), c(1, 3))
solve_gradient(function(sol) sum(sol$u), oprob, BFGS(), g_abstol = 1e-12)$p
#> [1] 4 1

Stochastic differential equations

For an SDE, solve_gradient() with a fixed step method, a dt and a seed differentiates the sampled path: the noise is held fixed and the result is the pathwise derivative. For geometric Brownian motion du=μudt+σudWdu = \mu u\, dt + \sigma u\, dW the path is u(T)=u0exp⁡((μ−σ2/2)T+σWT)u(T) = u_0 \exp((\mu - \sigma^2 / 2) T + \sigma W_T), so ∂u(T)/∂μ=Tu(T)\partial u(T) / \partial \mu = T u(T).

sprob <- SDEProblem(function(u, p, t) p[1] * u, function(u, p, t) p[2] * u, 1, c(0, 1),
                    c(1.5, 0.3))
send <- function(sol) tail(as.matrix(sol)[, 1], 1)
gs <- solve_gradient(send, sprob, EM(), dt = 0.01, seed = 3)
c(du0 = gs$u0, dp = gs$p)
#>        du0        dp1        dp2 
#>  4.4337211  4.3681981 -0.4795757
gs$value   # u(T), and T u(T) since T = 1
#> [1] 4.433721

The derivative in u0u_0 equals u(T)/u0u(T) / u_0 exactly, since the path is linear in u0u_0. The derivative in μ\mu is close to, but not equal to, Tu(T)T u(T): the pathwise derivative is that of the discrete Euler Maruyama path uN=u0∏k(1+μΔt+σΔWk)u_N = u_0 \prod_k (1 + \mu\, \Delta t + \sigma\, \Delta W_k), which is uN∑kΔt/(1+μΔt+σΔWk)u_N \sum_k \Delta t / (1 + \mu\, \Delta t + \sigma\, \Delta W_k).

The adjoint methods BacksolveAdjoint() and InterpolatingAdjoint() also run on SDEs (SDEAdjointProblem()) and random ODEs (RODEAdjointProblem()). They need the noise path to be reproducible backward in time, which a NoiseGrid provides:

tg <- seq(0, 1, by = 0.05)
W <- 0.3 * sin(3.1 * tg) + 0.25 * sin(7.3 * tg)
nprob2 <- SDEProblem(function(u, p, t) c(p[1] * u[1] - u[1] * u[2], -p[2] * u[2] + u[1] * u[2]),
                     function(u, p, t) c(p[3] * u[1], p[3] * u[2]),
                     c(1, 0.8), c(0, 1), c(1.2, 0.9, 0.3),
                     noise = NoiseGrid(tg, cbind(W, -W)))
ssol <- solve(nprob2, EulerHeun(), dt = 0.05)
for (sa in list(BacksolveAdjoint(), InterpolatingAdjoint()))
  print(adjoint_sensitivities(ssol, EulerHeun(), t = c(0.5, 1),
                              dgdu_discrete = function(u, p, t, i) u, sensealg = sa)$dp)
#> [1]  3.3281263 -0.2814743  1.0633915
#> [1]  3.3280829 -0.2817054  1.0659315

Discrete events, such as a dose given at a fixed time, are differentiated on SDEs as well, by the pathwise forward method and by both adjoints (an extension beyond SciMLSensitivity). A dose raises the prey at t=0.4t = 0.4 by a fraction that depends on a parameter:

dose <- PresetTimeCallback(0.4, function(integ) integ$u[1] <- integ$u[1] * (1 + integ$p[3]))
eprob <- SDEProblem(function(u, p, t) c(p[1] * u[1] - u[1] * u[2], -p[2] * u[2] + u[1] * u[2]),
                    function(u, p, t) 0.1 * u, c(1, 0.8), c(0, 1), c(1.2, 0.9, 0.3), callback = dose)
eloss <- function(sol) sum(as.matrix(sol)^2)
rbind(forward = solve_gradient(eloss, eprob, EM(), dt = 1e-3, saveat = 0.25, seed = 1)$p,
      adjoint = solve_gradient(eloss, eprob, EM(), dt = 1e-3, saveat = 0.25, seed = 1,
                               sensealg = InterpolatingAdjoint())$p)
#>             [,1]      [,2]     [,3]
#> forward 12.59786 -1.670125 12.41797
#> adjoint 12.59944 -1.670556 12.41582

The two differ at order Δt\Delta t: the adjoint integrates the continuous adjoint equation backward on the same noise path. Continuous events are refused, since the time at which a Brownian path crosses a level is not differentiable.

With a Stratonovich method such as EulerHeun() the adjoint is solved with the same scheme and needs no correction. An Ito method solved backward evaluates the adjoint noise term with the forward state at the end of each step, while the exact adjoint uses the state at its start; the adjoint drift carries the correction for this, built from the realized increments of the noise path. Without it (as in SciMLSensitivity) the gradient is biased whenever the noise is nonlinear in the state or depends on a parameter through the state, and the bias does not shrink with the step size:

mprob <- SDEProblem(function(u, p, t) -p[1] * u, function(u, p, t) p[2] * sin(u), 1, c(0, 1),
                    c(0.7, 0.4))
mloss <- function(sol) sum(as.matrix(sol)^2)
rbind(forward = unlist(solve_gradient(mloss, mprob, EM(), dt = 1 / 512, saveat = 0.25, seed = 2,
                                      sensealg = ForwardDiffSensitivity())[c("u0", "p")]),
      adjoint = unlist(solve_gradient(mloss, mprob, EM(), dt = 1 / 512, saveat = 0.25, seed = 2,
                                      sensealg = InterpolatingAdjoint())[c("u0", "p")]))
#>               u0        p1       p2
#> forward 7.870542 -3.610137 4.217304
#> adjoint 7.873141 -3.606907 4.213887

With noisemixing = TRUE the full Jacobian of a diagonal noise term enters the adjoint.

Second order sensitivities

second_order_sensitivities(loss, prob, alg, ...) returns the Hessian of a loss with respect to the parameters, and second_order_sensitivity_product(loss, v, prob, alg, ...) the product of the Hessian with a vector vv, the building block of Newton Krylov methods. Julia’s ForwardDiffOverAdjoint() runs forward mode automatic differentiation over an adjoint gradient; modelcompR takes central differences of the adjoint gradient of solve_gradient(), so the solves should use tight tolerances.

For u′=−p1p2uu' = -p_1 p_2 u, u(0)=1u(0) = 1, the loss u(1)=e−p1p2u(1) = e^{-p_1 p_2} has the Hessian e−p1p2(p22p1p2−1p1p2−1p12), e^{-p_1 p_2} \begin{pmatrix} p_2^2 & p_1 p_2 - 1 \\ p_1 p_2 - 1 & p_1^2 \end{pmatrix}, which at p=(2,0.5)p = (2, 0.5) is e−1diag⁡(0.25,4)e^{-1} \operatorname{diag}(0.25, 4).

eprob <- ODEProblem(function(u, p, t) -p[1] * p[2] * u, 1, c(0, 1), c(2, 0.5))
eloss <- function(sol) sol$u[[length(sol$t)]]
H <- second_order_sensitivities(eloss, eprob, Tsit5(), saveat = 1, reltol = 1e-12,
                                abstol = 1e-12)
round(H, 6)
#>         [,1]     [,2]
#> [1,] 0.09197 0.000000
#> [2,] 0.00000 1.471518
exp(-1) * diag(c(0.25, 4))
#>            [,1]     [,2]
#> [1,] 0.09196986 0.000000
#> [2,] 0.00000000 1.471518
second_order_sensitivity_product(eloss, c(1, 1), eprob, Tsit5(), saveat = 1,
                                 reltol = 1e-12, abstol = 1e-12)
#> [1] 0.09196984 1.47151773

Shadowing methods for chaotic systems

In a chaotic system nearby trajectories separate exponentially, so the ordinary sensitivities of a long time average grow without bound and are useless. The average itself, for example the mean height ⟨z⟩\langle z \rangle of the Lorenz attractor, still depends smoothly on the parameters. Shadowing methods compute that derivative by finding a perturbed trajectory that stays close to the original one.

  • ForwardLSS() and AdjointLSS() (least squares shadowing) solve one large least squares problem on the saved points of a solution; the regularizer TimeDilation(), CosWindowing() or Cos2Windowing() chooses how the time average is handled.
  • NILSS() and NILSAS() (non intrusive LSS and its adjoint) work in the unstable subspace only, integrating a few tangent or adjoint solutions over nseg segments of nstep saved points.

The derivative of ⟨z⟩\langle z \rangle with respect to ρ\rho is close to 1 (Lea, Allen and Haine, 2000).

lorenz <- function(u, p, t) c(p[1] * (u[2] - u[1]), u[1] * (p[2] - u[3]) - u[2],
                              u[1] * u[2] - p[3] * u[3])
u_attr <- c(-12.808828477348253, -18.197181420445414, 25.88373061170027)
lprob3 <- ODEProblem(lorenz, u_attr, c(0, 10), c(10, 28, 8 / 3))
gz <- function(u, p, t) u[3]
lsol <- solve(lprob3, Tsit5(), saveat = 0.02, reltol = 1e-8, abstol = 1e-8)
lss_f <- shadow_forward(ForwardLSSProblem(lsol, ForwardLSS(g = gz)))
lss_a <- shadow_adjoint(AdjointLSSProblem(lsol, AdjointLSS(g = gz)))
rbind(ForwardLSS = lss_f, AdjointLSS = lss_a)
#>                 [,1]     [,2]      [,3]
#> ForwardLSS 0.1289355 1.012402 -1.515039
#> AdjointLSS 0.1289355 1.012402 -1.515039

The second entry, the derivative in ρ\rho, is close to 1. NILSS integrates the tangent equations on short segments from the initial point:

nilss <- shadow_forward(NILSSProblem(lprob3, NILSS(10, 51, g = gz, seed = 1)), Tsit5(),
                        reltol = 1e-6, abstol = 1e-6)
nilss
#> [1]  0.1285218  1.0202754 -1.5470793

NILSASProblem(sol, NILSAS(nseg, nstep, M, g = g), alg) is the adjoint counterpart; it takes a dense solution and M homogeneous adjoint solutions (at least the number of positive Lyapunov exponents plus one).

Global sensitivity analysis

The methods above measure how a solution responds to small changes of the parameters at one point. Global sensitivity analysis asks which inputs drive the output over their whole range. gsa(f, method, p_range, samples = n) ports GlobalSensitivity.jl: f maps a parameter vector to a number, a vector or an ODE solution, and p_range lists the c(lower, upper) range of each parameter. The Ishigami function is the standard test case, with known first order indices 0.314, 0.442 and 0 and total indices 0.558, 0.442 and 0.244.

ishigami <- function(x) sin(x[1]) + 7 * sin(x[2])^2 + 0.1 * x[3]^4 * sin(x[1])
ranges <- rep(list(c(-pi, pi)), 3)
set.seed(1)
res <- gsa(ishigami, Sobol(order = c(0, 1, 2)), ranges, samples = 4096)
round(res$S1, 3)
#> [1] 0.312 0.443 0.001
round(res$ST, 3)
#> [1] 0.557 0.443 0.244
round(res$S2, 3)
#>      [,1]  [,2]   [,3]
#> [1,]    0 0.001  0.244
#> [2,]    0 0.000 -0.001
#> [3,]    0 0.000  0.000

Sobol() draws an Owen scrambled Sobol design of dimension 2 d and splits its rows into the matrices A and B, so every estimator sees independent pairs of uniform points and repeated runs are independent replicates. With nboot > 1 it draws nboot such designs and reports the mean with a confidence interval from the replicates. Choose the total effect estimator with Ei_estimator ("Jansen1999", "Homma1996", "Sobol2007" or "Janon2014"), and pass your own matrices with gsa(f, Sobol(), A, B); the chunk below builds the same kind of design by hand. GlobalSensitivity.jl uses the unscrambled sequence instead, which generate_design_matrices() with NoRand() reproduces. (The randomized generate_design_matrices() scrambles one d dimensional point set for every matrix, so its A and B share their base points and are strongly correlated; use it for replicated error estimates, not as a Sobol pair.)

set.seed(4)
U <- randomize(qmc_sample(4096, 6, SobolSample()), OwenScramble(2))
A <- -pi + 2 * pi * U[1:3, ]
B <- -pi + 2 * pi * U[4:6, ]
res <- gsa(ishigami, Sobol(nboot = 4), A, B, Ei_estimator = "Janon2014")
round(res$ST, 3)
#> [1] 0.565 0.450 0.248
round(res$ST_Conf_Int, 3)
#> [1] 0.002 0.004 0.000

The other methods share the interface:

round(gsa(ishigami, eFAST(), ranges, samples = 1000)$S1, 3)
#>       [,1]  [,2] [,3]
#> [1,] 0.294 0.442    0
m <- gsa(ishigami, Morris(num_trajectory = 20), ranges)
round(m$means_star, 2)
#>      [,1] [,2] [,3]
#> [1,] 2.28 4.91  1.7
round(gsa(ishigami, RegressionGSA(rank = TRUE), ranges, samples = 500)$partial_rank_correlation, 3)
#>       [,1]   [,2]  [,3]
#> [1,] 0.433 -0.008 0.001
round(gsa(ishigami, EASI(), ranges, samples = 2000)$S1, 3)
#> [1] 0.312 0.453 0.002
round(gsa(ishigami, DeltaMoment(nboot = 20), ranges, samples = 500)$deltas, 3)
#> [1] 0.177 0.230 0.149
Method Measures
Sobol() variance based first, second and total order indices
eFAST(), RBDFAST() first (and total) order indices from Fourier analysis; RBD-FAST with the Tissot and Prieur bias correction
Morris() elementary effects: means, absolute means, variances
RegressionGSA() Pearson, standardized regression and partial correlation coefficients, rank versions
DGSM() derivative based measures from forward mode gradients; tao and sigma bound the total index for uniform inputs
DeltaMoment() moment independent delta measure from kernel densities
EASI() first order indices from the spectrum of sorted samples, with a bias corrected S1_Corr
FractionalFactorial() main effects of a two level design
Shapley() Shapley effects, also for dependent inputs
RSA() regional sensitivity from accepted and rejected samples
MutualInformation() mutual information against a permutation bound

DGSM() and eFAST() also take distributions in place of ranges, and Shapley() takes a joint law with a Gaussian copula for correlated inputs:

D <- SklarDist(GaussianCopula(matrix(c(1, 0.6, 0.6, 1), 2)),
               list(univariate_distribution("norm"), univariate_distribution("norm", sd = 2)))
set.seed(2)
sh <- suppressMessages(gsa(function(x) x[1] + x[2], Shapley(n_var = 1000, n_outer = 100), D))
round(sh$shapley_effects, 3)
#> [1] 0.4 0.6

With batch = TRUE, f receives a matrix with one parameter set per column. For an ODE, return the solution: the indices come back per state and saved time.

lv <- function(u, p, t) c(p[1] * u[1] - p[2] * u[1] * u[2], -p[3] * u[2] + p[4] * u[1] * u[2])
prob <- ODEProblem(lv, c(1, 1), c(0, 5), c(1.5, 1, 3, 1))
final_prey <- function(p) {
  sol <- solve(remake(prob, p = p), Tsit5(), saveat = 5)
  sol$u[[2]][1]
}
set.seed(3)
round(gsa(final_prey, Sobol(), rep(list(c(1, 3)), 4), samples = 256)$S1, 3)
#> [1] -0.070 -0.038  0.115  0.174

The quasi Monte Carlo samplers of QuasiMonteCarlo.jl are available directly: qmc_sample(n, lb, ub, sampler) with SobolSample(), HaltonSample(), FaureSample(), LatticeRuleSample(), KroneckerSample(), GoldenSample(), LatinHypercubeSample() and others, and randomize() with OwenScramble(), MatousekScramble(), DigitalShift() or QMCShift(). The deterministic sequences match Julia bit for bit.

qmc_sample(4, c(0, 0), c(1, 10), HaltonSample())
#>       [,1]     [,2]     [,3]     [,4]
#> [1,] 0.125 0.625000 0.375000 0.875000
#> [2,] 1.250 4.583333 7.916667 2.361111

Summary

Task modelcompR Julia
forward sensitivities ODEForwardSensitivityProblem(), extract_local_sensitivities() the same
adjoint of a cost adjoint_sensitivities(), ODEAdjointProblem() the same
gradient of a loss of solve() solve_gradient(loss, prob, alg, ...) Zygote.gradient of a function calling solve
DAE, SDE, RODE adjoints DAEAdjointProblem(), SDEAdjointProblem(), RODEAdjointProblem() the same
steady states, nonlinear and optimization solutions SteadyStateAdjoint(), OptimizationAdjoint() the same
Hessians second_order_sensitivities(), second_order_sensitivity_product() the same
chaotic averages ForwardLSS(), AdjointLSS(), NILSS(), NILSAS() with shadow_forward(), shadow_adjoint() shadow_forward, shadow_adjoint
global sensitivity gsa(f, Sobol(), ranges, samples = n) and the other methods gsa of GlobalSensitivity.jl