Skip to contents

Get started with a template

Stock-and-flow models can be created in three ways in sdbuildR. Firstly, dozens of example models can be loaded using xmile(). Plot the stock-and-flow diagram to get an overview of the model:

sfm = xmile("SIR")
plot(sfm)

The model can be simulated using simulate():

sim = simulate(sfm)
plot(sim)

Import models from Insight Maker

Secondly, an Insight Maker model can be imported to R using its URL:

URL = "https://insightmaker.com/insight/5LxQr0waZGgBcPJcNTC029/Crielaard-2022"
sfm = insightmaker_to_sfm(URL = URL)
sim = simulate(sfm)
plot(sim)

Build a model from scratch

Lastly, a stock-and-flow model can be created from scratch. We first initialize an empty stock and flow model with xmile(), and then use build() to create a logistic model of population growth. The simulation specifications, such as the start time, stop time, and simulation time step (dt), are set with sim_specs(). Custom units such as people can be added with model_units(). Below, we make use of the convenient pipe operator %\>%, which simply passes the result of an expression to the next expression as a first argument.

sfm = xmile() %>%
  header(name = "Population growth") %>%
  build("X", "stock", eqn = ".01", label = "Population size") %>%
  build("change", "flow", eqn = "r * (1 - X/K)", to = "X", 
        label = "Births and Deaths") %>%
  build("r", "constant", eqn = "0.1", label = "Growth rate") %>%
  build("K", "constant", eqn = "1", label = "Carrying capacity") %>%
  sim_specs(stop = 200) 
plot(simulate(sfm))

An overview of the model components and simulation specifications can be accessed with summary():

summary(sfm)
#> Your model contains:
#> * 1 Stocks: X
#> * 1 Flows: change
#> * 2 Constants: r, K
#> * 0 Auxiliaries
#> * 0 Graphical Functions
#> * 0 Custom model units
#> * 0 Macros
#> 
#> Simulation time: 0.0 to 200.0 seconds (dt = 0.01)
#> Simulation settings: solver euler in R

To quickly view all model variable properties, use as.data.frame():

as.data.frame(sfm)
#>       type   name           eqn units             label   to non_negative
#> 1    stock      X           .01     1   Population size <NA>        FALSE
#> 2 constant      r           0.1     1       Growth rate <NA>        FALSE
#> 3 constant      K             1     1 Carrying capacity <NA>        FALSE
#> 4     flow change r * (1 - X/K)     1 Births and Deaths    X        FALSE
#>   conveyor            eqn_julia
#> 1    FALSE                  .01
#> 2       NA                  0.1
#> 3       NA                  1.0
#> 4       NA r .* (1.0 .- X ./ K)

Start building your own models!

See the vignettes to learn more about all features of sdbuildR: