---
title: "runMCMCbtadjust Presentation"
author: "Frédéric Gosselin"
email: "frederic.gosselin@inrae.fr"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
bibliography: references.bib
csl: ecology.csl 
vignette: >
  %\VignetteEngine{knitr::knitr}
  %\VignetteIndexEntry{runMCMCbtadjust Presentation}
  %\usepackage[UTF-8]{inputenc}

---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(warnings = FALSE)

### first calculates conditional (logical) variables to activate - or not - child documents whether the environment is OK to build this vignette
condition_rstan<-TRUE
if (nchar(system.file(package='rstan'))==0) {condition_rstan<-FALSE}
condition_greta<-TRUE
if (nchar(system.file(package='greta'))==0) {condition_greta<-FALSE}
	  if (nchar(system.file(package='R6'))==0) {condition_greta<-FALSE}
	  if (nchar(system.file(package='tensorflow'))==0) {condition_greta<-FALSE}
	#removed because interfers with Rmarkdown.  test<-capture.output(greta::greta_sitrep(),type="message")
	# if (max(regexpr("greta is ready to use",test))<=0) {stop("greta should be ready to use, which is not the case - call \"greta_sitrep()\" for more details")}
  if (condition_greta) {temp<-try(greta::normal(0,1)); if (class(temp)[1]=="try-error") {condition_greta<-FALSE}}
condition_jags<-TRUE                             
	  if (nchar(system.file(package='rjags'))==0) {condition_jags<-FALSE}
	  if (nchar(system.file(package='runjags'))==0) {condition_jags<-FALSE}
	  
if (condition_jags) 
  {suppressWarnings(temp<-runjags::testjags(silent=TRUE))
	 if(!(temp$JAGS.available&temp$JAGS.found&temp$JAGS.major==4)) {condition_jags<-FALSE}}

condition_nimble<-TRUE   
	  if (nchar(system.file(package='nimble'))==0) {condition_nimble<-FALSE}


```


# Introduction
This file is meant to present the function `runMCMC_btadjust()` in the `runMCMCbtadjust` package. The main aim of this function is to run a Markov Chain Monte Carlo (MCMC) for a specified Bayesian model while adapting automatically the burn-in and thinning parameters to meet pre-specified targets in terms of MCMC convergence and number of effective values of MCMC outputs - where the term “number of effective values” for the MCMC outputs refers to sample size adjusted for autocorrelation. This is done in only one call to the function that repeatedly calls the MCMC until criteria for convergence and number of effective values are met. This allows to obtain a MCMC output that is out of the transient phase of the MCMC (convergence) and that contains a pre-specified number of nearly independent draws from the posterior distribution (number of effective values). 

This function has four main advantages:

	(i) it saves the analyst's programming time since he/she does not have to repeatedly diagnose and re-run MCMCs until desired levels of convergence and number of effective values are reached;
	
	(ii) it allows a minimal, normalized quality control of MCMC outputs by allowing to meet pre-specified levels in terms of convergence and number of quasi-independent values;
	
	(iii) it may save computer’s time when compared to cases where we have to restart the MCMC from the beginning if it has not converged or reached the specified number of effective values (as e.g. with `runMCMC` function in `NIMBLE`);
	
	and (iv) it can be applied with different MCMC R languages. Indeed, `runMCMC_btadjust()` uses other Bayesian packages to fit the MCMC. At present, only `JAGS`, `NIMBLE` and `greta` can be used as these are the main Bayesian fitting tools in R known by the package author and that permit to continue an already fitted MCMC - which is required for numerical efficiency. We will here show how to fit and compare a very simple model under these three languages, using the possibilities allowed by `runMCMC_btadjust()`.
	
`runMCMC_btadjust()` has a stronger integration with NIMBLE, for which it has the **additional advantage of somewhat easing MCMC sampler control and extra calculations**, i.e. calculations on the fitted model, after the end of the MCMC (see the separate two vignettes on these two topics).

We will **here show how to fit and compare a very simple model under these three languages**, using the possibilities allowed by `runMCMC_btadjust()`.

Our model is one of the simplest statistical model we could think of: inspired from @Kery_2010, we model data of weights of 1,000 Pilgrim falcons (*Falco peregrinus*) simulated from a Gaussian distribution with mean 600 grams and standard error 30 grams:

```{r Simulating data}

set.seed(1)
y1000<-rnorm(n=1000,mean=600,sd=30)

```

```{r, child=if (condition_nimble & condition_rstan) "../man/fragments/Nimble1_alone_fragment.Rmd"}
```

```{r, child=if (condition_nimble & condition_jags & condition_rstan) "../man/fragments/Jags_fragment.Rmd"}
```

```{r, child=if (condition_nimble & condition_jags & condition_greta & condition_rstan) "../man/fragments/Greta_fragment.Rmd"}
```

```{r, child=if (condition_nimble & condition_jags & condition_greta & condition_rstan) "../man/fragments/Nimble_and_Jags2_fragment.Rmd"}
```

```{r, child=if (condition_nimble & condition_rstan) "../man/fragments/Nimble2_removed_chain.Rmd"}
```

# Conclusion
We hope we have convinced the R user of Bayesian models that `runMCMC_btadjust()` can help having a more efficient, quality oriented use of these types of models while saving analyst's and potentially computer time. Indeed, to recap, the aim of this function is to run a Markov Chain Monte Carlo (MCMC) for a specified Bayesian model while adapting automatically the burn-in and thinning parameters to meet pre-specified targets in terms of MCMC convergence and number of effective values of MCMC outputs. This is done in only one call to the function that repeatedly calls the MCMC until criteria for convergence and number of effective values are met. The function has four main advantages:

  (i) it saves the analyst’s programming time since he/she does not have to repeatedly diagnose and re-run MCMCs until desired levels of convergence and number of effective values are reached;
  
  (ii) it allows a minimal, normalized quality control of MCMC outputs by allowing to meet pre-specified levels in terms of convergence and number of quasi-independent values;
  
  (iii) it may save computer’s time when compared to cases where we have to restart the MCMC from the beginning if it has not converged or reached the specified number of effective values;
  
  (iv) it can be applied with different MCMC fitting tools available in R - at present `greta`, `NIMBLE` and `JAGS`. This comes with two positive consequences in practice: first, allowing the user a more rigorous comparison between the three Bayesian fitting languages in terms of comparability of inference and of MCMC efficiency - especially in terms of CPU time per effective value; second, making it easier to develop the same Bayesian model with these different languages, which is to our experience welcome in practical cases, since these different languages have advantages over the other ones that vary from one context to the other.

# Acknowledgements
I wished to thank Frédéric Mortier (ANR Gambas project supervisor, project in which the initial versions of the package were developed), Pierre Bouchet, Ugoline Godeau and Marion Gosselin (INRAE, for collaboration on some codes that were preliminary to this package) and `NIMBLE` and `greta` users mailing lists.

The initial development of this package (up to version 1.1.1) was performed within the GAMBAS project funded by the French Agence Nationale pour la Recherche (ANR-18-CE02-0025) (cf. <https://gambas.cirad.fr/>).

<img src="../man/figures/logo_gambas.jpg">

# References

