Author: Stan Development Team
Date: 2023-10-14

# Accessing the contents of a stanfit object

#### Stan Development Team

#### 2023-10-14

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] 13.3212042 14.8153607  6.5865173 16.0001848 10.6981082  0.7047223

    head(list_of_draws$tau)

    [1] 3.7350142 5.8608581 0.3487159 3.2358066 7.0687195 0.3506794

    head(list_of_draws$theta)

    iterations        [,1]         [,2]      [,3]       [,4]       [,5]      [,6]
          [1,]  8.85915640 17.274443596  9.719025 11.8454303 18.5036367 12.786830
          [2,]  4.42647454  6.222250808 15.407103  7.6874140  4.9630447  2.097809
          [3,]  6.45387288  6.376145007  6.610307  6.5675790  6.2417981  6.159547
          [4,] 19.67709933 12.940005771 18.043622 14.6041229 17.1902471 17.904162
          [5,]  1.67558670  4.630624727  3.890733  7.9450595 16.2425341  2.791847
          [6,]  0.01142897  0.001214198  1.234152  0.7985139  0.7600677  1.236998

    iterations       [,7]       [,8]
          [1,] 14.4416680  9.9219174
          [2,] 15.5869203 11.2871285
          [3,]  6.4175444  6.6798302
          [4,] 18.3065606 13.8728077
          [5,] 13.7616607 23.8159412
          [6,]  0.8628509  0.8517842

#### 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,]  3.342844  7.371265
          [2,]  2.692468  9.833861
          [3,]  1.247567 10.043951
          [4,]  9.426720  9.804634
          [5,] 11.046511 26.330013
          [6,] 13.425271 12.910125

## 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         7.698817169 0.16147780 5.1827995  -3.134666   4.5511659
    tau        6.485647812 0.18449557 5.4481749   0.258044   2.4976837
    eta[1]     0.361154031 0.01554519 0.9189432  -1.554034  -0.2453936
    eta[2]     0.003415669 0.01517788 0.8802417  -1.710428  -0.5732260
    eta[3]    -0.197730071 0.01599059 0.9433573  -2.002115  -0.8385973
    eta[4]    -0.034838256 0.01568604 0.8985815  -1.810332  -0.6290423
    eta[5]    -0.366826627 0.01615021 0.8738727  -2.005131  -0.9359947
    eta[6]    -0.227467878 0.01685473 0.8854476  -1.963065  -0.8209408
    eta[7]     0.338580948 0.01427317 0.8911706  -1.483719  -0.2422416
    eta[8]     0.050911151 0.01553126 0.9573438  -1.857891  -0.5795116
    theta[1]  10.950091414 0.15711227 8.1375906  -2.447700   5.7529748
    theta[2]   7.850553371 0.10085798 6.3796969  -4.687959   3.8401807
    theta[3]   5.892077782 0.17678905 7.7843989 -11.093990   1.6484095
    theta[4]   7.465017514 0.10557186 6.7298178  -6.359472   3.5652211
    theta[5]   4.976472811 0.10951295 6.4035072  -8.630574   1.0737667
    theta[6]   6.038874844 0.10399162 6.7442772  -9.455661   2.2417276
    theta[7]  10.470061217 0.12203383 6.7273826  -1.661039   6.0771787
    theta[8]   8.247470937 0.13967029 8.0694618  -7.514123   3.7369073
    lp__     -39.617893683 0.07600704 2.6429650 -45.842842 -41.2090454
                       50%         75%      97.5%     n_eff      Rhat
    mu         7.857491309  11.0280530  17.547551 1030.1564 1.0013811
    tau        5.180916979   8.9962900  20.274920  872.0275 1.0009789
    eta[1]     0.382392087   1.0029044   2.101476 3494.5004 0.9996257
    eta[2]     0.006395265   0.5931581   1.682653 3363.4227 1.0002048
    eta[3]    -0.201374307   0.4388211   1.630318 3480.3560 1.0007617
    eta[4]    -0.034712736   0.5733512   1.682458 3281.6191 1.0008941
    eta[5]    -0.398852307   0.1799011   1.461182 2927.7886 1.0010824
    eta[6]    -0.224152120   0.3405167   1.539924 2759.8279 1.0001101
    eta[7]     0.347008515   0.9476267   2.020013 3898.3509 0.9995406
    eta[8]     0.041715186   0.6926332   1.899227 3799.4677 1.0001401
    theta[1]   9.891088018  15.0502761  29.824384 2682.6961 1.0003242
    theta[2]   7.847118399  11.6930852  21.251618 4001.1018 0.9995204
    theta[3]   6.501065386  10.7251488  20.098080 1938.8286 1.0015354
    theta[4]   7.478735786  11.5943354  20.934503 4063.5935 1.0002556
    theta[5]   5.490246117   9.2467162  16.684115 3419.0452 1.0000111
    theta[6]   6.525678750  10.1860097  18.748818 4206.0470 0.9998108
    theta[7]   9.929853082  14.2088180  25.761954 3039.0073 0.9994757
    theta[8]   8.161486689  12.4254396  25.789576 3337.9596 0.9994041
    lp__     -39.310060531 -37.7191522 -35.262139 1209.1362 1.0017940

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.698817 0.1614778 5.182800 1.244899 13.99973 1030.1564 1.001381
    tau 6.485648 0.1844956 5.448175 1.050183 13.38310  872.0275 1.000979

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.244899 13.99973
    tau 1.050183 13.38310

## 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.8708411 0.8719242 0.8294883 0.8801992

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

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

    $tau
    [1] 0.514061

    $eta
    [1] -0.5349054  0.2124741  1.4081679  0.3378652  0.3349618  0.3154013 -1.9600864
    [8] -1.9206797

    $theta
    [1] -0.1262915  0.2579072  0.8725667  0.3223658  0.3208733  0.3108180 -0.8589215
    [8] -0.8386640

## (P)RNG seed

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

    print(get_seed(fit))

    [1] 1652741155

## 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.041  0.033
    chain:2  0.034  0.032
    chain:3  0.034  0.030
    chain:4  0.035  0.032