Post-run diagnostics and analyses

2023-09-21

In this tutorial, we assume that you successfully ran an MCMC on a network model, and that it is now time to have a critical look at the output of the run.

This tutorial will present how to check that the MCMC run went fine, but it will explain only very briefly how to check that the model is compatible with the observed data. More details about this important step is presented in the next vignette about posterior predictive checks.

This vignette is using the MCMC run from the Quick start tutorial. Please go back and run the code of that vignette to generate the MCMC data if you haven’t already!

Reminder: what is the result format returned by run_mcmc()?

In the Quick Start tutorial, we generated the run object by running run <- run_mcmc(m, iter = 1000). The output from run_mcmc() is a well-behaved mcmc.list object as implemented in the coda package:

is(run, "mcmc.list")
## [1] TRUE

It makes it very easy to use the tools already available for this class of objects, such as those implemented in the packages coda, bayesplot, ggmcmc or MCMCvis.

In addition to all those existing tools, the isotracer package also adds some extra methods to easily calculate derived parameters from an mcmc.list. You will learn more about how to do this in the vignette Derived parameters.

General diagnostics

Trace plot

You should always run several chains when performing a Bayesian MCMC. Trace plots allow to get a feeling for:

If you are not satisfied with the traces, you need to run a longer run or maybe to tweak the settings of the Stan run.

This is the trace plot we obtained from the previous vignette:

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

In this case, the chains have converged towards the same region, and the mixing looks good for all of them. There is no obvious problem visible in those traces.

Gelman and Rubin’s convergence diagnostic

It can be useful to have a more formal test of the convergence of the chains. The Gelman and Rubin’s convergence diagnostic is implemented in the coda package. We can run it with the coda::gelman.diag() function. See the coda documentation ?gelman.diag for more details about this diagnostic.

Let’s have a look at the diagnostic for our chains:

library(coda)
run %>% gelman.diag()
## Potential scale reduction factors:
## 
##                          Point est. Upper C.I.
## eta                            1.02       1.04
## lambda_algae                   1.00       1.01
## lambda_daphnia                 1.00       1.01
## lambda_NH4                     1.02       1.03
## upsilon_algae_to_daphnia       1.02       1.04
## upsilon_daphnia_to_NH4         1.01       1.01
## upsilon_NH4_to_algae           1.01       1.04
## zeta                           1.02       1.04
## 
## Multivariate psrf
## 
## 1.01

The diagnostic values should be very, very close to 1: it looks good in this case!

If some values were e.g. \(>1.05\), this would already be enough to cause us to wonder about the sampling quality.

Predicted trajectories

In order to check the quality of the model fit, the consistency between the parameter posteriors and the observed data can be checked by plotting the credible envelopes for the estimated trajectories along with the observed data points. This is called a posterior predictive check and is very important to check that the model can actually predict the observed data reasonably well. If the observed data cannot be satisfactorily predicted from the fitted model, then our model is not a good model of the data!

To do a posterior predictive check, the first step is to generate predictions for the model based on the MCMC posteriors with predict():

# From the Quick Start tutorial:
# 'm' is the network model we used when calling 'run <- run_mcmc(m, iter = 1000)'
predictions <- predict(m, run, probs = 0.95)

We can then visualize the predictions along with the observations with the plot() method:

plot(predictions)

This plot enables to compare both the size and the proportion observations with the predictions.

Post-run analyses

Parameter estimates

The quickest way to get parameter estimates is to use the summary() function on the posterior:

run %>% summary()
## 
## 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
## eta                      0.12975 0.048193 0.0010776       0.001750
## lambda_algae             0.10520 0.067634 0.0015123       0.002626
## lambda_daphnia           0.03635 0.040243 0.0008999       0.001548
## lambda_NH4               0.09119 0.068627 0.0015345       0.003257
## upsilon_algae_to_daphnia 0.08106 0.027435 0.0006135       0.001107
## upsilon_daphnia_to_NH4   0.04888 0.007384 0.0001651       0.000215
## upsilon_NH4_to_algae     0.33815 0.045176 0.0010102       0.001498
## zeta                     0.43263 0.230978 0.0051648       0.012713
## 
## 2. Quantiles for each variable:
## 
##                               2.5%      25%     50%     75%   97.5%
## eta                      0.0675638 0.095417 0.11923 0.15317 0.24470
## lambda_algae             0.0077299 0.055452 0.09633 0.14164 0.27581
## lambda_daphnia           0.0007531 0.008797 0.02344 0.04996 0.14831
## lambda_NH4               0.0051504 0.039730 0.07901 0.12577 0.26845
## upsilon_algae_to_daphnia 0.0456967 0.062317 0.07572 0.09238 0.15529
## upsilon_daphnia_to_NH4   0.0349468 0.044055 0.04866 0.05343 0.06414
## upsilon_NH4_to_algae     0.2518269 0.307402 0.33694 0.36788 0.43057
## zeta                     0.1771018 0.280644 0.36964 0.50929 1.07641

If you need to store those values, for example to plot them, you can assign the output of summary() to an object:

estimates <- run %>% summary()
names(estimates)
## [1] "statistics" "quantiles"  "start"      "end"        "thin"       "nchain"

The means and standard deviations are accessible in $statistics:

estimates$statistics
##                                Mean          SD     Naive SE Time-series SE
## eta                      0.12975071 0.048192894 0.0010776259   0.0017497862
## lambda_algae             0.10519705 0.067633765 0.0015123370   0.0026261674
## lambda_daphnia           0.03635458 0.040242625 0.0008998525   0.0015480504
## lambda_NH4               0.09119099 0.068626747 0.0015345407   0.0032572174
## upsilon_algae_to_daphnia 0.08106393 0.027434670 0.0006134579   0.0011067159
## upsilon_daphnia_to_NH4   0.04888479 0.007383861 0.0001651082   0.0002149579
## upsilon_NH4_to_algae     0.33814672 0.045175612 0.0010101574   0.0014976810
## zeta                     0.43262806 0.230978132 0.0051648280   0.0127129401

and the quantiles are in $quantiles:

estimates$quantiles
##                                  2.5%         25%        50%        75%      97.5%
## eta                      0.0675637722 0.095416804 0.11922521 0.15317186 0.24470337
## lambda_algae             0.0077299114 0.055452469 0.09633200 0.14163937 0.27581349
## lambda_daphnia           0.0007530601 0.008797266 0.02343532 0.04996465 0.14830752
## lambda_NH4               0.0051504088 0.039730484 0.07901059 0.12576583 0.26845212
## upsilon_algae_to_daphnia 0.0456966776 0.062317193 0.07572093 0.09237905 0.15528894
## upsilon_daphnia_to_NH4   0.0349468460 0.044055236 0.04865711 0.05342772 0.06414298
## upsilon_NH4_to_algae     0.2518268578 0.307401798 0.33693611 0.36788243 0.43056673
## zeta                     0.1771018376 0.280644193 0.36964304 0.50928816 1.07640560

Parameter correlations

The dependencies between your model parameters might be of interest to you. If you would like to analyse the correlations between parameters during the MCMC run, you can use a few ready-made functions to get a quick overview of the correlation structure.

The isotracer package comes with the minimalist function mcmc_heatmap() to draw the strength of parameter correlations:

mcmc_heatmap(run)

But of course you could use other functions provided by other packages, such as:

Extracting parameters, trajectories and flows

If you are interested in getting detailed tables containing all the samples of the parameter posteriors, you can use the tidy_mcmc() function:

tidy_mcmc(run)
## # A tibble: 2,000 × 3
##    mcmc.chain mcmc.iteration mcmc.parameters
##         <int>          <int> <list>         
##  1          1              1 <dbl [8]>      
##  2          1              2 <dbl [8]>      
##  3          1              3 <dbl [8]>      
##  4          1              4 <dbl [8]>      
##  5          1              5 <dbl [8]>      
##  6          1              6 <dbl [8]>      
##  7          1              7 <dbl [8]>      
##  8          1              8 <dbl [8]>      
##  9          1              9 <dbl [8]>      
## 10          1             10 <dbl [8]>      
## # ℹ 1,990 more rows

By default the parameter values are nested into a list column, but you can also get a flat table with spread = TRUE:

tidy_mcmc(run, spread = TRUE)
## # A tibble: 2,000 × 10
##    mcmc.chain mcmc.iteration    eta lambda_algae lambda_daphnia lambda_NH4
##         <int>          <int>  <dbl>        <dbl>          <dbl>      <dbl>
##  1          1              1 0.137        0.122         0.0396     0.00669
##  2          1              2 0.0837       0.0303        0.00587    0.0204 
##  3          1              3 0.0904       0.109         0.00203    0.0354 
##  4          1              4 0.102        0.0123        0.0428     0.0880 
##  5          1              5 0.114        0.132         0.00369    0.0202 
##  6          1              6 0.112        0.0533        0.00707    0.00243
##  7          1              7 0.132        0.170         0.0119     0.0799 
##  8          1              8 0.180        0.0772        0.0273     0.0486 
##  9          1              9 0.201        0.0881        0.0571     0.0472 
## 10          1             10 0.145        0.0579        0.00255    0.0689 
## # ℹ 1,990 more rows
## # ℹ 4 more variables: upsilon_algae_to_daphnia <dbl>, upsilon_daphnia_to_NH4 <dbl>,
## #   upsilon_NH4_to_algae <dbl>, zeta <dbl>

The above table only contains the primary parameters. If you are interested in getting the predicted trajectories for individual MCMC samples, you can use the tidy_trajectories() function:

# We have to also provide the original network model `m`
tt <- tidy_trajectories(m, run, n = 200)
tt
## # A tibble: 200 × 4
##    mcmc.chain mcmc.iteration mcmc.parameters trajectories    
##         <int>          <int> <list>          <list>          
##  1          4             28 <dbl [8]>       <tibble [1 × 5]>
##  2          2             87 <dbl [8]>       <tibble [1 × 5]>
##  3          2            319 <dbl [8]>       <tibble [1 × 5]>
##  4          4            295 <dbl [8]>       <tibble [1 × 5]>
##  5          1             71 <dbl [8]>       <tibble [1 × 5]>
##  6          2            184 <dbl [8]>       <tibble [1 × 5]>
##  7          1            371 <dbl [8]>       <tibble [1 × 5]>
##  8          2            257 <dbl [8]>       <tibble [1 × 5]>
##  9          2            198 <dbl [8]>       <tibble [1 × 5]>
## 10          1            307 <dbl [8]>       <tibble [1 × 5]>
## # ℹ 190 more rows

As you can see, the tt object is a tidy table which contains the parameter values and the corresponding trajectories calculated for 200 randomly selected MCMC samples. The calculated trajectories are stored in the trajectories column and provide the quantities of unmarked and marked tracer (e.g. light and heavy isotope) for each compartment at each time step:

tt$trajectories[[1]]
## # A tibble: 1 × 5
##   timepoints  unmarked        marked          sizes           proportions    
##   <list>      <list>          <list>          <list>          <list>         
## 1 <dbl [260]> <dbl [260 × 3]> <dbl [260 × 3]> <dbl [260 × 3]> <dbl [260 × 3]>

Because each trajectory is itself a table containing a time series for each compartment, the output of tidy_trajectories() has several levels of nesting. This makes it a bit cumbersome to manipulate. Note that the output format of this function might change in the future.

Here is an example of what can be done using the predicted trajectories:

algae <- tt %>%
  mutate(prop_algae = map(trajectories, function(tr) {
    tr[["proportions"]][[1]][, "algae"]
  })) %>%
  pull(prop_algae) %>%
  do.call(rbind, .)
time <- tt$trajectories[[1]]$timepoints[[1]]
plot(0, type = "n", xlim = range(time), ylim = range(algae), las = 1,
     xlab = "Time", ylab = "Proportion of marked tracer (algae)",
     main = "Posterior sample of trajectories (for 15N prop. in algae)")
invisible(sapply(seq_len(nrow(algae)), function(i) {
  lines(time, algae[i,], col = adjustcolor("seagreen3", alpha.f = 0.2))
}))

Finally, if what you are interested in are not the trajectories per se but the actual flows of nutrient during the experiment, you can use the tidy_flows() function to extract flows in a similar way:

#' Again, note that we also provide the original network model `m`
tf <- tidy_flows(m, run, n = 200)
tf
## # A tibble: 200 × 4
##    mcmc.chain mcmc.iteration mcmc.parameters flows             
##  *      <int>          <int> <list>          <list>            
##  1          1            372 <dbl [8]>       <gropd_df [6 × 3]>
##  2          2            215 <dbl [8]>       <gropd_df [6 × 3]>
##  3          4            226 <dbl [8]>       <gropd_df [6 × 3]>
##  4          1            172 <dbl [8]>       <gropd_df [6 × 3]>
##  5          1            222 <dbl [8]>       <gropd_df [6 × 3]>
##  6          2            221 <dbl [8]>       <gropd_df [6 × 3]>
##  7          3            310 <dbl [8]>       <gropd_df [6 × 3]>
##  8          2            205 <dbl [8]>       <gropd_df [6 × 3]>
##  9          2             34 <dbl [8]>       <gropd_df [6 × 3]>
## 10          2            110 <dbl [8]>       <gropd_df [6 × 3]>
## # ℹ 190 more rows

The returned object is very similar to the output of tidy_trajectories(), except that the trajectories column is replaced by a flows column:

tf$flows[[1]]
## # A tibble: 6 × 3
## # Groups:   from [3]
##   from    to      average_flow
##   <chr>   <chr>          <dbl>
## 1 NH4     algae         0.0709
## 2 NH4     <NA>          0.0120
## 3 algae   daphnia       0.0775
## 4 algae   <NA>          0.0911
## 5 daphnia NH4           0.103 
## 6 daphnia <NA>          0.0266

The average flow values are given in flow per unit of time. See ?tidy_flows() for more details, including the possibility of calculating steady state flows for network systems that admits a steady state equilibrium.

The tidy_trajectories() and tidy_flows() functions are especially useful when you want to do some calculations related to some specific properties of the trajectories or of the nutrient flows over the whole MCMC posterior.