# Supplementary Topics - [Other Blocks in a Stan Program](#3) - [User-Defined Functions](#4) - [Rhat](#5) - [Effective Sample Size](#6) - [Maximum a Posterior Estimation](#7) --- # Other Blocks in a Stan Program There are three additional blocks that can be included in your .stan file - `functions{...}`: User-defined functions - `transformed data{...}`: Fixed variable definition - E.g. Setting hyperparameter values - `transformed parameters{...}`: Parameters defined as transformations of other parameters and data - E.g. ODE trajectory computed from system parameters - `generated quantities{...}`: Any additional quantities that might be of interest - Does not affect sampling procedure; performed after sampling - E.g. posterior predictions, transformations of parameters, diagnostic quantities --- # User-defined Functions **Syntax:** ```r real decay(real N0, real rate, real t){ return N0 * exp(-rate * t); } ``` - Must specify data type of input and output <br> Stan supports function overloading as well: ```r real decay(real N0, real rate1, real rate2, real t){ return N0 * exp(-(rate1 + rate2) * t); } ``` - Function call must differ <br> These functions can then be used in subsequent blocks --- # Rhat as a Convergence Diagnostic Each of our MCMC chains should converge to the same distribution - The `\(\hat R\)` statistic assesses how similar the resulting chains are - Compares *within-chain variance* to *between-chain variance* through a ratio - Values less than 1.1 suggest convergence - After running `stan`, diagnostic message will be printed if `\(\hat R\)` is too high - Can be accessed through `rhat(fit)` --- # Effective Sample Size Due to the nature of the algorithm, samples drawn via MCMC are correlated - Ideally this correlation is low - Results in a loss of information, relative to a "perfect" independent sample from the posterior - The *effective sample size*, `\(N_{eff}\)`, is essentially a measure of how many "perfect" samples our MCMC draws are worth - Estimation of `\(N_{eff}\)` requires estimation of the autocorrelation function; larger autocorrelation results in smaller `\(N_{eff}\)` - RStan will print diagnostic message if `\(N_{eff}\)` falls too low --- # Maximum a Posteriori Estimation MAP estimation takes our point estimate of the unknown parameters to be the argmax of the posterior density - Obtained through the `optimizing(...)` function in the `rstan` package - Can access the LBFGS, BFGS, and Newton algorithms - Requires a `stanmodel` object (not a .stan file as with `stan`) - Can be created via the `stan_model(...)` function