Back to NIMBLE Vignettes
It turns out there's already a function that handles adding conjugate samplers.
It’s called addConjugateSampler()
.
library(nimble)
Create a model with a conjugate node.
And a non-conjugate node, for the sake of example.
code <- nimbleCode({
theta ~ dbeta(1, 1) ## theta will be conjugate
for(i in 1:2)
x[i] ~ dbin(prob = theta, size = 10)
for(i in 1:3)
y[i] ~ dnegbin(prob = theta, size = 50)
notConjugate ~ dbeta(1, 1) ## notConjugate will not be conjugate
z ~ dnorm(notConjugate, 1)
})
Rmodel <- nimbleModel(code)
## defining model...
## building model...
## running calculate on model (any error reports that follow may simply
## reflect missing values in model variables) ...
##
## checking model sizes and dimensions...
## note that missing values (NAs) or non-finite values were found in model
## variables: theta, x, y, notConjugate, z. This is not an error, but some or
## all variables may need to be initialized for certain algorithms to operate
## properly.
##
## model building finished.
Say you want to programmatically add a conjugate sampler for theta
, which is conjugate.
node <- 'theta'
conjInfo <- Rmodel$checkConjugacy2(node)[[node]]
## the conjInfo object has everything we need:
conjInfo
## $prior
## [1] "dbeta"
##
## $type
## [1] "conjugate_dbeta"
##
## $target
## [1] "theta"
##
## $control
## $control$dep_dbin
## [1] "x[1]" "x[2]"
##
## $control$dep_dnegbin
## [1] "y[1]" "y[2]" "y[3]"
conf <- configureMCMC(Rmodel, nodes = NULL)
conf$printSamplers() ## initially, no samplers
conf$addConjugateSampler(conjInfo)
conf$printSamplers() ## now we have the correct conjugate sampler for 'theta'
## [1] conjugate_dbeta_dbin_dnegbin sampler: theta, dep_dbin: x[1], x[2], dep_dnegbin: y[1], y[2], y[3]
If you try this procedure with a node that’s not conjugate:
node <- 'notConjugate' ## this node is not conjugate
conjInfo <- Rmodel$checkConjugacy2(node)[[node]]
## conjInfo should be NULL
conjInfo
## NULL
Let me know if you have any questions.