# First initialize an empty model
sfm <- stockflow()
print(sfm)
# \dontshow{
sfm <- sim_settings(sfm, save_at = .5)
# }
# Add two stocks. Specify their initial values in the "eqn" property
# and their plotting label.
sfm <- stock(sfm, predator, eqn = 10, label = "Predator") |>
stock(prey, eqn = 50, label = "Prey")
# Add four flows: the births and deaths of both the predators and prey. The
# "eqn" property of flows represents the rate of the flow. In addition, we
# specify which stock the flow is coming from ("from") or flowing to ("to").
sfm <- flow(sfm, predator_births,
eqn = delta * prey * predator,
label = "Predator Births", to = predator
) |>
flow(predator_deaths,
eqn = gamma * predator,
label = "Predator Deaths", from = predator
) |>
flow(prey_births,
eqn = alpha * prey,
label = "Prey Births", to = prey
) |>
flow(prey_deaths,
eqn = beta * prey * predator,
label = "Prey Deaths", from = prey
)
plot(sfm)
# The flows make use of four other variables: "delta", "gamma", "alpha", and
# "beta". Define these as constants in a vectorized manner for efficiency.
sfm <- constant(sfm, c(delta, gamma, alpha, beta),
eqn = c(.025, .5, .5, .05),
label = c("Delta", "Gamma", "Alpha", "Beta"),
doc = c(
"Birth rate of predators", "Death rate of predators",
"Birth rate of prey", "Death rate of prey by predators"
)
)
# We now have a complete predator-prey model which is ready to be simulated.
sim <- simulate(sfm)
plot(sim)
# Modify a variable - note that we no longer need to specify type
sfm <- update(sfm, delta, eqn = .03, label = "DELTA")
# To add and/or modify variables more quickly, pass a data.frame.
# The data.frame is processed per row.
# For instance, to create a logistic population growth model:
df <- data.frame(
type = c("stock", "flow", "flow", "constant", "constant"),
name = c("X", "inflow", "outflow", "r", "K"),
eqn = c(.01, "r * X", "r * X^2 / K", 0.1, 1),
label = c(
"Population size", "Births", "Deaths", "Growth rate",
"Carrying capacity"
),
to = c(NA, "X", NA, NA, NA),
from = c(NA, NA, "X", NA, NA)
)
sfm <- update(stockflow(), df = df)
# Run model diagnostics
summary(sfm)
# --- Programmatic usage ---
# To inject the value of an R variable, use !! (bang-bang)
my_name <- "growth"
sfm <- constant(sfm, !!my_name, eqn = 0.1)
# Strings also work
sfm <- constant(sfm, "growth", eqn = 0.2)
Run the code above in your browser using DataLab