Skip to contents

Convert a model written for deSolve into a stock-and-flow model of class stockflow.

Usage

import_desolve(model, params, init, times, method = "lsoda", name = NULL)

Arguments

model

A deSolve-style ODE function with arguments (t, state, parameters).

params

Named numeric vector of model parameters (constants).

init

Named numeric vector of initial state values (stocks).

times

Numeric vector of time points. Must be evenly spaced (e.g., from seq(start, stop, by = dt)).

method

Integration method. Defaults to "lsoda". See sim_methods().

name

Optional model name. Character scalar.

Value

A stock-and-flow model of class stockflow.

Details

The model function must follow the canonical deSolve convention:

model <- function(t, state, parameters) {
  with(as.list(c(state, parameters)), {
    dX <- <rate expression>   # d<VarName> for each state in init
    list(c(dX))
  })
}

State variable names are taken from names(init), parameter names from names(params). Each d<VarName> assignment inside the with() block is parsed as the net rate of change for stock VarName and becomes a flow in the sfm. Any other assignments in the with() block (intermediate calculations) are imported as auxiliary variables in the order they appear.

Examples

logistic_model <- function(t, state, parameters) {
  with(as.list(c(state, parameters)), {
    dN <- r * N * (1 - N / K)
    list(c(dN))
  })
}
sfm <- import_desolve(
  model  = logistic_model,
  params = c(r = 0.3, K = 100),
  init   = c(N = 10),
  times  = seq(0, 50, by = 0.1),
  method = "lsoda",
  name   = "Logistic growth"
)
sim <- simulate(sfm)
plot(sim)