## negative log likelihood function
nll = function(par, step, tod) {
# parameter transformations for unconstrained optimisation
beta = matrix(par[1:6], nrow = 2)
Gamma = tpm_p(1:24, beta = beta) # multinomial logit link for each time point
delta = stationary_p(Gamma, tod[1]) # stationary HMM
mu = exp(par[7:8])
sigma = exp(par[9:10])
# calculate all state-dependent probabilities
allprobs = matrix(1, length(step), 2)
ind = which(!is.na(step))
for(j in 1:2) allprobs[ind,j] = dgamma2(step[ind], mu[j], sigma[j])
# simple forward algorithm to calculate log-likelihood
-forward_p(delta, Gamma, allprobs, tod)
}
## fitting an HMM to the nessi data
par = c(-2,-2, # initial tpm intercepts (logit-scale)
rep(0, 4), # initial tpm slopes
log(c(0.3, 2.5)), # initial means for step length (log-transformed)
log(c(0.2, 1.5))) # initial sds for step length (log-transformed)
mod = nlm(nll, par, step = trex$step[1:500], tod = trex$tod[1:500])
Run the code above in your browser using DataLab