MCMC Sampling with Stan
Overview
This skill provides guidance for implementing Bayesian models and running MCMC sampling using Stan (via RStan or PyStan). It covers model specification, prior implementation, sampling configuration, and critical diagnostic checks that must be performed to validate results.
Workflow
Phase 1: Environment Setup
Before writing any Stan code:
Verify Stan installation and version
- Check that the required version of RStan/PyStan is installed
- RStan requires a C++ toolchain; verify compilation works before proceeding
- For RStan: Check with
packageVersion("rstan") and test compilation with a simple model
Check system dependencies first
- Stan requires compilation; missing system libraries cause cryptic errors
- On Linux: Ensure
g++, make, and development libraries are installed
- On macOS: Xcode command line tools required
- Verify the toolchain before attempting package installation
Common installation pitfalls
- R's
install.packages() does not accept a version parameter for CRAN packages
- To install a specific version, use
remotes::install_version() or install from source
- RStan compilation can fail silently; always test with a minimal model first
Phase 2: Data Exploration
Before implementing the model:
Analyze the data structure
- Examine dimensions: number of observations, groups, variables
- Check for missing values, zeros, or extreme values
- Understand the range and distribution of variables
Identify potential issues
- Zero counts in binomial/Poisson models (valid but worth noting)
- Extreme values that might cause numerical issues
- Small sample sizes that may not support complex models
Document data characteristics
- Record any data-specific considerations that affect model specification
- Note whether the data provides enough information for the chosen priors
Phase 3: Model Implementation
When writing the Stan model:
Prior specification
- Translate mathematical priors correctly to Stan syntax
- Use
target += for log-probability contributions (e.g., target += -2.5 * log(alpha + beta) for p(α,β) ∝ (α+β)^(-5/2))
- Document the reasoning behind prior choices
Parameter constraints
- Use appropriate bounds:
real<lower=0>, real<lower=0, upper=1>, etc.
- Consider whether improper priors will yield proper posteriors given the data
- Add small lower bounds if numerical stability is a concern (e.g.,
real<lower=0.001>)
Model block structure
- Follow Stan's block order: data, transformed data, parameters, transformed parameters, model, generated quantities
- Keep transformations in appropriate blocks for efficiency
Numerical stability considerations
- Improper priors (e.g., (α+β)^(-5/2)) may not integrate to finite values
- The data must provide sufficient information for posterior propriety
- Consider adding soft constraints if parameters can drift to extreme values
Phase 4: Sampling Configuration
Configure MCMC sampling appropriately:
Iteration and warmup settings
- RStan default: half of
iter for warmup, half for sampling
- Explicitly set
warmup parameter for clarity
- Example:
iter = 100000 with default settings = 50,000 warmup + 50,000 samples per chain
Control parameters
adapt_delta: Increase (e.g., 0.95 or 0.99) if divergent transitions occur
max_treedepth: Increase (e.g., 15) if hitting tree depth limits
- Document why non-default values are chosen
Chain configuration
- Multiple chains (typically 4) enable convergence diagnostics
- Set seeds for reproducibility
- Consider computational resources vs. chain count tradeoffs
Phase 5: Diagnostic Checks (CRITICAL)
Never skip diagnostics. Successful sampling completion does not guarantee valid results.
Convergence diagnostics (MANDATORY)
- R-hat (Gelman-Rubin statistic): Must be < 1.01 for all parameters
- Effective Sample Size (ESS): Should be > 400 for reliable estimates; > 100 minimum
- Check both bulk-ESS and tail-ESS
Sampling diagnostics (MANDATORY)
- Divergent transitions: Must be 0; any divergences indicate model problems
- Tree depth: Check for max treedepth warnings
- Energy diagnostics: E-BFMI should be > 0.3
Visual diagnostics (recommended)
- Trace plots: Chains should mix well ("fuzzy caterpillar" appearance)
- Density plots: Posteriors should be smooth and reasonable
- Pairs plots: Check for problematic correlations
How to access diagnostics in RStan
# Summary with R-hat and ESS
print(fit, pars = c("alpha", "beta"))
# Check for divergences
sampler_params <- get_sampler_params(fit, inc_warmup = FALSE)
sum(sapply(sampler_params, function(x) sum(x[, "divergent__"])))
# Check tree depth
sum(sapply(sampler_params, function(x) sum(x[, "treedepth__"] >= 15)))
Interpreting diagnostic failures
- Divergences: Reparameterize model or increase
adapt_delta
- Low ESS: Run longer chains or reparameterize
- High R-hat: Chains haven't converged; run longer or check model specification
Phase 6: Results Extraction
After diagnostics pass:
Extract posterior summaries
- Posterior means, medians, and credible intervals
- Standard deviations and quantiles
Validate against expectations
- Compare to known results for standard models (e.g., Bayesian Data Analysis examples)
- Check that posteriors are in reasonable ranges
- Verify that constraints are respected
Output file handling
- Use appropriate functions for clean file output
- In R:
writeLines() or cat() with explicit formatting
- Avoid artifacts like trailing newlines or formatting characters
Common Pitfalls
Installation Issues
- Attempting to specify version in
install.packages() (use remotes::install_version() instead)
- Missing C++ toolchain or system libraries
- Not testing compilation before running full models
Model Specification Errors
- Incorrect translation of mathematical priors to Stan code
- Missing or incorrect parameter bounds
- Not considering posterior propriety with improper priors
Sampling Problems
- Not explicitly setting warmup period
- Using default control parameters when model requires tuning
- Running insufficient iterations for convergence
Diagnostic Omissions
- Assuming successful sampling means valid results
- Not checking R-hat, ESS, or divergent transitions
- Ignoring warnings about tree depth or energy diagnostics
Output Errors
- Bash command parsing issues with redirection operators in R scripts
- Not verifying output file format and content
- Missing error handling for file operations
Verification Checklist
Before considering the task complete, verify:
References
For detailed information on Stan diagnostics and model reparameterization, consult:
references/stan_diagnostics.md - Detailed diagnostic interpretation guide
1---2name: mcmc-sampling-stan3description: Guide for performing Markov Chain Monte Carlo (MCMC) sampling using RStan or PyStan. This skill should be used when implementing Bayesian statistical models, fitting hierarchical models, working with Stan modeling language, or running MCMC diagnostics. Applies to tasks involving posterior sampling, Bayesian inference, and probabilistic programming with Stan.4---56# MCMC Sampling with Stan78## Overview910This skill provides guidance for implementing Bayesian models and running MCMC sampling using Stan (via RStan or PyStan). It covers model specification, prior implementation, sampling configuration, and critical diagnostic checks that must be performed to validate results.1112## Workflow1314### Phase 1: Environment Setup1516Before writing any Stan code:17181. **Verify Stan installation and version**19 - Check that the required version of RStan/PyStan is installed20 - RStan requires a C++ toolchain; verify compilation works before proceeding21 - For RStan: Check with `packageVersion("rstan")` and test compilation with a simple model22232. **Check system dependencies first**24 - Stan requires compilation; missing system libraries cause cryptic errors25 - On Linux: Ensure `g++`, `make`, and development libraries are installed26 - On macOS: Xcode command line tools required27 - Verify the toolchain before attempting package installation28293. **Common installation pitfalls**30 - R's `install.packages()` does not accept a `version` parameter for CRAN packages31 - To install a specific version, use `remotes::install_version()` or install from source32 - RStan compilation can fail silently; always test with a minimal model first3334### Phase 2: Data Exploration3536Before implementing the model:37381. **Analyze the data structure**39 - Examine dimensions: number of observations, groups, variables40 - Check for missing values, zeros, or extreme values41 - Understand the range and distribution of variables42432. **Identify potential issues**44 - Zero counts in binomial/Poisson models (valid but worth noting)45 - Extreme values that might cause numerical issues46 - Small sample sizes that may not support complex models47483. **Document data characteristics**49 - Record any data-specific considerations that affect model specification50 - Note whether the data provides enough information for the chosen priors5152### Phase 3: Model Implementation5354When writing the Stan model:55561. **Prior specification**57 - Translate mathematical priors correctly to Stan syntax58 - Use `target +=` for log-probability contributions (e.g., `target += -2.5 * log(alpha + beta)` for p(α,β) ∝ (α+β)^(-5/2))59 - Document the reasoning behind prior choices60612. **Parameter constraints**62 - Use appropriate bounds: `real<lower=0>`, `real<lower=0, upper=1>`, etc.63 - Consider whether improper priors will yield proper posteriors given the data64 - Add small lower bounds if numerical stability is a concern (e.g., `real<lower=0.001>`)65663. **Model block structure**67 - Follow Stan's block order: data, transformed data, parameters, transformed parameters, model, generated quantities68 - Keep transformations in appropriate blocks for efficiency69704. **Numerical stability considerations**71 - Improper priors (e.g., (α+β)^(-5/2)) may not integrate to finite values72 - The data must provide sufficient information for posterior propriety73 - Consider adding soft constraints if parameters can drift to extreme values7475### Phase 4: Sampling Configuration7677Configure MCMC sampling appropriately:78791. **Iteration and warmup settings**80 - RStan default: half of `iter` for warmup, half for sampling81 - Explicitly set `warmup` parameter for clarity82 - Example: `iter = 100000` with default settings = 50,000 warmup + 50,000 samples per chain83842. **Control parameters**85 - `adapt_delta`: Increase (e.g., 0.95 or 0.99) if divergent transitions occur86 - `max_treedepth`: Increase (e.g., 15) if hitting tree depth limits87 - Document why non-default values are chosen88893. **Chain configuration**90 - Multiple chains (typically 4) enable convergence diagnostics91 - Set seeds for reproducibility92 - Consider computational resources vs. chain count tradeoffs9394### Phase 5: Diagnostic Checks (CRITICAL)9596**Never skip diagnostics.** Successful sampling completion does not guarantee valid results.97981. **Convergence diagnostics (MANDATORY)**99 - **R-hat (Gelman-Rubin statistic)**: Must be < 1.01 for all parameters100 - **Effective Sample Size (ESS)**: Should be > 400 for reliable estimates; > 100 minimum101 - Check both bulk-ESS and tail-ESS1021032. **Sampling diagnostics (MANDATORY)**104 - **Divergent transitions**: Must be 0; any divergences indicate model problems105 - **Tree depth**: Check for max treedepth warnings106 - **Energy diagnostics**: E-BFMI should be > 0.31071083. **Visual diagnostics (recommended)**109 - Trace plots: Chains should mix well ("fuzzy caterpillar" appearance)110 - Density plots: Posteriors should be smooth and reasonable111 - Pairs plots: Check for problematic correlations1121134. **How to access diagnostics in RStan**114 ```r115 # Summary with R-hat and ESS116 print(fit, pars = c("alpha", "beta"))117118 # Check for divergences119 sampler_params <- get_sampler_params(fit, inc_warmup = FALSE)120 sum(sapply(sampler_params, function(x) sum(x[, "divergent__"])))121122 # Check tree depth123 sum(sapply(sampler_params, function(x) sum(x[, "treedepth__"] >= 15)))124 ```1251265. **Interpreting diagnostic failures**127 - Divergences: Reparameterize model or increase `adapt_delta`128 - Low ESS: Run longer chains or reparameterize129 - High R-hat: Chains haven't converged; run longer or check model specification130131### Phase 6: Results Extraction132133After diagnostics pass:1341351. **Extract posterior summaries**136 - Posterior means, medians, and credible intervals137 - Standard deviations and quantiles1381392. **Validate against expectations**140 - Compare to known results for standard models (e.g., Bayesian Data Analysis examples)141 - Check that posteriors are in reasonable ranges142 - Verify that constraints are respected1431443. **Output file handling**145 - Use appropriate functions for clean file output146 - In R: `writeLines()` or `cat()` with explicit formatting147 - Avoid artifacts like trailing newlines or formatting characters148149## Common Pitfalls150151### Installation Issues152- Attempting to specify version in `install.packages()` (use `remotes::install_version()` instead)153- Missing C++ toolchain or system libraries154- Not testing compilation before running full models155156### Model Specification Errors157- Incorrect translation of mathematical priors to Stan code158- Missing or incorrect parameter bounds159- Not considering posterior propriety with improper priors160161### Sampling Problems162- Not explicitly setting warmup period163- Using default control parameters when model requires tuning164- Running insufficient iterations for convergence165166### Diagnostic Omissions167- Assuming successful sampling means valid results168- Not checking R-hat, ESS, or divergent transitions169- Ignoring warnings about tree depth or energy diagnostics170171### Output Errors172- Bash command parsing issues with redirection operators in R scripts173- Not verifying output file format and content174- Missing error handling for file operations175176## Verification Checklist177178Before considering the task complete, verify:179180- [ ] Stan/RStan/PyStan version matches requirements181- [ ] Model compiles without errors182- [ ] Priors are correctly implemented (verify mathematical translation)183- [ ] Parameter bounds are appropriate184- [ ] Sampling completes without errors185- [ ] R-hat < 1.01 for all parameters186- [ ] ESS > 400 (or reasonable for the application)187- [ ] Zero divergent transitions188- [ ] No max treedepth warnings (or addressed if present)189- [ ] Posterior summaries are reasonable190- [ ] Output files are correctly formatted191192## References193194For detailed information on Stan diagnostics and model reparameterization, consult:195- `references/stan_diagnostics.md` - Detailed diagnostic interpretation guide