NIMBLE User Manual
NIMBLE User Manual
Version 0.12.2
https://r-nimble.org
https://github.com/nimble-dev/nimble
2
Contents
I Introduction 9
1 Welcome to NIMBLE 11
1.1 What does NIMBLE do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2 How to use this manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 Lightning introduction 13
2.1 A brief example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Creating a model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Compiling the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 One-line invocation of MCMC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5 Creating, compiling and running a basic MCMC configuration . . . . . . . . . . . . . 19
2.6 Customizing the MCMC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.7 Running MCEM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.8 Creating your own functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3 More introduction 27
3.1 NIMBLE adopts and extends the BUGS language for specifying models . . . . . . . 27
3.2 nimbleFunctions for writing algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.3 The NIMBLE algorithm library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4 Installing NIMBLE 31
4.1 Requirements to run NIMBLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.2 Installing a C++ compiler for NIMBLE to use . . . . . . . . . . . . . . . . . . . . . 31
4.2.1 MacOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.2.2 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.2.3 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.3 Installing the NIMBLE package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.4 Troubleshooting installation problems . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.5 Customizing your installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.5.1 Using your own copy of Eigen . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.5.2 Using libnimble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.5.3 BLAS and LAPACK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.5.4 Customizing compilation of the NIMBLE-generated C++ . . . . . . . . . . . 34
3
4 CONTENTS
II Models in NIMBLE 37
7 MCMC 69
7.1 One-line invocation of MCMC: nimbleMCMC . . . . . . . . . . . . . . . . . . . . . . 70
7.2 The MCMC configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.2.1 Default MCMC configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.2.2 Customizing the MCMC configuration . . . . . . . . . . . . . . . . . . . . . . 73
7.3 Building and compiling the MCMC . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.4 User-friendly execution of MCMC algorithms: runMCMC . . . . . . . . . . . . . . . 79
7.5 Running the MCMC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.5.1 Rerunning versus restarting an MCMC . . . . . . . . . . . . . . . . . . . . . 80
7.5.2 Measuring sampler computation times: getTimes . . . . . . . . . . . . . . . . 81
7.5.3 Assessing the adaption process of RW and RW_block samplers . . . . . . . . 81
7.6 Extracting MCMC samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.7 Calculating WAIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.8 k-fold cross-validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.9 Variable selection using Reversible Jump MCMC . . . . . . . . . . . . . . . . . . . . 84
CONTENTS 5
Overview 125
Introduction
9
Chapter 1
Welcome to NIMBLE
NIMBLE is a system for building and sharing analysis methods for statistical models from R, espe-
cially for hierarchical models and computationally-intensive methods. While NIMBLE is embedded
in R, it goes beyond R by supporting separate programming of models and algorithms along with
compilation for fast execution.
As of version 0.12.2, NIMBLE has been around for a while and is reasonably stable, but we have
a lot of plans to expand and improve it. The algorithm library provides MCMC with a lot of
user control and ability to write new samplers easily. Other algorithms include particle filtering
(sequential Monte Carlo) and Monte Carlo Expectation Maximization (MCEM).
But NIMBLE is about much more than providing an algorithm library. It provides a language for
writing model-generic algorithms. We hope you will program in NIMBLE and make an R package
providing your method. Of course, NIMBLE is open source, so we also hope you’ll contribute to
its development.
Please join the mailing lists (see R-nimble.org/more/issues-and-groups) and help improve NIMBLE
by telling us what you want to do with it, what you like, and what could be better. We have a
lot of ideas for how to improve it, but we want your help and ideas too. You can also follow and
contribute to developer discussions on our GitHub repository.
If you use NIMBLE in your work, please cite us, as this helps justify past and future funding for
the development of NIMBLE. For more information, please call citation('nimble') in R.
11
12 CHAPTER 1. WELCOME TO NIMBLE
4. A compiler that generates C++ for your models and algorithms, compiles that C++, and
lets you use it seamlessly from R without knowing anything about C++.
NIMBLE stands for Numerical Inference for statistical Models for Bayesian and Likelihood Esti-
mation.
Although NIMBLE was motivated by algorithms for hierarchical statistical models, it’s useful for
other goals too. You could use it for simpler models. And since NIMBLE can automatically
compile R-like functions into C++ that use the Eigen library for fast linear algebra, you can use it
to program fast numerical functions without any model involved2 .
One of the beauties of R is that many of the high-level analysis functions are themselves written in
R, so it is easy to see their code and modify them. The same is true for NIMBLE: the algorithms
are themselves written in the NIMBLE language.
2
The packages Rcpp and RcppEigen provide different ways of connecting C++, the Eigen library and R. In those
packages you program directly in C++, while in NIMBLE you program in R in a nimbleFunction and the NIMBLE
compiler turns it into C++.
Chapter 2
Lightning introduction
13
14 CHAPTER 2. LIGHTNING INTRODUCTION
Here x[i] is the number of failures recorded during a time duration of length t[i] for the i𝑡ℎ
pump. theta[i] is a failure rate, and the goal is estimate parameters alpha and beta. Now let’s
create the model and look at some of its nodes.
pump <- nimbleModel(code = pumpCode, name = "pump", constants = pumpConsts,
data = pumpData, inits = pumpInits)
pump$getNodeNames()
## [1] 5 1 5 14 3 19 1 1 4 22
pump$logProb_x
## [1] 1
pump$theta
## [1] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
pump$lambda
## [1] 9.430 1.570 6.290 12.600 0.524 3.140 0.105 0.105 0.210 1.050
Notice that in the list of nodes, NIMBLE has introduced a new node, lifted_d1_over_beta. We
2.2. CREATING A MODEL 15
call this a ‘lifted’ node. Like R, NIMBLE allows alternative parameterizations, such as the scale or
rate parameterization of the gamma distribution. Choice of parameterization can generate a lifted
node, as can using a link function or a distribution argument that is an expression. It’s helpful to
know why they exist, but you shouldn’t need to worry about them.
Thanks to the plotting capabilities of the igraph package that NIMBLE uses to represent the
directed acyclic graph, we can plot the model (Figure 2.1).
pump$plotGraph()
x[2]
x[5]
x[6]
lambda[2]
lambda[5] lambda[6]
x[10] theta[2]
theta[5] x[7]
lambda[10] theta[6]
lambda[7]
theta[10] theta[7]
alpha
lifted_d1_over_beta
beta
theta[4]
theta[8]
lambda[4]
x[4] theta[9] lambda[8]
theta[1]
theta[3] x[8]
lambda[9]
lambda[1]
x[9] lambda[3]
x[1]
x[3]
Figure 2.1: Directed Acyclic Graph plot of the pump model, thanks to the igraph package
You are in control of the model. By default, nimbleModel does its best to initialize a model, but
let’s say you want to re-initialize theta. To simulate from the prior for theta (overwriting the
initial values previously in the model) we first need to be sure the parent nodes of all theta[i]
nodes are fully initialized, including any non-stochastic nodes such as lifted nodes. We then use
the simulate function to simulate from the distribution for theta. Finally we use the calculate
function to calculate the dependencies of theta, namely lambda and the log probabilities of x to
ensure all parts of the model are up to date. First we show how to use the model’s getDependencies
method to query information about its graph.
16 CHAPTER 2. LIGHTNING INTRODUCTION
## [1] "lifted_d1_over_beta"
# Check that the lifted node was initialized.
pump[["lifted_d1_over_beta"]] # It was.
## [1] 1
# Now let's simulate new theta values
set.seed(1) # This makes the simulations here reproducible
pump$simulate("theta")
pump$theta # the new theta values
## [1] 9.430 1.570 6.290 12.600 0.524 3.140 0.105 0.105 0.210 1.050
pump$logProb_x
## [1] -96.10932
pump$calculate(pump$getDependencies(c("theta")))
## [1] -262.204
pump$lambda # Now they have.
Notice that the first getDependencies call returned dependencies from alpha and beta down to the
next stochastic nodes in the model. The second call requested only deterministic dependencies. The
call to pump$simulate("theta") expands "theta" to include all nodes in theta. After simulating
into theta, we can see that lambda and the log probabilities of x still reflect the old values of theta,
so we calculate them and then see that they have been updated.
## [Warning] There are individual pWAIC values that are greater than 0.4. This may indicate t
names(mcmc.out)
## $chain1
## Mean Median St.Dev. 95%CI_low 95%CI_upp
18 CHAPTER 2. LIGHTNING INTRODUCTION
## Field "lppd":
## [1] -19.99653
## Field "pWAIC":
## [1] 4.352945
See Section 7.1 or help(nimbleMCMC) for more details about using nimbleMCMC.
Note that the WAIC value varies depending on what quantities are treated as parameters. See
Section 7.7 or help(waic) for more details.
0.14
3.0
3.0
2.5
2.5
1.5
0.10
2.0
2.0
θ1
α
β
1.0
1.5
1.5
0.06
1.0
1.0
0.5
0.5
0.5
0.02
0.0
0.0
0 400 800 0 400 800 0.5 1.0 1.5 0 400 800
1.0
0.8
0.8
0.6
0.6
ACF
ACF
0.4
0.4
0.2
0.2
0.0
0.0
0 5 15 25 0 5 15 25
Lag Lag
Notice the posterior correlation between alpha and beta. A measure of the mixing for each is the
autocorrelation for each parameter, shown by the acf plots.
set.seed(1)
CpumpNewMCMC$run(niter)
2.6. CUSTOMIZING THE MCMC 21
## NULL
samplesNew <- as.matrix(CpumpNewMCMC$mvSamples)
0.15
3
3
1.5
0.10
2
θ1
α
β
1.0
0.05
1
1
0.5
1.0
0.8
0.8
0.6
0.6
ACF
ACF
0.4
0.4
0.2
0.2
0.0
0.0
0 5 15 25 0 5 15 25
Lag Lag
We can see that the block sampler has decreased the autocorrelation for both alpha and beta. Of
course these are just short runs, and what we are really interested in is the effective sample size of
the MCMC per computation time, but that’s not the point of this example.
Once you learn the MCMC system, you can write your own samplers and include them. The entire
system is written in nimbleFunctions.
22 CHAPTER 2. LIGHTNING INTRODUCTION
## Iteration Number: 1.
## Current number of MCMC iterations: 1000.
## Parameter Estimates:
## alpha beta
## 0.8160625 1.1230921
## Convergence Criterion: 1.001.
## Iteration Number: 2.
## Current number of MCMC iterations: 1000.
## Parameter Estimates:
## alpha beta
## 0.8045037 1.1993128
## Convergence Criterion: 0.0223464.
## Iteration Number: 3.
## Current number of MCMC iterations: 1250.
## Parameter Estimates:
## alpha beta
## 0.8203178 1.2497067
## Convergence Criterion: 0.004913688.
## Iteration Number: 4.
## Current number of MCMC iterations: 3032.
## Parameter Estimates:
## alpha beta
## 0.8226618 1.2602452
## Convergence Criterion: 0.0004201048.
pumpMLE
## alpha beta
## 0.8226618 1.2602452
Both estimates are within 0.01 of the values reported by George et al. (1993)3 . Some discrepancy
is to be expected since it is a Monte Carlo algorithm.
2
Note that for this model, one could analytically integrate over theta and then numerically maximize the resulting
marginal likelihood.
3
Table 2 of the paper accidentally swapped the two estimates.
2.8. CREATING YOUR OWN FUNCTIONS 23
1. The setup function is written in R. It creates relevant information specific to our model for
use in the run-time code.
2. The setup code creates a modelValues object to hold multiple sets of values for variables in
the model provided.
3. The run function is written in NIMBLE. It carries out the calculations using the information
determined once for each set of model and nodes arguments by the setup code. The run-time
code is what will be compiled.
4. The run code requires type information about the argument n. In this case it is a scalar
integer.
5. The for-loop looks just like R, but only sequential integer iteration is allowed.
6. The functions calculate and simulate, which were introduced above in R, can be used in
NIMBLE.
7. The special function copy is used here to record values from the model into the modelValues
object.
8. Multiple instances, or ‘specializations’, can be made by calling simNodesMany with different ar-
guments. Above, simNodesTheta1to5 has been made by calling simNodesMany with the pump
24 CHAPTER 2. LIGHTNING INTRODUCTION
model and nodes "theta[1:5]" as inputs to the setup function, while simNodesTheta6to10
differs by providing "theta[6:10]" as an argument. The returned objects are objects of a
uniquely generated R reference class with fields (member data) for the results of the setup
code and a run method (member function).
By the way, simNodesMany is very similar to a standard nimbleFunction provided with NIMBLE,
simNodesMV.
Now let’s execute this nimbleFunction in R, before compiling it.
set.seed(1) # make the calculation repeatable
pump$alpha <- pumpMLE[1]
pump$beta <- pumpMLE[2]
# make sure to update deterministic dependencies of the altered nodes
pump$calculate(pump$getDependencies(c("alpha","beta"), determOnly = TRUE))
## [1] 0
saveTheta <- pump$theta
simNodesTheta1to5$run(10)
simNodesTheta1to5$mv[["theta"]][1:2]
## [[1]]
## [1] 0.21829875 1.93210969 0.62296551 0.34197266 3.45729601 1.15835525
## [7] 0.99001994 0.30737332 0.09461909 0.15720154
##
## [[2]]
## [1] 0.82759981 0.08784057 0.34414959 0.29521943 0.14183505 1.15835525
## [7] 0.99001994 0.30737332 0.09461909 0.15720154
simNodesTheta1to5$mv[["logProb_x"]][1:2]
## [[1]]
## [1] -10.250111 -26.921849 -25.630612 -15.594173 -11.217566 -7.429868
## [7] -1.000761 -1.453644 -9.840589 -39.096527
##
## [[2]]
## [1] -61.043876 -1.057668 -11.060164 -11.761432 -3.425282 -7.429868
## [7] -1.000761 -1.453644 -9.840589 -39.096527
In this code we have initialized the values of alpha and beta to their MLE and then recorded
the theta values to use below. Then we have requested 10 simulations from simNodesTheta1to5.
Shown are the first two simulation results for theta and the log probabilities of x. Notice that
theta[6:10] and the corresponding log probabilities for x[6:10] are unchanged because the nodes
being simulated are only theta[1:5]. In R, this function runs slowly.
Finally, let’s compile the function and run that version.
CsimNodesTheta1to5 <- compileNimble(simNodesTheta1to5,
project = pump, resetFunctions = TRUE)
Cpump$alpha <- pumpMLE[1]
Cpump$beta <- pumpMLE[2]
2.8. CREATING YOUR OWN FUNCTIONS 25
## [1] 0
Cpump$theta <- saveTheta
set.seed(1)
CsimNodesTheta1to5$run(10)
## NULL
CsimNodesTheta1to5$mv[["theta"]][1:2]
## [[1]]
## [1] 0.21829875 1.93210969 0.62296551 0.34197266 3.45729601 1.15835525
## [7] 0.99001994 0.30737332 0.09461909 0.15720154
##
## [[2]]
## [1] 0.82759981 0.08784057 0.34414959 0.29521943 0.14183505 1.15835525
## [7] 0.99001994 0.30737332 0.09461909 0.15720154
CsimNodesTheta1to5$mv[["logProb_x"]][1:2]
## [[1]]
## [1] -10.250111 -26.921849 -25.630612 -15.594173 -11.217566 -2.782156
## [7] -1.042151 -1.004362 -1.894675 -3.081102
##
## [[2]]
## [1] -61.043876 -1.057668 -11.060164 -11.761432 -3.425282 -2.782156
## [7] -1.042151 -1.004362 -1.894675 -3.081102
Given the same initial values and the same random number generator seed, we got identical results
for theta[1:5] and their dependencies, but it happened much faster.
26 CHAPTER 2. LIGHTNING INTRODUCTION
Chapter 3
More introduction
Now that we have shown a brief example, we will introduce more about the concepts and design of
NIMBLE.
One of the most important concepts behind NIMBLE is to allow a combination of high-level pro-
cessing in R and low-level processing in C++. For example, when we write a Metropolis-Hastings
MCMC sampler in the NIMBLE language, the inspection of the model structure related to one
node is done in R, and the actual sampler calculations are done in C++. This separation between
setup and run steps will become clearer as we go.
3.1 NIMBLE adopts and extends the BUGS language for specify-
ing models
We adopted the BUGS language, and we have extended it to make it more flexible. The BUGS
language became widely used in WinBUGS, then in OpenBUGS and JAGS. These systems all
provide automatically-generated MCMC algorithms, but we have adopted only the language for
describing models, not their systems for generating MCMCs.
NIMBLE extends BUGS by:
1. allowing you to write new functions and distributions and use them in BUGS models;
2. allowing you to define multiple models in the same code using conditionals evaluated when
the BUGS code is processed;
3. supporting a variety of more flexible syntax such as R-like named parameters and more general
algebraic expressions.
By supporting new functions and distributions, NIMBLE makes BUGS an extensible language,
which is a major departure from previous packages that implement BUGS.
We adopted BUGS because it has been so successful, with over 30,000 users by the time they
stopped counting (Lunn et al., 2009). Many papers and books provide BUGS code as a way to
document their statistical models. We describe NIMBLE’s version of BUGS later. The web sites
for WinBUGS, OpenBUGS and JAGS provide other useful documntation on writing models in
BUGS. For the most part, if you have BUGS code, you can try NIMBLE.
NIMBLE does several things with BUGS code:
27
28 CHAPTER 3. MORE INTRODUCTION
1. NIMBLE creates a model definition object that knows everything about the variables and
their relationships written in the BUGS code. Usually you’ll ignore the model definition and
let NIMBLE’s default options take you directly to the next step.
2. NIMBLE creates a model object1 . This can be used to manipulate variables and operate
the model from R. Operating the model includes calculating, simulating, or querying the log
probability value of model nodes. These basic capabilities, along with the tools to query
model structure, allow one to write programs that use the model and adapt to its structure.
3. When you’re ready, NIMBLE can generate customized C++ code representing the model,
compile the C++, load it back into R, and provide a new model object that uses the compiled
model internally. We use the word ‘compile’ to refer to all of these steps together.
As an example of how radical a departure NIMBLE is from previous BUGS implementations,
consider a situation where you want to simulate new data from a model written in BUGS code.
Since NIMBLE creates model objects that you can control from R, simulating new data is trivial.
With previous BUGS-based packages, this isn’t possible.
More information about specifying and manipulating models is in Chapters 6 and 13.
1. NIMBLE creates a working R version of the nimbleFunction. This is most useful for debugging
(Section 15.7).
2. When you are ready, NIMBLE can generate C++ code, compile it, load it back into R and
give you new objects that use the compiled C++ internally. Again, we refer to these steps all
together as ‘compilation’. The behavior of compiled nimbleFunctions is usually very similar,
but not identical, to their uncompiled counterparts.
If you are familiar with object-oriented programming, you can think of a nimbleFunction as a class
definition. The setup function initializes a new object and run functions are class methods. Member
data are determined automatically as the objects from a setup function needed in run functions. If
no setup function is provided, the nimbleFunction corresponds to a simple (compilable) function
rather than a class.
More about writing algorithms is in Chapter 15.
Installing NIMBLE
4.2.1 MacOS
On MacOS, you should install Xcode. The command-line tools, which are available as a smaller
installation, should be sufficient. This is freely available from the Apple developer site and the App
1
This differs from most packages, which might need a C++ compiler only when the package is built. If you
normally install R packages using install.packages on Windows or MacOS, the package arrives already built to
your system.
31
32 CHAPTER 4. INSTALLING NIMBLE
Store.
In the somewhat unlikely event you want to install from the source package rather than the CRAN
binary package, the easiest approach is to use the source package provided at R-nimble.org. If you
do want to install from the source package provided by CRAN, you’ll need to install this gfortran
package.
4.2.2 Linux
On Linux, you can install the GNU compiler suite (gcc/g++). You can use the package manager
to install pre-built binaries. On Ubuntu, the following command will install or update make, gcc
and libc.
sudo apt-get install build-essential
4.2.3 Windows
On Windows, you should download and install Rtools.exe available from https://cran.r-project.
org/bin/windows/Rtools/. Select the appropriate executable corresponding to your version of R
(and follow the urge to update your version of R if you notice it is not the most recent).
Important: You must set the path so that the installer will add the location of the C++ compiler
and related tools to your system’s PATH variable, ensuring that R can find them. For R version
4.0 or greater (Rtools40) be sure to follow the instructions in the section Putting Rtools on the
PATH. For R version 3.6.3 or lesser (i.e., using Rtools35.exe) make sure to check the box labelled
“Add rtools to system PATH” (page 5 of the installation pages) (it should be checked by default).
After you click ‘Next’, you will get a page with a window for customizing the new PATH variable.
You shouldn’t need to do anything there, so you can simply click ‘Next’ again.
• If multiple C++ compilers are present on a system, be sure the PATH will find the right one.
All operating systems:
• If problems arise from generating and compiling C++ files from the default location in R’s
tempdir(), one can use the dirName argument to compileNimble to put such files elsewhere,
such as in a local working directory.
If those suggestions don’t help, please post about installation problems to the nimble-users Google
group or email [email protected].
/usr/local/include for the header file Eigen/Dense. You can specify a particular location in
either of two ways:
1. Set the environment variable EIGEN_DIR before installing the R package, for example: export
EIGEN_DIR=/usr/include/eigen3 in the bash shell.
2. Use R CMD INSTALL --configure-args='--with-eigen=/path/to/eigen' nimble_VERSION.tar.gz
or install.packages("nimble", configure.args = "--with-eigen=/path/to/eigen")
In these cases, the directory should be the full path to the directory that contains the Eigen
directory, e.g., /usr/include/eigen3. It is not the full path to the Eigen directory itself, i.e.,
NOT /usr/include/eigen3/Eigen.
Windows, and libnimble. Advanced users can also change their default compilers by editing the
Makevars file, see Section 1.2.1 of the Writing R Extensions manual available on CRAN.
Use of this file allows users to specify additional compilation and linking flags. See the Writing R
Extensions manual for more details of how this can be used and what it can contain.
36 CHAPTER 4. INSTALLING NIMBLE
Part II
Models in NIMBLE
37
Chapter 5
Models in NIMBLE are written using a variation on the BUGS language. From BUGS code,
NIMBLE creates a model object. This chapter describes NIMBLE’s version of BUGS. The next
chapter explains how to build and manipulate model objects.
39
40 CHAPTER 5. WRITING MODELS IN NIMBLE’S DIALECT OF BUGS
declarative language like BUGS is more like building a machine before using it. Each line declares
that a component should be plugged into the machine, but it doesn’t matter in what order they
are declared as long as all the right components are plugged in by the end of the code.
The machine in this case is a graphical model3 . A node (sometimes called a vertex) holds one value,
which may be a scalar or a vector. Edges define the relationships between nodes. A huge variety
of statistical models can be thought of as graphs.
Here is the code to define and create a simple linear regression model with four observations.
library(nimble)
mc <- nimbleCode({
intercept ~ dnorm(0, sd = 1000)
slope ~ dnorm(0, sd = 1000)
sigma ~ dunif(0, 100)
for(i in 1:4) {
predicted.y[i] <- intercept + slope * x[i]
y[i] ~ dnorm(predicted.y[i], sd = sigma)
}
})
library(igraph)
intercept slope
sigma
Figure 5.1: Graph of a linear regression model
The graph representing the model is shown in Figure 5.1. Each observation, y[i], is a node whose
edges say that it follows a normal distribution depending on a predicted value, predicted.y[i],
and standard deviation, sigma, which are each nodes. Each predicted value is a node whose edges
say how it is calculated from slope, intercept, and one value of an explanatory variable, x[i],
which are each nodes.
{
intercept ~ dnorm(0, sd = 1000)
slope ~ dnorm(0, sd = 1000)
sigma ~ dunif(0, 100)
for(i in 1:4) {
predicted.y[i] <- intercept + slope * x[i]
y[i] ~ dnorm(predicted.y[i], sd = sigma)
}
}
In this code, stochastic relationships are declared with ‘∼’ and deterministic relationships are de-
clared with ‘<-’. For example, each y[i] follows a normal distribution with mean predicted.y[i]
and standard deviation sigma. Each predicted.y[i] is the result of intercept + slope * x[i].
The for-loop yields the equivalent of writing four lines of code, each with a different value of i.
It does not matter in what order the nodes are declared. Imagine that each line of code draws
part of Figure 5.1, and all that matters is that the everything gets drawn in the end. Available
distributions, default and alternative parameterizations, and functions are listed in Section 5.2.4.
An equivalent graph can be created by this BUGS code:
{
intercept ~ dnorm(0, sd = 1000)
slope ~ dnorm(0, sd = 1000)
sigma ~ dunif(0, 100)
for(i in 1:4) {
y[i] ~ dnorm(intercept + slope * x[i], sd = sigma)
}
}
In this case, the predicted.y[i] nodes in Figure 5.1 will be created automatically by NIMBLE
and will have a different name, generated by NIMBLE.
for(i in 1:3)
mvx[8:10, i] ~ dmnorm(mvMean[3:5], cov = mvCov[1:3, 1:3, i])
# 5. User-provided distribution
w ~ dMyDistribution(hello = x, world = y)
# 6. Simple deterministic node
d1 <- a + b
# 7. Vector deterministic node with matrix multiplication
d2[] <- A[ , ] %*% mvMean[1:5]
# 8. Deterministic node with user-provided function
d3 <- foo(x, hooray = y)
}
When a variable appears only on the right-hand side, it can be provided via constants (in which
case it can never be changed) or via data or inits, as discussed in Chapter 6.
1. x follows a normal distribution with mean a + b*c and precision tau (default BUGS second
parameter for dnorm).
2. y follows a normal distribution with the same mean as x but a named standard deviation
parameter instead of a precision parameter (sd = 1/sqrt(precision)).
3. z[i, j] follows an exponential distribution with parameter r[ blockID[i] ]. This shows
how for-loops can be used for indexing of variables containing multiple nodes. Variables that
define for-loop indices (N and M) must also be provided as constants.
4. The arbitrary block mvx[8:10, i] follows a multivariate normal distribution, with a named
covariance matrix instead of BUGS’ default of a precision matrix. As in R, curly braces for
for-loop contents are only needed if there is more than one line.
5. w follows a user-defined distribution. See Chapter 12.
6. d1 is a scalar deterministic node that, when calculated, will be set to a + b.
7. d2 is a vector deterministic node using matrix multiplication in R’s syntax.
8. d3 is a deterministic node using a user-provided function. See Chapter 12.
NIMBLE does not allow multivariate nodes to be used without square brackets, which is an incom-
patibility with JAGS. Therefore a statement like xbar <- mean(x) in JAGS must be converted to
5.2. WRITING MODELS 45
xbar <- mean(x[]) (if x is a vector) or xbar <- mean(x[,]) (if x is a matrix) for NIMBLE4 .
Section 6.1.1.5 discusses how to provide NIMBLE with dimensions of x when needed.
Generally NIMBLE supports R-like linear algebra expressions and attempts to follow the same
rules as R about dimensions (although in some cases this is not possible). For example, x[1:3]
%*% y[1:3] converts x[1:3] into a row vector and thus computes the inner product, which is
returned as a 1 × 1 matrix (use inprod to get it as a scalar, which it typically easier). Like in R, a
scalar index will result in dropping a dimension unless the argument drop=FALSE is provided. For
example, mymatrix[i, 1:3] will be a vector of length 3, but mymatrix[i, 1:3, drop=FALSE]
will be a 1 × 3 matrix. More about indexing and dimensions is discussed in Section 11.3.2.7.
Since NIMBLE supports R-like algebraic expressions, an alternative in NIMBLE’s dialect of BUGS
is to use a vectorized declaration like this:
{
logY[1:10] <- log(Y[1:10])
}
There is an important difference between the models that are created by the above two methods.
The first creates 10 scalar nodes, logY[1] , … , logY[10]. The second creates one vector node,
logY[1:10]. If each logY[i] is used separately by an algorithm, it may be more efficient compu-
tationally if they are declared as scalars. If they are all used together, it will often make sense to
declare them as a vector.
4
In nimbleFunctions, as explained in later chapters, square brackets with blank indices are not necessary for
multivariate objects.
5
Note that the same distributions are available for writing nimbleFunctions, but in that case the default param-
eterizations and function names match R’s when possible. Please see Section 11.2.4 for how to use distributions in
nimbleFunctions.
46 CHAPTER 5. WRITING MODELS IN NIMBLE’S DIALECT OF BUGS
𝜏 >0
exp(−𝜆)𝜆𝑥
Poisson dpois(lambda = 𝜆) 𝑥! 0
𝜆>0
1 − (𝑘+1)
Γ( 𝑘+1
2 ) 𝜏 2 𝜏(𝑥−𝜇)2 2
Student t dt(mu = 𝜇, tau = 𝜏 , df = k) Γ( 𝑘
( 𝑘𝜋 ) {1 + 𝑘 }
2)
𝜏 > 0, 𝑘 > 0
1
Uniform dunif(min = a, max = b) 𝑏−𝑎 𝑎 𝑏
𝑎<𝑏
Weibull dweib(shape = v, lambda = 𝜆) 𝑣𝜆𝑥𝑣−1 exp(−𝜆𝑥𝑣 ) 0
𝑣 > 0, 𝜆 > 0
|𝑥|(𝑘−𝑝−1)/2 |𝑅|𝑘/2 exp{−tr(𝑅𝑥)/2}
Wishart dwish(R = R, df = k) 𝑝
2𝑝𝑘/2 𝜋𝑝(𝑝−1)/4 ∏𝑖=1 Γ((𝑘+1−𝑖)/2)
R 𝑝 × 𝑝 pos. def., 𝑘 ≥ 𝑝
|𝑥|−(𝑘+𝑝+1)/2 |𝑆|𝑘/2 exp{−tr(𝑆𝑥−1 )/2}
Inverse dinvwish(S = S, df = k) 𝑝
2𝑝𝑘/2 𝜋𝑝(𝑝−1)/4 ∏𝑖=1 Γ((𝑘+1−𝑖)/2)
Wishart S 𝑝 × 𝑝 pos. def., 𝑘 ≥ 𝑝
Note that dcar_normal, dflat and dhalfflat specify improper prior distributions and should
only be used when the posterior distribution of the model is known to be proper. Also for these
distributions, the density function returns the unnormalized density and the simulation function
returns NaN so these distributions are not appropriate for algorithms that need to simulate from
the prior or require proper (normalized) densities.
NIMBLE provides the LKJ distribution via dlkj_corr_cholesky for correlation matrices, dis-
cussed in Section 24 of Stan Development Team (2021a) and based on Lewandowski et al. (2009).
This distribution has various advantages (both from a modeling perspective and an MCMC fitting
perspective) over other prior distributions for correlation or covariance matrices such as the inverse
Wishart distribution.
For computational efficiency, the distribution is on the Cholesky factor of the correlation matrix
rather than the correlation matrix itself. As a result using this distribution in a model involves a
bit of care, including efficiently creating a covariance matrix from the correlation matrix and a set
of standard deviations.
Here is some example code illustrating how to use the distribution in a model.
code <- nimbleCode({
Ustar[1:p,1:p] ~ dlkj_corr_cholesky(1.3, p)
U[1:p,1:p] <- uppertri_mult_diag(Ustar[1:p, 1:p], sds[1:p])
for(i in 1:n)
y[i, 1:p] ~ dmnorm(mu[1:p], cholesky = U[1:p, 1:p], prec_param = 0)
})
48 CHAPTER 5. WRITING MODELS IN NIMBLE’S DIALECT OF BUGS
Note that we need to take the upper triangular Cholesky factor (Ustar) of the correlation matrix
and convert it to the upper triangular Cholesky factor of a covariance matrix (U), based on a vector
of standard deviations (sds), and use that in the parameterization of dmnorm that directly (and
therefore efficiently) uses the Cholesky of the covariance.
Other approaches are possible, but unless care is taken they are likely to be less computationally
efficient than the template above.
The template uses a user-defined nimbleFunction to efficiently combine the Cholesky of the correla-
tion matrix with a vector of standard deviations to produce the Cholesky of the covariance matrix.
That function is given here:
uppertri_mult_diag <- nimbleFunction(
run = function(mat = double(2), vec = double(1)) {
returnType(double(2))
p <- length(vec)
out <- matrix(nrow = p, ncol = p, init = FALSE)
for(i in 1:p)
out[ , i] <- mat[ , i] * vec[i]
return(out)
})
2. The BUGS parameterization is the one defined in the original BUGS language. In general this
is the parameterization for which conjugate MCMC samplers can be executed most efficiently.
For dgamma, this is (shape, rate).
3. An alternative parameterization is one that must be converted into the canonical parameter-
ization. For dgamma, NIMBLE provides both (shape, rate) and (mean, sd) parameterization
and creates nodes to calculate (shape, scale) from either (shape, rate) or (mean, sd). In the
case of dgamma, the BUGS parameterization is also an alternative parameterization.
Since NIMBLE provides compatibility with existing BUGS and JAGS code, the order of param-
eters places the BUGS parameterization first. For example, the order of parameters for dgamma
is dgamma(shape, rate, scale, mean, sd). Like R, if parameter names are not given, they are
taken in order, so that (shape, rate) is the default. This happens to match R’s order of parameters,
but it need not. If names are given, they can be given in any order. NIMBLE knows that rate is
an alternative to scale and that (mean, sd) are an alternative to (shape, scale or rate).
6
Usually this is the parameterization in the Rmath header of R’s C implementation of distributions.
5.2. WRITING MODELS 49
Note that for multivariate normal, multivariate t, Wishart, and Inverse Wishart, the canonical
parameterization uses the Cholesky decomposition of one of the precision/inverse scale or covari-
ance/scale matrix. For example, for the multivariate normal, if prec_param=TRUE, the cholesky
argument is treated as the Cholesky decomposition of a precision matrix. Otherwise it is treated
as the Cholesky decomposition of a covariance matrix.
In addition, NIMBLE supports alternative distribution names, known as aliases, as in JAGS, as
specified in Table 5.3.
We plan to, but do not currently, include the following distributions as part of core NIMBLE: beta-
binomial, Dirichlet-multinomial, F, Pareto, or forms of the multivariate t other than the standard
one provided.
See Section 12.1 to learn how to use nimbleFunctions to write new functions for use in BUGS code.
Link functions are specified as functions applied to a node on the left hand side of a BUGS expression.
To handle link functions in deterministic declarations, NIMBLE converts the declaration into an
equivalent inverse declaration. For example, log(y) <- x is converted into y <- exp(x). In other
words, the link function is just a simple variant for conceptual clarity.
To handle link functions in a stochastic declaration, NIMBLE does some processing that inserts an
additional node into the model. For example, the declaration logit(p[i]) ~ dnorm(mu[i],1), is
equivalent to the following two declarations:
• logit_p[i] ~ dnorm(mu[i], 1),
• p[i] <- expit(logit_p[i])
where expit is the inverse of logit.
Note that NIMBLE does not provide an automatic way of initializing the additional node
(logit_p[i] in this case), which is a parent node of the explicit node (p[i]), without explicitly
referring to the additional node by the name that NIMBLE generates.
5.2.7.1 Truncation
Either of the following forms,
x ~ dnorm(0, sd = 10) T(0, a)
x ~ T(dnorm(0, sd = 10), 0, a)
declares that x follows a normal distribution between 0 and a (inclusive of 0 and a). Either boundary
may be omitted or may be another node, such as a in this example. The first form is compatible
with JAGS, but in NIMBLE it can only be used when reading code from a text file. When writing
model code in R, the second version must be used.
Truncation means the possible values of x are limited a priori, hence the probability density of x
must be normalized7 . In this example it would be the normal probability density divided by its
integral from 0 to a. Like JAGS, NIMBLE also provides I as a synonym for T to accommodate
older BUGS code, but T is preferred because it disambiguates multiple usages of I in BUGS.
5.2.7.2 Censoring
Censoring refers to the situation where one datum gives the lower or upper bound on an unobserved
random variable. This is common in survival analysis, when for an individual still surviving at the
end of a study, the age of death is not known and hence is ‘censored’ (right-censoring). NIMBLE
adopts JAGS syntax for censoring, as follows:
censored[i] ~ dinterval(t[i], c[i])
t[i] ~ dweib(r, mu[i])
In the case of right-censoring, censored[i] should be given as data with a value of 1 if t[i]
is right-censored (t[i] > c[i]) and 0 if it is observed. The data vector for t should have NA
(indicating missing data) for any censored t[i] entries. (As a result, these nodes will be sampled
in an MCMC.) The vector for c should give the censoring times corresponding to censored entries
and a value above the observed times for uncensored entries (e.g., Inf). The values for c can be
provided via constants, inits, or data. We recommend providing via constants for values that
are fixed and via inits for values that are to be estimated or might be changed for some reason.
Left-censored observations would be specified by setting censored[i] to 0 and t[i] to NA.
The dinterval is not really a distribution but rather a trick: in the above example when
censored[i] = 1 it gives a ‘probability’ of 1 if t[i] > c[i] and 0 otherwise. This means
that t[i] <= c[i] is treated as impossible. More generally than simple right- or left-censoring,
censored[i] ~ dinterval(t[i], c[i, ]) is defined such that for a vector of increasing cut-
points, c[i, ], t[i] is enforced to fall within the censored[i]-th cutpoint interval. This is done
by setting data censored[i] as follows:
censored[i] = 0 if t[i] <= c[i, 1]
censored[i] = m if c[i, m] < t[i] <= c[i, m+1] for 1 ≤ 𝑚 ≤ 𝑀
censored[i] = M if c[i, M] < t[i]
7
NIMBLE uses the CDF and inverse CDF (quantile) functions of a distribution to do this; in some cases if one
uses truncation to include only the extreme tail of a distribution, numerical difficulties can arise.
5.2. WRITING MODELS 55
(The i index is provided only for consistency with the previous example.) The most common uses
of dinterval will be for left- and right-censored data, in which case c[i,] will be a single value
(and typically given as simply c[i]), and for interval-censored data, in which case c[i,] will be a
vector of two values.
Nodes following a dinterval distribution should normally be set as data with known values. Oth-
erwise, the node may be simulated during initialization in some algorithms (e.g., MCMC) and
thereby establish a permanent, perhaps unintended, constraint.
Censoring differs from truncation because censoring an observation involves bounds on a random
variable that could have taken any value, while in truncation we know a priori that a datum could
not have occurred outside the truncation range.
with constraint_data set (as data) to 1. This is equivalent to a half-normal distribution on the
half-plane 𝜇1 + 𝜇2 > 0. Nodes following dconstraint should be provided as data for the same
reason of avoiding unintended initialization described above for dinterval.
Of course, in many cases, parameterizing the model so that the constraints are automatically
respected may be a better strategy than using dconstraint. One should be cautious about con-
straints that would make it hard for an MCMC or optimization to move through the parameter
space (such as equality constraints that involve two or more parameters). For such restrictive con-
straints, general purpose algorithms that are not tailored to the constraints may fail or be inefficient.
If constraints are used, it will generally be wise to ensure the model is initialized with values that
satisfy them.
5.2.7.3.1 Ordering
To specify an ordering of parameters, such as 𝛼1 <= 𝛼2 <= 𝛼3 one can use dconstraint as follows:
constraint_data ~ dconstraint( alpha1 <= alpha2 & alpha2 <= alpha3 )
Note that unlike in BUGS, one cannot specify prior ordering using syntax such as
alpha[1] ~ dnorm(0, 1) I(, alpha[2])
alpha[2] ~ dnorm(0, 1) I(alpha[1], alpha[3])
alpha[3] ~ dnorm(0, 1) I(alpha[2], )
Also note that specifying prior ordering using T(,) can result in possibly unexpected results. For
example:
alpha1 ~ dnorm(0, 1)
alpha2 ~ dnorm(0, 1) T(alpha1, )
alpha3 ~ dnorm(0, 1) T(alpha2, )
will enforce alpha1 ≤ alpha2 ≤ alpha3, but it does not treat the three parameters symmetrically.
Instead it puts a marginal prior on alpha1 that is standard normal and then constrains alpha2
and alpha3 to follow truncated normal distributions. This is not equivalent to a symmetric prior
on the three alphas that assigns zero probability density when values are not in order.
NIMBLE does not support the JAGS sort syntax.
Chapter 6
This chapter explains how to build and manipulate model objects starting from BUGS code.
57
58 CHAPTER 6. BUILDING AND USING MODELS
WinBUGS, OpenBUGS and JAGS do not allow data values to be changed or different nodes to be
labeled as data without starting from the beginning again. Hence they do not distinguish between
constants and data.
For compatibility with BUGS and JAGS, NIMBLE allows both to be provided in the constants
argument to nimbleModel, in which case NIMBLE handles values for stochastic nodes as data and
everything else as constants.
Values for nodes that appear only on the right-hand side of BUGS declarations (e.g., covari-
ates/predictors) can be provided as constants or as data or initial values. There is no real difference
between providing as data or initial values and the values can be added after building a model via
setInits or setData.
6.1.1.2 Providing (or changing) data and initial values for an existing model
Whereas constants must be provided during the call to nimbleModel, data and initial values can be
provided later via the model member functions setData and setInits. For example, if pumpData
is a named list of data values (as above), then pump$setData(pumpData) sets the named variables
to the values in the list.
setData does two things: it sets the values of the data nodes, and it flags those nodes as containing
data. nimbleFunction programmers can then use that information to control whether an algorithm
should over-write data or not. For example, NIMBLE’s simulate functions by default do not
overwrite data values but can be told to do so. Values of data variables can be replaced, and the
indication of which nodes should be treated as data can be reset by using the resetData method,
e.g. pump$resetData().
To change data values without any modification of which nodes are flagged as containing data, sim-
ply use R’s usual assignment syntax to assign values in a compiled (or, more rarely, an uncompiled)
6.1. CREATING MODEL OBJECTS 59
model, e.g.,
cModel$y <- c(1.5, 2.5, 1.7)
This can be useful for running an MCMC with a different dataset of the same size (and of course the
same pattern of missingness, if any) without having to rebuild and recompile the MCMC, such as
in a simulation study. It is possible to change the data values in a compiled model using setData,
but we don’t recommend doing this because setData won’t modify which nodes are flagged as
containing data in the already-constructed MCMC, thereby potentially introducing confusion.
niter <- 10
set.seed(0)
Cobj$pumpMissMCMC$run(niter)
60 CHAPTER 6. BUILDING AND USING MODELS
## NULL
samples <- as.matrix(Cobj$pumpMissMCMC$mvSamples)
samples[1:5, 13:17]
Missing values may also occur in explanatory/predictor variables. Values for such variables should
be passed in via the data argument to nimbleModel, with NA for the missing values. In some
contexts, one would want to specify distributions for such explanatory variables, for example so
that an MCMC would impute the missing values.
Avoiding code duplication is a basic principle of good programming. In NIMBLE, one can use
definition-time if-then-else statements to create different models from the same code. As a simple
example, say we have a linear regression model and want to consider including or omitting x[2] as
an explanatory variable:
regressionCode <- nimbleCode({
intercept ~ dnorm(0, sd = 1000)
slope1 ~ dnorm(0, sd = 1000)
if(includeX2) {
slope2 ~ dnorm(0, sd = 1000)
for(i in 1:N)
predictedY[i] <- intercept + slope1 * x1[i] + slope2 * x2[i]
} else {
for(i in 1:N) predictedY[i] <- intercept + slope1 * x1[i]
}
sigmaY ~ dunif(0, 100)
for(i in 1:N) Y[i] ~ dnorm(predictedY[i], sigmaY)
})
Whereas the constants are a property of the model definition – since they may help determine the
model structure itself – data nodes can be different in different copies of the model generated from
the same model definition. The setData and setInits described above can be used for each copy
of the model.
Here’s an example with multivariate nodes. The first provides indices, so no dimensions argument
is needed, while the second omits the indices and provides a dimensions argument instead.
code <- nimbleCode({
y[1:K] ~ dmulti(p[1:K], n)
p[1:K] ~ ddirch(alpha[1:K])
log(alpha[1:K]) ~ dmnorm(alpha0[1:K], R[1:K, 1:K])
})
K <- 5
model <- nimbleModel(code, constants = list(n = 3, K = K,
alpha0 = rep(0, K), R = diag(K)),
check = FALSE)
In that example, since alpha0 and R are provided as constants, we don’t need to specify their
dimensions.
62 CHAPTER 6. BUILDING AND USING MODELS
6.1.2 Creating a model from standard BUGS and JAGS input files
Users with BUGS and JAGS experience may have files set up in standard formats for use in
BUGS and JAGS. readBUGSmodel can read in the model, data/constant values and initial values
in those formats. It can also take information directly from R objects somewhat more flexibly than
nimbleModel, specifically allowing inputs set up similarly to those for BUGS and JAGS. In either
case, after processing the inputs, it calls nimbleModel. Note that unlike BUGS and JAGS, only a
single set of initial values can be specified in creating a model. Please see help(readBUGSmodel)
for argument details.
As an example of using readBUGSmodel, let’s create a model for the pump example from BUGS.
pumpDir <- system.file('classic-bugs', 'vol1', 'pump', package = 'nimble')
pumpModel <- readBUGSmodel('pump.bug', data = 'pump-data.R',
inits = 'pump-init.R', dir = pumpDir)
Note that readBUGSmodel allows one to include var and data blocks in the model file as in some
of the BUGS examples (such as inhaler). The data block pre-computes constant and data values.
Also note that if data and inits are provided as files, the files should contain R code that creates
objects analogous to what would populate the list if a list were provided instead. Please see the
JAGS manual examples or the classic_bugs directory in the NIMBLE package for example syntax.
NIMBLE by and large does not need the information given in a var block but occasionally this is
used to determine dimensionality, such as in the case of syntax like xbar <- mean(x[]) where x
is a variable that appears only on the right-hand side of BUGS expressions.
Note that NIMBLE does not handle formatting such as in some of the original BUGS examples in
which data was indicated with syntax such as data x in 'x.txt'.
There are two ways to create new instances of a model, shown in this example:
simpleCode <- nimbleCode({
for(i in 1:N) x[i] ~ dnorm(0, 1)
})
Each copy of the model can have different nodes flagged as data and different values in any nodes.
They cannot have different values of N because that is a constant; it must be a constant because it
helps define the model.
6.2 NIMBLE models are objects you can query and manipulate
NIMBLE models are objects that can be modified and manipulated from R. In this section we
introduce some basic ways to use a model object. Chapter 13 covers more topics for writing
algorithms that use models.
In NIMBLE terminology:
• The variables of this model are a, y, z, and y.squared.
• The nodes of this model are a, y[1] , … , y[5], z[1,1] , … , z[5, 3], and y.squared[1:5].
In graph terminology, nodes are vertices in the model graph.
• The node functions of this model are a ~ dnorm(0, 0.001), y[i] ~ dnorm(a, 0.1),
z[i,j] ~ dnorm(y[i], sd = 0.1), and y.squared[1:5] <- y[1:5]^2. Each node’s
calculations are handled by a node function. Sometimes the distinction between nodes and
node functions is important, but when it is not important we may refer to both simply as
nodes.
• The scalar elements of this model include all the scalar nodes as well as the scalar elements
y.squared[1] , … , y.squared[5] of the multivariate node y.squared[1:5].
model$getVarNames()
Note that some of the nodes may be ‘lifted’ nodes introduced by NIMBLE (Section 13.1.2). In this
case lifted_d1_over_sqrt_oPtau_cP (this is a node for the standard deviation of the z nodes
using NIMBLE’s canonical parameterization of the normal distribution) is the only lifted node in
the model.
To determine the dependencies of one or more nodes in the model, you can use getDependencies
as discussed in Section 13.1.3.
## [1] 5
model[["a"]]
## [1] 5
model$y[2:4] <- rnorm(3)
model$y
model$z[1,]
## [1] -1.047984
model[["y[2]"]] <- -5
model$y
## [1] 0.4020118
model[["z[2:4, 1:2]"]][1, 2]
## [1] 1.464587
model$z[2, 2]
## [1] 1.464587
Notice that node names can include index blocks, such as model[["z[2:4, 1:2]"]], and these are
not strictly required to correspond to actual nodes. Such blocks can be subsequently sub-indexed
in the regular R manner, such as model[["z[2:4, 1:2]"]][1, 2].
multiVarModel$expandNodeNames("X[1,1:5]")
66 CHAPTER 6. BUILDING AND USING MODELS
## [1] TRUE
model$isData(c('z[1]', 'z[2]', 'a'))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
model$isData('z[1:3, 1]')
Algorithms in NIMBLE
67
Chapter 7
MCMC
NIMBLE provides a variety of paths to creating and executing an MCMC algorithm, which differ
greatly in their simplicity of use, and also in the options available and customizability.
The most direct approach to invoking the MCMC engine is using the nimbleMCMC function (Section
7.1). This one-line call creates and executes an MCMC, and provides a wide range of options for
controlling the MCMC: specifying monitors, burn-in, and thinning, running multiple MCMC chains
with different initial values, and returning posterior samples, summary statistics, and/or a WAIC
value. However, this approach is restricted to using NIMBLE’s default MCMC algorithm; further
customization of, for example, the specific samplers employed, is not possible.
The lengthier and more customizable approach to invoking the MCMC engine on a particular
NIMBLE model object involves the following steps:
1. (Optional) Create and customize an MCMC configuration for a particular model:
a. Use configureMCMC to create an MCMC configuration (see Section 7.2). The configura-
tion contains a list of samplers with the node(s) they will sample.
b. (Optional) Customize the MCMC configuration:
i. Add, remove, or re-order the list of samplers (Section 7.10 and help(samplers) in
R for details), including adding your own samplers (Section 15.5);
ii. Change the tuning parameters or adaptive properties of individual samplers;
iii. Change the variables to monitor (record for output) and thinning intervals for
MCMC samples.
2. Use buildMCMC to build the MCMC object and its samplers either from the model (using
default MCMC configuration) or from a customized MCMC configuration (Section 7.3).
3. Compile the MCMC object (and the model), unless one is debugging and wishes to run the
uncompiled MCMC.
4. Run the MCMC and extract the samples (Sections 7.4, 7.5 and 7.6).
5. Optionally, calculate the WAIC (Section 7.7).
Prior to version 0.8.0, NIMBLE provided two additional functions, MCMCsuite and compareMCMCs,
to facilitate comparison of multiple MCMC algorithms, either internal or external to NIMBLE.
69
70 CHAPTER 7. MCMC
Those capabilities have been redesigned and moved into a separate package called compareMCMCs.
End-to-end examples of MCMC in NIMBLE can be found in Sections 2.5-2.6 and Section 7.11.
# execute one MCMC chain, monitoring the "mu" and "sigma" variables,
# with thinning interval 10. fix the random number seed for reproducible
# results. by default, only returns posterior samples.
mcmc.out <- nimbleMCMC(code = code, data = data, inits = initsFunction,
monitors = c("mu", "sigma"), thin = 10,
niter = 20000, nchains = 1, setSeed = TRUE)
# using the existing Rmodel object, execute three MCMC chains with
# specified burn-in. return samples, summary statistics, and WAIC.
mcmc.out <- nimbleMCMC(model = Rmodel,
niter = 20000, nchains = 3, nburnin = 2000,
summary = TRUE, WAIC = TRUE)
The default configuration will contain a single sampler for each node in the model, and the default
72 CHAPTER 7. MCMC
The default configuration may be replaced by one generated from an automated parameter blocking
algorithm. This algorithm determines groupings of model nodes that, when jointly sampled with a
RW_block sampler, increase overall MCMC efficiency. Overall efficiency is defined as the effective
sample size of the slowest-mixing node divided by computation time. This is done by:
autoBlockConf <- configureMCMC(Rmodel, autoBlock = TRUE)
Note that this using autoBlock = TRUE compiles and runs MCMCs, progressively exploring differ-
ent sampler assignments, so it takes some time and generates some output. It is most useful for
determining effective blocking strategies that can be re-used for later runs. The additional control
argument autoIt may also be provided to indicate the number of MCMC samples to be used in
each trial of the automated blocking procedure (default 20,000).
If a data node is included in nodes, it will be assigned a sampler. This is the only way in which
a default sampler may be placed on a data node and will result in overwriting data values in the
node.
When adding samplers to a configuration using addSampler, the default control list can also be
over-ridden.
74 CHAPTER 7. MCMC
Samplers may be removed from the configuration object using removeSamplers, which accepts a
character vector of node or variable names, or a numeric vector of indices.
# Remove all samplers acting on "x" or any component of it
mcmcConf$removeSamplers("x")
7.2. THE MCMC CONFIGURATION 75
Samplers to retain may be specified reordered using setSamplers, which also accepts a character
vector of node or variable names, or a numeric vector of indices.
# Set the list of samplers to those acting on any components of the
# model variables "x", "y", or "z".
mcmcConf$setSamplers(c("x", "y", "z"))
# Truncate the current list of samplers to the first 10 and the 100th
mcmcConf$setSamplers(ind = c(1:10, 100))
The nimbleFunction definition underlying a particular sampler may be viewed using the
getSamplerDefinition method, using the sampler index as an argument. A node name argument
may also be supplied, in which case the definition of the first sampler acting on that node is
returned. In all cases, getSamplerDefinition only returns the definition of the first sampler
specified either by index or node name.
# Return the definition of the third sampler in the mcmcConf object
mcmcConf$getSamplerDefinition(3)
# change the 'adaptive' element of the control list of the third sampler
control <- samplerConfList[[3]]$control
control$adaptive <- FALSE
samplerConfList[[3]]$setControl(control)
A new set of monitor variables can be added to the MCMC configuration, overwriting the current
monitors, using the setMonitors method:
# Replace old monitors, now monitor "delta" and "gamma" only
mcmcConf$setMonitors("gamma", "delta")
The current lists of monitors and thinning intervals may be displayed using the printMonitors
1
See Section 14.1 for general information on modelValues.
78 CHAPTER 7. MCMC
method. Both sets of monitors (monitors and monitors2) may be reset to empty character vectors
by calling the resetMonitors method. The methods getMonitors and getMonitors2 return the
currently specified monitors and monitors2 as character vectors.
To record model log-probabilities from an MCMC, one can add monitors for logProb variables
(which begin with the prefix logProb_) that correspond to variables with (any) stochastic nodes.
For example, to record and extract log-probabilities for the variables alpha, sigma_mu, and Y:
mcmcConf <- configureMCMC(Rmodel, enableWAIC = TRUE)
mcmcConf$addMonitors("logProb_alpha", "logProb_sigma_mu", "logProb_Y")
Rmcmc <- buildMCMC(mcmcConf)
Cmodel <- compileNimble(Rmodel)
Cmcmc <- compileNimble(Rmcmc, project = Rmodel)
Cmcmc$run(10000)
samples <- as.matrix(Cmcmc$mvSamples)
The samples matrix will contain both MCMC samples and model log-probabilities.
Note that if you would like to be able to calculate the WAIC of the model, you should usu-
ally set enableWAIC = TRUE as an argument toconfigureMCMC (or to buildMCMC if not using
configureMCMC), or set nimbleOptions(MCMCenableWAIC = TRUE), which will enable WAIC cal-
culations for all subsequently built MCMC functions. For more information on WAIC calculations,
including situations in which you can calculate WAIC without having set enableWAIC = TRUE see
Section 7.7 or help(waic) in R.
When no customization is needed, one can skip configureMCMC and simply provide a model object
to buildMCMC. The following two MCMC functions will be identical:
mcmcConf <- configureMCMC(Rmodel) # default MCMC configuration
Rmcmc1 <- buildMCMC(mcmcConf)
For speed of execution, we usually want to compile the MCMC function to C++ (as is the case
for other NIMBLE functions). To do so, we use compileNimble. If the model has already been
compiled, it should be provided as the project argument so the MCMC will be part of the same
compiled project. A typical compilation call looks like:
7.4. USER-FRIENDLY EXECUTION OF MCMC ALGORITHMS: RUNMCMC 79
Alternatively, if the model has not already been compiled, they can be compiled together in one
line:
Cmcmc <- compileNimble(Rmodel, Rmcmc)
Note that if you compile the MCMC with another object (the model in this case), you’ll need to
explicitly refer to the MCMC component of the resulting object to be able to run the MCMC:
Cmcmc$Rmcmc$run(niter = 1000)
# run two chains, and specify the initial values for each
initsList <- list(list(mu = 1, sigma = 1),
list(mu = 2, sigma = 10))
mcmc.out <- runMCMC(Cmcmc, nchains = 2, inits = initsList)
The run method has optional arguments nburnin, thin and thin2. These can be used to specify
the number of pre-thinning burn-in samples to discard, and the post-burnin thinning intervals
for recording samples (corresponding to monitors and monitors2). If either thin and thin2
are provided, they will override the thinning intervals that were specified in the original MCMC
configuration object.
1. All model nodes are checked and filled or updated as needed, in valid (topological) order.
If a stochastic node is missing a value, it is populated using a call to simulate and its log
probability value is calculated. The values of deterministic nodes are calculated from their
parent nodes. If any right-hand-side-only nodes (e.g., explanatory variables) are missing a
value, an error results.
2. All MCMC sampler functions are reset to their initial state: the initial values of any sampler
control parameters (e.g., scale, sliceWidth, or propCov) are reset to their initial values, as
were specified by the original MCMC configuration.
3. The internal modelValues objects mvSamples and mvSamples2 are each resized to the appro-
priate length for holding the requested number of samples (niter/thin, and niter/thin2,
respectively).
This means that one can begin a new run of an existing MCMC without having to rebuild or
recompile the model or the MCMC. This can be helpful if one wants to use the same model and
MCMC configuration, but with different initial values, different values of data nodes (but which
7.5. RUNNING THE MCMC 81
nodes are data nodes must be the same), changes to covariate values(or other non-data, non-
parameter values) in the model, or a different number of MCMC iterations, thinning interval or
burn-in.
In contrast, when mcmc$run(niter, reset = FALSE) is called, the MCMC picks up from where it
left off, continuing the previous chain and expanding the output as needed. No values in the model
are checked or altered, and sampler functions are not reset to their initial states.
The run method also has an optional resetMV argument. This argument is only considered
when'reset is set to FALSE. When mcmc$run(niter, reset = FALSE, resetMV = TRUE) is called
the internal modelValues objects mvSamples and mvSamples2 are each resized to the appropriate
length for holding the requested number of samples (niter/thin, and niter/thin2, respectively)
and the MCMC carries on from where it left off. In other words, the previously obtained samples
are deleted (e.g. to reduce memory usage) prior to continuing the MCMC. The default value of
resetMV is FALSE.
will return a vector of the total time spent in each sampler, measured in seconds.
Note that modifying elements of the control list may greatly affect the performance of the RW_block
sampler. In particular, the sampler can take a long time to find a good proposal covariance when
the elements being sampled are not on the same scale. We recommend providing an informed
value for ‘propCov’ in this case (possibly simply a diagonal matrix that approximates the relative
scales), as well as possibly providing a value of ‘scale’ that errs on the side of being too small. You
may also consider decreasing ‘adaptFactorExponent’ and/or ‘adaptInterval’, as doing so has greatly
improved performance in some cases.
82 CHAPTER 7. MCMC
These modelValues objects can be converted into matrices using as.matrix or lists using as.list:
samplesMatrix <- as.matrix(mvSamples)
samplesList <- as.list(mvSamples)
samplesMatrix2 <- as.matrix(mvSamples2)
samplesList2 <- as.list(mvSamples2)
The column names of the matrices will be the node names of nodes in the monitored variables.
Then, for example, the mean of the samples for node x[2] could be calculated as:
mean(samplesMatrix[, "x[2]"])
The list version will contain an element for each variable that will be the size and shape of the
variable with an additional index for MCMC iteration. By default MCMC iteration will be the
first index, but including iterationAsLastIndex = TRUE will make it the last index.
Obtaining samples as matrices or lists is most common, but see Section 14.1 for more about pro-
gramming with modelValues objects, especially if you want to write nimbleFunctions to use the
samples.
runMCMC or nimbleMCMC output lists. One can use the member method mcmc$getWAICdetails for
additional quantities related to WAIC that are discussed below. “‘
Note that there is not a unique value of WAIC for a model. WAIC is calculated from Equations 5,
12, and 13 in Gelman et al. (2014) (i.e., using pWAIC2), as discussed in detail in Hug and Paciorek
(2021). Therefore, NIMBLE provides user control over how WAIC is calculated in two ways.
First, by default NIMBLE provides the conditional WAIC, namely the version of WAIC where all
parameters directly involved in the likelihood are treated as 𝜃 for the purposes of Equation 5 from
Gelman et al. (2014). Users can request the marginal WAIC (see Ariyo et al. (2020)), namely the
version of WAIC where latent variables are integrated over (i.e., using a marginal likelihood). This
is done by providing the waicControl list with a marginalizeNodes element to configureMCMC
or buildMCMC (when providing a model as the argument to buildMCMC). See help(waic) for more
details.
Second, WAIC relies on a partition of the observations, i.e., ‘pointwise’ prediction. By default, in
NIMBLE the sum over log pointwise predictive density values treats each data node as contributing
a single value to the sum. When a data node is multivariate, that data node contributes a single
value to the sum based on the joint density of the elements in the node. If one wants to group
data nodes such that the joint density within each group is used, one can provide the waicControl
list with a dataGroups element to configureMCMC or buildMCMC (when providing a model as the
argument to buildMCMC). See help(waic) for more details.
Note that based on a limited set of simulation experiments in Hug and Paciorek (2021), our tentative
recommendation is that users only use marginal WAIC if also using grouping.
Marginal WAIC requires using Monte Carlo simulation at each iteration of the MCMC to average
over draws for the latent variables. To assess the stability of the marginal WAIC to the number
of Monte Carlo iterations, one can examine how the WAIC changes with increasing iterations (up
to the full number of iterations specified via the nItsMarginal element of the waicControl list)
based on the WAIC_partialMC, lppd_partialMC, and pWAIC_partialMC elements of the detailed
WAIC output.
For comparing WAIC between two models, Vehtari et al. (2017) discuss using the per-observation
(more generally, per-data group) contributions to the overall WAIC values to get an approximate
standard error for the difference in WAIC between the models. These element-wise values are
available as the WAIC_elements, lppd_elements, and pWAIC_elements components of the detailed
WAIC output.
The second overall approach to WAIC available in NIMBLE allows one to calculate WAIC post
hoc after MCMC sampling using an MCMC object or matrix (or dataframe) containing posterior
samples. Simply set up the MCMC and run it without enabling WAIC (but making sure to
include in the monitors all stochastic parent nodes of the data nodes) and then use the function
calculateWAIC, as shown in this example:
samples <- runMCMC(Cmcmc, niter = 10000, nburnin = 1000)
## Using calculateWAIC with an MCMC object
calculateWAIC(Cmcmc)
## Using calculateWAIC with a matrix of samples
calculateWAIC(samples, model)
## Specifying additional burnin, so only last 5000 (1000+4000) iterations used
84 CHAPTER 7. MCMC
This approach only provides conditional WAIC without any grouping of data nodes (though one
can achieve grouping by grouping data nodes into multivariate nodes).
variables will be sampled using RJMCMC, but otherwise they are like any other nodes in the
model.
The configureRJ function modifies the MCMC configuration to (1) assign samplers that turn on
and off variable in the model and (2) modify the existing samplers for the regression coefficients to
use ‘toggled’ versions. The toggled versions invoke the samplers only when corresponding variable
is currently in the model. In the case where indicator variables are included in the model, sampling
to turn on and off variables is done using RJ_indicator samplers. In the case where indicator
variables are not included, sampling is done using RJ_fixed_prior samplers.
In the following we provide an example for the two different model specifications.
The targetNodes argument gives the coefficients (nodes) for which we want to do variable selection.
The indicatorNodes gives the corresponding indicator nodes, ordered to match targetNodes. The
control list gives the means and scale (standard deviation) for normal reversible jump proposals
for targetNodes. The means will typically be 0 (by default mean = 0 and scale = 1), but they
could be anything. An optional control element called fixedValue can be provided in the non-
indicator setting; this gives the value taken by nodes in targetNodes when they are out of the
model (by default, fixedValue is 0). All control elements can be scalars or vectors. A scalar
values will be used for all targetNodes. A vector value must be of equal length as targetNodes
and will be used in order.
To use RJMCMC on a vector of coefficients with a corresponding vector of indicator variables, sim-
ply provide the variable names for targetNodes and indicatorNodes. For example, targetNodes
= "beta" is equivalent to targetNodes = c("beta[1]", "beta[2]") and indicatorNodes =
"z" is equivalent to indicatorNodes = c("z[1]", "z[2]"). Expansion of variable names into a
vector of node names will occur as described in Section 13.3.1.1. When using this method, both
arguments must be provided as variable names to be expanded.
Next we can see the result of configureRJ by printing the modified list of samplers:
RJexampleConf$printSamplers()
vector of values for the argument priorProb. This case does not allow for a stochastic prior.
configureRJ(conf = RJexampleConf2,
targetNodes = c("beta1", "beta2"),
priorProb = 0.5,
control = list(mean = 0, scale = 2, fixedValue = c(1.5, 0)))
## print samplers after configureRJ
RJexampleConf2$printSamplers()
3
NIMBLE’s internal definitions of these relationships can be viewed with
nimble:::conjugacyRelationshipsInputList.
7.10. SAMPLERS PROVIDED WITH NIMBLE 89
Conjugate sampler functions may (optionally) dynamically check that their own posterior likelihood
calculations are correct. If incorrect, a warning is issued. However, this functionality will roughly
double the run-time required for conjugate sampling. By default, this option is disabled in NIMBLE.
This option may be enabled with nimbleOptions(verifyConjugatePosteriors = TRUE).
If one wants information about conjugate node relationships for other purposes, they can be ob-
tained using the checkConjugacy method on a model. This returns a named list describing all
conjugate relationships. The checkConjugacy method can also accept a character vector argument
specifying a subset of node names to check for conjugacy.
ically (or numerically) integrates over latent model nodes. Or one could use a sampler with a log-
likelihood that comes from a stochastic approximation such as a particle filter (see below), allowing
composition of a particle MCMC (PMCMC) algorithm (Andrieu et al., 2010). The RW_llFunction
sampler handles this by using a Metropolis-Hastings algorithm with a normal proposal distribution
and a user-provided log-likelihood function. To allow compiled execution, the log-likelihood func-
tion must be provided as a specialized instance of a nimbleFunction. The log-likelihood function
may use the same model as the MCMC as a setup argument (as does the example below), but
if so the state of the model should be unchanged during execution of the function (or you must
understand the implications otherwise).
The RW_llFunction sampler can be customized using the control list argument to set the initial
proposal distribution scale and the adaptive properties for the Metropolis-Hastings sampling. In
addition, the control list argument must contain a named llFunction element. This is the
specialized nimbleFunction that calculates the log-likelihood; it must accept no arguments and
return a scalar double number. The return value must be the total log-likelihood of all stochastic
dependents of the target nodes – and, if includesTarget = TRUE, of the target node(s) themselves
– or whatever surrogate is being used for the total log-likelihood. This is a required control list
element with no default. See help(samplers) for details.
Note that we need to return ll[1] and not just ll because there are no scalar variables in compiled
models. Hence y and other variables, and therefore ll, are of dimension 1 (i.e., vectors / one-
dimensional arrays), so we need to specify the first element in order to have the return type be a
scalar.
###########################################
##### MCMC configuration and building #####
###########################################
###################################
##### compile to C++, and run #####
###################################
###################################
#### run multiple MCMC chains #####
###################################
lapply(samplesList, dim)
The NIMBLE algorithm library is growing and currently includes a suite of sequential Monte Carlo
(particle filtering) algorithms, particle MCMC for combining particle filters with MCMC, iterated
filtering version 2 and Monte Carlo expectation maximization (MCEM) for maximum likelihood
estimation, and k-fold cross-validation.
95
96CHAPTER 8. SEQUENTIAL MONTE CARLO, PARTICLE MCMC, ITERATED FILTERING, AND MCEM
unequally-weighted samples from the posterior distribution of the latent states, along with weights
for each particle. In addition, the bootstrap and auxiliary particle filters return estimates of the
log-likelihood of the given state-space model.
We first create a linear state-space model to use as an example for our particle filter algorithms.
# Building a simple linear state-space model.
# x is latent space, y is observed data
timeModelCode <- nimbleCode({
x[1] ~ dnorm(mu_0, 1)
y[1] ~ dnorm(x[1], 1)
for(i in 2:t){
x[i] ~ dnorm(x[i-1] * a + b, 1)
y[i] ~ dnorm(x[i] * c, 1)
}
a ~ dunif(0, 1)
b ~ dnorm(0, 1)
c ~ dnorm(1,1)
mu_0 ~ dnorm(0, 1)
})
Once each filter has been run, we can extract samples from the posterior distribution of our latent
states as follows:
# Equally-weighted samples (available from all filters)
bootEWSamp <- as.matrix(cBootF$mvEWSamples) # alternative: as.list
auxEWSamp <- as.matrix(cAuxF$mvEWSamples)
LWFEWSamp <- as.matrix(cLWF$mvEWSamples)
ENKFEWSamp <- as.matrix(cENKF$mvEWSamples)
Here we apply IF2 to Nile River flow data, specifying a changepoint in the year the Aswan Dam
was constructed, as the dam altered river flows.
library(FKF)
Note that the prior distributions for the parameters are not used by IF2, except possibly to obtain
boundaries of valid parameter values (not the case here).
Now we build the filter, specifying user-controlled standard deviations (in this case the same as
the perturbation sigma values) for use in generating the initial particles for the parameters via the
control list.
filter <- buildIteratedFilter2(model = flowModel,
nodes = 'x',
params = c('logSigmaInnovations',
'logSigmaMeasurements',
'meanShift1899'),
baselineNode = 'x0',
control = list(sigma = c(0.1, 0.1, 5),
initParamSigma = c(0.1, 0.1, 5)))
cFlowModel <- compileNimble(flowModel)
cFilter <- compileNimble(filter, project = flowModel)
We now run the algorithm with 1000 particles for 100 iterations with the schedule parameter equal
to 0.2.
In addition to the estimates, we can extract the values of the log-likelihood, the estimates and the
standard deviation of the parameter particles as they evolve over the iterations, in order to assess
convergence.
100CHAPTER 8. SEQUENTIAL MONTE CARLO, PARTICLE MCMC, ITERATED FILTERING, AND MCEM
set.seed(1)
est <- cFilter$run(m = 1000, niter = 100, alpha = 0.2)
Comparing to use of the the Kalman Filter from the FKF package, we see the log-likelihood is
fairly similar:
dtpred <- matrix(0, ncol = length(Nile))
dtpred[28] <- est[3]
ct <- matrix(0)
Zt <- Tt <- matrix(1)
## [1] -626.5521
= "RW_PF" or type = "RW_PF_block", a syntax similar to the other MCMC samplers listed in
Section 7.10.
The RW_PF sampler and RW_PF_block sampler can be customized using the control list argument
to set the adaptive properties of the sampler and options for the particle filter algorithm to be
used. In addition, providing pfOptimizeNparticles=TRUE in the control list will use an exper-
imental algorithm to estimate the optimal number of particles to use in the particle filter. See
help(samplers) for details. The MCMC configuration for the timeModel in the previous section
will serve as an example for the use of our PMCMC sampler. Here we use the identity matrix as
our proposal covariance matrix.
timeConf <- configureMCMC(rTimeModel) # default MCMC configuration
The type = "RW_PF" and type = "RW_PF*block" samplers default to using a bootstrap filter.
The adapatation control parameters adaptive, adaptInterval, and adaptScaleOnly work in the
same way as for an RW and RW*block samplers. However, it is not clear if the same approach
to adaptation works well for PMCMC, so one should consider turning off adaptation and using a
well-chosen proposal covariance.
It is also possible that more efficient results can be obtained by using a custom filtering algorithm.
Choice of filtering algorithm can be controlled by the pfType control list entry. The pfType
entry can be set either to 'bootstrap' (the default), 'auxiliary', or the name of a user-defined
nimbleFunction that returns a likelihood approximation.
Any user-defined filtering nimbleFunction named in the pfType control list entry must satsify the
following:
2. The nimbleFunction must have setup code that accepts the following (and only the following)
arguments:
• model, the NIMBLE model object that the MCMC algorithm is defined on.
• latents, a character vector specifying the latent model nodes over which the particle
filter will stochastically integrate over to estimate the log-likelihood function.
• control, an R list object. Note that the control list can be used to pass in any
additional information or arguments that the custom filter may require.
3. The nimbleFunction must have a run function that accepts a single integer arugment (the
number of particles to use), and returns a scalar double (the log-likelihood estimate).
4. The nimbleFunction must define, in setup code, a modelValues object named mvEWSamples
that is used to contain equally weighted samples of the latent states (that is, the latents
argument to the setup function). Each time the run() method of the nimbleFunction is
called with number of particles m, the mvEWSamples modelValues object should be resized to
be of size m via a call to resize(mvEWSamples, m).
102CHAPTER 8. SEQUENTIAL MONTE CARLO, PARTICLE MCMC, ITERATED FILTERING, AND MCEM
compileNimble(pump)
The first argument buildMCEM, model, is a NIMBLE model, which can be either the uncompiled or
compiled version. At the moment, the model provided cannot be part of another MCMC sampler.
Initial values for the parameters are taken to be the values in the model at the time buildMCEM is
called, unless the values in the compiled model are changed before running the MCEM.
The ascent-based MCEM algorithm has a number of control options:
The latentNodes argument should indicate the nodes that will be integrated over (sampled via
MCMC), rather than maximized. These nodes must be stochastic, not deterministic! latentNodes
will be expanded as described in Section 13.3.1.1. I.e., either latentNodes = "x" or latentNodes
= c("x[1]", "x[2]") will treat x[1] and x[2] as latent nodes if x is a vector of two values. All
other non-data nodes will be maximized over. Note that latentNodes can include discrete nodes,
but the nodes to be maximized cannot.
The burnIn argument indicates the number of samples from the MCMC for the E-step that should
be discarded when computing the expected likelihood in the M-step. Note that burnIn can be set
to values lower than in standard MCMC computations, as each iteration will start where the last
left off.
8.2. MONTE CARLO EXPECTATION MAXIMIZATION (MCEM) 103
The mcmcControl argument will be passed to configureMCMC to define the MCMC to be used.
The MCEM algorithm automatically detects box constraints for the nodes that will be optimized,
using NIMBLE’s getBounds function. It is also possible for a user to manually specify constraints
via the boxConstraints argument. Each constraint given should be a list in which the first element
is the names of the nodes or variables that the constraint will be applied to and the second element
is a vector of length two, in which the first value is the lower limit and the second is the upper limit.
Values of Inf and -Inf are allowed. If a node is not listed, its constraints will be automatically
determined by NIMBLE. These constraint arguments are passed as the lower and upper arguments
to R’s optim function, using method = "L-BFGS-B". Note that NIMBLE will give a warning if a
user-provided constraint is more extreme than the constraint determined by NIMBLE.
The value of the buffer argument shrinks the boxConstraints by this amount. This can help
protect against non-finite values occurring when a parameter is on the boundary.
In addition, the MCEM has some extra control options that can be used to further tune the
convergence criterion. See help(buildMCEM) for more information.
The buildMCEM function returns a list with two elements. The first element is a function called
run, which will use the MCEM algorithm to estimate the MLEs. The second function is called
estimateCov, and is described in Section 8.2.1. The run function can be run as follows. There
is only one run-time argument, initM, which is the number of MCMC iterations to use when the
algorithm is initialized.
pumpMLE <- pumpMCEM$run(initM = 1000)
## Iteration Number: 1.
## Current number of MCMC iterations: 1000.
## Parameter Estimates:
## alpha beta
## 0.8219803 1.1492317
## Convergence Criterion: 1.001.
## Iteration Number: 2.
## Current number of MCMC iterations: 1000.
## Parameter Estimates:
## alpha beta
## 0.818586 1.237039
## Convergence Criterion: 0.02393763.
## Iteration Number: 3.
## Current number of MCMC iterations: 1000.
## Parameter Estimates:
## alpha beta
## 0.8274042 1.2673636
## Convergence Criterion: 0.002330748.
## Iteration Number: 4.
## Current number of MCMC iterations: 3845.
## Parameter Estimates:
## alpha beta
## 0.8270797 1.2730042
## Convergence Criterion: 0.0002820885.
104CHAPTER 8. SEQUENTIAL MONTE CARLO, PARTICLE MCMC, ITERATED FILTERING, AND MCEM
pumpMLE
## alpha beta
## 0.8270797 1.2730042
Direct maximization after analytically integrating over the latent nodes (possible for this model
but often not feasible) gives estimates of 𝛼̂ = 0.823 and 𝛽 ̂ = 1.261, so the MCEM seems to do
pretty well, though tightening the convergence criteria may be warranted in actual usage.
## alpha beta
## alpha 0.1283888 0.2180972
## beta 0.2180972 0.6377524
# Alternatively, you can manually specify the MLE values as a named vector.
pumpCov <- pumpMCEM$estimateCov(MLEs = c(alpha = 0.823, beta = 1.261))
Chapter 9
Spatial models
NIMBLE supports two variations of conditional autoregressive (CAR) model structures: the im-
proper intrinsic Gaussian CAR (ICAR) model, and a proper Gaussian CAR model. This includes
distributions to represent these spatially-dependent model structures in a BUGS model, as well as
specialized MCMC samplers for these distributions.
ICAR models are improper priors for random fields (e.g., temporal or spatial processes). The
prior is a joint prior across a collection of latent process values. For more technical details on CAR
models, including higher-order CAR models, please see Rue and Held (2005), Banerjee et al. (2015),
and Paciorek (2009). Since the distribution is improper it should not be used as the distribution
for data values, but rather to specify a prior for an unknown process. As discussed in the references
above, the distribution can be seen to be a proper density in a reduced dimension subspace; thus
the impropriety only holds on one or more linear combinations of the latent process values.
In addition to our focus here on CAR modeling for spatial data, the ICAR model can also be used
in other contexts, such as for temporal data in a discrete time context.
9.1.1.1 Specification
The dcar_normal distribution is specified for a set of N spatially dependent regions as:
105
106 CHAPTER 9. SPATIAL MODELS
The adj, weights and num parameters define the adjacency structure and associated weights of
the spatially-dependent field. See help('CAR-Normal') for details of these parameters. When
specifying a CAR distribution, these parameters must have constant values. They do not necessarily
have to be specified as constants when creating a model object using nimbleModel, but they
should be defined in a static way: as right-hand-side only variables with initial values provided as
constants, data or inits, or using fixed numerical deterministic declarations. Each of these two
approaches for specifying values are shown in the example.
The adjacency structure defined by adj and the associated weights must be symmetric. That is,
if region 𝑖 is neighbor of region 𝑗, then region 𝑗 must also be a neighbor of region 𝑖. Further, the
weights associated with these reciprocating relationships must be equal. NIMBLE performs a check
of these symmetries and will issue an error message if asymmetry is detected.
The scalar precision tau may be treated as an unknown model parameter and itself assigned a
prior distribution. Care should be taken in selecting a prior distribution for tau, and WinBUGS
suggests that users be prepared to carry out a sensitivity analysis for this choice.
When specifying a higher-order CAR process, the number of constraints c can be explicitly provided
in the model specification. This would be the case, for example, when specifying a thin-plate spline
(second-order) CAR model, for which c should be 2 for a one-dimensional process and 3 for a two-
dimensional (e.g., spatial) process, as discussed in Rue and Held (2005) and Paciorek (2009). If c
is omitted, NIMBLE will calculate c as the number of disjoint groups of regions in the adjacency
structure, which implicitly assumes a first-order CAR process for each group.
By default there is no zero-mean constraint imposed on the CAR process, and thus the mean is
implicit within the CAR process values, with an implicit improper flat prior on the mean. To
avoid non-identifiability, one should not include an additional parameter for the mean (e.g., do
not include an intercept term in a simple CAR model with first-order neighborhood structure).
When there are disjoint groups of regions and the constraint is not imposed, there is an implicit
distinct improper flat prior on the mean for each group, and it would not make sense to impose
the constraint since the constraint holds across all regions. Similarly, if one sets up a neighborhood
structure for higher-order CAR models, it would not make sense to impose the zero-mean constraint
as that would account for only one of the eigenvalues that are zero. Imposing this constraint (by
specifying the parameter zero_mean = 1) allows users to model the process mean separately, and
hence a separate intercept term should be included in the model.
• A symmetric adjacency matrix of weights (with diagonal elements equal to zero), using
as.carAdjacency(weightMatrix)
• Two length-N lists with numeric vector elements giving the neighboring indices and associated
weights for each region, using as.carAdjacency(neighborList, weightList)
These conversions should be done in R, and the resulting adj, weights, num vectors can be passed
as constants into nimbleModel.
9.1.1.2 Density
For process values 𝑥 = (𝑥1 , … , 𝑥𝑁 ) and precision 𝜏 , the improper CAR density is given as:
9.1. INTRINSIC GAUSSIAN CAR MODEL: DCAR_NORMAL 107
𝜏 2
𝑝(𝑥|𝜏 ) ∝ 𝜏 (𝑁−𝑐)/2 𝑒− 2 ∑𝑖≠𝑗 𝑤𝑖𝑗 (𝑥𝑖 −𝑥𝑗 )
where the summation over all (𝑖, 𝑗) pairs, with the weight between regions 𝑖 and 𝑗 given by 𝑤𝑖𝑗 , is
equivalent to summing over all pairs for which region 𝑖 is a neighbor of region 𝑗. Note that the
value of 𝑐 modifies the power to which the precision is raised, accounting for the impropriety of the
density based on the number of zero eigenvalues in the implicit precision matrix for 𝑥.
For the purposes of MCMC sampling the individual CAR process values, the resulting conditional
prior of region 𝑖 is:
where 𝑥−𝑖 represents all elements of 𝑥 except 𝑥𝑖 , the neighborhood 𝒩𝑖 of region 𝑖 is the set of all
𝑗 for which region 𝑗 is a neighbor of region 𝑖, 𝑤𝑖+ = ∑𝑗∈𝒩 𝑤𝑖𝑗 , and the Normal distribution is
𝑖
parameterized in terms of precision.
9.1.2 Example
Here we provide an example model using the intrinsic Gaussian dcar_normal distribution. The
CAR process values are used in a spatially-dependent Poisson regression.
To mimic the behavior of WinBUGS, we specify zero_mean = 1 to enforce a zero-mean constraint
on the CAR process, and therefore include a separate intercept term alpha in the model. Note
that we do not necessarily recommend imposing this constraint, per the discussion earlier in this
chapter.
code <- nimbleCode({
alpha ~ dflat()
beta ~ dnorm(0, 0.0001)
tau ~ dgamma(0.001, 0.001)
s[1:N] ~ dcar_normal(adj[1:L], weights[1:L], num[1:N], tau, zero_mean = 1)
for(i in 1:N) {
log(lambda[i]) <- alpha + beta*x[i] + s[i]
y[i] ~ dpois(lambda[i])
}
})
L <- 8
constants <- list(N = 4, L = L, num = c(3, 2, 2, 1), weights = rep(1, L),
adj = c(2,3,4,1,3,1,2,1), x = c(0, 2, 2, 8))
data <- list(y = c(6, 9, 7, 12))
inits <- list(alpha = 0, beta = 0, tau = 1, s = c(0, 0, 0, 0))
Rmodel <- nimbleModel(code, constants, data, inits)
The resulting model may be carried through to MCMC sampling. NIMBLE will assign a specialized
sampler to the update the elements of the CAR process. See Chapter 7 for information about
NIMBLE’s MCMC engine, and Section 9.3 for details on MCMC sampling of the CAR processes.
108 CHAPTER 9. SPATIAL MODELS
9.2.1.1 Specification
The dcar_proper distribution is specified for a set of N spatially dependent regions as:
x[1:N] ~ dcar_proper(mu, C, adj, num, M, tau, gamma)
There is no option of a zero-mean constraint for proper CAR process, and instead the mean for
each region is specified by the mu parameter. The elements of mu can be assigned fixed values or
may be specified using one common, or multiple, prior distributions.
The C, adj, num and M parameters define the adjacency structure, normalized weights, and con-
ditional variances of the spatially-dependent field. See help('CAR-Proper') for details of these
parameters. When specifying a CAR distribution, these parameters must have constant values.
They do not necessarily have to be specified as constants when creating a model object using
nimbleModel, but they should be defined in a static way: as right-hand-side only variables with
initial values provided as constants, data or inits, or using fixed numerical deterministic decla-
rations.
The adjacency structure defined by adj must be symmetric. That is, if region 𝑖 is neighbor of
region 𝑗, then region 𝑗 must also be a neighbor of region 𝑖. In addition, the normalized weights
specified in C must satisfy a symmetry constraint jointly with the conditional variances given in
M. This constraint requires that 𝑀 −1 𝐶 is symmetric, where 𝑀 is a diagonal matrix of conditional
variances and 𝐶 is the normalized (each row sums to one) weight matrix. Equivalently, this implies
that 𝐶𝑖𝑗 𝑀𝑗𝑗 = 𝐶𝑗𝑖 𝑀𝑖𝑖 for all pairs of neighboring regions 𝑖 and 𝑗. NIMBLE performs a check of
these symmetries and will issue an error message if asymmetry is detected.
Two options are available to simplify the process of constructing the C and M arguments; both options
are demonstrated in the example. First, these arguments may be omitted from the dcar_proper
specification. In this case, values of C and M will be generated that correspond to all weights being
equal to one, or equivalently, a symmetric weight matrix containing only zeros and ones. Note that
C and M should either both be provided, or both be omitted from the specification.
9.2. PROPER GAUSSIAN CAR MODEL: DCAR_PROPER 109
Second, a convenience function as.carCM is provided to generate the C and M arguments corre-
sponding to a specified set of symmetric unnormalized weights. If weights contains the non-zero
weights corresponding to an unnormalized weight matrix (weights is precisely the argument that
can be used in the dcar_normal specification), then a list containing C and M can be generated
using as.carCM(adj, weights, num). In this case, the resulting C contains the row-normalized
weights, and the resulting M is a vector of the inverse row-sums of the unnormalized weight matrix.
The scalar precision tau may be treated as an unknown model parameter and itself assigned a
prior distribution. Care should be taken in selecting a prior distribution for tau, and WinBUGS
suggests that users be prepared to carry out a sensitivity analysis for this choice.
An appropriate value of the gamma parameter ensures the propriety of the dcar_proper distribution.
The value of gamma must lie between fixed bounds, which are given by the reciprocals of the largest
and smallest eigenvalues of 𝑀 −1/2 𝐶𝑀 1/2 . These bounds can be calculated using the function
carBounds or separately using the functions carMinBound and carMaxBound. For compatibility
with WinBUGS, NIMBLE provides min.bound and max.bound as aliases for carMinBound and
carMaxBound. Rather than selecting a fixed value of gamma within these bounds, it is recommended
that gamma be assigned a uniform prior distribution over the region of permissible values.
Note that when C and M are omitted from the dcar_proper specification (and hence all weights are
taken as one), or C and M are calculated from a symmetric weight matrix using the utility function
as.carCM, then the bounds on gamma are necessarily (−1, 1). In this case, gamma can simply be
assigned a prior over that region. This approach is shown in both examples.
9.2.1.2 Density
The proper CAR density is given as:
1
𝑝(𝑥|𝜇, 𝐶, 𝑀 , 𝜏 , 𝛾) ∼ MVN (𝜇, 𝜏 (𝐼 − 𝛾𝐶)−1 𝑀 )
𝑀𝑖𝑖
𝑝(𝑥𝑖 |𝑥−𝑖 , 𝜇, 𝐶, 𝑀 , 𝜏 , 𝛾) ∼ N (𝜇𝑖 + ∑𝑗∈𝒩 𝛾 𝐶𝑖𝑗 (𝑥𝑗 − 𝜇𝑗 ), 𝜏 )
𝑖
where 𝑥−𝑖 represents all elements of 𝑥 except 𝑥𝑖 , the neighborhood 𝒩𝑖 of region 𝑖 is the set of all 𝑗
for which region 𝑗 is a neighbor of region 𝑖, and the Normal distribution is parameterized in terms
of variance.
9.2.2 Example
We provide two example models using the proper Gaussian dcar_proper distribution. In both,
the CAR process values are used in a spatially-dependent logistic regression to model binary pres-
ence/absence data. In the first example, the C and M parameters are omitted, which uses weights
equal to one for all neighbor relationships. In the second example, symmetric unnormalized weights
are specified, and as.carCM is used to construct the C and M parameters to the dcar_proper dis-
tribution.
110 CHAPTER 9. SPATIAL MODELS
Each of the resulting models may be carried through to MCMC sampling. NIMBLE will assign
a specialized sampler to update the elements of the CAR process. See Chapter 7 for information
about NIMBLE’s MCMC engine, and Section 9.3 for details on MCMC sampling of the CAR
processes.
9.3. MCMC SAMPLING OF CAR MODELS 111
Note that these univariate CAR samplers are not the same as NIMBLE’s standard conjugate,
RW, and posterior_predictive samplers, but rather specialized versions for operating on a CAR
distribution. Details of these assignments are strictly internal to the CAR samplers.
In future versions of NIMBLE we expect to provide block samplers that update the entire CAR
process as a single sample. This may provide improved MCMC performance by accounting for
dependence between elements, particularly when conjugacy is available.
For compatibility with WinBUGS, NIMBLE also allows an initial value of NA to be provided for
regions with zero neighbors. This particular initialization is required in WinBUGS, so this allows
users to make use of existing WinBUGS code.
This behavior is different from that of WinBUGS, where the value of zero-neighbor regions of
car.normal nodes is set to and fixed at zero.
112 CHAPTER 9. SPATIAL MODELS
Also note that for the dcar_proper distribution if any regions have zero neighbors the joint density
of the process cannot be calculated. As a result one cannot do MCMC sampling of unknown
parameters affecting the mean (mu) of the process, though one can instead use an uncentered
parameterization in which the mean is added to the process rather than the process being centered
on the mean. Or one could remove such regions from the process and model them separately.
𝑖𝑖𝑑
𝑦𝑖 ∣ 𝐺 ∼ ∫ ℎ(𝑦𝑖 ∣ 𝜃)𝐺(𝑑𝜃),
𝐺 ∣ 𝛼, 𝐺0 ∼ 𝐷𝑃 (𝛼, 𝐺0 ),
where ℎ(⋅ ∣ 𝜃) is a suitable kernel with parameter 𝜃, and 𝛼 and 𝐺0 are the concentration and baseline
distribution parameters of the DP, respectively. DP mixture models can be written with different
levels of hierarchy, all being equivalent to the model above.
When the random measure 𝐺 is integrated out from the model, the DP mixture model can be
written using latent or membership variables, 𝑧𝑖 , following a Chinese Restaurant Process (CRP)
distribution (Blackwell and MacQueen, 1973), discussed in Section 10.2. The model takes the form
𝑖𝑛𝑑
𝑦𝑖 ∣ 𝜃,̃ 𝑧𝑖 ∼ ℎ(⋅ ∣ 𝜃𝑧̃ 𝑖 ),
𝑖𝑖𝑑
𝑧 ∣ 𝛼 ∼ CRP(𝛼), 𝜃𝑗̃ ∼ 𝐺0 ,
where CRP(𝛼) denotes the CRP distribution with concentration parameter 𝛼.
If a stick-breaking representation (Sethuraman, 1994), discussed in section 10.3, is assumed for the
random measure 𝐺, then the model takes the form
∞
⋆ 𝑖𝑛𝑑
𝑦𝑖 ∣ 𝜃 , 𝑣 ∼ ∑ {𝑣𝑙 ∏ (1 − 𝑣𝑚 )} ℎ(⋅ ∣ 𝜃𝑙⋆ ),
𝑙=1 𝑚<𝑙
𝑖𝑖𝑑 𝑖𝑖𝑑
𝑣𝑙 ∣ 𝛼 ∼ 𝐵𝑒𝑡𝑎(1, 𝛼), 𝜃𝑙⋆ ∼ 𝐺0 .
113
114 CHAPTER 10. BAYESIAN NONPARAMETRIC MODELS
𝑖𝑛𝑑
More general representations of the random measure can be specify by considering 𝑣𝑙 ∣ 𝜈𝑙 , 𝛼𝑙 ∼
𝐵𝑒𝑡𝑎(𝜈𝑙 , 𝛼𝑙 ). Finite dimensional approximations can be obtained by truncating the infinite sum to
have 𝐿 components.
Different representations of DP mixtures lead to different computational algorithms. NIMBLE
supports sampling algorithms based on the CRP representation, as well as on the stick-breaking
representation. NIMBLE includes definitions of structures required to implement the CRP and
stick-breaking distributions, and the associated MCMC algorithms.
10.2.1.1 Specification
The dCRP distribution is specified in NIMBLE for a membership vector z as
z[1:N] ~ dCRP(conc, size)
The conc parameter is the concentration parameter of the CRP, controlling the probability of a
customer sitting on a new table, i.e., creating a new cluster. The size parameter defines the size
of the set of integers to be partitioned.
The conc parameter is a positive real value that can be treated as known or unknown. When a
gamma prior is assumed for the conc parameter, a specialized sampler is assigned. See more on
this in section 10.4.1.
The size parameter is a positive integer that has to be fixed and equal to the length of vector z.
It defines the set of consecutive integers from 1 to N to be partitioned. Each element in z can be
an integer from 1 to N, and repetitions are allowed.
10.2.1.2 Density
The CRP distribution partitions the set of positive integers 1, … , 𝑁 , into 𝑁 ⋆ ≤ 𝑁 disjoint subsets,
indicating to which subset each element belongs. For instance, if 𝑁 = 6, the set {1, 2, 3, 4, 5, 6}
can be partitioned into the subsets 𝑆1 = {1, 2, 6}, 𝑆2 = {4, 5}, and 𝑆3 = {3}. Note that 𝑁 ⋆ = 3,
and this is one partition from out of 203 possibilities. The CRP-distributed vector 𝑧 encodes this
partition and its observed values would be (1, 1, 3, 2, 2, 1), for this example. In mixture modeling,
this indicates that observations 1, 2, and 6 belong to cluster 1, observations 4 and 5 to cluster 2,
10.2. CHINESE RESTAURANT PROCESS MODEL 115
and observation 3 to cluster 3. Note that this representation is not unique, vector (2, 2, 1, 3, 3, 2)
encodes the same partition.
The joint probability function of 𝑧 = (𝑧1 , … , 𝑧𝑁 ), with concentration parameter 𝛼, is given by
𝑁 ⋆ (𝑧)
Γ(𝛼) ⋆
𝑝(𝑧 ∣ 𝛼) ∝ 𝛼𝑁 (𝑧) ∏ Γ(𝑚𝑘 (𝑧)),
Γ(𝛼 + 𝑛) 𝑘=1
where 𝑚𝑘 (𝑧) denotes the number of elements in 𝑧 that are equal to 𝑘, 𝑁 ⋆ (𝑧) denotes the number
of unique elements in 𝑧, and Γ(⋅) denotes the gamma function. The full conditional distribution
for 𝑧𝑖 given 𝑧−𝑖 is
1 𝛼
𝑝(𝑧𝑖 = 𝑚 ∣ 𝑧−𝑖 , 𝛼) = ∑ 1 (𝑚) + 1 𝑛𝑒𝑤 (𝑚),
𝑛 − 1 + 𝛼 𝑗≠𝑖 {𝑧𝑗 } 𝑛 − 1 + 𝛼 {𝑧 }
where 𝑧−𝑖 denotes vector 𝑧 after removing its 𝑖−th component, 𝑧𝑛𝑒𝑤 is a value not in 𝑧−𝑖 , and 1𝐴
denotes the indicator function at set 𝐴.
Note that the probability of creating a new cluster is proportional to 𝛼: the larger the concentration
parameter, the more clusters are created.
10.2.2 Example
The following example illustrates how to use NIMBLE to perform single density estimation for real-
valued data, under a BNP approach, using the dCRP distribution. (Note that the BNP approach is
also often used to perform density estimation on random effects.) The model is given by
2 𝑖𝑛𝑑
𝑦𝑖 ∣ 𝜃,̃ 𝜎̃ , 𝑧𝑖 ∼ 𝑁 (𝜃𝑧̃ 𝑖 , 𝜎̃𝑧2𝑖 , ) 𝑖 = 1, … , 𝑁 ,
𝑧 ∼ CRP(𝛼), 𝛼 ∼ Gamma(1, 1),
𝑖𝑖𝑑 𝑖𝑖𝑑
𝜃𝑗̃ ∼ 𝑁 (0, 100), 𝜎̃𝑗2 ∼ InvGamma(1, 1), 𝑗 = 1, … , 𝑀 .
set.seed(1)
constants <- list(N = 100, M = 50)
data <- list(y = c(rnorm(50, -5, sqrt(3)), rnorm(50, 5, sqrt(4))))
inits <- list(thetatilde = rnorm(constants$M, 0, 10),
116 CHAPTER 10. BAYESIAN NONPARAMETRIC MODELS
The model can be fitted through MCMC sampling. NIMBLE will assign a specialized sampler to
update z and alpha. See Chapter 7 for information about NIMBLE’s MCMC engine, and Section
10.4.1 for details on MCMC sampling of the CRP.
One of the advantages of BNP mixture models is that the number of clusters is treated as random.
Therefore, in MCMC sampling, the number of cluster parameters varies with the iteration. Since
NIMBLE does not currently allow dynamic length allocation, the number of unique cluster param-
eters, 𝑁 ⋆ , has to be fixed. One safe option is to set this number to 𝑁 , but this is inefficient, both
in terms of computation and in terms of storage, because in practice it is often that 𝑁 ⋆ < 𝑁 . In
addition, configuring and building the MCMC can be slow (and use a lot of memory) for large 𝑁 .
In an effort to mitigate these inefficiencies, we allow the user to set 𝑁 ⋆ = 𝑀 , with 𝑀 < 𝑁 , as
seen in the example above. However, if this number is too small and is exceeded in any iteration a
warning is issued.
10.2.3 Extensions
The BNP functionality in NIMBLE was extended in version 0.10.0 to more general models. These
extensions enable users, for instance, to use a DP or DPM prior for the distribution of the random
effects in a generalized linear mixed effects model with mutiple measurements over time or multiple
trials per participant.
The following example illustrates how to use NIMBLE in a random effects model with repeated
measurements per subject using a DP prior for the distribution of the subject’s random effects.
The model is given by
𝑖𝑖𝑑
̃ ∼ 𝑁 (0, 100), 𝑚 = 1, … , 𝑀 ,
𝜃𝑚 𝜎2 ∼ 𝐼𝑛𝑣𝐺𝑎𝑚𝑚𝑎(1, 1).
set.seed(1)
constants <- list(N = 10, J = 5, M = 5)
data <- list(y = matrix(c(rnorm(25, -25, 1), rnorm(25, 25, 1)), ncol=constants$J,
nrow=constants$N, byrow=TRUE))
inits <- list(thetatilde = rnorm(constants$M, 0, 10),
z = sample(1:5, size = constants$N, replace = TRUE),
alpha = 1,
sigma2 = 1)
modelRandEff <- nimbleModel(code, constants, data, inits)
Alternatively, each subject could have a vector of parameters being clustered. For example in the
model above one could instead specify a vector of means, such as thetaTilde[z[i], j], instead
of a single mean.
As before, the model can be fitted through MCMC sampling. NIMBLE will assign a specialized
sampler to update z and alpha. See Chapter 7 for information about NIMBLE’s MCMC engine,
and Section 10.4.1 for details on MCMC sampling of the CRP.
10.3.1.1 Function
The weights (𝑤1 , … , 𝑤𝐿 ) follow a finite stick-breaking construction if
𝑤1 = 𝑣 1 ,
𝑤𝑙 = 𝑣𝑙 ∏ (1 − 𝑣𝑚 ), 𝑙 = 2, … , 𝐿 − 1
𝑚<𝑙
𝑤𝐿 = ∏ (1 − 𝑣𝑚 ).
𝑚<𝐿
10.3.1.2 Specification
The stick_breaking function is specified in NIMBLE for a vector w of probabilities as
w[1:L] <- stick_breaking(v[1:(L-1)])
The argument v is a vector of values between 0 and 1 defining the sequential breaking points of
the stick after removing the previous portions already broken off. It is of length 𝐿 − 1, implicitly
assuming that its last component is equal to 1.
In order to complete the definition of the weights in the stick-breaking representation of 𝐺, a prior
distribution on (0, 1) should to be assumed for 𝑣𝑙 , 𝑙 = 1, … , 𝐿 − 1, for instance a beta prior.
10.3.2 Example
Here we illustrate how to use NIMBLE for the example described in section 10.2.2, but considering
a stick-breaking representation for 𝐺. The model is given by
⋆ 2 𝑖𝑛𝑑 ⋆
𝑦𝑖 ∣ 𝜃 , 𝜎⋆ , 𝑧𝑖 ∼ 𝑁 (𝜃⋆ 𝑧𝑖 , 𝜎2 𝑧𝑖 ), 𝑖 = 1, … , 𝑁 ,
𝑖𝑖𝑑
𝑧 ∼ 𝐷𝑖𝑠𝑐𝑟𝑒𝑡𝑒(𝑤), 𝑣𝑙 ∼ 𝐵𝑒𝑡𝑎(1, 𝛼), 𝑙 = 1, … , 𝐿 − 1,
𝛼 ∼ Gamma(1, 1),
𝑖𝑖𝑑 ⋆ 𝑖𝑖𝑑
𝜃𝑙⋆ ∼ 𝑁 (0, 100), 𝜎2 𝑙 ∼ InvGamma(1, 1), 𝑙 = 1, … , 𝐿.
set.seed(1)
constants <- list(N = 100, L=50)
data <- list(y = c(rnorm(50, -5, sqrt(3)), rnorm(50, 5, sqrt(4))))
inits <- list(thetastar = rnorm(constants$L, 0, 100),
s2star = rinvgamma(constants$L, 1, 1),
z = sample(1:10, size = constants$N, replace = TRUE),
v = rbeta(constants$L, 1, 1),
10.4. MCMC SAMPLING OF BNP MODELS 119
alpha = 1)
modelSB <- nimbleModel(code, constants, data, inits)
The resulting model may be carried through to MCMC sampling. NIMBLE will assign a specialized
sampler to update v. See Chapter 7 for information about NIMBLE’s MCMC engine, and Section
10.4.2 for details on MCMC sampling of the stick-breaking weights.
To reduce computation and improve mixing, we only sample the parameters of the clusters (e.g.,
̃ 𝑗 in 10.2.2 when the associated cluster is occupied, using the CRP_cluster_wrapper sampler,
𝑡ℎ𝑒𝑡𝑎
which wraps around an underlying actual sampler. In addition, this approach requires that any
sampler assigned to parameters of the base measure, 𝐺0 , (i.e., unknown parameters in the prior for
̃ 𝑗 ) ignore cluster parameters associated with clusters that are not occupied, since their current
𝑡ℎ𝑒𝑡𝑎
values are meaningless. We assign a special slice sampler that determines the occupied clusters
in any given iteration, called slice_CRP_base_param. Note that if you choose to use a different
sampler for the base measure parameters, you should also avoid using the CRP_cluster_wrapper
sampler.
Finally, a specialized sampler is assigned to the conc hyper parameter when a gamma hyper prior
is assigned, see section 6 in Escobar and West (1995) for more details. Otherwise, a random walk
Metropolis-Hastings sampler is assigned.
The MCMC argument is a compiled or uncompiled MCMC object. The MCMC object should monitor
the membership (or clustering) variable, the cluster parameters, all stochastic nodes of the cluster
parameters, and the concentration parameter, if it is random. Use the monitors argument when
configuring the MCMC to ensure these variables are monitored.
The epsilon argument is used to determine the truncation level of the representation of the random
measure. Its default value is 1𝑒 − 04.
The sampler is used only after the MCMC for the model has been run; more details are available
from help(getsamplesDPmeasure).
∞
Posterior samples of the random measure 𝐺 are (almost surely) of the form ∑𝑙=1 𝑤𝑙 𝛿𝜃𝑙 , where 𝛿𝜃
is the Dirac measure at 𝜃, 𝑤𝑙 are stick-breaking weights, and 𝜃𝑙 are atoms (or point masses). The
variables that define the stick-breaking weights are iid 𝐵𝑒𝑡𝑎(1, 𝛼 + 𝑁 ) distributed, where 𝛼 is the
concentration parameter of the CRP distribution and 𝑁 is the sample size. Independently, the
atoms, 𝜃𝑙 , are iid and follow a distribution of the form
𝑁 ⋆ (𝑧)
(𝛼 + 𝑁 )−1 ∑ 𝑚𝑘 (𝑧)𝛿{𝜃 ̃ } + 𝛼(𝛼 + 𝑁 )−1 𝐺0 ,
𝑘
𝑘=1
where 𝐺0 is the prior baseline distribution, and 𝑧 and 𝜃𝑘̃ are posterior samples of the labeling vector
and cluster parameters, respectively. Their values, together with the values of 𝛼 (if random) are
obtained from the MCMC’s output. Expressions 𝑚𝑘 (𝑧) and 𝑁 ⋆ (𝑧) are defined as in section 10.2.
The getsamplesDPmeasure function provides samples of a truncated version of the infinite mixture
to a level 𝐿. The truncation level 𝐿 is such that the tail probability left from the approximation
is at most epsilon, denoted 𝜖. The following relationship determines the truncation level: 𝐿 =
log(𝜖)/ log[(𝛼 + 𝑁 )/(𝛼 + 𝑁 + 1)]. The value of 𝐿 varies at each iteration of the MCMC’s output
when 𝛼 is random, while it is the same at each iteration when 𝛼 is fixed. For more details about
sampling the random measure and its truncation level see Gelfand and Kottas (2002).
Because of the discrete nature of the atom’s distribution, the stick-breaking representation trun-
cated to a level 𝐿 will generally have repeated values. Therefore, in order to reduce the output’s
dimensionality, the stick-breaking weights of identical atoms are added up. This results in samples
of 𝐺 that have only the ‘unique’ atoms in {𝜃𝑙 }𝐿𝑙=1 .
The following code exemplifies how to generate samples from 𝐺 after defining the model as in
Section 10.2.2.
cmodel <- compileNimble(model)
123
Overview
Part IV is the programmer’s guide to NIMBLE. At the heart of programming in NIMBLE are
nimbleFunctions. These support two principal features: (1) a setup function that is run once for
each model, nodes, or other setup arguments, and (2) run functions that will be compiled to C++
and are written in a subset of R enhanced with features to operate models. Formally, what can be
compiled comprises the NIMBLE language, which is designed to be R-like.
This part of the manual is organized as follows:
• Chapter 11 describes how to write simple nimbleFunctions, which have no setup code and
hence don’t interact with models, to compile parts of R for fast calculations. This covers the
subset of R that is compilable, how to declare argument types and return types, and other
information.
• Chapter 12 explains how to write nimbleFunctions that can be included in BUGS code as
user-defined distributions or user-defined functions.
• Chapter 13 introduces more features of NIMBLE models that are useful for writing nimble-
Functions to use models, focusing on how to query model structure and carry out model
calculations.
• Chapter 14 introduces two kinds of data structures: modelValues are used for holding mul-
tiple sets of values of model variables; nimbleList data structures are similar to R lists but
require fixed element names and types, allowing the NIMBLE compiler to use them.
• Chapter 15 draws on the previous chapters to show how to write nimbleFunctions that work
with models, or more generally that have a setup function for any purpose. Typically a
setup function queries model structure (Chapter 13) and may establish some modelValues or
nimbleList data structures or configurations (Chapter 14). Then run functions written in
the same way as simple nimbleFunctions (Chapter 11) along with model operations (Chapter
13) define algorithm computations that can be compiled via C++.
125
126
Chapter 11
Here’s a basic example implementing the textbook calculation of least squares estimation of linear
regression parameters1 :
solveLeastSquares <- nimbleFunction(
run = function(X = double(2), y = double(1)) { # type declarations
ans <- inverse(t(X) %*% X) %*% (t(X) %*% y)
return(ans)
returnType(double(2)) # return type declaration
} )
## [,1]
## [1,] 0.088547575
## [2,] 0.002025635
## [3,] -0.090387283
## [4,] -0.072660391
1
Of course, in general, explicitly calculating the inverse is not the recommended numerical recipe for least squares.
127
128 CHAPTER 11. WRITING SIMPLE NIMBLEFUNCTIONS
## [,1]
## [1,] 0.088547575
## [2,] 0.002025635
## [3,] -0.090387283
## [4,] -0.072660391
In this example, we fit a linear model for 100 random response values (y) to four columns of
randomly generated explanatory variables (X). We ran the nimbleFunction solveLeastSquares
uncompiled, natively in R, allowing testing and debugging (Section 15.7). Then we compiled it and
showed that the compiled version does the same thing, but faster2 . NIMBLE’s compiler creates
C++ that uses the Eigen (http://eigen.tuxfamily.org) library for linear algebra.
Notice that the actual NIMBLE code is written as an R function definition that is passed to
nimbleFunction as the run argument. Hence we call it the run code. run code is written in the
NIMBLE language. This is similar to a narrow subset of R with some additional features. Formally,
we view it as a distinct language that encompasses what can be compiled from a nimbleFunction.
To write nimbleFunctions, you will need to learn:
• what R functions are supported for NIMBLE compilation and any ways they differ from their
regular R counterparts;
• how NIMBLE handles types of variables;
• how to declare types of nimbleFunction arguments and return values;
• that compiled nimbleFunctions always pass arguments to each other by reference.
The next sections cover each of these topics in turn.
2
On the machine this is being written on, the compiled version runs a few times faster than the uncompiled version.
However we refrain from formal speed tests.
11.2. R FUNCTIONS (OR VARIANTS) IMPLEMENTED IN NIMBLE 129
In addition to the above functions, we provide functions any_na() and any_nan() for finding if
there are any NA or NaN values in a vector. These are equivalent to using any(is.na()) and
any(is.nan()) in R.
Other R functions with numeric arguments and return value can be called during compiled execution
by wrapping them as a nimbleRcall (see Section 11.7).
Next we cover some of these functions in more detail.
If first use of the variable does not rely on initial values, using init = FALSE will yield slightly
more efficient performance.
matrix creates a 2-dimensional matrix object of either floating-point (if type = "double", the
default), integer (if type = "integer"), or logical (if type = "logical") values. As in R, nrow
and ncol arguments specify the number of rows and columns, respectively. The value and init
arguments are used in the same way as for numeric, integer, and logical.
array creates a vector or higher-dimensional object, depending on the dim argument, which takes
a vector of sizes for each dimension. The type, value and init argument behave the same as for
matrix.
The best way to create an identity matrix is with diag(n), which returns an 𝑛 × 𝑛 identity matrix.
NIMBLE also provides a deprecated nimbleFunction identityMatrix that does the same thing.
Examples of these functions, and the related function ‵ 𝑠𝑒𝑡𝑆𝑖𝑧𝑒‵ for changing the size of a numeric
object, are given in Section 11.3.2.4.
More information on the nimbleLists returned by the eigen and svd functions in NIMBLE can be
found in Section 14.2.1.
11.2. R FUNCTIONS (OR VARIANTS) IMPLEMENTED IN NIMBLE 133
• Names of the distributions generally (but not always) match those of R, which sometimes
differ from BUGS. See the list below.
• Supported parameterizations are also indicated in the list below.
• For multivariate distributions (multivariate normal, Dirichlet, and Wishart), ‘r’ functions only
return one random draw at a time, and the first argument must always be 1.
• R’s recycling rule (re-use of an argument as needed to accommodate longer values of other
arguments) is generally followed, but the returned object is always a scalar or a vector, not a
matrix or array.
As in R (and nimbleFunctions), arguments are matched by order or by name (if given). Standard
arguments to distribution functions in R (log, log.p, lower.tail) can be used and have the same
defaults. User-defined distributions for BUGS (Chapter 12) can also be used from nimbleFunctions.
For standard distributions, we rely on R’s regular help pages (e.g., help(dgamma). For distributions
unique to NIMBLE (e.g., dexp_nimble, ddirch), we provide help pages.
In the last three, cholesky stands for Cholesky decomposition of the relevant matrix; prec_param
is a logical indicating whether the Cholesky is of a precision matrix (TRUE) or covariance matrix
(FALSE)3 ; and scale_param is a logical indicating whether the Cholesky is of a scale matrix (TRUE)
or an inverse scale matrix (FALSE).
We plan to include more flexible for-loops in the future, but for now we’ve included just
one additional useful feature: for(i in seq_along(NFL)) will work as in R, where NFL is a
nimbleFunctionList. This is described in Section 15.4.8.
stop, or equivalently nimStop, throws control to R’s error-handling system and can take a character
argument that will be displayed in an error message.
3
For the multivariate t, these are more properly termed the ‘inverse scale’ and ‘scale’ matrices
11.3. HOW NIMBLE HANDLES TYPES OF VARIABLES 135
NIMBLE tries to avoid conflicts by replacing some keywords immediately upon creating a nimble-
Function. These replacements include
• c → nimC
• copy → nimCopy
• dim → nimDim
• print → nimPrint
• cat → nimCat
• step → nimStep
• equals → nimEquals
• rep → nimRep
• round → nimRound
• seq → nimSeq
• stop → nimStop
• switch → nimSwitch
• numeric, integer, logical → nimNumeric, nimInteger, nimLogical
• matrix, array → nimMatrix, nimArray
This system gives programmers the choice between using the keywords like nimPrint directly, to
avoid confusion in their own code about which ‘print’ is being used, or to use the more intuitive
keywords like print but remember that they are not the same as R’s functions.
The elemental types supported by NIMBLE include double (floating-point), integer, logical, and
character. The type of a numeric or logical object refers to the number of dimensions and the
elemental type of the elements. Hence if x is created as a double matrix, it can only be used
subsequently for a double matrix. The size of each dimension is not part of its type and thus can
be changed. Up to four dimensions are supported for double, integer, and logical. Only vectors
(one dimension) are supported for character. Unlike R, NIMBLE supports true scalars, which have
0 dimensions.
is created from a configuration that declares what types of objects it will hold. nimbleLists are
covered in Chapter 14.2.
will create x to be a double matrix of the correct size (determined during execution).
for(i in 1:10)
x[i] <- foo(y[i])
In the line that creates b, the index range i:i is not evaluated until run time. Even though i:i
will always evaluate to simpy i, the compiler does not determine that. Since there is a vector index
range provided, the result of randomValues[i:i] is determined to be a vector. The following line
then creates d as a vector, because a vector plus a scalar returns a vector. Another way to create
a vector from a scalar is to use c, as illustrated in the last line.
This creates a matrix A, a vector B, and matrix-multiplies them. The vector B is automatically
treated as a one-column matrix in matrix algebra computations. The result of matrix multiplication
is always a matrix, but a programmer may expect a vector, since they know the result will have
one column. To make it a vector, simply extract the first column. More information about such
handling is provided in the next section.
• The default promotion for a vector is to a 1-column matrix. Therefore, v1 %*% t(v2) is
equivalent to v1 %*% asRow(v2) .
• When indexing, dimensions with scalar indices will be dropped. For example, M1[1,] and
M1[,1] are both vectors. If you do not want this behavior, use drop=FALSE just as in R. For
example, M1[1,,drop=FALSE] is a matrix.
• The left-hand side of an assignment can use indexing, but if so it must already be correctly
sized for the result. For example, Y[5:10, 20:30] <- x will not work – and could crash
11.4. DECLARING ARGUMENT AND RETURN TYPES 139
your R session with a segmentation fault – if Y is not already at least 10x30 in size. This
can be done by setSize(Y, c(10, 30)). See Section 11.3.2.4 for more details. Note that
non-indexed assignment to Y, such as Y <- x, will automatically set Y to the necessary size.
Here are some examples to illustrate the above points, assuming M2 is a square matrix.
• Y <- v1 + M2 %*% v2 will return a 1-column matrix. If Y is created by this statement, it
will be a 2-dimensional variable. If Y already exists, it must already be 2-dimesional, and it
will be automatically re-sized for the result.
• Y <- v1 + (M2 %*% v2)[,1] will return a vector. Y will either be created as a vector or
must already exist as a vector and will be re-sized for the result.
Functions with return values must have their return type explicitly declared using returnType,
which can occur anywhere in the run code. For example returnType(integer(2)) declares the
140 CHAPTER 11. WRITING SIMPLE NIMBLEFUNCTIONS
return type to be a matrix of integers. A return type of void() means there is no return value,
which is the default if no returnType statement is included.
Note that because all values in models are stored as doubles and because of some limitations
in NIMBLE’s automatic casting, non-scalar return values of user-defined distributions must be
doubles.
NIMBLE allows you to define your own functions and distributions as nimbleFunctions for use
in BUGS code. As a result, NIMBLE frees you from being constrained to the functions and
distributions discussed in Chapter 5. For example, instead of setting up a Dirichlet prior with
multinomial data and needing to use MCMC, one could recognize that this results in a Dirichlet-
multinomial distribution for the data and provide that as a user-defined distribution instead.
Since NIMBLE allows you to wrap calls to external compiled code or arbitrary R functions as
nimbleFunctions, and since you can define model functions and distributions as nimbleFunctions,
you can combine these features to build external compiled code or arbitrary R functions into a
model. See Sections 11.6-11.7.
Note that NIMBLE generally expects user-defined distributions or functions to be defined in the
global environment. If you define them in a function (which would generally be the case if you are
using them in the context of parallelization), one approach would be to assign them to the global
environment in your function:
## for a user-defined function
assign('myfun', myfun, envir = .GlobalEnv)
## for a user-defined distribution
assign('dfoo', dfoo, envir = .GlobalEnv)
assign('rfoo', rfoo, envir = .GlobalEnv)
## similarly for 'p' and 'q' functions if you define them
141
142CHAPTER 12. CREATING USER-DEFINED BUGS DISTRIBUTIONS AND FUNCTIONS
The x = double(0) argument and returnType(double(0)) establish that the input and output
will both be zero-dimensional (scalar) numbers.
You can define nimbleFunctions that take inputs and outputs with more dimensions. Here is an
example that takes a vector (1-dimensional) as input and returns a vector with twice the input
values:
vectorTimesTwo <- nimbleFunction(
run = function(x = double(1)) {
returnType(double(1))
return(2*x)
}
)
code <- nimbleCode({
for(i in 1:3) {
mu[i] ~ dnorm(0, 1)
}
mu_times_two[1:3] <- vectorTimesTwo(mu[1:3])
})
There is a subtle difference between the mu_times_two variables in the two examples. In the first
example, there are individual nodes for each mu_times_two[i]. In the second example, there is
a single multivariate node, mu_times_two[1:3]. Each implementation could be more efficient for
different needs. For example, suppose an algorithm modifies the value of mu[2] and then updates
nodes that depend on it. In the first example, mu_times_two[2] would be updated. In the second
example mu_times_two[1:3] would be updated because it is a single, vector node.
At present in compiled use of a model, you cannot provide a scalar argument where the user-defined
nimbleFunction expects a vector; unlike in R, scalars are not simply vectors of length 1.
NIMBLE, while in a few special cases1 you need to explicitly register your distribution as described
in Section 12.2.1.
You need to provide the simulation (‘r’) function if any algorithm used with a model that uses
the distribution needs to simulate from the distribution. This is not the case for NIMBLE’s built-
in MCMC sampler functions, and therefore the simulation function is not generally required for
standard MCMC in NIMBLE. However, the ‘r’ function is necessary for initialization of nodes
that are assigned the user-defined distribution if no initial value is provided, and for sampling
posterior predictive nodes (those nodes with no downstream data dependencies) that are assigned
the user-defined distribution.
You can optionally provide distribution (‘p’) and quantile (‘q’) functions, which will allow trun-
cation to be applied to a user-defined distribution. You can also provide a list of alternative
parameterizations, but only if you explicitly register the distribution.
Here is an extended example of providing a univariate exponential distribution (solely for illustration
as this is already provided by NIMBLE) and a multivariate Dirichlet-multinomial distribution.
dmyexp <- nimbleFunction(
run = function(x = double(0), rate = double(0, default = 1),
log = integer(0, default = 0)) {
returnType(double(0))
logProb <- log(rate) - x*rate
if(log) return(logProb)
else return(exp(logProb))
})
1
These include providing alternative parameterizations, specifying the range of the distribution, or specifying that
the distribution is a discrete distribution.
144CHAPTER 12. CREATING USER-DEFINED BUGS DISTRIBUTIONS AND FUNCTIONS
else return(log(p))
}
})
The distribution-related functions should take as input the parameters for a single parameterization,
which will be the canonical parameterization that NIMBLE will use.
Here are more details on the requirements for distribution-related nimbleFunctions, which follow
R’s conventions:
12.2. USER-DEFINED DISTRIBUTIONS 145
• Your distribution-related functions must have names that begin with ‘d’, ‘r’, ‘p’ and ‘q’. The
name of the distribution must not be identical to any of the NIMBLE-provided distributions.
• All simulation (‘r’) functions must take n as their first argument. Note that you may simply
have your function only handle n=1 and return an warning for other values of n.
• NIMBLE uses doubles for numerical calculations, so we suggest simply using doubles in
general, even for integer-valued parameters or values of random variables. In fact, non-scalars
must be declared as doubles.
• All density functions must have as their last argument log and implement return of the log
probability density. NIMBLE algorithms typically use only log = 1, but we recommend you
implement the log = 0 case for completeness.
• All distribution and quantile functions must have their last two arguments be (in order)
lower.tail and log.p. These functions must work for lower.tail = 1 (i.e., TRUE) and
log.p = 0 (i.e., FALSE), as these are the inputs we use when working with truncated dis-
tributions. It is your choice whether you implement the necessary calculations for other
combinations of these inputs, but again we recommend doing so for completeness.
• Define the nimbleFunctions in R’s global environment. Don’t expect R’s standard scoping to
work2 .
))
There are a few rules for how you specify the information about a distribution that you provide to
registerDistributions:
• The function name in the BUGSdist entry in the list provided to registerDistributions
will be the name you can use in BUGS code.
• The names of your nimbleFunctions must match the function name in the Rdist entry. If
missing, the Rdist entry defaults to be the same as the BUGSdist entry.
• Your distribution-related functions must take as arguments the parameters in default order,
starting as the second argument and in the order used in the parameterizations in the Rdist
argument to registerDistributions or the BUGSdist argument if there are no alternative
parameterizations.
• You must specify a types entry in the list provided to registerDistributions if the distri-
bution is multivariate or if any parameter is non-scalar.
Further details on using registerDistributions can be found via R help on registerDistributions.
NIMBLE uses the same list format as registerDistributions to define its distributions. This
list can be found in the R/distributions_inputList.R file in the package source code directory
or as the R list nimble:::distributionsInputList.
Chapter 13
Here we describe how one can get information about NIMBLE models and carry out operations on
a model. While all of this functionality can be used from R, its primary use occurs when writing
nimbleFunctions (see Chapter 15). Information about node types, distributions, and dimensions
can be used to determine algorithm behavior in setup code of nimbleFunctions. Information about
node or variable values or the parameter and bound values of a node would generally be used for
algorithm calculations in run code of nimbleFunctions. Similarly, carrying out numerical operations
on a model, including setting node or variable values, would generally be done in run code.
147
148 CHAPTER 13. WORKING WITH NIMBLE MODELS
## [1] "x[1]" "x[2]" "x[3]" "x[4]" "x[5]" "x[6]" "x[7]" "x[8]" "x[9]"
## [10] "x[10]"
You can see one lifted node (see next section), lifted_d1_over_beta, involved in a reparameteri-
zation to NIMBLE’s canonical parameterization of the gamma distribution for the theta nodes.
We can determine the set of nodes contained in one or more nodes or variables us-
ing expandNodeNames, illustrated here for an example with multivariate nodes. The
returnScalarComponents argument also allows us to return all of the scalar elements of
multivariate nodes.
multiVarCode2 <- nimbleCode({
X[1, 1:5] ~ dmnorm(mu[], cov[,])
X[6:10, 3] ~ dmnorm(mu[], cov[,])
for(i in 1:4)
Y[i] ~ dnorm(mn, 1)
})
multiVarModel2$expandNodeNames("Y")
## [1] "X[1, 1]" "X[1, 2]" "X[1, 3]" "X[6, 3]" "X[7, 3]" "X[8, 3]"
## [7] "X[9, 3]" "X[10, 3]" "X[1, 4]" "X[1, 5]" "Y[1]" "Y[2]"
13.1. THE VARIABLES AND NODES IN A NIMBLE MODEL 149
## [1] "x[1]" "x[2]" "x[3]" "x[4]" "x[5]" "x[6]" "x[7]" "x[8]" "x[9]"
## [10] "x[10]"
In addition, one can determine parent nodes using getParents.
pump$getParents("alpha")
## character(0)
## sigma
13.2. ACCESSING INFORMATION ABOUT NODES AND VARIABLES 151
## "dunif"
m$isDiscrete(c('y', 'mu', 'sigma'))
## mu
## FALSE
m$getDimension('mu')
## value
## 0
m$getDimension('mu', includeParams = TRUE)
## [1] 1.2
gammaModel$getParam('x', 'rate')
## [1] 0.8333333
getParam is part of the NIMBLE language, so it can be used in run code of nimbleFunctions.
Here is an example:
exampleModel <- nimbleModel(
nimbleCode({
y ~ T(dnorm(mu, sd = sig), a, Inf)
a ~ dunif(-1, b)
b ~ dgamma(1, 1)
}), inits = list(a = -0.5, mu = 1, sig = 1, b = 4),
data = list(y = 4))
getBound(exampleModel, 'y', 'lower')
## [1] -0.5
getBound(exampleModel, 'y', 'upper')
## [1] Inf
exampleModel$b <- 3
exampleModel$calculate(exampleModel$getDependencies('b'))
## [1] -4.386294
getBound(exampleModel, 'a', 'upper')
## [1] 3
exampleModel$getBound('b','lower')
## [1] 0
getBound is part of the NIMBLE language, so it can be used in run code of nimbleFunctions. In
fact, we anticipate that most use of getBound will be for algorithms, such as for the reflection
version of the random walk MCMC sampler.
13.3. CARRYING OUT MODEL CALCULATIONS 153
mc <- nimbleCode({
a ~ dnorm(0, 0.001)
for(i in 1:5) {
y[i] ~ dnorm(a, 0.1)
for(j in 1:3)
z[i,j] ~ dnorm(y[i], sd = 0.1)
}
y.squared[1:5] <- y[1:5]^2
})
model$a <- 1
model$y
## [1] NA NA NA NA NA
model$simulate("y[1:3]")
# simulate(model, "y[1:3]")
1
Standard usage is model$calculate(nodes) but calculate(model, nodes) is synonymous.
154 CHAPTER 13. WORKING WITH NIMBLE MODELS
model$y
5. The data nodes z were not simulated into until includeData = TRUE was used.
Use of calculate, calculateDiff and getLogProb are similar to simulate, except that they
return a value (described above) and they have no includeData argument.
For simNodes, the nodes provided will be topologically sorted to simulate in the correct order. For
calcNodes and getLogProbNodes, the nodes will be sorted and dependent nodes will be included.
Recall that the calculations must be up to date (from a calculate call) for getLogProbNodes to
return the values you are probably looking for.
simpleModelCode <- nimbleCode({
for(i in 1:4){
x[i] ~ dnorm(0,1)
y[i] ~ dnorm(x[i], 1) # y depends on x
z[i] ~ dnorm(y[i], 1) # z depends on y
# z conditionally independent of x
}
})
cSimpleModel$x
## [1] NA NA NA NA
156 CHAPTER 13. WORKING WITH NIMBLE MODELS
cSimpleModel$y
## [1] NA NA NA NA
# simulating x and y
cSimXY$run()
## NULL
cSimpleModel$x
## [1] -12.46535
# gives correct answer because logProbs
# updated by 'calculate' after simulation
cGetLogProbXDep$run()
## [1] -12.46535
cSimXY$run()
## NULL
# gives old answer because logProbs
# not updated after 'simulate'
cGetLogProbXDep$run()
## [1] -12.46535
cCalcXDep$run()
## [1] -9.277808
## [1] NA NA NA NA NA
model$calculate("y")
13.3. CARRYING OUT MODEL CALCULATIONS 157
## [1] -11.02766
model$logProb_y
x may be 10 × 20 (dimensions must be provided), but logProb_x will be 10 × 1. For the most part
you do not need to worry about how NIMBLE is storing the log probability values, because you
can always get them using getLogProb.
158 CHAPTER 13. WORKING WITH NIMBLE MODELS
Chapter 14
## [1] 5 1 5 14 3 19 1 1 4 22
1
One may want to read this section after an initial reading of Chapter 15.
159
160 CHAPTER 14. DATA STRUCTURES IN NIMBLE
pumpModelValues$x
## [[1]]
## [1] NA NA NA NA NA NA NA NA NA NA
##
## [[2]]
## [1] NA NA NA NA NA NA NA NA NA NA
In this example, pumpModelValues has the same variables as pumpModel, and we set
pumpModelValues to have m = 2 rows. As you can see, the rows are stored as elements of
a list.
Alternatively, one can define a modelValues object manually by first defining a modelValues config-
uration via the modelValuesConf function, and then creating an instance from that configuration,
like this:
mvConf = modelValuesConf(vars = c('a', 'b', 'c'),
type = c('double', 'int', 'double'),
size = list(a = 2, b =c(2,2), c = 1) )
customMV = modelValues(mvConf, m = 2)
customMV$a
## [[1]]
## [1] NA NA
##
## [[2]]
## [1] NA NA
The arguments to modelValuesConf are matching lists of variable names, types, and sizes. See
help(modelValuesConf) for more details. Note that in R execution, the types are not enforced.
But they will be the types created in C++ code during compilation, so they should be specified
carefully.
The object returned by modelValues is an uncompiled modelValues object. When a nimbleFunction
is compiled, any modelValues objects it uses are also compiled. A NIMBLE model always contains
a modelValues object that it uses as a default location to store the values of its variables.
Here is an example where the customMV created above is used as the setup argument for a nimble-
Function, which is then compiled. Its compiled modelValues is then accessed with $.
# simple nimbleFunction that uses a modelValues object
resizeMV <- nimbleFunction(
setup = function(mv){},
run = function(k = integer() ){
resize(mv,k)})
## NULL
14.1. THE MODELVALUES DATA STRUCTURE 161
## [[1]]
## [1] NA NA
##
## [[2]]
## [1] NA NA
##
## [[3]]
## [1] 0 0
##
## [[4]]
## [1] 0 0
##
## [[5]]
## [1] 0 0
Compiled modelValues objects can be accessed and altered in all the same ways as uncompiled ones.
However, only uncompiled modelValues can be used as arguments to setup code in nimbleFunctions.
In the example above a modelValues object is passed to setup code, but a modelValues configuration
can also be passed, with creation of modelValues object(s) from the configuration done in setup
code.
## [[1]]
## [1] 0 1
##
## [[2]]
## [1] 2 4
162 CHAPTER 14. DATA STRUCTURES IN NIMBLE
Currently, only the syntax customMV["a", 2] works in the NIMBLE language, not customMV[["a"][[2]].
We can query and change the number of rows using getsize and resize, respectively. These work
in both R and NIMBLE. Note that we don’t specify the variables in this case: all variables in a
modelValues object will have the same number of rows.
getsize(customMV)
## [1] 2
resize(customMV, 3)
getsize(customMV)
## [1] 3
customMV$a
## [[1]]
## [1] 0 1
##
## [[2]]
## [1] 2 4
##
## [[3]]
## [1] NA NA
Often it is useful to convert a modelValues object to a matrix for use in R. For example, we may
want to convert MCMC output into a matrix, for use with the coda package for processing MCMC
samples, or into a list. This can be done with the as.matrix and as.list methods for modelValues
objects, respectively. as.matrix will generate column names from every scalar element of variables
(e.g. “b[1, 1]” ,“b[2, 1]”, etc.). The rows of the modelValues will be the rows of the matrix, with
any matrices or arrays converted to a vector based on column-major ordering.
as.matrix(customMV, 'a') # convert 'a'
## a[1] a[2]
## [1,] 0 1
## [2,] 2 4
## [3,] NA NA
14.1. THE MODELVALUES DATA STRUCTURE 163
as.list will return a list with an element for each variable. Each element will be an array of
the same size and shape as the variable with an additional index for the iteration (e.g., MCMC
iteration when used for MCMC output). By default iteration is the first index, but it can be the
last if needed.
as.list(customMV, 'a') # get only 'a'
## $a
## [,1] [,2]
## [1,] 0 1
## [2,] 2 4
## [3,] NA NA
as.list(customMV) # get all variables
## $a
## [,1] [,2]
## [1,] 0 1
## [2,] 2 4
## [3,] NA NA
##
## $b
## , , 1
##
## [,1] [,2]
## [1,] 1 1
## [2,] 2 2
## [3,] NA NA
##
## , , 2
##
## [,1] [,2]
## [1,] 1 1
## [2,] 2 2
## [3,] NA NA
##
##
## $c
## [,1]
## [1,] NA
## [2,] NA
## [3,] NA
164 CHAPTER 14. DATA STRUCTURES IN NIMBLE
## $a
## [,1] [,2] [,3]
## [1,] 0 2 NA
## [2,] 1 4 NA
If a variable is a scalar, using unlist in R to extract all rows as a vector can be useful.
customMV['c', 1] <- 1
customMV['c', 2] <- 2
customMV['c', 3] <- 3
unlist(customMV['c', ])
## [1] 1 2 3
Once we have a modelValues object, we can see the structure of its contents via the varNames and
sizes components of the object.
customMV$varNames
## $a
## [1] 2
##
## $b
## [1] 2 2
##
## $c
## [1] 1
As with most NIMBLE objects, modelValues are passed by reference, not by value. That means any
modifications of modelValues objects in either R functions or nimbleFunctions will persist outside
of the function. This allows for more efficient computation, as stored values are immediately shared
among nimbleFunctions.
alter_a <- function(mv){
mv['a',1][1] <- 1
}
customMV['a', 1]
## [1] 0 1
alter_a(customMV)
customMV['a',1]
## [1] 1 1
However, when you retrieve a variable from a modelValues object, the result is a standard R list,
which is subsequently passed by value, as usual in R.
14.2. THE NIMBLELIST DATA STRUCTURE 165
## NULL
cCalcManyXDeps$run(saveLP = TRUE) # calculating
arguments to a nimbleFunction, described in Section 11.4. For example, the following line of code
creates a nimbleList definition with two elements: x, which is a scalar integer, and Y, which is a
matrix of doubles.
exampleNimListDef <- nimbleList(x = integer(0), Y = double(2))
Creating definitions using a list of nimbleTypes can be useful, as it allows for programmatic gener-
ation of nimbleList elements.
Once a nimbleList definition has been created, new instances of nimbleLists can be made from that
definition using the new member function. The new function can optionally take initial values for
the list elements as arguments. Below, we create a new nimbleList from our exampleNimListDef
and specify values for the two elements of our list:
exampleNimList <- exampleNimListDef$new(x = 1, Y = diag(2))
Once created, nimbleList elements can be accessed using the $ operator, just as with lists in R. For
example, the value of the x element of our exampleNimbleList can be set to 7 using
exampleNimList$x <- 7
nimbleList definitions can be created either in R’s global environment or in setup code of a nimble-
Function. Once a nimbleList definition has been made, new instances of nimbleLists can be created
using the new function in R’s global environment, in setup code, or in run code of a nimbleFunction.
nimbleLists can also be passed as arguments to run code of nimbleFunctions and returned from
nimbleFunctions. To use a nimbleList as a run function argument, the name of the nimbleList
definition should be provided as the argument type, with a set of parentheses following. To return
a nimbleList from the run code of a nimbleFunction, the returnType of that function should be
the name of the nimbleList definition, again using a following set of parentheses.
Below, we demonstrate a function that takes the exampleNimList as an argument, modifies its Y
element, and returns the nimbleList.
mynf <- nimbleFunction(
run = function(vals = exampleNimListDef()){
onesMatrix <- matrix(value = 1, nrow = 2, ncol = 2)
vals$Y <- onesMatrix
returnType(exampleNimListDef())
return(vals)
14.2. THE NIMBLELIST DATA STRUCTURE 167
})
## [,1] [,2]
## [1,] 1 1
## [2,] 1 1
In addition to storing basic data types, nimbleLists can also store other nimbleLists. To achieve this,
we must create a nimbleList definition that declares the types of nested nimbleLists a nimbleList
will store. Below, we create two types of nimbleLists: the first, named innerNimList, will be stored
inside the second, named outerNimList:
# first, create definitions for both inner and outer nimbleLists
innerNimListDef <- nimbleList(someText = character(0))
outerNimListDef <- nimbleList(xList = innerNimListDef(),
z = double(0))
Note that definitions for inner, or nested, nimbleLists must be created before the definition for an
outer nimbleList.
can be used to specify if x is a symmetric matrix or not. If symmetric = FALSE (the default value),
x will be checked for symmetry. Eigendecompositions in NIMBLE for symmetric matrices are both
faster and more accurate. Additionally, eigendecompostions of non-symmetric matrices can have
complex entries, which are not supported by NIMBLE. If a complex entry is detected, NIMBLE
will issue a warning and that entry will be set to NaN. The only.values arument defaults to FALSE.
If only.values = TRUE, the eigen function will not calculate the eigenvectors of x, leaving the
vectors nimbleList element empty. This can reduce calculation time if only the eigenvalues of x
are needed.
The svd function takes an 𝑛 × 𝑝 matrix x as an argument, and returns a nimbleList of type
svdNimbleList. nimbleLists of type svdNimbleList have three elements: d, a vector with the
singular values of x, u a matrix with the left singular vectors of x, and v, a matrix with the right
singular vectors of x. The svd function has an optional argument vectors which defaults to a
value of "full". The vectors argument can be used to specify the number of singular vectors that
are returned. If vectors = "full", v will be an 𝑛 × 𝑛 matrix and u will be an 𝑝 × 𝑝 matrix. If
vectors = "thin", v will be an𝑛 × 𝑚 matrix, where 𝑚 = min(𝑛, 𝑝), and u will be an 𝑚 × 𝑝 matrix.
If vectors = "none", the u and v elements of the returned nimbleList will not be populated.
nimbleLists created by either eigen or svd can be returned from a nimbleFunction, using
returnType(eigenNimbleList()) or returnType(svdNimbleList()) respectively. nimbleLists
created by eigen and svd can also be used within other nimbleLists by specifying the nimbleList
element types as eigenNimbleList() and svdNimbleList(). The below example demonstrates
the use of eigen and svd within a nimbleFunction.
eigenListFunctionGenerator <- nimbleFunction(
setup = function(){
demoMatrix <- diag(4) + 2
eigenAndSvdListDef <- nimbleList(demoEigenList = eigenNimbleList(),
demoSvdList = svdNimbleList())
eigenAndSvdList <- eigenAndSvdListDef$new()
},
run = function(){
# we will take the eigendecomposition and svd of a symmetric matrix
eigenAndSvdList$demoEigenList <<- eigen(demoMatrix, symmetric = TRUE,
only.values = TRUE)
eigenAndSvdList$demoSvdList <<- svd(demoMatrix, vectors = 'none')
returnType(eigenAndSvdListDef())
return(eigenAndSvdList)
})
eigenListFunction <- eigenListFunctionGenerator()
## [1] 9 1 1 1
outputList$demoSvdList$d
## [1] 9 1 1 1
The eigenvalues and singular values returned from the above function are the same since the matrix
14.2. THE NIMBLELIST DATA STRUCTURE 169
being decomposed was symmetric. However, note that both eigendecompositions and singular value
decompositions are numerical procedures, and computed solutions may have slight differences even
for a symmetric input matrix.
170 CHAPTER 14. DATA STRUCTURES IN NIMBLE
Chapter 15
15.1 Overview
When you write an R function, you say what the input arguments are, you provide the code for
execution, and in that code you give the value to be returned1 . Using the function keyword in R
triggers the operation of creating an object that is the function.
Creating nimbleFunctions is similar, but there are two kinds of code and two steps of execution:
1. Setup code is provided as a regular R function, but the programmer does not control what
it returns. Typically the inputs to setup code are objects like a model, a vector of nodes, a
modelValues object or a modelValues configuration, or another nimbleFunction. The setup
code, as its name implies, sets up information for run-time code. It is executed in R, so it
can use any aspect of R.
2. Run code is provided in the NIMBLE language, which was introduced in Chapter 11. This is
similar to a narrow subset of R, but it is important to remember that it is different – defined
by what can be compiled – and much more limited. Run code can use the objects created by
the setup code. In addition, some information on variable types must be provided for input
arguments, the return value, and in some circumstances for local variables. There are two
kinds of run code:
a. There is always a primary function, given as the argument run2 .
b. There can optionally be other functions, or ‘methods’ in the language of object-oriented
programming, that share the same objects created by the setup function.
Here is a small example to fix ideas:
logProbCalcPlus <- nimbleFunction(
setup = function(model, node) {
dependentNodes <- model$getDependencies(node)
valueToAdd <- 1
1
Normally this is the value of the last evaluated code, or the argument to return.
2
This can be omitted if you don’t need it.
171
172 CHAPTER 15. WRITING NIMBLEFUNCTIONS TO INTERACT WITH MODELS
},
run = function(P = double(0)) {
model[[node]] <<- P + valueToAdd
return(model$calculate(dependentNodes))
returnType(double(0))
})
## [1] -2.650377
dnorm(1.25,0,1,TRUE)+dnorm(1.5,1.25,1,TRUE) # direct validation
## [1] -2.650377
testModel$a # "a" was set to 0.5 + valueToAdd
## [1] 1.25
The call to the R function called nimbleFunction returns a function, similarly to defining a func-
tion in R. That function, logProbCalcPlus, takes arguments for its setup function, executes it,
and returns an object, logProbCalcPlusA, that has a run member function (method) accessed
by $run. In this case, the setup function obtains the stochastic dependencies of the node us-
ing the getDependencies member function of the model (see Section 13.1.3) and stores them in
dependentNodes. In this way, logProbCalcPlus can adapt to any model. It also creates a variable,
valueToAdd, that can be used by the nimbleFunction.
Readers familiar with object-oriented programming may find it useful to think in terms of class
definitions and objects. nimbleFunction creates a class definition. Each specialized nimbleFunction
is one object in the class. The setup arguments are used to define member data in the object.
3
Note the use of the global assignment operator to assign into the model. This is necessary for assigning into
variables from the setup function, at least if you want to avoid warnings from R. These warnings come from R’s
reference class system.
15.2. USING AND COMPILING NIMBLEFUNCTIONS 173
These have been initialized with the values from their uncompiled versions and can be used in the
same way:
CtestModel$a # values were initialized from testModel
## [1] 1.25
CtestModel$b
## [1] 1.5
lpA <- ClogProbCalcPlusA$run(1.5)
lpA
## [1] -5.462877
# verify the answer:
dnorm(CtestModel$b, CtestModel$a, 1, log = TRUE) +
dnorm(CtestModel$a, 0, 1, log = TRUE)
## [1] -5.462877
CtestModel$a # a was modified in the compiled model
## [1] 2.5
testModel$a # the uncompiled model was not modified
## [1] 1.25
• nimbleList objects New instances of nimbleLists can be created from a nimbleList defini-
tion in either setup or run code. See Section 14.2 for more information.
• specializations of other nimbleFunctions A useful NIMBLE programming technique is
to have one nimbleFunction contain other nimbleFunctions, which it can use in its run-time
code (Section 15.4.7).
• lists of other nimbleFunctions In addition to containing single other nimbleFunctions, a
nimbleFunction can contain a list of other nimbleFunctions (Section 15.4.8).
If one wants a nimbleFunction that does get specialized but has empty setup code, use setup =
function() {} or setup = TRUE.
## [1] 1
logProbCalcPlusA$valueToAdd <- 2
ClogProbCalcPlusA$valueToAdd # or in the compiled version
## [1] 1
ClogProbCalcPlusA$valueToAdd <- 3
ClogProbCalcPlusA$run(1.5)
## [1] -16.46288
CtestModel$a # a == 1.5 + 3
## [1] 4.5
tion. However, sometimes a programmer may want to force a numeric or character variable to be
included in compilation, even if it is not used directly in run code. As shown below, such variables
can be directly accessed in one nimbleFunction from another, which provides a way of using nim-
bleFunctions as general data structures. To force NIMBLE to include variables during compilation,
for example X and Y, simply include
setupOutputs(X, Y)
Note that in the last line of code, one must have that the length of nodes is equal to that of
values(model, nodes), which means that all the nodes in nodes must be scalar nodes.
Also note that one cannot create new vectors of nodes in run code. They can only be indexed
within a call to calculate, calculateDiff, simulate or getLogProb.
• One can also use model$varName, with the caveat that varName must be a variable name.
This usage would only make sense for a nimbleFunction written for models known to have
a specific variable. (Note that if a is a scalar node in model, then model[['a']] will be a
scalar but model$a will be a vector of length -)
• one should use the <<- global assignment operator to assign into model nodes.
Note that NIMBLE does not allow variables to change dimensions. Model nodes are the same, and
indeed are more restricted because they can’t change sizes. In addition, NIMBLE distinguishes
between scalars and vectors of length 1. These rules, and ways to handle them correctly, are
illustrated in the following code as well as in Section 11.3.
code <- nimbleCode({
z ~ dnorm(0, sd = sigma)
sigma ~ dunif(0, 10)
y[1:n] ~ dmnorm(zeroes[1:n], cov = C[1:5, 1:5])
})
n <- 5
m <- nimbleModel(code, constants = list(n = n, zeroes = rep(0, n),
C = diag(n)))
cm <- compileNimble(m)
Use of [[ ]] allows one to programmatically access a node based on a character variable containing
the node name; this character variable would generally be set in setup code. In contrast, use of $
hard codes the variable name and would not generally be suitable for nimbleFunctions intended for
use with arbitrary models.
15.4.2.2 Getting and setting more than one model node or variable at a time using
values
Sometimes it is useful to set a collection of nodes or variables at one time. For example, one might
want a nimbleFunction that will serve as the objective function for an optimizer. The input to the
nimbleFunction would be a vector, which should be used to fill a collection of nodes in the model
before calculating their log probabilities. This can be done using values:
# get values from a set of model nodes into a vector
P <- values(model, nodes)
# or put values from a vector into a set of model nodes
values(model, nodes) <- P
where the first line would assign the collection of values from nodes into P, and the second would
do the inverse. In both cases, values from nodes with two or more dimensions are flattened into a
vector in column-wise order.
One can also index elements of nodes in the argument to values, in the same manner as discussed
for calculate and related functions in Section 15.4.1.
Note again the potential for confusion between scalars and vectors of length 1. values returns a
vector and expects a vector when used on the left-hand side of an assignment. If only a single value
is being assigned, it must be a vector of length 1, not a scalar. This can be achieved by wrapping
a scalar in c() when necessary. For example:
# c(rnorm(1)) creates vector of length one:
values(model, nodes[1]) <- c(rnorm(1))
# won't compile because rnorm(1) is a scalar
# values(model, nodes[1]) <- rnorm(1)
The simplest way to pass values back and forth between models and modelValues inside of a
nimbleFunction is with copy, which has the synonym nimCopy. See help(nimCopy) for argument
details.
Alternatively, the values may be accessed via indexing of individual rows, using the notation
mv[var, i], where mv is a modelValues object, var is a variable name (not a node name), and i
is a row number. Likewise, the getsize and resize functions can be used as discussed in Section
14.1. However the function as.matrix does not work in run code.
Here is a run function to use these modelValues:
run = function(){
# gets the number of rows of propSamples
m <- getsize(propModelValues)
Once the nimbleFunction is built, the modelValues object can be accessed using $, which is shown
in more detail below. In fact, since modelValues, like most NIMBLE objects, are reference class
objects, one can get a reference to them before the function is executed and then use that reference
afterwards.
# simple model and modelValues for example use with code above
targetModelCode <- nimbleCode({
x ~ dnorm(0,1)
for(i in 1:4)
y[i] ~ dnorm(0,1)
})
},
run = function(m = integer() ){
resize(mv, m)
for(i in 1:m){
propModel$simulate()
nimCopy(from = propModel, to = mv, nodes = nodeNames, row = i)
mv["propLL", i][1] <<- propModel$calculate()
}
}
)
# compiling
CPropSamp <- compileNimble(RPropSamp, project = propModel)
CImpWeights <- compileNimble(RImpWeights, project = targetModel)
## NULL
# calculating the importance weights and saving to mv
CImpWeights$run()
## NULL
# retrieving the modelValues objects
# extracted objects are C-based modelValues objects
savedPropSamp_1 = CImpWeights$propModelValues
savedPropSamp_2 = CPropSamp$mv
savedPropSamp_1["x",1]
## [1] -0.3998956
15.4. WRITING RUN CODE 181
savedPropSamp_2["x",1]
## [1] -0.3998956
savedPropSamp_1["x",1] <- 0 # example of directly setting a value
savedPropSamp_2["x",1]
## [1] 0
# viewing the saved importance weights
savedWeights <- CImpWeights$savedWeights
unlist(savedWeights[["w"]])
if B is a vector or matrix.
The NIMBLE language allows scalars, but models defined from BUGS code are never created as
purely scalar nodes. Instead, a single node such as defined by z ~ dnorm(0, 1) is implemented as
a vector of length 1, similar to R. When using z via model$z or model[["z"]], NIMBLE will try
to do the right thing by treating this as a scalar. In the event of problems5 , a more explicit way to
access z is model$z[1] or model[["z"]][1].
## sharedValues = 1
##
## sharedValues = 2
## [1] 10 20 30 40 50 60 70 80 90 100
methodsDemo1$sharedValue <- 1
CmethodsDemo1 <- compileNimble(methodsDemo1)
CmethodsDemo1$run(1:10)
## sharedValues = 1
##
## sharedValues = 2
## [1] 10 20 30 40 50 60 70 80 90 100
print(myMethodsDemo$sharedValue)
A <- myMethodsDemo$run(x[1:5])
print(A)
B <- myMethodsDemo$times(10)
return(B)
returnType(double())
})
## 2
## sharedValues = 2
##
## sharedValues = 3
##
## 15 30 45 60 75
## [1] 30
CusePreviousDemo1 <- compileNimble(usePreviousDemo1)
CusePreviousDemo1$run(1:10)
## 2
## sharedValues = 2
##
## sharedValues = 3
##
## 15
## 30
## 45
## 60
## 75
## [1] 30
To make such a list, NIMBLE provides a way to declare the arguments and return types of methods:
virtual nimbleFunctions created by nimbleFunctionVirtual. Other nimbleFunctions can inherit
from virtual nimbleFunctions, which in R is called ‘containing’ them. Readers familiar with object
oriented programming will recognize this as a simple class inheritance system. In Version 0.12.2 it
is limited to simple, single-level inheritance.
for(i in seq_along(nfl)) {
print( nfl[[i]]$run(x) )
print( nfl[[i]]$foo() )
}
}
)
## run 1
## 15
## foo 1
## -0.6264538
## run 2
## 120
## foo 2
## 157.2853
CuseThem1 <- compileNimble(useThem1)
set.seed(1)
CuseThem1$run(1:5)
## run 1
## 15
## foo 1
## -0.626454
## run 2
## 120
## foo 2
## 157.285
## NULL
One can also use seq_along with nimbleFunctionLists (and only with nimbleFunctionLists). As
in R, seq_along(myFunList) is equivalent to 1:length(myFunList) if the length of myFunList is
greater than zero. It is an empty sequence if the length is zero.
Note that character vectors of model node and variable names are processed during compilation. For
example, in model[[node]], node may be a character object, and the NIMBLE compiler processes
this differently than print("The node name was ", node). In the former, the NIMBLE compiler
186 CHAPTER 15. WRITING NIMBLEFUNCTIONS TO INTERACT WITH MODELS
sets up a C++ pointer directly to the node in the model, so that the character content of node is
never needed in C++. In the latter, node is used as a C++ string and therefore is needed in C++.
## [1] 100
myDataNF$Y
## [1] 100 101 102 103 104 105 106 107 108 109 110
myDataNF$Z
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 101 103 105 107 109 111 113 115 117 119
## [2,] 102 104 106 108 110 112 114 116 118 120
myUseDataNF$myDataNF$X
## [1] 100
nimbleOptions(buildInterfacesForCompiledNestedNimbleFunctions = TRUE)
CmyUseDataNF <- compileNimble(myUseDataNF)
CmyUseDataNF$run(-100, -(100:110), matrix(-(101:120), nrow = 2))
15.5. EXAMPLE: WRITING USER-DEFINED SAMPLERS TO EXTEND NIMBLE’S MCMC ENGINE187
## NULL
CmyDataNF <- CmyUseDataNF$myDataNF
CmyDataNF$X
## [1] -100
CmyDataNF$Y
## [1] -100 -101 -102 -103 -104 -105 -106 -107 -108 -109 -110
CmyDataNF$Z
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] -101 -103 -105 -107 -109 -111 -113 -115 -117 -119
## [2,] -102 -104 -106 -108 -110 -112 -114 -116 -118 -120
You’ll notice that:
• After execution of the compiled function, access to the X, Y, and Z is the same as for
the uncompiled case. This occurs because CmyUseDataNF is an interface to the compiled
version of myUseDataNF, and it provides access to member objects and functions. In this
case, one member object is myDataNF, which is an interface to the compiled version of
myUseDataNF$myDataNF, which in turn provides access to X, Y, and Z. To reduce memory
use, NIMBLE defaults to not providing full interfaces to nested nimbleFunctions like
myUseDataNF$myDataNF. In this example we made it provide full interfaces by setting
the buildInterfacesForCompiledNestedNimbleFunctions option via nimbleOptions to
TRUE. If we had left that option FALSE (its default value), we could still get to the values
of interest using valueInCompiledNimbleFunction(CmyDataNF, 'X')
• We need to take care that at the time of compilation, the X, Y and Z values contain doubles
via as.numeric so that they are not compiled as integer objects.
• The myDataNF could be created in the setup code. We just provided it as a setup argument
to illustrate that option.
contains = sampler_BASE,
run = function() {
# initial model logProb
model_lp_initial <- getLogProb(model, calcNodes)
# generate proposal
proposal <- rnorm(1, model[[target]], scale)
# store proposal into model
model[[target]] <<- proposal
# proposal model logProb
model_lp_proposed <- model$calculate(calcNodes)
# log-Metropolis-Hastings ratio
log_MH_ratio <- model_lp_proposed - model_lp_initial
To be used within the MCMC engine, sampler functions definitions must adhere exactly to the
following:
• The nimbleFunction must include the contains statement contains = sampler_BASE.
• The setup function must have the four arguments model, mvSaved, target, control, in
that order.
• The run function must accept no arguments, and have no return value. Further, after execu-
tion it must leave the mvSaved modelValues object as an up-to-date copy of the values and
logProb values in the model object.
15.6. COPYING NIMBLEFUNCTIONS (AND NIMBLE MODELS) 189
• The nimbleFunction must have a member method called reset, which takes no arguments
and has no return value.
The purpose of the setup function is generally two-fold. First, to extract control parameters from
the control list; in the example, the proposal standard deviation scale. It is good practice to
specify default values for any control parameters that are not provided in the control argument,
as done in the example. Second, to generate any sets of nodes needed in the run function. In
many sampling algorithms, as here, calcNodes is used to represent the target node(s) and depen-
dencies up to the first layer of stochastic nodes, as this is precisely what is required for calculating
the Metropolis-Hastings acceptance probability. These probability calculations are done using
model$calculate(calcNodes).
The purpose of the mvSaved modelValues object is to store the state of the model, including both
node values and log probability values, as it exists before any changes are made by the sampler.
This allows restoration of the state when a proposal is rejected, as can be seen in the example
above. When a proposal is accepted, one should copy from the model into the mvSaved object.
NIMBLE’s MCMC engine expects that mvSaved contains an up-to-date copy of model values and
logProb values at the end of the run code of a sampler.
Note that NIMBLE generally expects the user-defined sampler to be defined in the global environ-
ment. If you define it in a function (which would generally be the case if you are using it in the
context of parallelization), one approach would be to assign the user-defined sampler to the global
environment in your function:
assign('sampler_yourSampler', sampler_yourSampler, envir = .GlobalEnv)
The reliable way to create new copies of nimbleFunctions is to re-run the R function called
nimbleFunction and record the result in a new object. For example, say you have a
nimbleFunction called foo and 1000 instances of foo are compiled as part of an algorithm
related to a model called model1. If you then need to use foo in an algorithm for another model,
model2, doing so may work without any problems. However, there are cases where the NIMBLE
compiler will tell you during compilation that the second set of foo instances cannot be built
from the previous compiled version. A solution is to re-define foo from the beginning – i.e. call
nimbleFunction again – and then proceed with building and compiling the algorithm for model2.
190 CHAPTER 15. WRITING NIMBLEFUNCTIONS TO INTERACT WITH MODELS
If your nimbleFunctions are very fast, say under 1ms, then microbenchmark will be inaccurate due
to R-to-C++ conversion overhead (that won’t happen in your actual functions). To get timing
information in C++, NIMBLE provides a run.time function that avoids the R-to-C++ overhead.
myMicrobenchmark <- compileNimble(nimbleFunction(
run = function(iters = integer(0)){
time1 <- run.time({
for (t in 1:iters) myCompiledFunVersion1(1.234)
})
time2 <- run.time({
for (t in 1:iters) myCompiledFunVersion2(1.234)
})
return(c(time1, time2))
returnType(double(1))
}))
print(myMicroBenchmark(100000))
R objects that interfaced to compiled C++ objects that have been removed, and you attempt to
use those R objects after clearing their compiled counterparts, you will crash R. We have tried to
minimize that risk, but we can’t guarantee safe behavior.
Andrieu, C., Doucet, A., and Holenstein, R. (2010). Particle Markov chain Monte Carlo methods.
Journal of the Royal Statistical Society: Series B (Statistical Methodology), 72(3):269––342.
Ariyo, O., Quintero, A., Muñoz, J., Verbeke, G., and Lesaffre, E. (2020). Bayesian model selection
in linear mixed models for longitudinal data. Journal of Applied Statistics, 47(5):890–913.
Banerjee, S., Carlin, B., and Gelfand, A. (2015). Hierarchical Modeling and Analysis for Spatial
Data. Chapman & Hall, Boca Raton, 2 edition.
Blackwell, D. and MacQueen, J. (1973). Ferguson distributions via Pólya urn schemes. The Annals
of Statistics, 1:353–355.
Escobar, M. D. (1994). Estimating normal means with a Dirichlet process prior. Journal of the
American Statistical Association, 89:268–277.
Escobar, M. D. and West, M. (1995). Bayesian density estimation and inference using mixtures.
Journal of the American Statistical Association, 90:577–588.
Ferguson, T. S. (1973). A Bayesian analysis of some nonparametric problems. Annals of Statistics,
1:209–230.
Ferguson, T. S. (1974). Prior distribution on the spaces of probability measures. Annals of Statistics,
2:615–629.
Gelfand, A. E. and Kottas, A. (2002). A computational approach for full nonparametric bayesian
inference under dirichlet process mixture models. Journal of Computational and Graphical Statis-
tics, 11(2):289–305.
Gelman, A., Hwang, J., and Vehtari, A. (2014). Understanding predictive information criteria for
Bayesian model. Statistics and Computing, 24(6):997–1016.
George, E., Makov, U., and Smith, A. (1993). Conjugate likelihood distributions. Scandinavian
Journal of Statistics, 20(2):147––156.
Green, P. J. (1995). Reversible jump Markov chain Monte Carlo computation and Bayesian model
determination. Biometrika, 82(4):711–732.
Hug, J. E. and Paciorek, C. J. (2021). A numerically stable online implementation and exploration
of WAIC through variations of the predictive density, using NIMBLE. Technical report, arXiv
preprint.
Ishwaran, H. and James, L. F. (2001). Gibbs sampling methods for stick-breaking priors. Journal
of the American Statistical Association, 96(453):161–173.
193
194 BIBLIOGRAPHY
Ishwaran, H. and James, L. F. (2002). Approximate Dirichlet process computing in finite normal
mixtures: smoothing and prior information. Journal of Computational and Graphical Statistics,
11:508–532.
Lewandowski, D., Kurowicka, D., and Joe, H. (2009). Generating random correlation matrices
based on vines and extended onion method. Journal of multivariate analysis, 100(9):1989–2001.
Lo, A. Y. (1984). On a class of Bayesian nonparametric estimates I: Density estimates. The Annals
of Statistics, 12:351–357.
Lunn, D., Spiegelhalter, D., Thomas, A., and Best, N. (2009). The BUGS project: Evolution,
critique and future directions. Statistics in Medicine, 28(25):3049––3067.
Neal, R. (2000). Markov chain sampling methods for Dirichlet process mixture models. Journal of
Computational and Graphical Statistics, 9:249–265.
Neal, R. M. (2003). Slice sampling. The Annals of Statistics, 31(3):705–741.
Paciorek, C. (2009). Understanding intrinsic Gaussian Markov random field spatial models, in-
cluding intrinsic conditional autoregressive models. Technical report, University of California,
Berkeley.
Roberts, G. O. and Sahu, S. K. (1997). Updating schemes, correlation structure, blocking and
parameterization for the Gibbs sampler. Journal of the Royal Statistical Society: Series B
(Statistical Methodology), 59(2):291–317.
Rue, H. and Held, L. (2005). Gaussian Markov Random Fields: Theory and Applications. Chapman
& Hall, Boca Raton.
Sethuraman, J. (1994). A constructive definition of Dirichlet prior. Statistica Sinica, 2:639–650.
Stan Development Team (2021a). Stan language functions reference manual. Technical report.
Stan Development Team (2021b). Stan language reference manual. Technical report.
Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical bayesian model evaluation using leave-
one-out cross-validation and waic. Statistics and computing, 27(5):1413–1432.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applica-
ble information criterion in singular learning theory. Journal of Machine Learning Research,
11(Dec):3571–3594.