Further reading: not part of the course. This material is not included in the course, but it is relevant if you want to learn more about the topic.

Introduction to R-STAN

Further reading — Introduction to R-STAN

Quantitative biology and integrative omics

About this lecture

In the Bayesian inference units you learned the idea: combine a prior with a likelihood to get a posterior. Today we learn the tool that computes that posterior for real models — Stan, driven from R.

  • What Stan is, and why we need a computer once a model is bigger than a toy.
  • The anatomy of a Stan model: the data, parameters, and model blocks.
  • How to declare a prior and a likelihood in that language.
  • How to run the model from R with rstan, and the shortcut package brms.
  • The idea of MCMC: the fit is a big pile of draws from the posterior, not one number.
  • How to read the output: posterior means, credible intervals, Rhat, and effective sample size.

Problem: With only 20 cells, we want all plausible fractions

You stain a tissue and score cells for a marker gene. Out of 20 cells, 13 express it. What fraction \theta of cells in this tissue express the marker?

  • The naive point estimate is 13/20 = 0.65. But with only 20 cells, how sure are we?
  • A frequentist gives a confidence interval. A Bayesian wants the whole posterior distribution of \theta — a probability curve over every value \theta could take.
  • We also have prior knowledge: this marker is usually expressed in roughly half the cells, rarely near 0 or 1.

The question is not “what is \theta?” but “what does the data plus prior tell us about the plausible values of \theta?” That is a posterior, and Stan will compute it.

Recap: prior, likelihood, posterior

Bayes’ theorem, in the form we actually use:

\underbrace{p(\theta \mid y)}_{\text{posterior}} \;\propto\; \underbrace{p(y \mid \theta)}_{\text{likelihood}} \times \underbrace{p(\theta)}_{\text{prior}}

For the marker example:

  • Parameter: \theta, the fraction expressing (a number between 0 and 1).
  • Likelihood: the count y=13 out of N=20 is Binomial: y \sim \text{Binomial}(N, \theta).
  • Prior: “usually about half” — a Beta distribution, e.g. \theta \sim \text{Beta}(2,2), a gentle hump centred on 0.5.

The posterior is the prior reshaped by the data. Stan’s job is to produce that posterior for us.

Most posteriors have no formula, so we sample them

For this one example the posterior happens to have a clean formula (Beta prior + Binomial likelihood is conjugate). But that is a lucky special case.

p(\theta \mid y) = \frac{p(y \mid \theta)\,p(\theta)}{\displaystyle\int p(y \mid \theta)\,p(\theta)\,d\theta}

  • The denominator is an integral over all parameter values. For one parameter it is doable; for a realistic model with dozens or hundreds of parameters it is a hopeless high-dimensional integral.
  • Almost no real model is conjugate, so there is no formula for the posterior.
  • The escape: don’t compute the curve — draw samples from it. That is what MCMC does, and what Stan is built for.

Stan samples the posterior of a model you describe

Stan is a probabilistic programming language: you describe a model, and Stan figures out how to sample from its posterior.

  • You write the model in Stan’s own small language (a .stan file or a string).
  • Stan compiles it to fast C++ and runs an MCMC sampler (a modern one called HMC / NUTS).
  • You drive it entirely from R. Two common front-ends:
    • rstan — you write the Stan model yourself. Maximum control; you see every block.
    • brms — you write a familiar R formula (y ~ x) and it generates the Stan model for you.

Today we write one model by hand with rstan to see the moving parts, then show the brms shortcut.

A Stan model is built from named blocks

A Stan model is organised into named blocks. The three essential ones:

Block What it declares Analogy
data the known inputs (counts, sample sizes, predictors) what you pass in from R
parameters the unknowns you want to learn what the posterior is over
model the priors and the likelihood how data and parameters connect

Order matters: data, then parameters, then model. Every variable must be declared with a type before use (Stan is strict, like C++).

The data block

Declare everything you will pass in from R, with its type and any constraints.

data {
  int<lower=0> N;   // number of cells assayed
  int<lower=0> y;   // number of them expressing the marker
}
  • int = integer; real = continuous. Vectors and matrices have their own types.
  • <lower=0> is a constraint: a count cannot be negative. Constraints are checked — they catch bad input early.
  • The names here (N, y) are exactly the names R must supply.

The parameters block

Declare the unknowns — the quantities the posterior is a distribution over.

parameters {
  real<lower=0, upper=1> theta;   // fraction of cells expressing
}
  • theta is our unknown fraction. It is real (continuous).
  • <lower=0, upper=1> constrains it to a valid probability. Stan samples only inside this range.
  • This one line is why the whole model exists: the posterior we want is p(\theta \mid y).

The model block: prior + likelihood

Two statements: the prior on the parameter, and the likelihood of the data.

model {
  theta ~ beta(2, 2);          // prior: gentle hump around 0.5
  y ~ binomial(N, theta);      // likelihood: 13 of 20 expressed
}
  • ~ reads “is distributed as”. theta ~ beta(2,2) is the prior p(\theta).
  • y ~ binomial(N, theta) is the likelihood p(y \mid \theta) — it links the known counts to the unknown \theta.
  • Stan multiplies these together (adds their logs) to get the posterior — you never write the normalising integral.

The full model, assembled

// gene_marker.stan
data {
  int<lower=0> N;                 // cells assayed
  int<lower=0> y;                 // cells expressing the marker
}
parameters {
  real<lower=0, upper=1> theta;   // fraction expressing
}
model {
  theta ~ beta(2, 2);             // prior
  y ~ binomial(N, theta);         // likelihood
}

That is a complete, runnable Bayesian model. Save it as gene_marker.stan. Three blocks, seven lines of logic — this is the whole thing.

Running it from R with rstan

Pass the data as a named list whose names match the data block, then call stan().

library(rstan)

stan_data <- list(N = 20, y = 13)     # names match the data block

fit <- stan(
  file   = "gene_marker.stan",
  data   = stan_data,
  chains = 4,          # run 4 independent samplers
  iter   = 2000,       # 2000 iterations each (half are warmup)
  seed   = 1           # reproducibility
)
  • The list keys N and y are the same identifiers declared in the model’s data block.
  • stan() compiles the model (once) and runs the sampler. fit holds all the posterior draws.

What comes back: draws from the posterior

MCMC does not return the value of \theta. It returns thousands of samples of \theta, drawn in proportion to the posterior.

  • After warmup, 4 chains \times 1000 kept iterations = 4000 draws of \theta.
  • A histogram of those draws is the posterior distribution.
  • Any summary you want is just a summary of the draws:
    • posterior mean \approx mean(draws)
    • 95% credible interval \approx the 2.5% and 97.5% quantiles of the draws.

\theta_1, \theta_2, \theta_3, \dots, \theta_{4000} \quad\longrightarrow\quad \text{histogram} = \text{posterior}

Chains that agree are a check on the result

Why four chains instead of one long run?

  • Each chain starts from a different random point and wanders the posterior.
  • The first half (warmup) is discarded — the sampler is still finding the high-probability region and tuning itself.
  • If all four chains, from different starts, end up exploring the same distribution, we trust the result. If they disagree, something is wrong.

Running several chains is a built-in sanity check, not just extra samples.

Try it: inside the sampler

Reading the output: print(fit)

print(fit, pars = "theta")
        mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
theta   0.63    0.00 0.10  0.42  0.56  0.63  0.70  0.82  1580    1
  • mean 0.63 — the posterior mean of \theta (pulled slightly from 13/20=0.65 toward the prior’s 0.5).
  • 2.5% … 97.5% = [0.42,\ 0.82] — a 95% credible interval: there is a 95% posterior probability that \theta lies in this range.
  • n_eff and Rhat are diagnostics — the next slide.

Did it work? Rhat and n_eff

Two numbers tell you whether to trust the draws:

  • Rhat (\hat R): compares variation between chains to variation within chains.
    • \hat R \approx 1.00 means the chains agree → converged. Want \hat R < 1.01.
    • \hat R = 1.1 or more → chains disagree → do not trust the result. Run longer or fix the model.
  • n_eff (effective sample size): MCMC draws are correlated, so 4000 draws are worth fewer independent ones. n_eff is that effective count.
    • Bigger is better; a few hundred is usually plenty. Very low n_eff → estimates are noisy.

Always check these before reading the means. A pretty posterior from an unconverged sampler is meaningless.

brms writes the Stan model for you

For standard models you rarely hand-write Stan. brms takes an lm-style formula and generates the Stan model for you.

Say each of many cells has a marker outcome (expressed = 0/1) and a treatment:

library(brms)

fit <- brm(
  expressed ~ treatment,          # familiar formula interface
  data   = cells,
  family = bernoulli(),           # 0/1 outcome -> logistic regression
  prior  = prior(normal(0, 1), class = "b"),   # prior on coefficients
  chains = 4, iter = 2000, seed = 1
)

summary(fit)                      # same Rhat / credible-interval output

Same engine, same diagnostics — you just didn’t write the blocks. Understanding the rstan version is what lets you read and trust what brms builds.

Common pitfalls

  • Data names must match. The list passed from R must use the exact identifiers in the data block (N, y), or Stan errors.
  • Types and constraints are strict. A count is int; a probability is real<lower=0, upper=1>. Mismatches fail to compile.
  • Ignoring Rhat / n_eff. Never quote a posterior before checking convergence.
  • Too few iterations. If Rhat is high or n_eff low, increase iter (and warmup).
  • The prior is a choice. State it and, ideally, check whether the posterior is sensitive to it. A flat prior is still a prior.

Summary

Idea Takeaway
Goal compute the posterior p(\theta\mid y) for real models
Stan a language + engine that samples the posterior
data block the knowns you pass in from R (typed, constrained)
parameters block the unknowns the posterior is over
model block ~ statements: prior and likelihood
Run it stan(file, data = list(...), chains, iter)
Output thousands of draws; summarise them
Posterior mean mean of the draws
Credible interval 2.5% / 97.5% quantiles of the draws
Rhat \approx 1 = chains agree = trust it (<1.01)
n_eff effective (independent) sample size — bigger is better
brms writes the Stan model from an lm-style formula

The mantra: describe the model, sample the posterior, check Rhat, then read the draws.