# define a population matrix (columns move to rows)
nclass <- 5
popmat <- matrix(0, nrow = nclass, ncol = nclass)
popmat[reproduction(popmat, dims = 4:5)] <- c(10, 20)
popmat[transition(popmat)] <- c(0.25, 0.3, 0.5, 0.65)
# can extract standard population matrix summary stats
lambda <- Re(eigen(popmat)$values[1])
# define a dynamics object
dyn <- dynamics(popmat)
# simulate from this (50 time steps, 100 replicates)
sims <- simulate(dyn, nsim = 100, options = list(ntime = 50))
# plot the simulated trajectories
plot(sims)
# add some density dependence
dd <- density_dependence(
masks = reproduction(popmat, dims = 4:5),
funs = ricker(1000)
)
# update the dynamics object
dyn <- update(dyn, dd)
# simulate again
sims <- simulate(dyn, nsim = 100, options = list(ntime = 50))
# and plot
plot(sims)
# what if we want to add initial conditions?
sims <- simulate(
dyn,
init = c(50, 20, 10, 10, 5),
nsim = 100,
options = list(ntime = 50),
)
# and plot again
plot(sims)
# note that there is only one trajectory now because
# this simulation is deterministic.
#
# let's change that by adding some environmental stochasticity
envstoch <- environmental_stochasticity(
masks = list(
reproduction(popmat, dims = 4:5),
transition(popmat)
),
funs = list(
\(x) rpois(n = length(x), lambda = x),
\(x) runif(n = length(x), min = 0.9 * x, max = pmin(1.1 * x, 1))
)
)
# update the dynamics object and simulate from it
dyn <- update(dyn, envstoch)
sims <- simulate(
dyn,
init = c(50, 20, 10, 10, 5),
nsim = 100,
options = list(ntime = 50),
)
# can also add covariates that influence vital rates
# e.g., a logistic function
covars <- covariates(
masks = transition(popmat),
funs = \(mat, x) mat * (1 / (1 + exp(-10 * x)))
)
# simulate 50 random covariate values
xvals <- matrix(runif(50), ncol = 1)
# update the dynamics object and simulate from it.
# Note that ntime is now captured in the 50 values
# of xvals, assuming we pass xvals as an argument
# to the covariates functions
dyn <- update(dyn, covars)
sims <- simulate(
dyn,
init = c(50, 20, 10, 10, 5),
nsim = 100,
args = list(covariates = format_covariates(xvals))
)
# a simple way to add demographic stochasticity is to change
# the "updater" that converts the population at time t
# to its value at time t + 1. The default in aae.pop
# uses matrix multiplication of the vital rates matrix
# and current population. A simple tweak is to update
# with binomial draws. Note that this also requires a
# change to the "tidy_abundances" option so that population
# abundances are always integer values.
sims <- simulate(
dyn,
init = c(50, 20, 10, 10, 5),
nsim = 100,
options = list(
update = update_binomial_leslie,
tidy_abundances = floor
),
args = list(covariates = format_covariates(xvals))
)
# and can plot these again
plot(sims)
Run the code above in your browser using DataLab