# define some populations, all with identical vital rates
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)
# define a dynamics object
dyn <- lapply(
1:3,
function(i) dynamics(popmat)
)
# define metapopulation structure with populations
# 1 and 3 dispersing into population 2
pop_structure <- matrix(0, nrow = 3, ncol = 3)
pop_structure[1, 2] <- 1
pop_structure[3, 2] <- 1
# define dispersal between populations
dispersal_matrix <- matrix(0, nrow = nclass, ncol = nclass)
dispersal_matrix[survival(dispersal_matrix, dims = 20:25)] <- 0.2
pop_dispersal1 <- dispersal(dispersal_matrix, proportion = TRUE)
pop_dispersal2 <- dispersal(dispersal_matrix, proportion = FALSE)
pop_dispersal <- list(pop_dispersal1, pop_dispersal2)
# create metapopulation object
metapop <- metapopulation(pop_structure, dyn, pop_dispersal)
# simulate without covariates
sims <- simulate(metapop, nsim = 2)
# simulate with shared covariates
# define a covariates function
covar_fn <- function(mat, x) {
mat * (1 / (1 + exp(-0.5 * (x + 10))))
}
# and some covariates
xsim <- matrix(rnorm(20), ncol = 1)
# update the population dynamics objects with covariates
dyn <- lapply(
dyn,
update,
covariates(masks = transition(dyn[[1]]$matrix), funs = covar_fn)
)
# (re)create metapopulation object
metapop <- metapopulation(pop_structure, dyn, pop_dispersal)
sims <- simulate(
metapop,
nsim = 2,
args = list(covariates = format_covariates(xsim))
)
# simulate with separate covariates
# (requires re-definition of covariate functions)
new_fn <- function(i) {
force(i)
function(mat, x) {
mat * (1 / (1 + exp(-0.5 * (x[i] + 10))))
}
}
new_fn <- lapply(
1:3,
new_fn
)
# update the population dynamics objects with covariates
dyn <- lapply(
dyn,
update,
covariates(masks = transition(dyn[[1]]$matrix), funs = covar_fn)
)
# (re)create metapopulation object
metapop <- metapopulation(pop_structure, dyn, pop_dispersal)
# and simulate with one column of predictors for each population
xsim <- matrix(rnorm(60), ncol = 3)
sims <- simulate(
metapop,
nsim = 2,
args = list(covariates = format_covariates(xsim))
)
Run the code above in your browser using DataLab