nll <- function(par) {
getAll(par, dat)
Gamma <- tpm(eta)
allprobs <- statedens(step, dgamma2, exp(log_mu), exp(log_sigma)) *
statedens(angle, dvm, 0, exp(log_kappa))
-forward(stationary(Gamma), Gamma, allprobs)
}
dat <- list(step = trex$step[1:500], angle = trex$angle[1:500])
par <- list(eta = c(-2, -2), log_mu = log(c(0.3, 2.5)), log_sigma = log(c(0.2, 1.5)),
log_kappa = log(c(0.2, 1.5)))
obj <- MakeADFun(nll, par, silent = TRUE)
opt <- nlminb(obj$par, obj$fn, obj$gr)
mod <- lama(obj)
sim <- simulate(mod, seed = 1)
head(sim)
# simulate without data: all-NA streams as placeholders, parameters of your choice, then refit
dat$step <- dat$angle <- rep(NA, 500)
obj0 <- MakeADFun(nll, par, silent = TRUE)
sim <- simulate(lama(obj0), seed = 1)
dat$step <- sim$step; dat$angle <- sim$angle
obj1 <- MakeADFun(nll, par, silent = TRUE)
opt1 <- nlminb(obj1$par, obj1$fn, obj1$gr)
# random effects: RTMB draws them first, then the states and data are simulated given them
nll_re <- function(par) {
getAll(par, dat)
u %~% dnorm(0, exp(log_su)) # track-level random effect on the mean step length in state 1
mu <- exp(cbind(log_mu[1] + u[id], log_mu[2]))
Gamma <- tpm(eta)
.nll <- .nll - forward(stationary(Gamma), Gamma, statedens(step, dgamma2, mu, exp(log_sigma)), id)
.nll
}
dat <- list(step = trex$step[1:500], id = rep(1:5, each = 100))
par_re <- list(eta = c(-2, -2), log_mu = log(c(0.3, 2.5)), log_sigma = log(c(0.2, 1.5)),
log_su = log(0.3), u = rep(0, 5))
obj_re <- MakeADFun(nll_re, par_re, random = "u", silent = TRUE)
sim_re <- simulate(lama(obj_re), random = TRUE, seed = 1)
Run the code above in your browser using DataLab