Skip to contents

modelcompR is a native R port of ModelingToolkit.jl. A model is a set of symbolic equations; mtkcompile() simplifies it and generates the R functions that the numerical solvers call. This article walks through the basic workflow: declare variables, write equations, compile, build a problem, solve and inspect the solution.

library(modelcompR)
#> Loading required package: symcompR
#> 
#> Attaching package: 'modelcompR'
#> The following objects are masked from 'package:symcompR':
#> 
#>     compose, Differential, distance, extend, flatten, hadamard_product,
#>     IdentityOperator, System, Variable, WienerProcess

A first order lag

The time variable and its derivative operator come with the package. t_nounits is used instead of t, which would mask base::t().

t <- t_nounits
D <- D_nounits
variables("x(t)")
parameters("tau")

variables() and parameters() mirror @variables and @parameters: they create the symbols and assign them in the calling environment. Equations are R formulas, so they read as in Julia.

sys <- System(list(D(x) ~ (1 - x) / tau), t, name = "lag")
sys <- mtkcompile(sys)
unknowns(sys)
#> [[1]]
#> x(t)

A problem takes the values of the unknowns and the parameters as equations, and the time span.

prob <- ODEProblem(sys, list(x ~ 0, tau ~ 3), c(0, 10))
sol <- solve(prob)
sol$retcode
#> [1] "Success"

The solution is indexed by symbols or by any expression of the model, and is called as a function for dense output.

head(sol[x])
#> [1] 0.000000e+00 3.333278e-05 2.834924e-01 4.627197e-01 6.522151e-01
#> [6] 7.827956e-01
sol(5)
#>      x(t) 
#> 0.8111274
head(sol[(1 - x) / tau])
#> [1] 0.33333333 0.33332222 0.23883586 0.17909342 0.11592828 0.07240148
plot(sol)

A second order equation

Higher derivatives are lowered to first order systems, as in ModelingToolkit, and equations that only define a variable become observed equations.

variables("y(t)", "v(t)")
parameters("k = 2")
osc <- mtkcompile(System(list(D(D(y)) ~ -k * y, v ~ 2 * D(y)), t, name = "osc"))
unknowns(osc)
#> [[1]]
#> y(t)
#> 
#> [[2]]
#> yˍt(t)
observed(osc)
#> [[1]]
#> v(t) ~ 2*yˍt(t)
sol <- solve(ODEProblem(osc, list(y ~ 1, D(y) ~ 0), c(0, 5)))
sol(c(1, 2, 3), idxs = v)
#> [1] -2.7938283 -0.8713393  2.5221781

Choosing a solver

solve() picks a method automatically. Any of the ported OrdinaryDiffEq methods can be named instead, with the usual tolerances.

sol_tsit <- solve(prob, Tsit5(), reltol = 1e-10, abstol = 1e-10)
sol_rodas <- solve(prob, Rodas5P())
c(sol_tsit(10)[1], sol_rodas(10)[1], 1 - exp(-10 / 3))
#>     x(t)     x(t)          
#> 0.964326 0.964326 0.964326

Where to go next

The reference index groups every function by area: modeling and components, structural simplification, problems and solutions, initialization, events and clocks, the ODE, DAE, stochastic, jump, delay and boundary value solvers, nonlinear solvers, optimization, sensitivity analysis, and linearization.