-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.Rmd
1277 lines (918 loc) · 33.3 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: |
Introduction to NIMBLE
{width=3in}
author: "Olivier Gimenez, Maud Quéroué, Valentin Lauret"
date: "last updated: `r Sys.Date()`"
output:
xaringan::moon_reader:
css: [default, "slides-theme.css"]
lib_dir: libs
nature:
ratio: '16:9'
highlightStyle: github
highlightLines: true
slideNumberFormat: ''
titleSlideClass: [center, middle]
---
```{r setup, include=FALSE, echo=FALSE, massage = FALSE, warning=FALSE}
options(htmltools.dir.version = FALSE)
knitr::opts_chunk$set(comment = "")
library(tidyverse)
theme_set(theme_light())
update_geom_defaults("point", list(size = 2))
library(here)
library(nimble)
```
class: middle center
background-color: black

---
class: middle center
background-color: white

---
# What is NIMBLE?
--
+ **N**umerical **I**nference for statistical **M**odels using **B**ayesian and **L**ikelihood **E**stimation.
--
+ A framework for statistical models and algorithms.
--
+ Uses almost same model syntax as WinBUGS, OpenBUGS, and JAGS, with C++ in the background for faster computations.
--
+ Extension of BUGS language: Additional syntax, call to existing R functions, and implementation of your own functions/distributions.
--
+ Flexibility in MCMC samplers config: Change defaults, write your own algorithms.
--
+ A library of other methods (SMC, MCEM).
???
+ Sequential Monte Carlo (particle filtering)
+ Monte Carlo Expectation Maximization (maximum likelihood)
--
+ A team of friendly, active and helpful developers: de Valpine, Paciorek, Turek.
---
# This workshop
+ Getting started with NIMBLE
+ Programming and coding functions/distributions
+ Choosing and coding MCMC samplers
+ Material from [a book in progress](https://oliviergimenez.github.io/banana-book/), NIMBLE chapter is [here](https://github.com/oliviergimenez/nimble-workshop/blob/master/Overview_IntroductionNIMBLE.pdf)
+ [R codes on GitHub](https://github.com/oliviergimenez/nimble-workshop/blob/master/Rcodes_NimbleGDR.R) for easier manipulation
+ Slides available in PDF format from [there](https://github.com/oliviergimenez/nimble-workshop/blob/master/IntroductionNIMBLE.pdf).
---
# Example
Say we capture, mark and release $n = 57$ animals at the beginning of a winter, out of which we recapture $y = 19$ animals alive:
```{r}
y <- 19 # nb of success
n <- 57 # nb of attempts
```
Assuming all animals are independent of each other and have the same survival probability $\theta$, then $y$ the number of alive animals at the end of the winter is binomial. Using a uniform prior for survival, we have:
\begin{align*}
y &\sim \text{Binomial}(n, \theta) &\text{[likelihood]}
\\
\theta &\sim \text{Uniform}(0, 1) &\text{[prior for }\theta \text{]} \\
\end{align*}
We'd like to estimate winter survival $\theta$.
---
# NIMBLE workflow
To run NIMBLE, you will need to:
1. Build a model consisting of a likelihood and priors.
2. Read in some data.
3. Specify parameters you want to make inference about.
4. Pick initial values for parameters to be estimated (for each chain).
5. Provide MCMC details namely the number of chains, the length of the burn-in period and the number of iterations following burn-in.
---
## Load `nimble` package
First things first:
```{r}
library(nimble)
```
---
class: center, middle
# Getting started
---
# 1. Build model
+ Specify binomial likelihood and uniform prior on survival probability `theta`.
+ We use the `nimbleCode()` function and wrap code within curly brackets:
```{r}
model <- nimbleCode({
# likelihood
survived ~ dbinom(theta, released)
# prior
theta ~ dunif(0, 1)
# derived quantity
lifespan <- -1/log(theta) # expected lifespan
# w/ constant survival
})
```
+ It does not matter in what order you write each line of code, NIMBLE uses a declarative language (vs imperative language).
---
# 1. Build model
You can check that the `model` R object contains your code:
```{r}
model
```
---
# 1. Build model
+ The most common distributions are available in NIMBLE.
+ Among others, `dunif`, `dbeta`, `dmultinom` and `dnorm`.
+ If you cannot find what you need in NIMBLE, you can write your own distribution (more soon).
---
# 2. Read in data
We use a list in which each component corresponds to a known quantity in the model:
```{r}
my.data <- list(released = 57, survived = 19)
```
---
# 2. Distinguish constants and data
+ NIMBLE distinguishes data and constants.
+ Constants are values that do not change, e.g. vectors of known index values or the indices used to define for loops.
+ Data are values that you might want to change, basically anything that only appears on the left of a `~`.
+ For computational efficiency, better to specify as much as possible as constants.
```{r eval = FALSE}
my.constants <- list(released = 57)
my.data <- list(survived = 19)
```
+ Nimble will help you with this!
---
# 3. Specify parameters
+ In our model, we want survival `theta` and `lifespan`:
```{r}
parameters.to.save <- c("theta", "lifespan")
```
+ In general you have many quantities in your model, including some of little interest that are not worth monitoring, and having full control on verbosity will prove handy.
---
# 4. Pick initial values
You can specify initial values for each chain in a list and put them in yet another list:
```{r}
init1 <- list(theta = 0.1)
init2 <- list(theta = 0.5)
initial.values <- list(init1, init2)
initial.values
```
---
# 4. Pick initial values
Alternatively, you can write a simple R function that generates random initial values:
```{r}
initial.values <- function() list(theta = runif(1,0,1))
initial.values()
```
---
# 5. Provide MCMC details
+ You need to tell NIMBLE:
+ The number of chains to run, say `n.chain`
+ How long the burn-in period should be, say `n.burnin`
+ The total number of iterations, say `n.iter`
+ In NIMBLE, the number of posterior samples per chain is `n.iter - n.burnin`
```{r}
n.iter <- 5000
n.burnin <- 1000
n.chains <- 2
```
---
class: middle center
background-color: black

---
class: center, middle
# Run NIMBLE
---
# Run NIMBLE
+ We now sample in the posterior distribution of model parameters using MCMC simulations.
+ This is accomplished using function `nimbleMCMC()`:
```{r, warning=FALSE, message=FALSE, eval = FALSE}
mcmc.output <- nimbleMCMC(code = model,
data = my.data,
inits = initial.values,
monitors = parameters.to.save,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains)
```
```{r, cache = TRUE, echo = FALSE, warning = FALSE, message=FALSE}
mcmc.output <- nimbleMCMC(code = model,
data = my.data,
inits = initial.values,
monitors = parameters.to.save,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains,
progressBar = FALSE)
```
---
class: center, middle
# Inspect outputs
---
# Structure
+ Now let's inspect what we have in `mcmc.output`:
```{r}
str(mcmc.output)
```
+ The R object `mcmc.output` is a list with two components, one for each MCMC chain.
---
# Dimensions
```{r}
dim(mcmc.output$chain1)
```
---
# Return values
```{r}
head(mcmc.output$chain1)
```
---
# Compute posterior summaries
You can compute the posterior mean of `theta`:
```{r}
mean(mcmc.output$chain1[,'theta'])
```
You can also obtain the 95% credible interval for `theta`:
```{r}
quantile(mcmc.output$chain1[,'theta'], probs = c(2.5, 97.5)/100)
```
---
## Visualize posterior distribution with a histogram
.center.nogap[
```{r, echo = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
mcmc.output %>%
as_tibble() %>%
ggplot() +
geom_histogram(aes(x = chain1[,"theta"]), color = "white") +
labs(x = "survival probability")
```
]
---
## R code to produce histogram
```{r, eval = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
mcmc.output %>%
as_tibble() %>%
ggplot() +
geom_histogram(aes(x = chain1[,"theta"]), color = "white") +
labs(x = "survival probability")
```
---
# Painless ways of doing posterior inference
+ The R package `MCMCvis` can be used to summarise and visualize MCMC outputs.
+ There are other perfectly valid options out there like `ggmcmc` and `basicMCMCplots`.
+ Let's load the package `MCMCvis`:
```{r}
library(MCMCvis)
```
---
# Numerical summaries
To get common numerical summaries, function `MCMCsummary()` does the job:
```{r}
MCMCsummary(object = mcmc.output, round = 2)
```
---
# Visualize
A caterpillar plot to visualise posterior distribution of `theta` with `MCMCplot()`:
```{r, eval = FALSE}
MCMCplot(object = mcmc.output, params = 'theta')
```
---
# Visualize
A caterpillar plot to visualise posterior distribution of `theta` with `MCMCplot()`:
.center.nogap[
```{r, echo = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
MCMCplot(object = mcmc.output,
params = 'theta')
```
]
---
# Trace and posterior density
The trace and posterior density of theta can be obtained with `MCMCtrace()`:
```{r, eval = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
MCMCtrace(object = mcmc.output,
pdf = FALSE, # no export to PDF
ind = TRUE, # separate density lines per chain
params = "theta")
```
---
# Trace and posterior density
The trace and posterior density of theta can be obtained with `MCMCtrace()`:
.center.nogap[
```{r, echo = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
MCMCtrace(object = mcmc.output,
pdf = FALSE, # no export to PDF
ind = TRUE, # separate density lines per chain
params = "theta")
```
]
---
# Diagnostics of convergence
You can also add diagnostics of convergence:
```{r, eval = FALSE}
MCMCtrace(object = mcmc.output,
pdf = FALSE,
ind = TRUE,
Rhat = TRUE, # add Rhat
n.eff = TRUE, # add eff sample size
params = "theta")
```
---
# Diagnostics of convergence
You can also add diagnostics of convergence:
.center.nogap[
```{r, echo = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
MCMCtrace(object = mcmc.output,
pdf = FALSE,
ind = TRUE,
Rhat = TRUE, # add Rhat
n.eff = TRUE, # add eff sample size
params = "theta")
```
]
---
class: center, middle
# Derived quantities
---
# Compute lifespan (1)
+ We calculated lifespan directly in our model with `lifespan <- -1/log(theta)`.
+ But you can also calculate this quantity from outside NIMBLE.
+ In our example, all you need is samples from the posterior distribution of `theta`, which we pool between the three chains with:
```{r}
theta_samples <- c(mcmc.output$chain1[,'theta'],
mcmc.output$chain2[,'theta'],
mcmc.output$chain3[,'theta'])
```
---
# Compute lifespan (2)
+ To get samples from the posterior distribution of lifespan, we apply the function to calculate lifespan to the samples from the posterior distribution of survival:
```{r}
lifespan <- -1/log(theta_samples)
```
---
# Numerical summaries
Then, as usual, you can calculate posterior mean and 95% credible interval:
```{r}
mean(lifespan)
quantile(lifespan, probs = c(2.5, 97.5)/100)
```
---
# Visualize
You can also visualise the posterior distribution of lifespan:
```{r, eval = FALSE}
lifespan %>%
as_tibble() %>%
ggplot() +
geom_histogram(aes(x = value), color = "white") +
labs(x = "lifespan")
```
---
# Visualize
.center.nogap[
```{r, echo = FALSE, fig.width = 7.5, fig.asp = 0.618, dev = "svg", message=FALSE, warning=FALSE}
lifespan %>%
as_tibble() %>%
ggplot() +
geom_histogram(aes(x = value), color = "white") +
labs(x = "lifespan")
```
]
---
```{r simple-workflow, echo = FALSE, fig.align="center", out.width="40%"}
knitr::include_graphics("img/simpleNIMBLEworkflow.png")
```
---
class: center, middle
## NIMBLE is more than just another MCMC engine
---
# NIMBLE is a programming environment
+ Allows full control when building models and estimating parameters.
+ Allows you to write your own functions and distributions to build models, and to choose alternative MCMC samplers or code new ones.
+ Here, we're gonna tell you more about programming, and show you a NIMBLE detailed workflow.
---
class: middle center
background-color: black

---
class: center, middle
# Programming: NIMBLE functions
---
# NIMBLE functions
+ NIMBLE provides `nimbleFunctions` for programming.
+ A `nimbleFunction` is like an R function, which can be compiled for faster computation.
---
# Example
+ Going back to our animal survival example, we can write a `nimbleFunction` to compute lifespan:
```{r}
computeLifespan <- nimbleFunction(
run = function(theta = double(0)) { # type declarations
ans <- -1/log(theta)
return(ans)
returnType(double(0)) # return type declaration
} )
```
---
# Example
+ The `run` section gives the function to be executed. It is written in the NIMBLE language.
+ The `theta = double(0)` and `returnType(double(0))` arguments tell NIMBLE that the input and output are single numeric values (scalars).
+ Alternatively, `double(1)` and `double(2)` are for vectors and matrices, while `logical()`, `integer()` and `character()` are for logical, integer and character values.
---
# Example
You can use your `nimbleFunction` in R:
```{r}
computeLifespan(0.8)
```
You can compile it and use the C++ code for faster computation:
```{r message = FALSE, warning=FALSE}
CcomputeLifespan <- compileNimble(computeLifespan)
CcomputeLifespan(0.8)
```
---
# Example
You can also use your `nimbleFunction` in a model:
```{r}
model <- nimbleCode({
# likelihood
survived ~ dbinom(theta, released)
# prior
theta ~ dunif(0, 1)
# derived quantity
lifespan <- computeLifespan(theta)
})
```
---
## The rest of the workflow remains the same
<style type="text/css">
pre {
font-size: 22px
}
</style>
```{r eval = FALSE}
my.data <- list(survived = 19, released = 57)
parameters.to.save <- c("theta", "lifespan")
initial.values <- function() list(theta = runif(1,0,1))
n.iter <- 5000
n.burnin <- 1000
n.chains <- 2
mcmc.output <- nimbleMCMC(code = model,
data = my.data,
inits = initial.values,
monitors = parameters.to.save,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains)
MCMCsummary(object = mcmc.output, round = 2)
```
---
# More about nimbleFunctions
+ With `nimbleFunctions`, you can mimic basic R syntax, do linear algebra (e.g. compute eigenvalues), operate on vectors and matrices (e.g. inverse a matrix), use logical operators (e.g. and/or) and flow control (e.g. if-else).
+ There is also a long list of common and less common distributions that can be used with `nimbleFunctions`.
+ To learn everything you need to know on writing `nimbleFunctions`, make sure to read chapter 11 of the NIMBLE manual at <https://r-nimble.org/html_manual/cha-RCfunctions.html#cha-RCfunctions>.
---
class: middle center
background-color: black

---
class: center, middle
# Programming: Calling R/C++ functions
---
# Calling R/C++ functions
+ If you're like us, and too lazy to write your own functions, you can rely on the scientific community and use existing C, C++ or R code.
+ The trick is to write a `nimbleFunction` that wraps access to that code which can then be used by NIMBLE.
---
# R function example
+ As an example, imagine you'd like to use an R function `myfunction()`, either a function you wrote yourself, or a function available in your favorite R package:
```{r}
myfunction <- function(x) {
-1/log(x)
}
```
---
# R function example
Just wrap this function using `nimbleRcall()` (`nimbleExternalCall()` for a C/C++ function):
```{r}
Rmyfunction <-
nimbleRcall(prototype = function(x = double(0)){},
Rfun = 'myfunction',
returnType = double(0))
```
In the call to `nimbleRcall()` above, the argument `prototype` specifies inputs (a single numeric value `double(0)`) of the R function `Rfun` that generates outputs `returnType` (a single numeric value `double(0)`).
---
# R function example
Now you can call your R function from a model (or any `nimbleFunctions`):
```{r}
model <- nimbleCode({
# likelihood
survived ~ dbinom(theta, released)
# prior
theta ~ dunif(0, 1)
lifespan <- Rmyfunction(theta)
})
```
---
## The rest of the workflow remains the same
<style type="text/css">
pre {
font-size: 22px
}
</style>
```{r eval = FALSE}
my.data <- list(survived = 19, released = 57)
parameters.to.save <- c("theta", "lifespan")
initial.values <- function() list(theta = runif(1,0,1))
n.iter <- 5000
n.burnin <- 1000
n.chains <- 2
mcmc.output <- nimbleMCMC(code = model,
data = my.data,
inits = initial.values,
monitors = parameters.to.save,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains)
MCMCsummary(object = mcmc.output, round = 2)
```
---
# Calling external R/C++ functions
+ Evaluating an R function from within NIMBLE slows MCMC sampling down.
+ But if you can live with it, the cost is easily offset by the convenience of being able to use existing R functions.
+ Another advantage of using `nimbleRcall()` (or `nimbleExternalCall()`) is that you can keep large objects out of your model, so that NIMBLE does not have to handle them in MCMC sampling.
+ These objects should be constants and not change when you run NIMBLE.
+ Letting R manipulating these objects will save you time, usually more than the time you lose by calling R from within NIMBLE.
---
class: center, middle
# Programming: User-defined distributions
---
class: middle center
background-color: black

---
# User-defined distributions
+ With `nimbleFunctions` you can provide user-defined distributions to NIMBLE.
+ You need to write functions for density (`d`) and simulation (`r`) for your distribution.
---
## Let's write our own binomial distribution: density
```{r}
# density
dmybinom <- nimbleFunction(
run = function(x = double(0),
size = double(0),
prob = double(0),
log = integer(0, default = 1)) {
returnType(double(0))
# compute binomial coefficient
lchoose <- lfactorial(size) - lfactorial(x) - lfactorial(size - x)
# binomial density function
logProb <- lchoose + x * log(prob) + (size - x) * log(1 - prob)
if(log) return(logProb)
else return(exp(logProb))
})
```
---
## Let's write our own binomial distribution: simulation
```{r}
# simulation using the coin flip method (p. 524 in Devroye 1986)
rmybinom <- nimbleFunction(
run = function(n = integer(0, default = 1),
size = double(0),
prob = double(0)) {
returnType(double(0))
x <- 0
y <- runif(n = size, min = 0, max = 1)
for (j in 1:size){
if (y[j] < prob){
x <- x + 1
}else{
x <- x
}
}
return(x)
})
```
---
# Example
You need to define the `nimbleFunctions` in R's global environment for them to be accessed:
```{r}
assign('dmybinom', dmybinom, .GlobalEnv)
assign('rmybinom', rmybinom, .GlobalEnv)
```
---
# Try your functions out
You can try out your function and simulate a random value from a binomial distribution with size 5 and probability 0.1:
```{r}
rmybinom(n = 1, size = 5, prob = 0.1)
```
Again with probability 0.8:
```{r}
rmybinom(n = 1, size = 5, prob = 0.8)
```
---
### All set. You can proceed with your usual workflow now.
```{r eval = FALSE}
model <- nimbleCode({
# likelihood
survived ~ dmybinom(prob = theta, size = released)
# prior
theta ~ dunif(0, 1)
})
...
mcmc.output <- nimbleMCMC(code = model,
data = my.data,
inits = initial.values,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains)
MCMCsummary(mcmc.output)
```
---
class: center, middle
# Detailed NIMBLE workflow
---
class: middle center
background-color: black

---
# Under the hood
+ So far, we have used `nimbleMCMC()` which runs the default MCMC workflow.
+ This is perfecly fine for most applications.
+ However, in some situations you need to customize the MCMC samplers to improve or fasten convergence.
+ NIMBLE allows you to look under the hood by using a detailed workflow in several steps: `nimbleModel()`, `configureMCMC()`, `buildMCMC()`, `compileNimble()` and `runMCMC()`.
+ Note that `nimbleMCMC()` does all of this at once.
---
# NIMBLE detailed workflow
We write the model code, read in data and pick initial values as before:
```{r}
model <- nimbleCode({
# likelihood
survived ~ dbinom(theta, released)
# prior
theta ~ dunif(0, 1)
# derived quantity
lifespan <- -1/log(theta)
})
my.data <- list(survived = 19, released = 57)
initial.values <- list(theta = 0.5)
```
---
# 1. Create the model as an R object
First step is to create the model as an R object (uncompiled model) with `nimbleModel()`:
```{r message=FALSE, warning=FALSE}
survival <- nimbleModel(code = model,
data = my.data,
inits = initial.values)
```
---
# 1. Create the model as an R object
You can look at its components (or nodes):
```{r}
survival$getNodeNames()
```
---
# 1. Create the model as an R object
You can look at the values stored at each node:
```{r}
survival$theta
survival$survived
survival$lifespan
# this is -1/log(0.5)
```
---
# 1. Create the model as an R object
We can also calculate the log-likelihood at the initial value for `theta`:
```{r}
survival$calculate()
# this is dbinom(x = 19, size = 57, prob = 0.5, log = TRUE)
```
The ability in NIMBLE to access the nodes of your model and to evaluate the model likelihood can help you in identifying bugs in your code (not covered here).
---
# 2. Compile model
We compile the model with `compileNimble()`:
```{r message=FALSE, warning=FALSE}
Csurvival <- compileNimble(survival)
```
With `compileNimble()`, the C++ code is generated, compiled and loaded back into R so that it can be used in R (compiled model):
```{r}
Csurvival$theta
```
---
## NIMBLE can do maximum likelihood estimation
+ Now you have two versions of the model, `survival` is in R and `Csurvival` in C++.
+ Being able to separate the steps of model building and parameter estimation is a strength of NIMBLE.
+ This gives you a lot of flexibility at both steps.
+ For example, imagine you would like to fit your model with maximum likelihood. You can do it by wrapping your model in an R function that gets the likelihood and maximise this function.
---
class: middle center
background-color: black

---
## NIMBLE can do maximum likelihood estimation
Using the C version of the model, you can write:
```{r}
# function for negative log-likelihood to minimize
f <- function(par) {
Csurvival[['theta']] <- par # assign par to theta
ll <- Csurvival$calculate() # update log-likelihood with par value
return(-ll) # return negative log-likelihood
}
```
---
## NIMBLE can do maximum likelihood estimation
```{r}
# evaluate function at 0.5 and 0.9
f(0.5)
f(0.9)
```
---
## NIMBLE can do maximum likelihood estimation
```{r}
# minimize function
out <- optimize(f, interval = c(0,1))
round(out$minimum, 2)
```
By maximising the likelihood (or minimising the negative log-likelihood), you obtain the maximum likelihood estimate of animal survival, which is exactly 19 surviving animals over 57 released animals or `r round(19/57, 2)`.
---
# 3. MCMC configuration
We create a MCMC configuration for our model with `configureMCMC()`:
```{r}
survivalConf <- configureMCMC(survival)
```
+ This steps tells you the nodes that are monitored by default, and the MCMC samplers than have been assigned to them.
+ Here `theta` is monitored, and samples from its posterior distribution are simulated with a random walk sampler.
---
# 3. MCMC configuration
To monitor `lifespan` in addition to `theta`, you write:
```{r}
survivalConf$addMonitors(c("lifespan"))