*! version 2.1.0 09mar2026

Title

stanrun -- Run Bayesian models via CmdStan with HMC/NUTS and Variational Inference

Syntax

stanrun
varlist
[if] [in]
[, options]

Required
modelfile(filename) Stan model file (must end in .stan)

File Specifications
datafile(filename) data file name; default stanrun_data.R

outputfile(basename) output CSV base name; default output

chainfile(filename) combined chains file; default stanrun_chains.csv

initsfile(filename) initial values file

cmdstandir(path) path to CmdStan installation

Model Specification
inline read Stan model from comment block in do-file

thisfile(path) path to do-file with inline model

rerun skip compilation, use existing executable

MCMC Sampling
chains(#) number of chains; default 4

warmup(#) warmup iterations; default 1000

iter(#) sampling iterations; default 1000

thin(#) thinning interval; default 1

seed(#) random seed

HMC Tuning
stepsize(#) HMC step size

stepsizejitter(#) step size jitter; default 0

adaptdelta(#) target acceptance rate (0-1)

maxtreedepth(#) maximum NUTS tree depth

Variational Inference
variational use ADVI instead of MCMC

vialgorithm(string) meanfield (default) or fullrank

viiter(#) max VI iterations; default 10000

vioutput_samples(#) posterior draws from VI; default 1000

vieta(#) step size for VI; default auto

vitol_rel_obj(#) convergence tolerance; default 0.01

Operations
load import posterior draws into Stata

diagnose run basic convergence diagnostics

mode find posterior mode via optimization

Data Handling
skipmissing variable-wise missing deletion

matrices(list|all) pass Stata matrices to Stan

globals(list|all) pass global macros to Stan

Display
verbose detailed execution output

log synonym for verbose

nopywarn suppress Python integration note

keepfiles preserve intermediate files

Description

stanrun is a modern interface to CmdStan for running Bayesian models in Stata.
It supports both full MCMC via Hamiltonian Monte Carlo (HMC) with the No-U-Turn
Sampler (NUTS), and fast approximate inference via Automatic Differentiation
Variational Inference (ADVI).

Key features include:

- Synchronous shell execution (reliable on StataNow 19.5)

- Automatic RTools detection (4.2-4.5) for compilation

- Skip recompilation when executable exists

- CmdStan CSV import with automatic variable renaming

- Variational Inference (ADVI) for fast approximate posteriors

- Quiet mode by default; verbose CmdStan output with verbose

- Divergent transition and tree depth diagnostics

Requires CmdStan 2.26+ and RTools (Windows). Tested with CmdStan 2.38 and
StataNow 19.5 MP on Windows.

Options

File Specifications

modelfile(filename) specifies the Stan model file. Must end in .stan.
The executable is derived from this name (e.g. mymodel.stan -> mymodel.exe).

cmdstandir(path) specifies the path to CmdStan. If omitted, the global
macro $CMDSTAN is used. Example: cmdstandir("C:\Users\me\.cmdstan\cmdstan-2.38.0").

outputfile(basename) base name for chain CSV files. With 4 chains, creates
basename1.csv through basename4.csv. Default is output.

MCMC Sampling

chains(#) number of MCMC chains. Default is 4. Chains run sequentially.

warmup(#) warmup (burn-in) iterations per chain. Default is 1000.

iter(#) post-warmup sampling iterations per chain. Default is 1000.

thin(#) thinning interval. Default is 1 (keep all samples).

seed(#) random number seed for reproducibility.

HMC Tuning

adaptdelta(#) target acceptance rate (0-1). Default is 0.8. Increase
to 0.95 or 0.99 if you see divergent transitions.

maxtreedepth(#) maximum NUTS tree depth. Default is 10. Increase if
sampling hits the tree depth limit.

Variational Inference

variational uses Automatic Differentiation Variational Inference (ADVI)
instead of HMC/NUTS. This is much faster but provides approximate posteriors.
ADVI fits a Gaussian approximation to the posterior; the quality of this
approximation depends on the model.

vialgorithm(string) specifies meanfield (default; diagonal covariance)
or fullrank (dense covariance). Fullrank captures correlations but is slower
and may not converge for high-dimensional models.

viiter(#) maximum iterations for VI optimization. Default is 10000.

vioutput_samples(#) number of posterior draws from the fitted approximation.
Default is 1000.

vitol_rel_obj(#) convergence tolerance for the ELBO. Default is 0.01.

Operations

load imports posterior draws into Stata memory after sampling. The CmdStan
CSV files are stripped of comment lines, combined across chains, and variable
names are automatically mapped (e.g. Sigma.1.1 -> sigma11).

diagnose reports divergent transitions and tree depth warnings after loading.

Display

verbose (or log) shows full CmdStan output including iteration progress,
adaptation details, and timing. Without this option, CmdStan output is redirected
to a log file and only progress dots are shown.

Examples

Setup

. global CMDSTAN "C:\Users\me\.cmdstan\cmdstan-2.38.0"

Basic usage with 4 chains and automatic loading

. stanrun y x1 x2, modelfile(mymodel.stan) load

Detailed output with seed

. stanrun y x, modelfile(model.stan) chains(4) iter(2000) seed(123) load diagnose verbose

High-precision sampling for difficult posteriors

. stanrun y x, modelfile(hier.stan) adaptdelta(0.99) maxtreedepth(15) load

Fast approximate inference via ADVI

. stanrun y x, modelfile(model.stan) variational load

ADVI with full-rank approximation

. stanrun y x, modelfile(model.stan) variational vialgorithm(fullrank) load

Pass matrices and globals to Stan

. matrix priors = (0, 10)

. global K = 5

. stanrun y x, modelfile(model.stan) matrices(priors) globals(K) load

Rerun without recompilation

. stanrun y x, modelfile(model.stan) rerun load

Companion programs

stanrun_extract -- Compute posterior summaries (mean, SD, quantiles,
R-hat, ESS) from a stanrun draws file. Optional trace and density plots.

. stanrun_extract, drawfile(stanrun_chains.csv)

. stanrun_extract, drawfile(stanrun_chains.csv) parameters(mu sigma) trace(mu sigma)

stanrun_diagnostics -- Flag parameters with R-hat > 1.01 or ESS
below a threshold (default 100).

. stanrun_diagnostics, drawfile(stanrun_chains.csv)

. stanrun_diagnostics, drawfile(stanrun_chains.csv) essmin(400)

Stored results

When load is specified, posterior samples are loaded into Stata memory with:

Variable

parameter names Posterior draws for each model parameter

lp__ Log-posterior density (unnormalized)

accept_stat__ HMC acceptance statistic

stepsize__ Step size used

treedepth__ Tree depth reached

divergent__ Divergent transition indicator (0/1)

energy__ Hamiltonian energy

chain Chain identifier

Files created in the working directory:

File

chainfile Combined posterior draws (.csv or .dta)

datafile Data in R/S dump format

modelfile Stan model (.stan)

execfile Compiled model (.exe)

References

Carpenter, B., et al. 2017. Stan: A probabilistic programming language.
Journal of Statistical Software 76(1). doi:10.18637/jss.v076.i01

Hoffman, M. D. and A. Gelman. 2014. The No-U-Turn Sampler: Adaptively setting
path lengths in Hamiltonian Monte Carlo.
Journal of Machine Learning Research 15: 1593-1623.

Kucukelbir, A., et al. 2017. Automatic Differentiation Variational Inference.
Journal of Machine Learning Research 18(14): 1-45.

Stan Development Team. 2025. CmdStan User's Guide.
https://mc-stan.org/users/documentation/

Author

Ben A. Dwamena, MD

Clinical Associate Professor Emeritus of Radiology

Division of Nuclear Medicine and Molecular Imaging

University of Michigan

info@creedghana.org

Original StataStan by Robert Grant and Mustafa Ascha.

Also see

Online: mc-stan.org,
CmdStan documentation

If installed: stanrun_extract, stanrun_diagnostics, bayesmh