Hello all,
I recently started using RTMB and encountered an error where I need some help.
My minimal example is not so minimal, but the specific model details do not matter and the bottom line is: I build a 3D array from some parameters, and at the bottom of my likelihood function I extract a slice from it for each observation, which works just fine R.
But when I want to build the AD function, I get the error:
Error in advector(y) :
Invalid argument to 'advector' (lost class attribute?)
Minimal example:
library(RTMB)
# generating some data from Poisson HMM with covariate effect on transition probabilities
set.seed(123)
n = 100 # number of data points
lambda = c(1, 5) # state-dependent Poisson means
z = rnorm(n) # white noise covariate
beta = matrix(c(-2, -2, 1, -1), nrow = 2) # parameter matrix for t.p.m.
s = rep(NA, n) # simulating Markov chain of hidden states
s[1] = sample(1:2, 1) # initial state
expEta = exp(cbind(1, z) %*% t(beta))
for(t in 2:n){
# computing t.p.m. from linear predictors via inverse multinomial logit link
G = diag(2)
G[!G] = expEta[t,] # covariate dependent transition probability matrix
G = G / rowSums(G)
s[t] = sample(1:2, 1, prob = G[s[t-1],])
}
x = rpois(n, lambda[s]) # simulating observations based on hidden states
# negative log-likelihood function for Poisson HMM with covariate effect on transition probabilities
nllk = function(par) {
getAll(par, dat)
lambda = exp(loglambda) # state-dependent Poisson mean
beta = matrix(betavec, nrow = 2, ncol = 2) # parameter matrix for t.p.m.
expEta = exp(cbind(1, z) %*% t(beta)) # exp linear predictors for t.p.m.
Gamma = array(NA, dim = c(2, 2, nrow(expEta)))
for(t in 1:nrow(expEta)) {
# each tpm slice is computed via inverse multinomial logit link
G = diag(2)
G[!G] = expEta[t,]
Gamma[,,t] = G / rowSums(G)
}
delta = c(0.5, 0.5) # initial state probabilities fixed
allprobs = cbind(dpois(x, lambda[1]), dpois(x, lambda[2])) # state-dependent probabilities
# forward algorithm
foo = t(delta) * allprobs[1,]
phi = foo / sum(foo)
l = log(sum(foo))
for(t in 2:nrow(allprobs)) {
# I get an AD error here when extracting the matrix from the array
foo = phi %*% Gamma[,,t] * allprobs[t,]
phi = foo / sum(foo)
l = l + log(sum(foo))
}
-l
}
par = list(loglambda = log(c(1,5)), betavec = c(-2, -2, 1, -1))
dat = list(x = x, z = z)
nllk(par) # works
obj = MakeADFun(nllk, par) # does not work
# Error in advector(y) :
# Invalid argument to 'advector' (lost class attribute?)
Best regards and thanks in advance,
Ole