From e07863aa6f323bb022e028ac51ff40f15d9acb10 Mon Sep 17 00:00:00 2001 From: Pierre Gloaguen Date: Mon, 19 Aug 2024 17:46:59 +0200 Subject: [PATCH] definition modele negative binomial --- 01_nimble.qmd | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/01_nimble.qmd b/01_nimble.qmd index b3506fb..42f70d8 100644 --- a/01_nimble.qmd +++ b/01_nimble.qmd @@ -1,8 +1,24 @@ --- title: "Introduction to `nimble`" format: html +editor_options: + chunk_output_type: console --- +# Required packages for this tutorial {.unnumbered} + +```{r} +#| label: packages_nimble_section +#| warning: false +#| message: false +#| cache: false +library(nimble) +library(tidyverse) +library(ggmcmc) +``` + + + # Short presentation of `nimble` First, a very good reference: https://r-nimble.org/html_manual/cha-welcome-nimble.html @@ -19,3 +35,64 @@ But, this remains limited and to have full flexibility, ones need to build its o # A simple example with functions being available in `nimble` +## Defining a negative binomial model + +```{r} +#| label: example1_data + +data_ex1 <- rnbinom(n = 10, prob = 0.4, size = 12) +``` + + + +```{r} +code_neg_bin <- nimbleCode({ + # Observation model + for(i in 1:n){# n is never defined before, it will be a constant + y[i] ~ dnbinom(prob, theta) + } + # Alternative vectorized formulation + # y[1:n] ~ dnbinom(prob, theta) + # PRIORS + prob ~ dunif(0, 1) + theta ~ dexp(0.1) +}) +``` + +Note that in this code, nothing distinguishes observed data from unknown (or latent variables). +The order of lines has no importance as everything will be compiled afterwards + +## Defining the nimble model + +```{r} +#| label: model_neg_bin +model_neg_bin <- nimbleModel(code = code_neg_bin, + name = "Negative binomial", + constants = list(n = length(data_ex1)), + data = list(y = data_ex1), + inits = list(prob = 0.5, theta = 1)) +``` + +```{r} +#| label: posterior_samples +#| cache: true +posterior_samples_neg_bin <- nimbleMCMC(model_neg_bin) +``` + +## Exploring the results + + + +## Alternative MCMC sampler + + + + + + + + + + + +