MCMC output format

In this tutorial, we will have a closer look at the object returned by calling run_mcmc() on a network model. Understanding the structure of the object containing the results of a run is important for model diagnostics and interpretation.

The default format: mcmc.list

To quickly obtain an MCMC run output for us to examine, let's run the simple model aquarium_mod which is provided with the package. Feel free to read the help ?aquarium_mod if you are curious about the model itself.

library(isotracer)
aquarium_mod
fit <- run_mcmc(aquarium_mod, iter = 1000)

By default, run_mcmc() returns an mcmc.list object. An mcmc.list has a simple format to store the content of parallel MCMC chains:

length(fit)
## [1] 4
str(fit[[1]])
##  'mcmc' num [1:500, 1:8] 0.182 0.167 0.145 0.196 0.206 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:8] "eta" "lambda_algae" "lambda_daphnia" "lambda_NH4" ...
##  - attr(*, "mcpar")= num [1:3] 501 1000 1

The output above can seem a little obscure if you are not familiar with R data structures, but in a nutshell it tells us that the mcmc.list is basically a list with one element per chain, each chain being stored as a matrix.

The mcmc.list class is implemented by the coda package, and it has the advantage of being recognized by many other R packages dealing with Bayesian MCMC such as bayesplot of ggmcmc.

In the isotracer package, the returned fit is very slightly extended compared to the base mcmc.list class:

class(fit)
## [1] "networkModelStanfit" "mcmc.list"

By having also a networkModelStanfit class, the output from run_mcmc() can be recognized automatically by some methods implemented in isotracer, such as plot():

plot(fit)
# Note: the figure below only shows a few of the traceplots for vignette concision

How to convert the default output to a table?

An mcmc.list object can be converted to an even simpler, flat matrix:

z <- as.matrix(fit)
head(z)
##            eta lambda_algae lambda_daphnia lambda_NH4 upsilon_algae_to_daphnia
## [1,] 0.1820520  0.005600588    0.013365970 0.06106272               0.10972743
## [2,] 0.1668992  0.092296470    0.004996048 0.04038633               0.09823474
## [3,] 0.1447189  0.104923525    0.002918309 0.08099013               0.08869545
## [4,] 0.1960058  0.121400912    0.008882116 0.02672072               0.13615116
## [5,] 0.2063181  0.160801075    0.017978947 0.01132191               0.12374308
## [6,] 0.1147825  0.096939568    0.035169770 0.06792774               0.04784297
##      upsilon_daphnia_to_NH4 upsilon_NH4_to_algae      zeta
## [1,]             0.05000101            0.3200703 0.3134398
## [2,]             0.04445935            0.3174082 0.2124831
## [3,]             0.04553316            0.3139307 0.2037186
## [4,]             0.05336519            0.3278934 0.3092583
## [5,]             0.05244057            0.3125726 0.3431028
## [6,]             0.04944598            0.3111450 0.2893755
str(z)
##  num [1:2000, 1:8] 0.182 0.167 0.145 0.196 0.206 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:8] "eta" "lambda_algae" "lambda_daphnia" "lambda_NH4" ...

or to a data frame:

z <- as.data.frame(as.matrix(fit))
head(z)
##         eta lambda_algae lambda_daphnia lambda_NH4 upsilon_algae_to_daphnia
## 1 0.1820520  0.005600588    0.013365970 0.06106272               0.10972743
## 2 0.1668992  0.092296470    0.004996048 0.04038633               0.09823474
## 3 0.1447189  0.104923525    0.002918309 0.08099013               0.08869545
## 4 0.1960058  0.121400912    0.008882116 0.02672072               0.13615116
## 5 0.2063181  0.160801075    0.017978947 0.01132191               0.12374308
## 6 0.1147825  0.096939568    0.035169770 0.06792774               0.04784297
##   upsilon_daphnia_to_NH4 upsilon_NH4_to_algae      zeta
## 1             0.05000101            0.3200703 0.3134398
## 2             0.04445935            0.3174082 0.2124831
## 3             0.04553316            0.3139307 0.2037186
## 4             0.05336519            0.3278934 0.3092583
## 5             0.05244057            0.3125726 0.3431028
## 6             0.04944598            0.3111450 0.2893755
str(z)
## 'data.frame':    2000 obs. of  8 variables:
##  $ eta                     : num  0.182 0.167 0.145 0.196 0.206 ...
##  $ lambda_algae            : num  0.0056 0.0923 0.1049 0.1214 0.1608 ...
##  $ lambda_daphnia          : num  0.01337 0.005 0.00292 0.00888 0.01798 ...
##  $ lambda_NH4              : num  0.0611 0.0404 0.081 0.0267 0.0113 ...
##  $ upsilon_algae_to_daphnia: num  0.1097 0.0982 0.0887 0.1362 0.1237 ...
##  $ upsilon_daphnia_to_NH4  : num  0.05 0.0445 0.0455 0.0534 0.0524 ...
##  $ upsilon_NH4_to_algae    : num  0.32 0.317 0.314 0.328 0.313 ...
##  $ zeta                    : num  0.313 0.212 0.204 0.309 0.343 ...

or to a tibble:

z <- tibble::as_tibble(as.matrix(fit))
z
## # A tibble: 2,000 × 8
##       eta lambda_algae lambda_daphnia lambda_NH4 upsilon_algae_to_daphnia
##     <dbl>        <dbl>          <dbl>      <dbl>                    <dbl>
##  1 0.182       0.00560        0.0134      0.0611                   0.110 
##  2 0.167       0.0923         0.00500     0.0404                   0.0982
##  3 0.145       0.105          0.00292     0.0810                   0.0887
##  4 0.196       0.121          0.00888     0.0267                   0.136 
##  5 0.206       0.161          0.0180      0.0113                   0.124 
##  6 0.115       0.0969         0.0352      0.0679                   0.0478
##  7 0.0951      0.0560         0.0291      0.0219                   0.0660
##  8 0.0950      0.0529         0.00946     0.0131                   0.0625
##  9 0.106       0.0671         0.0189      0.0136                   0.0803
## 10 0.0803      0.106          0.00741     0.112                    0.0630
## # ℹ 1,990 more rows
## # ℹ 3 more variables: upsilon_daphnia_to_NH4 <dbl>, upsilon_NH4_to_algae <dbl>,
## #   zeta <dbl>

How to calculate derived parameters?

Converting your output to one of those simple tabular formats can be useful if you want to manipulate and perform operations on your MCMC samples.

However, for simple manipulations, isotracer provides convenient methods to perform calculations on parameter chains directly from the output of run_mcmc(). You can thus produce derived parameter chains directly from the mcmc.list object, without having to convert your output to another format:

algal_total_out <- fit[, "upsilon_algae_to_daphnia"] + fit[, "lambda_algae"]
algal_turnover <- 1 / algal_total_out
plot(algal_turnover)

You can read more about this in the vignette about calculating derived parameters.

How to combine derived parameters?

You can combine derived parameters into a single mcmc.listobject using the usual c() syntax. This can be convenient for more compact plotting or summary calculations:

my_derived <- c("out rate" = algal_total_out, "turnover" = algal_turnover)
plot(my_derived)

summary(my_derived)
## 
## Iterations = 501:1000
## Thinning interval = 1 
## Number of chains = 4 
## Sample size per chain = 500 
## 
## 1. Empirical mean and standard deviation for each variable,
##    plus standard error of the mean:
## 
##            Mean      SD Naive SE Time-series SE
## out rate 0.1683 0.05956 0.001332       0.002038
## turnover 6.8562 2.92403 0.065383       0.112872
## 
## 2. Quantiles for each variable:
## 
##             2.5%    25%    50%    75%   97.5%
## out rate 0.06783 0.1262 0.1619 0.2084  0.2961
## turnover 3.37673 4.7974 6.1749 7.9247 14.7428

A more detailed format: stanfit

Calling run_mcmc() will run a Stan model behind the scenes. Stan is great since it will let you know loudly when something went wrong with the run, such as problems with divergent chains or low Bayesian fraction of missing information. Such problems should not be ignored! The Stan development team has a nice page explaining Stan's warnings.

In any case, if something went wrong with your run, you might want to have a more complete output than simply the mcmc.list object. You can ask run_mcmc() to return the original stanfit object produced by Stan with:

fit2 <- run_mcmc(aquarium_mod, iter = 1000, stanfit = TRUE)

fit2 is now a regular stanfit object:

class(fit2)
## [1] "stanfit"
## attr(,"package")
## [1] "rstan"

This is a more complicated type of object than an mcmc.list, but it also contains much more information about the Stan run. It also comes with the benefit of the existing methods for stanfit object, for example:

rstan::plot(fit2)

You can go through Stan documentation for more details about this format. If you are reading about solving Stan model issues on online forums and the suggested solutions require to examine some Stan output, that's the object you want to look at!

For example, you can examine it with ShinyStan:

library(shinystan)
launch_shinystan(fit2)


Try the isotracer package in your browser

Any scripts or data that you put into this service are public.

isotracer documentation built on Sept. 22, 2023, 1:07 a.m.