Skip to contents

This article covers the three kinds of random dynamics that modelcompR models and simulates:

  • Stochastic differential equations (SDEs), du=f(u,p,t)dt+g(u,p,t)dWdu = f(u, p, t)\,dt + g(u, p, t)\,dW, where WW is a Brownian motion. They are built symbolically from brownian variables, as with @brownians in ModelingToolkit.jl, or directly from R functions, and they are solved by a port of the StochasticDiffEq.jl solver catalog.
  • Jump processes, where the state changes by discrete amounts at random times whose rates depend on the state: chemical reaction networks, epidemics, birth death processes. This is the JumpProcesses.jl layer.
  • Random ODEs (RODEs), u′=f(u,p,t,W(t))u' = f(u, p, t, W(t)), ordinary differential equations driven pathwise by a noise process.

All three share the noise processes of DiffEqNoiseProcess.jl, the ensemble machinery of SciMLBase and the solution interface of the deterministic solvers. Every random computation below takes a seed, so the article renders identically each time.

The time variable t_nounits and its derivative D_nounits come with the package; they are aliased to t and D here.

t <- t_nounits
D <- D_nounits

Part 1: stochastic differential equations

Brownian variables and noise equations

A brownian is a symbolic white noise term ξ(t)=dW/dt\xi(t) = dW/dt. It is declared with brownians() (the counterpart of @brownians B) or Brownian("B"), and it may appear linearly in the right hand side of a differential equation. mtkcompile() collects the coefficients of the brownians into a noise matrix and removes the brownians from the equations, exactly as ModelingToolkit does.

variables("x(t)", "y(t)")
parameters("mu = 1.5", "sigma = 0.3")
brownians("Bx")
gbm <- mtkcompile(System(list(D(x) ~ mu * x + sigma * x * Bx), t, name = "gbm"))
equations(gbm)
#> [[1]]
#> Derivative(x(t), t) ~ mu*x(t)
get_noise_eqs(gbm)
#>      [,1]      
#> [1,] sigma*x(t)

The drift mu*x(t) stays in the equation; the diffusion sigma*x(t) is now a noise equation. The shape of the noise depends on how brownians are shared between equations:

  • Diagonal noise: each equation has its own brownian. The noise is a vector with one entry per unknown, and dWdW has as many independent components as there are unknowns.
  • Scalar noise: one brownian drives every equation. The noise is a matrix with one column.
  • General (non diagonal) noise: any other pattern, for example two equations sharing a brownian and a third with its own. The noise is an n×mn \times m matrix and dWdW has mm components.

The rows of the noise follow the order of unknowns(sys), which mtkcompile() may permute; print the unknowns alongside the noise to read it.

brownians("By", "Bz")
variables("z(t)")
diag_sys <- mtkcompile(System(list(D(x) ~ -x + sigma * x * Bx, D(y) ~ -y + By), t, name = "dg"))
vapply(unknowns(diag_sys), format, "")
#> [1] "y(t)" "x(t)"
get_noise_eqs(diag_sys)
#> [[1]]
#> 1
#> 
#> [[2]]
#> sigma*x(t)
scalar_sys <- mtkcompile(System(list(D(x) ~ -x + sigma * x * Bx, D(y) ~ -y + Bx), t, name = "sc"))
get_noise_eqs(scalar_sys)
#>      [,1]      
#> [1,] 1         
#> [2,] sigma*x(t)
general_sys <- mtkcompile(System(list(D(x) ~ -x + Bx, D(y) ~ -y + 2 * Bx, D(z) ~ -z + Bz), t,
                                 name = "gn"))
vapply(unknowns(general_sys), format, "")
#> [1] "z(t)" "y(t)" "x(t)"
get_noise_eqs(general_sys)
#>      [,1] [,2]
#> [1,] 0    1   
#> [2,] 2    0   
#> [3,] 1    0

A brownian must enter linearly: D(x) ~ -x + Bx^2 is rejected by mtkcompile() because it is not an SDE in the Ito sense.

Explicit noise equations

SDESystem(eqs, noise_eqs, iv) takes the drift equations and the noise equations directly, the older ModelingToolkit form. noise_to_brownians() converts such a system back to the brownian form, naming the new brownians from names.

parameters("a", "b")
sde <- SDESystem(list(D(x) ~ a * x), list(b * x), t, name = "lin")
equations(noise_to_brownians(sde, names = "w"))
#> [[1]]
#> Derivative(x(t), t) ~ a*x(t) + b*w_1*x(t)
cs <- mtkcompile(sde)
get_noise_eqs(cs)
#>      [,1]  
#> [1,] b*x(t)

Building and solving an SDEProblem from a system

SDEProblem(sys, op, tspan) is built like an ODEProblem: the operating point op lists initial conditions and parameter values (defaults are used for anything missing). solve() picks a default algorithm when none is given: SOSRI() for diagonal noise, LambaEM() otherwise. A single equation with one brownian is scalar noise (a one column matrix), so the default here is LambaEM(). The result is an RODESolution, which supports symbolic indexing, interpolation and plot().

prob <- SDEProblem(gbm, list(x ~ 1), c(0, 1))
prob$noise_type
#> [1] "scalar"
sol <- solve(prob, seed = 1)
sol
#> RODESolution with retcode Success (LambaEM)
#> Saved time points: 119 in [0, 1]
#> Final state:
#>     x(t) 
#> 5.803962
sol$alg$name
#> [1] "LambaEM"
head(sol[x])
#> [1] 1.0000000 0.9999833 1.0005915 0.9983600 1.0032878 1.0045090
sol(0.5)
#>     x(t) 
#> 2.502796

The Brownian path of the solve is stored in sol$W, with the times sol$W$t and the values sol$W$W (one column per noise component). For geometric Brownian motion the exact Ito solution on that path is x(t)=exp⁡((μ−σ2/2)t+σW(t))x(t) = \exp((\mu - \sigma^2/2) t + \sigma W(t)), so we can measure the pathwise error of the order 0.5 default and of the order 1.5 SOSRI(), each on its own path.

exact_end <- function(s) exp((1.5 - 0.3^2 / 2) + 0.3 * tail(s$W$W, 1)[1])
sol_sri <- solve(prob, SOSRI(), seed = 1)
rbind(LambaEM = c(numeric = tail(sol[x], 1), exact = exact_end(sol)),
      SOSRI = c(tail(sol_sri[x], 1), exact_end(sol_sri)))
#>          numeric    exact
#> LambaEM 5.803962 5.875060
#> SOSRI   3.764484 3.764515
plot(sol, main = "Geometric Brownian motion, one path")

One path of geometric Brownian motion

Observed variables work as in deterministic models: an algebraic equation w ~ 2 * x is eliminated by mtkcompile() and recovered on demand.

variables("w(t)")
brownians("Bo")
osys <- mtkcompile(System(list(D(x) ~ -w + 0.1 * Bo, w ~ 2 * x), t, name = "obs"))
osol <- solve(SDEProblem(osys, list(x ~ 1), c(0, 1)), SOSRI(), seed = 1)
all.equal(osol[w], 2 * osol[x])
#> [1] TRUE

The general noise system above becomes an SDEProblem whose diffusion function returns a matrix:

gprob <- SDEProblem(general_sys, list(x ~ 1, y ~ 2, z ~ 3), c(0, 1))
gprob$noise_type
#> [1] "general"
gprob$f$g(gprob$u0, gprob$p, 0)
#>      [,1] [,2]
#> [1,]    0    1
#> [2,]    2    0
#> [3,]    1    0
gsol <- solve(gprob, seed = 2)
gsol$alg$name
#> [1] "LambaEM"
ncol(gsol$W$W)
#> [1] 2

SDEProblems from R functions

Without a symbolic model, SDEProblem(f, g, u0, tspan, p) takes the drift f(u, p, t) and diffusion g(u, p, t) as plain R functions, as in StochasticDiffEq.jl. The noise shape is declared as follows:

  • diagonal (the default): g returns a vector the length of u;
  • scalar: noise = "scalar", g returns a vector, all components share one Brownian motion;
  • general: noise_rate_prototype = matrix(0, n, m), g returns an n×mn \times m matrix.
f <- function(u, p, t) p[1] * u
g <- function(u, p, t) p[2] * u
rprob <- SDEProblem(f, g, 1, c(0, 1), c(1.5, 0.3))
solve(rprob, SRIW1(), seed = 2)$retcode
#> [1] "Success"

sp <- SDEProblem(function(u, p, t) 0 * u, function(u, p, t) c(1, 2), c(0, 0), c(0, 1),
                 noise = "scalar")
s3 <- solve(sp, EM(), dt = 0.1, seed = 5)
all.equal(2 * s3[1], s3[2])
#> [1] TRUE

gp <- SDEProblem(function(u, p, t) -u, function(u, p, t) matrix(c(0.1, 0, 0.05, 0.2), 2, 2),
                 c(1, 1), c(0, 1), noise_rate_prototype = matrix(0, 2, 2))
solve(gp, LambaEM(), seed = 3)$retcode
#> [1] "Success"

SDEFunction(f, g, mass_matrix = M) wraps the functions with extra information; a singular mass matrix turns the SDE into a stochastic DAE, solved by the drift implicit methods (see below).

Seeds and reproducibility

Every solve() takes seed. The same seed gives the same path, and a seeded solve leaves the session’s random number generator untouched, so seeded solves can be mixed freely with other random code. Without a seed the solve draws from the session generator, so set.seed() also makes it reproducible.

a1 <- solve(rprob, EM(), dt = 0.01, seed = 42)
a2 <- solve(rprob, EM(), dt = 0.01, seed = 42)
identical(a1$u, a2$u)
#> [1] TRUE
set.seed(1); r1 <- runif(1)
set.seed(1); invisible(solve(rprob, EM(), dt = 0.01, seed = 99)); r2 <- runif(1)
identical(r1, r2)
#> [1] TRUE

Ito and Stratonovich

An SDE can be read in the Ito sense, where the integrand is evaluated at the start of each interval, or in the Stratonovich sense (midpoint evaluation). For dx=μxdt+σxdWdx = \mu x\,dt + \sigma x\,dW the Ito solution is exp⁡((μ−σ2/2)t+σW)\exp((\mu - \sigma^2/2)t + \sigma W) while the Stratonovich solution is exp⁡(μt+σW)\exp(\mu t + \sigma W). Each algorithm carries its interpretation: EM() is Ito, EulerHeun() its Stratonovich counterpart.

EM()$interpretation
#> [1] "Ito"
EulerHeun()$interpretation
#> [1] "Stratonovich"
RKMil(interpretation = "Stratonovich")$interpretation
#> [1] "Stratonovich"
p2 <- SDEProblem(function(u, p, t) 1.01 * u, function(u, p, t) 0.87 * u, 0.5, c(0, 1))
ito <- solve(p2, EM(), dt = 1 / 512, seed = 7)
strat <- solve(p2, EulerHeun(), dt = 1 / 512, seed = 7)
Wend <- tail(ito$W$W, 1)[1]
rbind(Ito = c(numeric = tail(ito$u, 1)[[1]], exact = 0.5 * exp(1.01 - 0.87^2 / 2 + 0.87 * Wend)),
      Stratonovich = c(tail(strat$u, 1)[[1]], 0.5 * exp(1.01 + 0.87 * Wend)))
#>               numeric    exact
#> Ito          1.766335 1.771254
#> Stratonovich 2.583392 2.586066

The two readings of the same equations differ by a drift correction ±12g∂ug\pm\frac12 g\,\partial_u g. stochastic_integral_transform(sys, c) adds c times that correction, so -1/2 converts an Ito system to the equivalent Stratonovich system and 1/2 converts back:

st <- stochastic_integral_transform(sde, -1/2)
equations(st)
#> [[1]]
#> Derivative(x(t), t) ~ a*x(t) - 0.5*b^2*x(t)
equations(stochastic_integral_transform(st, 1/2))
#> [[1]]
#> Derivative(x(t), t) ~ a*x(t)

The Girsanov transform

Girsanov_transform(sys, u, theta0) changes the probability measure so that the drift of the observable u is modified, and adds an unknown, the likelihood weight, that must multiply every sample. In ModelingToolkit this is used to reduce the variance of Monte Carlo estimates. The result has two unknowns, a two row noise matrix and an observed weight.

gm <- Girsanov_transform(sde, x, theta0 = 0.1)
unknowns(gm)
#> [[1]]
#> x(t)
#> 
#> [[2]]
#> θ(t)
equations(gm)
#> [[1]]
#> Derivative(x(t), t) ~ a*x(t) + b^2*x(t) 
#> 
#> [[2]]
#> Derivative(θ(t), t) ~ 0
get_noise_eqs(gm)
#>      [,1]   
#> [1,] b*x(t) 
#> [2,] -b*θ(t)
observed(gm)
#> [[1]]
#> weight(t) ~ 10.0*θ(t)

The solver catalog

modelcompR ports the StochasticDiffEq.jl algorithms under their Julia names. The families are summarized here and exercised below.

Family Algorithms Noise Notes
Euler type EM, EulerHeun, LambaEM, LambaEulerHeun, SimplifiedEM, SplitEM, PCEuler any strong order 0.5; Lamba methods adapt
Milstein RKMil, RKMilCommute, RKMilGeneral, WangLi3SMil_A to _F diagonal, scalar, commutative, general strong order 1
Roessler SRI SRIW1, SRIW2, SOSRI, SOSRI2, SRI(tableau) diagonal, scalar strong order 1.5, adaptive
Roessler SRA SRA1, SRA2, SRA3, SOSRA, SOSRA2, SRA(tableau) additive strong order 1.5, adaptive
Implicit ImplicitEM, STrapezoid, SImplicitMidpoint, ImplicitEulerHeun, ImplicitRKMil, ISSEM, ISSEulerHeun, SKenCarp any (SKenCarp additive) stiff drift, mass matrices
Stabilized SROCK1, SROCK2, SROCKEM, SKSROCK, TangXiaoSROCK2, KomBurSROCK2, SROCKC2 any stiff drift without linear solves, fixed step
Weak DRI1, DRI1NM, RI1, RI3, RI5, RI6, RDI1WM to RDI4WM, RS1, RS2, PL1WM, PL1WMA, NON, NON2, COM, SIEA, SIEB, SMEA, SMEB, W2Ito1, IRI1 various match moments, not paths
Split and dynamical IIF1M, IIF2M, IIF1Mil, BAOAB various SplitSDEProblem, DynamicalSDEProblem
Composite AutoSOSRI2, AutoSOSRA2, AutoAlgSwitch, StochasticCompositeAlgorithm any switch on stiffness

Fixed step methods need dt; adaptive methods accept abstol and reltol and use rejection sampling with memory (RSwM), so rejected steps do not bias the Brownian path. Every adaptive method also runs on a fixed grid with adaptive = FALSE, dt = h.

Strong order of convergence

The strong order measures the pathwise error. On geometric Brownian motion with many independent components (diagonal noise on a vector state) we can estimate it from the slope of the log error against the log step size.

N <- 100
cprob <- SDEProblem(function(u, p, t) u, function(u, p, t) 0.5 * u, rep(1, N), c(0, 1))
dts <- 2^-(3:6)
slope <- function(alg) {
  errs <- vapply(seq_along(dts), function(i) {
    s <- solve(cprob, alg, dt = dts[i], adaptive = FALSE, seed = 100 + i)
    Wn <- s$W$W[nrow(s$W$W), ]
    mean(abs(s$u[[length(s$t)]] - exp(1 - 0.125 + 0.5 * Wn)))
  }, 0)
  unname(coef(lm(log(errs) ~ log(dts)))[2])
}
round(c(EM = slope(EM()), RKMil = slope(RKMil()), SRIW1 = slope(SRIW1())), 2)
#>    EM RKMil SRIW1 
#>  0.45  0.89  1.27

The slopes are close to the theoretical orders 0.5, 1 and 1.5.

Additive noise

When the diffusion does not depend on the state the SRA methods reach order 1.5 cheaply. For du=cos⁡(t)dt+0.3dWdu = \cos(t)\,dt + 0.3\,dW the exact solution is 1+sin⁡(t)+0.3W(t)1 + \sin(t) + 0.3 W(t).

add <- SDEProblem(function(u, p, t) cos(t) + 0 * u, function(u, p, t) 0.3 + 0 * u, 1, c(0, 1))
vapply(list(SRA1(), SRA3(), SOSRA(), SKenCarp()), function(alg) {
  s <- solve(add, alg, dt = 1 / 16, adaptive = FALSE, seed = 2)
  abs(tail(s$u, 1)[[1]] - (1 + sin(1) + 0.3 * tail(s$W$W, 1)[1]))
}, 0)
#> [1] 6.906897e-05 4.458792e-09 3.432131e-05 3.469766e-08

The default algorithm follows the alg_hints of StochasticDiffEq: "additive", "commutative", "stiff" and "stratonovich".

solve(add, alg_hints = "additive", seed = 1)$alg$name
#> [1] "SOSRA"
solve(add, alg_hints = c("additive", "stiff"), seed = 1)$alg$name
#> [1] "SKenCarp"

Stiff problems: implicit and stabilized methods

A stiff drift (here a diffusion operator on ten grid points) forces explicit methods to tiny steps. The drift implicit methods solve a nonlinear system each step; the stabilized Chebyshev methods (SROCK family) instead use many cheap stages whose number grows with the spectral radius of the drift Jacobian.

n <- 10
lap <- function(u, p, t) (c(0, u[-n]) - 2 * u + c(u[-1], 0)) * (n + 1)^2
stiff <- SDEProblem(lap, function(u, p, t) 0.1 * u, rep(1, n), c(0, 0.5))
fin_u <- function(s) tail(s$u, 1)[[1]][1:5]
deterministic <- fin_u(solve(ODEProblem(lap, rep(1, n), c(0, 0.5)), Rodas5P()))
round(rbind(deterministic,
            ImplicitEM = fin_u(solve(stiff, ImplicitEM(), dt = 0.05, adaptive = FALSE, seed = 1)),
            SROCK1 = fin_u(solve(stiff, SROCK1(), dt = 0.05, seed = 1)),
            SROCK2 = fin_u(solve(stiff, SROCK2(), dt = 0.05, seed = 1)),
            SROCKEM = fin_u(solve(stiff, SROCKEM(eigen_est = 4 * (n + 1)^2), dt = 0.05, seed = 1))), 4)
#>                 [,1]   [,2]   [,3]   [,4]   [,5]
#> deterministic 0.0026 0.0051 0.0071 0.0086 0.0093
#> ImplicitEM    0.0066 0.0128 0.0179 0.0215 0.0234
#> SROCK1        0.0020 0.0039 0.0055 0.0065 0.0073
#> SROCK2        0.0042 0.0044 0.0079 0.0098 0.0094
#> SROCKEM       0.0020 0.0040 0.0055 0.0066 0.0073

The spectral radius of the drift is about 4(n+1)2≈4804(n+1)^2 \approx 480, so explicit Euler needs dt<2/480≈0.004dt < 2/480 \approx 0.004; the methods above take ten steps of 0.05, remain stable and stay at the scale of the noise free solution (the noise here is small). The remaining differences are the first order time discretization error: implicit Euler, for instance, damps the slowest mode by (1+9.8dt)−10(1 + 9.8\,dt)^{-10} instead of e−4.9e^{-4.9}. The stabilized methods estimate the spectral radius by a power iteration unless eigen_est gives it. The other stabilized methods (SKSROCK, KomBurSROCK2, SROCKC2, TangXiaoSROCK2(version_num)) are called the same way; in this example they damp the stiffest modes only weakly at dt=0.05dt = 0.05 and need smaller steps for a smooth result.

Implicit methods also handle a singular mass matrix: here x′=−x+zx' = -x + z, 0=z−2x0 = z - 2x with noise 0.1xdW0.1\,x\,dW.

mm <- SDEProblem(SDEFunction(function(u, p, t) c(-u[1] + u[2], u[2] - 2 * u[1]),
                             function(u, p, t) c(0.1 * u[1], 0), mass_matrix = diag(c(1, 0))),
                 c(1, 2), c(0, 1))
ms <- solve(mm, ImplicitEM(), dt = 0.01, adaptive = FALSE, seed = 1)
u_end <- tail(ms$u, 1)[[1]]
c(u_end, constraint = u_end[2] - 2 * u_end[1])
#>                       constraint 
#>   2.923177   5.846353   0.000000

Composite algorithms

AutoSOSRI2(stiff_alg) starts with the nonstiff SOSRI2 and switches to the stiff method while a stiffness estimate is large; AutoAlgSwitch(nonstiff, stiff) pairs any two methods and StochasticCompositeAlgorithm(algs, choice) takes a custom choice function. sol$alg_choice records which method took each step. The decay rate below rises from 1 to about 500 in the middle of the interval; once the problem turns stiff the solve switches to ImplicitRKMil() for a few steps. maxstiffstep and maxnonstiffstep set how many consecutive steps must look stiff (or nonstiff) before a switch.

cp <- SDEProblem(function(u, p, t) -(1 + 8000 * t^2 * (1 - t)^2) * u, function(u, p, t) 0.1 * u,
                 1, c(0, 1))
csol <- solve(cp, AutoSOSRI2(ImplicitRKMil(), maxstiffstep = 2, maxnonstiffstep = 1), dt = 0.01,
              seed = 1)
table(csol$alg_choice)
#> 
#>   1   2 
#> 492   8
range(csol$t[csol$alg_choice == 2])
#> [1] 0.4463442 1.0000000

Weak methods

When only expectations matter (option prices, moments), weak methods are cheaper: they replace the Gaussian increments by discrete random variables that match the first moments. Here DRI1 (weak order 2) estimates E[u(1)]=0.5e1.01E[u(1)] = 0.5\,e^{1.01} for geometric Brownian motion du=1.01udt+0.3udWdu = 1.01u\,dt + 0.3u\,dW with an ensemble (see the ensemble section below).

wprob <- SDEProblem(function(u, p, t) 1.01 * u, function(u, p, t) 0.3 * u, 0.5, c(0, 1))
wsim <- solve(EnsembleProblem(wprob), DRI1(), trajectories = 1000, dt = 0.1, adaptive = FALSE,
              seed = 2)
mv <- timepoint_meanvar(wsim, 1)
c(estimate = mv$mean, std_error = sqrt(mv$var / 1000), exact = 0.5 * exp(1.01))
#>   estimate  std_error      exact 
#> 1.39201179 0.01331518 1.37280051

Ten steps per path suffice; the remaining difference is Monte Carlo error, of the size of the standard error.

Split and dynamical problems

SplitSDEProblem(f1, f2, g, u0, tspan) separates a linear drift part f1 (here returning the coefficient) from a nonlinear part f2; the integrating factor methods IIF1M, IIF2M and IIF1Mil treat f1 exactly. DynamicalSDEProblem(f1, f2, g, v0, u0, tspan) describes Langevin dynamics with velocity v and position u, solved by BAOAB(gamma).

spl <- SplitSDEProblem(function(u, p, t) -1.3, function(u, p, t) 0.4 * u + 0.1 * t,
                       function(u, p, t) 0.3 * u, 0.8, c(0, 1))
tail(solve(spl, IIF1M(), dt = 1 / 16, seed = 1)$u, 1)
#> [[1]]
#> [1] 0.3914724
lang <- DynamicalSDEProblem(function(v, u, p, t) -u - 0.1 * u^3, function(v, u, p, t) v,
                            function(v, u, p, t) 0.3 + 0.1 * u, 0.5, 1, c(0, 1))
tail(solve(lang, BAOAB(gamma = 0.7), dt = 1 / 16, seed = 1)$u, 1)
#> [[1]]
#> [1] -0.4819170  0.9790929

Noise processes

The Brownian motion of a solve is a noise process object. The processes of DiffEqNoiseProcess.jl are available and can be simulated on their own with NoiseProblem(process, tspan), or passed to SDEProblem(..., noise =) and RODEProblem(..., noise =) to replace the default Wiener process.

wp <- solve(NoiseProblem(WienerProcess(0, 0), c(0, 1)), dt = 0.1, seed = 1)
wp
#> WienerProcess at t = 1 with 11 saved points
wp(0.55)
#> [1] 0.02308419

Evaluating a process between its grid points samples a Brownian bridge and stores the new point, so later evaluations are consistent with it.

The other processes are constructed with their parameters (see ?WienerProcess for the full list):

ou <- solve(NoiseProblem(OrnsteinUhlenbeckProcess(2, 1, 0.5, 0, 1), c(0, 3)), dt = 0.5, seed = 4)
round(unlist(ou$W), 3)
#> [1] 1.000 1.050 0.892 1.168 1.200 1.454 1.327
bb <- solve(NoiseProblem(BrownianBridge(0, 1, 0, 2), c(0, 1)), dt = 0.25, seed = 5)
round(unlist(bb$W), 3)
#> [1] 0.000 0.136 1.322 1.217 2.000
gb <- solve(NoiseProblem(GeometricBrownianMotionProcess(0.1, 0.2, 0, 1), c(0, 1)), dt = 0.25, seed = 6)
round(unlist(gb$W), 3)
#> [1] 1.000 1.048 1.004 1.117 1.355
cpp <- solve(NoiseProblem(CompoundPoissonProcess(5, 0, 0), c(0, 2)), dt = 0.5, seed = 7)
unlist(cpp$W)
#> [1]  0  7  9 10 10
cw <- solve(NoiseProblem(CorrelatedWienerProcess(matrix(c(1, 0.9, 0.9, 1), 2), 0, c(0, 0)), c(0, 1)),
            dt = 0.01, seed = 8)
cor(diff(do.call(rbind, cw$W)))[1, 2]
#> [1] 0.9133145

The OU process has stationary mean 1, the bridge ends at 2, the geometric process stays positive, the compound Poisson process counts events, and the correlated Wiener process has increments with correlation close to 0.9. GeometricBrownianBridge, OrnsteinUhlenbeckBridge, CompoundPoissonBridge, RealWienerProcess, SimpleWienerProcess and BoxWedgeTail are also exported.

Path based noises fix the noise in advance:

  • NoiseGrid(t, W) interpolates given values (and optionally Z values for the methods that need a second process); it cannot extrapolate.
  • NoiseFunction(t0, W) evaluates a function of time.
  • VirtualBrownianTree(t0, W0, tend, seed) produces a Brownian path that can be queried at any time in any order without storing it.
  • NoiseWrapper(sol) replays the noise of an earlier solve, and pCN(noise, rho) builds a correlated perturbation of it (preconditioned Crank Nicolson).
ng <- NoiseGrid(seq(0, 1, 0.5), c(0, 1, 3))
ng(0.75)
#> [1] 2
nf <- NoiseFunction(0, function(u, p, t) sin(t))
nf(1)
#> [1] 0.841471
vbt <- VirtualBrownianTree(0, 0, tend = 1, seed = 10)
identical(vbt(0.3), vbt(0.3))
#> [1] TRUE

A NoiseGrid makes an SDE solve deterministic: with dWdW increments of 0.01 on each step of a unit time interval, du=dWdu = dW ends at the grid value.

tg <- seq(0, 1, by = 0.01)
Wg <- cumsum(c(0, rep(0.01, 100)))
sg <- solve(SDEProblem(function(u, p, t) 0, function(u, p, t) 1, 0, c(0, 1), noise = NoiseGrid(tg, Wg)),
            EM(), dt = 0.1)
tail(sg$u, 1)[[1]]
#> [1] 1

NoiseWrapper lets two solvers run on the same Brownian path, which is how pathwise comparisons are made:

base <- solve(p2, SRIW1(), seed = 3)
replay <- solve(SDEProblem(function(u, p, t) 1.01 * u, function(u, p, t) 0.87 * u, 0.5, c(0, 1),
                           noise = NoiseWrapper(base$W)), EM(), dt = 1 / 256)
c(SRIW1 = tail(base$u, 1)[[1]], EM_same_path = tail(replay$u, 1)[[1]],
  exact = 0.5 * exp(1.01 - 0.87^2 / 2 + 0.87 * tail(base$W$W, 1)[1]))
#>        SRIW1 EM_same_path        exact 
#>     2.813433     2.956518     2.807694

Both solves see the same Brownian path, so their difference is the discretization error alone: the order 1.5 SRIW1 is much closer to the exact value than Euler Maruyama with 256 steps.

An SDE driven by an Ornstein Uhlenbeck process instead of white noise:

s_ou <- solve(SDEProblem(function(u, p, t) -u, function(u, p, t) 0.1, 1, c(0, 1),
                         noise = OrnsteinUhlenbeckProcess(1, 0, 0.3, 0, 1)), EM(), dt = 0.01, seed = 2)
s_ou$retcode
#> [1] "Success"

Ensembles of SDE paths

A single path says little about a stochastic model. EnsembleProblem(prob) repeats a problem; solve(ens, alg, trajectories = n, seed = s) returns an EnsembleSolution, a list of solutions. prob_func(prob, i, repeat_) can alter the problem of trajectory i (for example its initial condition) and output_func(sol, i) can reduce each solution as it is produced.

ens <- EnsembleProblem(prob)
sim <- solve(ens, EM(), trajectories = 100, dt = 0.02, seed = 42)
length(sim)
#> [1] 100
summ <- EnsembleSummary(sim, ts = c(0, 0.5, 1))
summ
#> EnsembleSummary of 100 trajectories at 3 times
cbind(t = summ$t, mean = summ$u[, 1], exact_mean = exp(1.5 * summ$t), q05 = summ$qlow[, 1],
      q95 = summ$qhigh[, 1])
#>        t     mean exact_mean      q05      q95
#> [1,] 0.0 1.000000   1.000000 1.000000 1.000000
#> [2,] 0.5 2.096020   2.117000 1.458706 2.769327
#> [3,] 1.0 4.246859   4.481689 2.573239 6.657230

EnsembleSummary() gives the mean, variance and a quantile band at chosen times, and has a plot() method:

plot(EnsembleSummary(sim, ts = seq(0, 1, by = 0.1)))

Ensemble mean and quantile band of geometric Brownian motion

The analysis functions of SciMLBase’s EnsembleAnalysis are also available: timepoint_mean, timepoint_meanvar, timepoint_median, timepoint_quantile, timestep_mean, timeseries_steps_mean, timeseries_point_mean, timeseries_point_meancov, componentwise_meanvar and their relatives.

timepoint_meanvar(sim, 1)
#> $mean
#> [1] 4.246859
#> 
#> $var
#> [1] 1.763549
timepoint_quantile(sim, 0.9, 1)
#> [1] 5.661024
dim(timeseries_steps_mean(sim)$u)
#> [1] 51  1

A prob_func that randomizes the initial condition:

pf <- function(prob, i, repeat_) remake(prob, u0 = runif(1, 0.5, 1.5))
sim2 <- solve(EnsembleProblem(prob, prob_func = pf), EM(), trajectories = 50, dt = 0.05, seed = 3)
range(vapply(seq_len(length(sim2)), function(i) sim2[[i]]$u[[1]], 0))
#> [1] 0.5011317 1.4970992

Trajectories can run in parallel with EnsembleThreads(cores = k). Each trajectory has its own random stream, so the result does not depend on the number of workers.

e1 <- solve(ens, EM(), EnsembleThreads(cores = 1), trajectories = 8, dt = 0.05, seed = 1)
e2 <- solve(ens, EM(), EnsembleThreads(cores = 2), trajectories = 8, dt = 0.05, seed = 1)
fin <- function(s) vapply(seq_len(length(s)), function(i) tail(s[[i]]$u, 1)[[1]], 0)
all.equal(fin(e1), fin(e2))
#> [1] TRUE

Part 2: jump processes

A jump process changes its state by discrete amounts at random times. Each jump has a rate (propensity) a(u,p,t)a(u, p, t) and an affect, the change it makes. JumpProcesses.jl, and this port, distinguish:

  • ConstantRateJump(rate, affect): the rate changes only when a jump fires (it may depend on the state, but not continuously on time).
  • VariableRateJump(rate, affect): the rate changes between jumps, because it depends on time or on states that follow an ODE or SDE. The rate is integrated along with the continuous dynamics.
  • MassActionJump and SymbolicMassActionJump: reactions with mass action rates, given by reactant and net stoichiometries. They are the most efficient form.

Symbolic jumps live in a JumpSystem (the ModelingToolkit JumpSystem, or a System with jumps =). JumpProblem(sys, op, tspan, aggregator = ) builds the problem; the aggregator is the stochastic simulation algorithm that picks the next jump.

A birth death process

Births at rate λ\lambda and deaths at rate μX\mu X: the mean count is λμ(1−e−μt)\frac{\lambda}{\mu}(1 - e^{-\mu t}), and X(t)X(t) is Poisson distributed.

variables("X(t)")
parameters("lam = 10", "mu_d = 1")
birth <- SymbolicMassActionJump(lam, list(), list(X ~ 1))
death <- SymbolicMassActionJump(mu_d, list(X ~ 1), list(X ~ -1))
bd <- mtkcompile(JumpSystem(list(birth, death), t, name = "bd"))
unknowns(bd)
#> [[1]]
#> X(t)
jprob <- JumpProblem(bd, list(X ~ 0), c(0, 5))
class(jprob$prob)
#> [1] "DiscreteProblem" "SciMLProblem"
bsol <- solve(jprob, seed = 1)
length(bsol$t)
#> [1] 104
tail(bsol[X], 1)
#> [1] 12

A pure jump problem wraps a DiscreteProblem and is stepped by SSAStepper() (the default). The solution is piecewise constant.

plot(bsol$t, bsol[X], type = "s", xlab = "t", ylab = "X", main = "Birth death process")
curve(10 * (1 - exp(-x)), add = TRUE, lty = 2)

One path of a birth death process

Aggregators

The aggregators of JumpProcesses.jl are all exported: Direct() (Gillespie’s direct method), SortingDirect(), NRM() (next reaction method), DirectCR() and RSSACR() (composition rejection), RSSA() (rejection SSA), RDirect(), CCNRM(), FRM() (first reaction method), DirectFW(), FRMFW() and Coevolve() (for bounded variable rate jumps). All sample the same law; they differ in cost on large networks. ModelingToolkit builds the dependency graphs that NRM, RSSA and others need.

ts <- 1:3
exact <- 10 * (1 - exp(-ts))
agg_mean <- function(agg, seed) {
  jp <- JumpProblem(bd, list(X ~ 0), c(0, 3), aggregator = agg, save_positions = c(FALSE, FALSE))
  s <- solve(EnsembleProblem(jp), SSAStepper(), trajectories = 60, saveat = 1, seed = seed)
  EnsembleSummary(s, ts = ts)$u[, 1]
}
res <- rbind(exact = exact, Direct = agg_mean(Direct(), 1), SortingDirect = agg_mean(SortingDirect(), 2),
             NRM = agg_mean(NRM(), 3), RSSA = agg_mean(RSSA(), 4), DirectCR = agg_mean(DirectCR(), 5))
colnames(res) <- paste0("t=", ts)
round(res, 2)
#>                t=1  t=2   t=3
#> exact         6.32 8.65  9.50
#> Direct        5.75 8.22  9.80
#> SortingDirect 5.85 8.67  9.38
#> NRM           6.42 8.57  9.58
#> RSSA          6.55 8.85  9.40
#> DirectCR      5.87 8.50 10.18

save_positions = c(FALSE, FALSE) turns off saving before and after every jump, and saveat then fixes the output times.

An SIR epidemic with constant rate jumps

ConstantRateJump(rate, affect) with symbolic arguments: the affect is a list of equations in which Pre(S) is the value just before the jump.

variables("S(t)", "I(t)", "R(t)")
parameters("beta", "gamma")
infection <- ConstantRateJump(beta * S * I, list(S ~ Pre(S) - 1, I ~ Pre(I) + 1))
recovery <- ConstantRateJump(gamma * I, list(I ~ Pre(I) - 1, R ~ Pre(R) + 1))
sir <- complete(JumpSystem(list(infection, recovery), t, list(S, I, R), list(beta, gamma), name = "sir"))
Npop <- 300
op <- list(S ~ Npop - 10, I ~ 10, R ~ 0, beta ~ 0.3 / Npop, gamma ~ 0.1)
sir_prob <- JumpProblem(sir, op, c(0, 40), save_positions = c(FALSE, FALSE))
sir_sim <- solve(EnsembleProblem(sir_prob), trajectories = 25, saveat = 0:40, seed = 7)
sir_summ <- EnsembleSummary(sir_sim, ts = c(10, 20, 30, 40))
round(sir_summ$u, 1)
#>       S(t) I(t)  R(t)
#> [1,] 221.8 52.6  25.6
#> [2,] 107.1 92.0 101.0
#> [3,]  49.2 67.2 183.6
#> [4,]  30.8 35.3 233.9

The ensemble mean is close to the solution of the mean field ODE, which we can build from the same symbols:

ode <- mtkcompile(System(list(D(S) ~ -beta * S * I, D(I) ~ beta * S * I - gamma * I, D(R) ~ gamma * I),
                         t, name = "sirode"))
osol <- solve(ODEProblem(ode, op, c(0, 40)), Tsit5())
round(osol(c(10, 20, 30, 40), idxs = list(S, I, R)), 1)
#>       S(t) I(t)  R(t)
#> [1,] 222.1 51.2  26.7
#> [2,] 101.9 93.5 104.6
#> [3,]  44.1 67.6 188.3
#> [4,]  26.7 34.8 238.5
plot(NULL, xlim = c(0, 40), ylim = c(0, 120), xlab = "t", ylab = "I", main = "SIR jump paths")
for (i in 1:10) lines(sir_sim[[i]]$t, sir_sim[[i]][I], col = "grey60")
lines(osol$t, osol[I], lwd = 2)

Infected count over time for several SIR jump paths

Mass action jumps with indices

MassActionJump(rates, reactant_stoch, net_stoch) is the index based form of JumpProcesses.jl: each reaction lists c(species, count) pairs. The isomerization A⇌BA \rightleftharpoons B:

maj <- MassActionJump(c(1, 1), list(list(c(1, 1)), list(c(2, 1))),
                      list(list(c(1, -1), c(2, 1)), list(c(1, 1), c(2, -1))))
iso <- JumpProblem(DiscreteProblem(c(150, 50), c(0, 10)), NRM(), maj,
                   dependencies = list(dep_graph = list(1:2, 1:2)))
tail(solve(iso, SSAStepper(), seed = 1)$u, 1)
#> [[1]]
#> [1]  92 108

Without a symbolic system, NRM() needs the dependency graph explicitly (JumpDependencies() builds one too).

Jumps from R functions

As in Julia, rates are rate(u, p, t) and affects modify the integrator in place: integ$u[1] <- integ$u[1] + 1.

b_r <- ConstantRateJump(function(u, p, t) 10, function(integ) integ$u[1] <- integ$u[1] + 1)
d_r <- ConstantRateJump(function(u, p, t) u[1], function(integ) integ$u[1] <- integ$u[1] - 1)
raw <- JumpProblem(DiscreteProblem(0, c(0, 5)), Direct(), b_r, d_r)
tail(solve(raw, SSAStepper(), seed = 1)$u, 1)
#> [[1]]
#> [1] 12

Variable rate jumps and jumps coupled to ODEs

A VariableRateJump with a time dependent rate k(sin⁡t+1)k(\sin t + 1) needs a continuous problem, so JumpProblem() builds an ODEProblem and the rate is integrated by the ODE solver. The expected count by time TT is k(T+1−cos⁡T)k(T + 1 - \cos T).

variables("A(t)")
parameters("k")
vrj <- VariableRateJump(k * (sin(t) + 1), list(A ~ Pre(A) + 1))
vjs <- complete(JumpSystem(list(vrj), t, list(A), list(k), name = "vjs"))
vjp <- JumpProblem(vjs, list(A ~ 0, k ~ 1), c(0, 6))
class(vjp$prob)
#> [1] "ODEProblem"   "SciMLProblem"
vsim <- solve(EnsembleProblem(vjp), Tsit5(), trajectories = 30, saveat = 6, seed = 11)
c(estimate = EnsembleSummary(vsim, ts = 6)$u[1, 1], exact = 6 + 1 - cos(6))
#> estimate    exact 
#> 5.866667 6.039830

Jumps can also be added to an ODE model with System(..., jumps = ): the continuous unknowns evolve by the ODE and the jumps act between steps.

variables("Xc(t)", "Yc(t)")
parameters("kc = 2")
cj <- ConstantRateJump(kc, list(Xc ~ Pre(Xc) + 1))
hyb <- complete(System(list(D(Yc) ~ -Yc), t, list(Xc, Yc), list(kc), jumps = list(cj), name = "hyb"))
hsol <- solve(JumpProblem(hyb, list(Xc ~ 0, Yc ~ 1), c(0, 5), save_positions = c(FALSE, FALSE)),
              Tsit5(), saveat = 1, seed = 4)
rbind(t = hsol$t, X = hsol[Xc], Y = round(hsol[Yc], 4))
#>   [,1]   [,2]   [,3]   [,4]    [,5]    [,6]
#> t    0 1.0000 2.0000 3.0000  4.0000  5.0000
#> X    0 3.0000 5.0000 6.0000 11.0000 14.0000
#> Y    1 0.3679 0.1353 0.0498  0.0183  0.0067

Poissonians

poissonians(dN = rate) declares the increment of a Poisson counting process, ModelingToolkit’s @poissonians. Written linearly in a differential equation, D(x) ~ f + h * dN, it becomes a jump at mtkcompile(): a constant rate jump when the rate depends only on parameters, a variable rate jump otherwise.

variables("Xp(t)", "Yp(t)")
parameters("lp = 2", "kp = 0.5")
poissonians(dNp = lp, dMp = kp * Xp)
pp <- mtkcompile(System(list(D(Xp) ~ dNp - dMp, D(Yp) ~ -Yp + 3 * dNp), t, name = "pp"))
vapply(jumps(pp), function(j) class(j)[1], "")
#> [1] "VariableRateJump" "ConstantRateJump"
solve(JumpProblem(pp, list(Xp ~ 0, Yp ~ 0), c(0, 2)), seed = 2)$retcode
#> [1] "Success"

Jump diffusions

Brownians and jumps in one system give a jump diffusion; JumpProblem() then wraps an SDEProblem and any SDE solver applies.

variables("Xj(t)")
parameters("kj = 1")
brownians("Bj")
jd <- mtkcompile(System(list(D(Xj) ~ -kj * Xj + sqrt(kj) * Bj), t, name = "jd",
                        jumps = list(SymbolicMassActionJump(kj, list(Xj ~ 1), list(Xj ~ -1)))))
jdp <- JumpProblem(jd, list(Xj ~ 10), c(0, 1))
class(jdp$prob)
#> [1] "SDEProblem"   "SciMLProblem"
jds <- solve(jdp, SOSRI(), seed = 4)
jds$retcode
#> [1] "Success"
tail(jds[Xj], 1)
#> [1] 0.1561321

Regular jumps and tau leaping

For large populations, simulating each jump is wasteful. Tau leaping fires a Poisson number of each reaction per step of length τ\tau. A RegularJump(rate, c, numjumps) gives the vector of rates and the state change c(u, p, t, counts, mark) for given counts; PureLeaping() marks the problem as a leaping problem.

rj <- RegularJump(function(u, p, t) 0.1 * u[1], function(u, p, t, counts, mark) -counts[1], 1)
decay <- JumpProblem(DiscreteProblem(20, c(0, 2)), PureLeaping(), rj)
v <- vapply(1:100, function(i) tail(solve(decay, SimpleTauLeaping(), dt = 0.05, seed = i)$u, 1)[[1]], 0)
c(estimate = mean(v), exact = 20 * exp(-0.2))
#> estimate    exact 
#> 16.42000 16.37462

The SIR model as a regular jump, solved with the tau leaping methods of StochasticDiffEq (TauLeaping, CaoTauLeaping, ImplicitTauLeaping, ThetaTrapezoidalTauLeaping) and JumpProcesses (SimpleTauLeaping, SimpleExplicitTauLeaping, SimpleImplicitTauLeaping, SimpleTrapezoidalLeaping, SimpleAdaptiveTauLeaping):

sir_rate <- function(u, p, t) c(0.1 / 1000 * u[1] * u[2], 0.01 * u[2])
sir_c <- function(u, p, t, counts, mark) c(-counts[1], counts[1] - counts[2], counts[2])
jsir <- JumpProblem(DiscreteProblem(c(999, 10, 0), c(0, 250)), PureLeaping(), RegularJump(sir_rate, sir_c, 2))
round(rbind(SimpleTauLeaping = tail(solve(jsir, SimpleTauLeaping(), dt = 1, seed = 1)$u, 1)[[1]],
            TauLeaping = tail(solve(jsir, TauLeaping(), dt = 1, seed = 1)$u, 1)[[1]],
            CaoTauLeaping = tail(solve(jsir, CaoTauLeaping(), dt = 1, seed = 1)$u, 1)[[1]]), 1)
#>                  [,1] [,2] [,3]
#> SimpleTauLeaping    0  143  866
#> TauLeaping          2  137  870
#> CaoTauLeaping       0  134  875

The mass action form works with the leaping methods too, including the adaptive one that chooses τ\tau itself:

leap <- JumpProblem(DiscreteProblem(c(150, 50), c(0, 10)), PureLeaping(), maj)
solve(leap, SimpleAdaptiveTauLeaping(), seed = 1, saveat = c(1, 10))$u
#> [[1]]
#> [1]  98 102
#> 
#> [[2]]
#> [1] 108  92

Coupled jump problems

SplitCoupledJumpProblem(prob, prob_control, aggregator, coupling_map) simulates two jump problems with common random numbers (the split coupling of Anderson and Higham), which reduces the variance of differences between two models. The state is c(u, u_control).

d2 <- ConstantRateJump(function(u, p, t) 1.1 * u[1], function(integ) integ$u[1] <- integ$u[1] - 1)
j1 <- JumpProblem(DiscreteProblem(0, c(0, 5)), Direct(), b_r, d_r)
j2 <- JumpProblem(DiscreteProblem(0, c(0, 5)), Direct(), b_r, d2)
coupled <- SplitCoupledJumpProblem(j1, j2, Direct(), list(c(1, 1), c(2, 2)))
tail(solve(coupled, SSAStepper(), seed = 1)$u, 1)
#> [[1]]
#> [1] 13 12

Part 3: random ordinary differential equations

A random ODE u′=f(u,p,t,W)u' = f(u, p, t, W) is an ODE whose right hand side depends on the current value of a noise process W(t)W(t) rather than on its increments. It is solved pathwise; no Ito calculus is involved. RODEProblem(f, u0, tspan, noise = ) uses a Wiener process unless another process is given.

The solvers are RandomEM() and RandomTamedEM() (order 0.5), RandomHeun() and RandomTaylor15() (order 1.5, which needs the noise as a NoiseGrid to compute path integrals).

fr <- function(u, p, t, W) 1.01 * u + 0.87 * u * W
rsol <- solve(RODEProblem(fr, 0.5, c(0, 1)), RandomEM(), dt = 0.01, seed = 1)
rsol
#> RODESolution with retcode Success (RandomEM)
#> Saved time points: 101 in [0, 1]
#> Final state:
#> [1] 2.240383

With the noise fixed at zero the RODE is the ODE u′=1.01uu' = 1.01u, a convenient check:

zero <- RODEProblem(fr, 0.5, c(0, 1), noise = NoiseFunction(0, function(u, p, t) 0))
c(RandomHeun = tail(solve(zero, RandomHeun(), dt = 0.001)$u, 1)[[1]], exact = 0.5 * exp(1.01))
#> RandomHeun      exact 
#>   1.372800   1.372801

RandomTaylor15 on a prescribed path, compared with a fine RandomHeun reference on the same path:

tg <- seq(0, 1, length.out = 1001)
set.seed(11)
Wf <- c(0, cumsum(rnorm(1000, 0, sqrt(1 / 1000))))
rf <- function(u, p, t, W) -u + sin(W)
c(RandomTaylor15 = tail(solve(RODEProblem(rf, 1, c(0, 1), noise = NoiseGrid(tg, Wf)), RandomTaylor15(),
                              dt = 0.05)$u, 1)[[1]],
  reference = tail(solve(RODEProblem(rf, 1, c(0, 1), noise = NoiseGrid(tg, Wf)), RandomHeun(),
                         dt = 0.001)$u, 1)[[1]])
#> RandomTaylor15      reference 
#>      0.5000250      0.4999847

Summary of Julia equivalents

Julia modelcompR
@brownians B brownians("B") or Brownian("B")
@poissonians dN(lambda) poissonians(dN = lambda)
SDESystem(eqs, noiseeqs, t) SDESystem(eqs, noise_eqs, t)
SDEProblem(sys, op, tspan) SDEProblem(sys, op, tspan)
SDEProblem(f, g, u0, tspan, p) SDEProblem(f, g, u0, tspan, p)
solve(prob, SOSRI(); seed = 1) solve(prob, SOSRI(), seed = 1)
stochastic_integral_transform(sys, -1//2) stochastic_integral_transform(sys, -1/2)
EnsembleProblem, EnsembleSummary same names
JumpProblem(sys, op, tspan; aggregator = NRM()) JumpProblem(sys, op, tspan, aggregator = NRM())
JumpProblem(prob, Direct(), jumps...) JumpProblem(prob, Direct(), jumps...)
RODEProblem(f, u0, tspan) RODEProblem(f, u0, tspan)