Hi All,
I'm trying to estimate the parameters of Zero-Inflated Conway Maxwell Poisson distribution in Nimble using MCMC algorithm.
I took reference from the example provided on the Nimble website for Zero-inflated Poisson distribution.
I was expecting the same behavior of the algorithm as in Zero-Inflated Poisson example, But I don't why it is behaving so weirdly,
Can somebody please help me out in this situation.
library(CompGLM)
library(nimble)
ZICMPcode <- nimbleCode({
p~dunif(0,1)
lam~dunif(0,100)
nu~dunif(0,100)
for(i in 1:N) {
y[i] ~ dZICMP(lam, nu,sumTo = 200L,zeroProb = p)
}
} )
## constants, data, and initial values
constants <- list(N = 100)
dCMP <- nimbleRcall(function(y = integer(), lam = double(), nu = double(),sumTo = integer(),logP = logical(0, default = 0)){}, Rfun = 'dcomp',
returnType = double(), envir = .GlobalEnv)
rCMP <- nimbleRcall(function(n = integer(), lam = double(), nu = double(),sumTo = integer()){}, Rfun = 'rcomp',
returnType = integer(), envir = .GlobalEnv)
dZICMP <- nimbleFunction(
run = function(x = integer(), lam = double(), nu = double(),sumTo = integer(), zeroProb = double(), log = logical(0, default = 0)) {
returnType(double())
## First handle non-zero data
if(x != 0) {
## return the log probability if log = TRUE
if(log) return(dCMP(x, lam, nu,sumTo = 200L, log = TRUE) + log(1-zeroProb))
## or the probability if log = FALSE
else return((1-zeroProb) * dCMP(x, lam, nu,sumTo = 200L, log = FALSE))
}
## From here down we know x is 0
totalProbZero <- zeroProb + (1-zeroProb) * dCMP(0, lam, nu,sumTo = 200L, log = FALSE)
if(log) return(log(totalProbZero))
return(totalProbZero)
})
rZICMP <- nimbleFunction(
run = function(n = integer(), lam = double(), nu = double(),sumTo = integer(), zeroProb = double()) {
returnType(integer())
isStructuralZero <- rbinom(1, prob = zeroProb, size = 1)
if(isStructuralZero) return(0)
return(rCMP(1, lam,nu,sumTo = 200L))
})
registerDistributions(list(
dZICMP = list(
BUGSdist = "dZICMP(lam, nu,sumTo, zeroProb)",
discrete = TRUE,
range = c(0, Inf),
types = c('value = integer()', 'lam = double()', 'nu = double()','sumTo = integer()', 'zeroProb = double()')
)))
ZICMPmodel <- nimbleModel( ZICMPcode,constants=constants,check = FALSE)
ZICMPmodel$p <- .4
ZICMPmodel$lam <- 1.8
ZICMPmodel$nu<-0.9
ZICMPmodel$simulate('y')
simulatedData <- ZICMPmodel$y
simulatedData
hist(simulatedData)
ZICMPmodel$setData(list(y = simulatedData))
cZICMPmodel <- compileNimble(ZICMPmodel)
ZICMPmcmc <- buildMCMC(ZICMPmodel)
cZICMPmcmc <- compileNimble(ZICMPmcmc, project = ZICMPmodel)
cZICMPmcmc$run(10000)
samples <- as.matrix(cZICMPmcmc$mvSamples)
summary(samples)
plot(samples[,'lam'], main = 'lambda trace plot')
plot(samples[,'nu'], main = 'nu trace plot')
plot(samples[,'p'], main = 'zeroProb trace plot')
Thank you