# Ensemble simulation in R (no parallelization)
# Load example
sfm <- stockflow("predator_prey")
# Set random initial conditions
sfm <- update(sfm, c(predator, prey),
eqn = runif(1, min = 20, max = 80)
)
# For ensemble simulations, it is highly recommended to reduce the
# returned output. For example, to save only 20 values per simulation:
sfm <- sim_settings(sfm, save_n = 20)
# Run ensemble simulation with a small number of simulations
sims <- ensemble(sfm, n = 3)
if (interactive()) plot(sims)
if (FALSE) { # Sys.getenv("NOT_CRAN") == "true"
# To plot individual trajectories, rerun the ensemble with save_sims = TRUE.
# Note that this can consume a lot of memory for large simulations.
sims <- ensemble(sfm, n = 10, save_sims = TRUE)
plot(sims, which = "sims")
# Specify which trajectories to plot
plot(sims, which = "sims", sim = 1)
# Plot the median with lighter individual trajectories
plot(sims, central_tendency = "median", which = "sims", alpha = 0.1)
# For larger ensembles, we can use parallelization with future
if (requireNamespace("future", quietly = TRUE) &&
requireNamespace("future.apply", quietly = TRUE)) {
future::plan(future::multisession, workers = 4)
}
# Ensembles can also be run with exact values for the initial conditions
# and parameters. Below, we vary the initial values of the predator and the
# birth rate of the predators (delta). We generate a hundred samples per
# condition. By default, the parameters are crossed, meaning that all
# combinations of the parameters are run.
sims <- ensemble(sfm,
n = 50,
conditions = list(predator = c(10, 50), delta = c(.025, .05))
)
plot(sims)
# By default, a maximum of nine conditions is plotted.
# Plot specific conditions:
plot(sims, condition = c(1, 3), nrows = 1)
# Generate a non-crossed design, where the length of each conditions vector
# needs to be equal:
sims <- ensemble(sfm,
n = 10, cross = FALSE,
conditions = list(
predator = c(10, 20, 30),
delta = c(.020, .025, .03)
)
)
plot(sims, nrows = 3)
# Stop parallelization after use
if (requireNamespace("future", quietly = TRUE) &&
requireNamespace("future.apply", quietly = TRUE)) {
future::plan(future::sequential)
}
}
Run the code above in your browser using DataLab