# Accessing the contents of a stanfit object

#### Stan Development Team

#### 2017-07-03

This vignette demonstrates how to access most of data stored in a stanfit object. A stanfit object (an object of class `"stanfit"`) contains the output derived from fitting a Stan model using Markov chain Monte Carlo or one of Stan’s variational approximations (meanfield or full-rank). Throughout the document we’ll use the stanfit object obtained from fitting the Eight Schools example model:

    library(rstan)
    fit <- stan_demo("eight_schools", refresh = 0)

    Warning: There were 4 divergent transitions after warmup. Increasing adapt_delta above 0.8 may help. See
    http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup

    Warning: Examine the pairs() plot to diagnose sampling problems

    class(fit)

    [1] "stanfit"
    attr(,"package")
    [1] "rstan"

## Posterior draws

There are several functions that can be used to access the draws from the posterior distribution stored in a stanfit object. These are `extract`, `as.matrix`, `as.data.frame`, and `as.array`, each of which returns the draws in a different format.

#### extract()

The `extract` function (with its default arguments) returns a list with named components corresponding to the model parameters.

    list_of_draws <- extract(fit)
    print(names(list_of_draws))

    [1] "mu"    "tau"   "eta"   "theta" "lp__"

In this model the parameters `mu` and `tau` are scalars and `theta` is a vector with eight elements. This means that the draws for `mu` and `tau` will be vectors (with length equal to the number of post-warmup iterations times the number of chains) and the draws for `theta` will be a matrix, with each column corresponding to one of the eight components:

    head(list_of_draws$mu)

    [1] 4.178689 7.896903 5.230637 9.477452 5.166316 5.575505

    head(list_of_draws$tau)

    [1]  1.8210255  0.3198835  3.5427238 10.9788963  1.5416283  6.5294129

    head(list_of_draws$theta)

    iterations      [,1]      [,2]      [,3]      [,4]      [,5]     [,6]
          [1,]  4.328065  2.035497  2.687295  4.830606  2.591323 3.415279
          [2,]  7.701131  8.079618  7.415463  8.012570  7.721320 8.004710
          [3,] 12.080879  6.458229  4.256499  3.626688  6.189494 7.787423
          [4,] 15.436545 15.575352 -1.666966  8.823516 -6.225512 6.897776
          [5,]  5.427178  5.698364  5.923378  4.087328  5.174217 2.535239
          [6,] 14.797413  2.227443  1.963443 13.695857 13.611430 3.288641

    iterations      [,7]      [,8]
          [1,]  5.631401  4.327563
          [2,]  7.843496  7.791768
          [3,]  3.987610  1.214433
          [4,]  8.292774 13.447035
          [5,]  6.470211  8.030746
          [6,] 13.736938  2.483708

#### as.matrix(), as.data.frame(), as.array()

The `as.matrix`, `as.data.frame`, and `as.array` functions can also be used to retrieve the posterior draws from a stanfit object:

    matrix_of_draws <- as.matrix(fit)
    print(colnames(matrix_of_draws))

     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

    df_of_draws <- as.data.frame(fit)
    print(colnames(df_of_draws))

     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

    array_of_draws <- as.array(fit)
    print(dimnames(array_of_draws))

    $iterations
    NULL

    $chains
    [1] "chain:1" "chain:2" "chain:3" "chain:4"

    $parameters
     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

The `as.matrix` and `as.data.frame` methods essentially return the same thing except in matrix and data frame form, respectively. The `as.array` method returns the draws from each chain separately and so has an additional dimension:

    print(dim(matrix_of_draws))
    print(dim(df_of_draws))
    print(dim(array_of_draws))

    [1] 4000   19
    [1] 4000   19
    [1] 1000    4   19

By default all of the functions for retrieving the posterior draws return the draws for all parameters (and generated quantities). The optional argument `pars` (a character vector) can be used if only a subset of the parameters is desired, for example:

    mu_and_theta1 <- as.matrix(fit, pars = c("mu", "theta[1]"))
    head(mu_and_theta1)

              parameters
    iterations         mu  theta[1]
          [1,]  8.7078861  7.698465
          [2,]  0.8769045  3.818568
          [3,] 14.8421405 12.974890
          [4,] 13.2551953 21.464781
          [5,] 10.9892924  4.396455
          [6,]  1.0052114 28.014937

## Posterior summary statistics and convergence diagnostics

Summary statistics are obtained using the `summary` function. The object returned is a list with two components:

    fit_summary <- summary(fit)
    print(names(fit_summary))

    [1] "summary"   "c_summary"

In `fit_summary$summary` all chains are merged whereas `fit_summary$c_summary` contains summaries for each chain individually. Typically we want the summary for all chains merged, which is what we’ll focus on here.

The summary is a matrix with rows corresponding to parameters and columns to the various summary quantities. These include the posterior mean, the posterior standard deviation, and various quantiles computed from the draws. The `probs` argument can be used to specify which quantiles to compute and `pars` can be used to specify a subset of parameters to include in the summary.

For models fit using MCMC, also included in the summary are the Monte Carlo standard error (`se_mean`), the effective sample size (`n_eff`), and the R-hat statistic (`Rhat`).

    print(fit_summary$summary)

                      mean    se_mean        sd        2.5%         25%
    mu         8.048679487 0.10855021 4.8844478  -1.5270458   4.7956486
    tau        6.557081758 0.14082445 5.4953624   0.2443783   2.4172257
    eta[1]     0.352512349 0.01456519 0.9211836  -1.4828920  -0.2395504
    eta[2]     0.001035813 0.01391937 0.8803384  -1.7609156  -0.5578358
    eta[3]    -0.210298411 0.01451442 0.9179728  -2.0459843  -0.8182240
    eta[4]    -0.046330692 0.01399663 0.8852245  -1.7858954  -0.6395271
    eta[5]    -0.354773627 0.01389684 0.8789130  -2.0387730  -0.9241866
    eta[6]    -0.242147628 0.01406086 0.8892870  -1.9917021  -0.8297227
    eta[7]     0.344116861 0.01528489 0.9006204  -1.4912825  -0.2527849
    eta[8]     0.054117112 0.01476876 0.9340583  -1.7048651  -0.5703094
    theta[1]  11.179939131 0.14049641 7.9699140  -2.5322883   6.0314217
    theta[2]   8.139112021 0.10033489 6.3457354  -4.0253160   4.1476907
    theta[3]   6.157855087 0.11955944 7.5616029 -10.4333424   2.0474438
    theta[4]   7.706870487 0.10183980 6.4409143  -5.4322317   3.8157935
    theta[5]   5.169066290 0.10015811 6.3345549  -8.7036114   1.5443474
    theta[6]   6.109612619 0.10500089 6.6408396  -8.5017959   2.3172212
    theta[7]  10.811708319 0.10782097 6.8191970  -0.9882565   6.0876259
    theta[8]   8.424636902 0.12081343 7.6409122  -7.2523268   4.0548291
    lp__     -39.503782098 0.07847223 2.6924066 -45.5837397 -41.1328365
                       50%         75%      97.5%    n_eff      Rhat
    mu         7.994847396  11.2254151  17.658561 2024.741 1.0019591
    tau        5.356981530   9.0604728  20.124940 1522.778 1.0033007
    eta[1]     0.359401600   0.9678725   2.151131 4000.000 1.0007800
    eta[2]    -0.005405507   0.5806379   1.754201 4000.000 1.0013342
    eta[3]    -0.194855108   0.3980163   1.574262 4000.000 1.0002214
    eta[4]    -0.050960318   0.5300522   1.681861 4000.000 1.0004579
    eta[5]    -0.373137019   0.2164363   1.431801 4000.000 0.9999436
    eta[6]    -0.242018489   0.3228345   1.507530 4000.000 1.0007736
    eta[7]     0.377271785   0.9532751   2.046999 3471.835 1.0013864
    eta[8]     0.033099352   0.6799525   1.875869 4000.000 0.9992675
    theta[1]  10.046211535  15.3792620  29.470367 3217.932 1.0012703
    theta[2]   7.999553815  12.0080307  21.110053 4000.000 0.9996522
    theta[3]   6.698712608  10.8766773  20.326054 4000.000 0.9999629
    theta[4]   7.775685400  11.6781117  20.492719 4000.000 0.9998420
    theta[5]   5.542552626   9.4562901  16.385787 4000.000 0.9998813
    theta[6]   6.499023855  10.2922662  18.184320 4000.000 0.9996696
    theta[7]  10.172402385  14.7617284  26.181687 4000.000 1.0000294
    theta[8]   8.302620439  12.6568257  24.369944 4000.000 1.0001679
    lp__     -39.297076824 -37.5638248 -35.020254 1177.198 1.0035031

If, for example, we wanted the only quantiles included to be 10% and 90%, and for only the parameters included to be `mu` and `tau`, we would specify that like this:

    mu_tau_summary <- summary(fit, pars = c("mu", "tau"), probs = c(0.1, 0.9))$summary
    print(mu_tau_summary)

            mean   se_mean       sd      10%      90%    n_eff     Rhat
    mu  8.048679 0.1085502 4.884448 1.987987 14.03885 2024.741 1.001959
    tau 6.557082 0.1408245 5.495362 1.030037 13.46754 1522.778 1.003301

Since `mu_tau_summary` is a matrix we can pull out columns using their names:

    mu_tau_80pct <- mu_tau_summary[, c("10%", "90%")]
    print(mu_tau_80pct)

             10%      90%
    mu  1.987987 14.03885
    tau 1.030037 13.46754

## Sampler diagnostics

For models fit using MCMC the stanfit object will also contain the values of parameters used for the sampler. The `get_sampler_params` function can be used to access this information.

The object returned by `get_sampler_params` is a list with one component (a matrix) per chain. Each of the matrices has number of columns corresponding to the number of sampler parameters and the column names provide the parameter names. The optional argument inc_warmup (defaulting to `TRUE`) indicates whether to include the warmup period.

    sampler_params <- get_sampler_params(fit, inc_warmup = FALSE)
    sampler_params_chain1 <- sampler_params[[1]]
    colnames(sampler_params_chain1)

    [1] "accept_stat__" "stepsize__"    "treedepth__"   "n_leapfrog__"
    [5] "divergent__"   "energy__"

To do things like calculate the average value of `accept_stat__` for each chain (or the maximum value of `treedepth__` for each chain if using the NUTS algorithm, etc.) the `sapply` function is useful as it will apply the same function to each component of `sampler_params`:

    mean_accept_stat_by_chain <- sapply(sampler_params, function(x) mean(x[, "accept_stat__"]))
    print(mean_accept_stat_by_chain)

    [1] 0.9503392 0.6811747 0.8134112 0.9048823

    max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
    print(max_treedepth_by_chain)

    [1] 4 5 5 5

## Model code

The Stan program itself is also stored in the stanfit object and can be accessed using `get_stancode`:

    code <- get_stancode(fit)

The object `code` is a single string and is not very intelligible when printed:

    print(code)

    [1] "data {\n  int<lower=0> J;          // number of schools \n  real y[J];               // estimated treatment effects\n  real<lower=0> sigma[J];  // s.e. of effect estimates \n}\nparameters {\n  real mu; \n  real<lower=0> tau;\n  vector[J] eta;\n}\ntransformed parameters {\n  vector[J] theta;\n  theta = mu + tau * eta;\n}\nmodel {\n  target += normal_lpdf(eta | 0, 1);\n  target += normal_lpdf(y | theta, sigma);\n}"
    attr(,"model_name2")
    [1] "schools"

A readable version can be printed using `cat`:

    cat(code)

    data {
      int<lower=0> J;          // number of schools
      real y[J];               // estimated treatment effects
      real<lower=0> sigma[J];  // s.e. of effect estimates
    }
    parameters {
      real mu;
      real<lower=0> tau;
      vector[J] eta;
    }
    transformed parameters {
      vector[J] theta;
      theta = mu + tau * eta;
    }
    model {
      target += normal_lpdf(eta | 0, 1);
      target += normal_lpdf(y | theta, sigma);
    }

## Initial values

The `get_inits` function returns initial values as a list with one component per chain. Each component is itself a (named) list containing the initial values for each parameter for the corresponding chain:

    inits <- get_inits(fit)
    inits_chain1 <- inits[[1]]
    print(inits_chain1)

    $mu
    [1] -1.461743

    $tau
    [1] 0.1964472

    $eta
    [1] -0.8751053 -1.7047613 -0.9337199  1.3190496  0.4229845 -0.7018442
    [7]  0.2604412  1.1808317

    $theta
    [1] -1.633655 -1.796638 -1.645169 -1.202619 -1.378649 -1.599618 -1.410580
    [8] -1.229772

## (P)RNG seed

The `get_seed` function returns the (P)RNG seed as an integer:

    print(get_seed(fit))

    [1] 308838208

## Warmup and sampling times

The `get_elapsed_time` function returns a matrix with the warmup and sampling times for each chain:

    print(get_elapsed_time(fit))

              warmup   sample
    chain:1 0.059357 0.061835
    chain:2 0.051969 0.034312
    chain:3 0.059145 0.053630
    chain:4 0.058807 0.057540