# Accessing the contents of a stanfit object

#### Stan Development Team

#### 2023-01-16

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 2 divergent transitions after warmup. See
    https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
    to find out why this is a problem and how to eliminate them.

    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] 17.274226  5.090239 -6.408210 14.456119 18.402022 11.812651

    head(list_of_draws$tau)

    [1]  0.5937676  1.4858371 13.2502252  9.7262200  1.2033232  3.1740290

    head(list_of_draws$theta)

    iterations      [,1]      [,2]       [,3]       [,4]      [,5]      [,6]
          [1,] 16.402656 18.031121  16.751690  16.893137 17.021494 17.239407
          [2,]  3.122463  5.140563   4.381396   4.245066  7.256745  4.892094
          [3,] 28.485055  1.147092 -12.479531 -10.327054 -4.270984  6.303271
          [4,] 14.804967  8.923697  19.253787  12.753586  3.982765 13.986249
          [5,] 19.705760 17.377461  17.299791  17.543248 17.314794 17.611039
          [6,] 13.309395  4.111409  16.211279   8.637398  9.443989 10.207214

    iterations      [,7]      [,8]
          [1,] 16.999547 16.502022
          [2,]  6.104974  4.411244
          [3,]  9.406242 27.091147
          [4,] 19.661096 13.293024
          [5,] 18.852170 19.197917
          [6,] 15.300133 11.618251

#### 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.402644  8.105842
          [2,] 10.493817 11.960729
          [3,]  5.252259 10.747517
          [4,]  2.308751  8.084447
          [5,] -2.175566  2.968503
          [6,] -2.864512 20.764761

## 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%          50%
    mu         7.83459151 0.12184038 5.0931984  -2.3239945   4.5347705   7.87004590
    tau        6.59952312 0.14283826 5.3242025   0.2841719   2.6143224   5.33454541
    eta[1]     0.39595383 0.01588689 0.9685000  -1.5247662  -0.2618551   0.41528204
    eta[2]    -0.01267148 0.01379185 0.8648998  -1.7391931  -0.5680380  -0.01239772
    eta[3]    -0.21497643 0.01586675 0.9316284  -2.0207644  -0.8440214  -0.22953526
    eta[4]    -0.02753598 0.01479701 0.9066592  -1.7791639  -0.6378606  -0.04074761
    eta[5]    -0.37200835 0.01521760 0.8738341  -2.0109614  -0.9584787  -0.39676042
    eta[6]    -0.22877807 0.01424952 0.8595866  -1.8970919  -0.7999620  -0.23296597
    eta[7]     0.34681529 0.01425898 0.8697059  -1.4579614  -0.2086765   0.37460442
    eta[8]     0.06577136 0.01615268 0.9516225  -1.8261023  -0.5864090   0.06072396
    theta[1]  11.43077135 0.14377277 8.0185880  -1.6596600   6.0506089  10.32350735
    theta[2]   7.75765707 0.09212887 6.1248053  -4.3834775   3.9141609   7.73611359
    theta[3]   5.98168952 0.15307838 7.9347869 -12.0209813   1.7457806   6.54313583
    theta[4]   7.51466823 0.10279368 6.6191425  -6.1640866   3.5640514   7.53967236
    theta[5]   4.90888344 0.11326238 6.4404350  -9.6364502   1.0778706   5.43893080
    theta[6]   6.06023293 0.10474364 6.6648832  -7.9043576   2.3069328   6.33245093
    theta[7]  10.66363023 0.11364868 6.7519446  -1.2046854   6.0349129  10.06643947
    theta[8]   8.44955019 0.14520159 7.8110911  -6.5212394   3.7070023   8.13255470
    lp__     -39.50817049 0.07054898 2.6524971 -45.6128673 -41.0644842 -39.28792057
                     75%      97.5%    n_eff      Rhat
    mu        11.2100986  17.771010 1747.426 1.0001446
    tau        9.2681292  20.375401 1389.377 1.0025371
    eta[1]     1.0406206   2.304537 3716.392 0.9993584
    eta[2]     0.5484362   1.718100 3932.660 1.0000844
    eta[3]     0.3730559   1.659586 3447.540 0.9993751
    eta[4]     0.5767603   1.752631 3754.394 0.9996501
    eta[5]     0.1874962   1.396765 3297.354 1.0003817
    eta[6]     0.3077821   1.509771 3638.971 0.9995296
    eta[7]     0.9154990   2.041881 3720.212 0.9995329
    eta[8]     0.7129673   1.903744 3470.886 0.9997915
    theta[1]  15.5642888  30.157718 3110.588 1.0005067
    theta[2]  11.5827100  20.267519 4419.703 0.9998289
    theta[3]  10.7698383  20.586743 2686.846 0.9997248
    theta[4]  11.5787287  21.036961 4146.395 0.9999516
    theta[5]   9.2735488  16.284819 3233.397 1.0004119
    theta[6]  10.3227851  18.606200 4048.832 0.9994783
    theta[7]  14.8105030  25.926736 3529.628 1.0016584
    theta[8]  12.8008190  25.460922 2893.881 1.0000217
    lp__     -37.6026454 -35.111530 1413.606 1.0040354

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  7.834592 0.1218404 5.093198 1.538679 14.36096 1747.426 1.000145
    tau 6.599523 0.1428383 5.324203 1.077891 13.54497 1389.377 1.002537

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.538679 14.36096
    tau 1.077891 13.54497

## 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.8010475 0.8109660 0.8804079 0.8654666

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

    [1] 4 4 5 4

## 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] 0.02909534

    $tau
    [1] 3.714874

    $eta
    [1]  0.04084279 -0.16905186  1.25040438  1.26885665  0.83871661 -1.09271081
    [7] -1.16658563 -1.35583167

    $theta
    [1]  0.1808211 -0.5989110  4.6741897  4.7427376  3.1448216 -4.0301873 -4.3046229
    [8] -5.0076481

## (P)RNG seed

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

    print(get_seed(fit))

    [1] 98195687

## 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.035726 0.030838
    chain:2 0.031989 0.028497
    chain:3 0.035644 0.035243
    chain:4 0.035589 0.030456