# Accessing the contents of a stanfit object

#### Stan Development Team

#### 2024-01-10

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 1 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]  5.383476  4.259927  3.773597  5.466592  6.588603 13.404230

    head(list_of_draws$tau)

    [1]  3.4376655  3.8935749 21.2406208  1.0448334  0.0428121  0.1155494

    head(list_of_draws$theta)

    iterations      [,1]      [,2]      [,3]      [,4]       [,5]       [,6]
          [1,]  4.073177  4.784386  5.980737  5.431588  6.7625026 -1.7959618
          [2,] -5.478766 -2.610753  5.670680  2.879631  5.1155202 -0.1764268
          [3,] 30.829292  7.974888  7.947629  4.284104 -0.3401116 16.7858948
          [4,]  5.696482  7.297221  4.605994  6.486964  6.1890079  5.1381530
          [5,]  6.504383  6.618376  6.610435  6.579370  6.5386955  6.6227491
          [6,] 13.421515 13.463637 13.422910 13.271886 13.4840941 13.4339324

    iterations      [,7]      [,8]
          [1,]  3.064505  1.695676
          [2,]  7.233268 -0.929307
          [3,] 12.418555 12.867065
          [4,]  5.527287  8.000315
          [5,]  6.686698  6.625466
          [6,] 13.321305 13.466787

#### 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,] 12.294436 10.2946760
          [2,]  8.083146  7.2673147
          [3,]  7.050771 24.2162877
          [4,]  9.663047 11.2475908
          [5,]  7.068416  5.9276186
          [6,] -2.398115  0.9736401

## 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         8.12522362 0.10543295 4.9418227  -1.6916254   4.8892048   8.07321948
    tau        6.58614056 0.13328284 5.3510302   0.3028005   2.5433639   5.33964019
    eta[1]     0.39724794 0.01513050 0.9543864  -1.5419715  -0.2031095   0.41086420
    eta[2]    -0.01075482 0.01530338 0.8483966  -1.7073219  -0.5758459  -0.02502340
    eta[3]    -0.22081500 0.01677053 0.9275588  -2.0440687  -0.8354153  -0.22846245
    eta[4]    -0.03561663 0.01484608 0.8959867  -1.8110925  -0.6209377  -0.02911226
    eta[5]    -0.38864870 0.01489854 0.8891847  -2.1672920  -0.9612040  -0.40092400
    eta[6]    -0.19644806 0.01520503 0.8923989  -1.9271772  -0.7897538  -0.21008728
    eta[7]     0.36064597 0.01511057 0.8727346  -1.4024953  -0.1905596   0.36105649
    eta[8]     0.05628648 0.01545371 0.9486657  -1.7995728  -0.5671822   0.05449893
    theta[1]  11.78534121 0.16684539 8.5954849  -1.5310472   6.1435927  10.40794080
    theta[2]   7.96961129 0.09413415 6.2626214  -4.8075733   4.2037808   7.96903459
    theta[3]   6.09287412 0.13829410 7.7266011 -11.8098608   2.0036229   6.61427388
    theta[4]   7.62404665 0.10095742 6.6220885  -5.8614275   3.5185197   7.66786315
    theta[5]   5.08963645 0.10133845 6.4625099  -9.0375331   1.2950346   5.67086449
    theta[6]   6.30804934 0.10871398 6.8057938  -8.6100492   2.2471665   6.63691149
    theta[7]  10.80131200 0.11700021 6.7325358  -1.0770481   6.2887084  10.25576210
    theta[8]   8.62092983 0.14475281 8.1621693  -6.8275700   3.9479337   8.26511019
    lp__     -39.54481281 0.07849596 2.6604631 -45.6436033 -41.1301979 -39.29168235
                     75%      97.5%    n_eff      Rhat
    mu        11.4339051  17.962924 2196.957 1.0006081
    tau        9.2721739  20.020787 1611.856 1.0005018
    eta[1]     1.0157440   2.234923 3978.708 0.9999563
    eta[2]     0.5353172   1.721535 3073.427 0.9993953
    eta[3]     0.3833220   1.663098 3059.068 1.0000438
    eta[4]     0.5619414   1.736866 3642.333 0.9996340
    eta[5]     0.1840037   1.415889 3562.020 1.0017262
    eta[6]     0.3957598   1.635603 3444.635 0.9999902
    eta[7]     0.9309946   2.103064 3335.819 1.0008580
    eta[8]     0.6739109   1.931676 3768.433 0.9993490
    theta[1]  16.0149389  33.139961 2654.070 1.0005255
    theta[2]  11.8857421  20.546013 4426.066 0.9995913
    theta[3]  10.7650010  20.444246 3121.546 1.0005744
    theta[4]  11.8440778  20.968700 4302.426 0.9997326
    theta[5]   9.5195398  16.565089 4066.811 0.9996950
    theta[6]  10.7773185  18.676699 3919.104 1.0002833
    theta[7]  14.7056071  25.422768 3311.190 1.0004802
    theta[8]  12.8273735  26.781811 3179.488 0.9994721
    lp__     -37.6681294 -35.074027 1148.735 1.0016283

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.125224 0.1054329 4.941823 1.927823 14.34993 2196.957 1.000608
    tau 6.586141 0.1332828 5.351030 1.018044 13.78748 1611.856 1.000502

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.927823 14.34993
    tau 1.018044 13.78748

## 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.8946750 0.8043410 0.8784134 0.7977858

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

    [1] 5 4 4 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.9807931

    $tau
    [1] 3.772335

    $eta
    [1] -1.5529622 -0.8238692 -1.2685297 -1.0187685 -0.3050989  1.7212214  1.6778877
    [8]  0.2406339

    $theta
    [1] -4.8775012 -2.1271178 -3.8045261 -2.8623432 -0.1701422  7.4738173  7.3103483
    [8]  1.8885450

## (P)RNG seed

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

    print(get_seed(fit))

    [1] 1349966339

## 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.085  0.064
    chain:2  0.043  0.037
    chain:3  0.041  0.034
    chain:4  0.065  0.057