Getting Started

This tutorial takes you from a fresh Julia installation to a fitted Bayesian model. By the end you will have written a hierarchical growth-curve model in BUGS notation, drawn posterior samples from it, and read off posterior summaries that you can check against published results.

Setup

If you do not have Julia yet, download it from julialang.org/downloads; any recent version will do. Then start Julia and install the packages this tutorial uses:

using Pkg
Pkg.add(["JuliaBUGS", "AbstractMCMC", "AdvancedHMC", "ADTypes", "Mooncake", "FlexiChains"])

JuliaBUGS compiles the model. The other packages do the sampling and bookkeeping: AdvancedHMC provides the NUTS sampler, AbstractMCMC runs it, ADTypes and Mooncake supply the gradients that NUTS needs, and FlexiChains stores the posterior draws. Load them all:

using JuliaBUGS
using AbstractMCMC, AdvancedHMC, ADTypes, Mooncake, FlexiChains

The model

We will fit Rats, the first example in the classic BUGS examples (Volume 1), taken from Gelfand et al. (1990). Thirty young rats were weighed weekly for five weeks, so we have weights $Y_{ij}$ for rat $i = 1, \dots, 30$ at ages $x_j = 8, 15, 22, 29, 36$ days. Each rat grows roughly along a straight line, but rats differ, so each gets its own intercept $\alpha_i$ and slope $\beta_i$, and those in turn are drawn from population-level distributions — a normal hierarchical model:

\[\begin{aligned} Y_{ij} &\sim \text{Normal}\!\left(\alpha_i + \beta_i (x_j - \bar{x}),\ \tau_c\right) \\ \alpha_i &\sim \text{Normal}(\alpha_c,\ \alpha_\tau) \\ \beta_i &\sim \text{Normal}(\beta_c,\ \beta_\tau) \end{aligned}\]

Here $\bar{x} = 22$ is the mean age (centering the ages reduces correlation between intercepts and slopes), and — following the BUGS convention — normal distributions are written in terms of a precision (1/variance), not a variance.

In JuliaBUGS you write this model with the @bugs macro:

rats = @bugs begin
    for i in 1:N
        for j in 1:T
            Y[i, j] ~ dnorm(mu[i, j], tau_c)
            mu[i, j] = alpha[i] + beta[i] * (x[j] - xbar)
        end
        alpha[i] ~ dnorm(alpha_c, alpha_tau)
        beta[i] ~ dnorm(beta_c, beta_tau)
    end
    tau_c ~ dgamma(0.001, 0.001)
    sigma = 1 / sqrt(tau_c)
    alpha_c ~ dnorm(0.0, 1.0e-6)
    alpha_tau ~ dgamma(0.001, 0.001)
    beta_c ~ dnorm(0.0, 1.0e-6)
    beta_tau ~ dgamma(0.001, 0.001)
    alpha0 = alpha_c - xbar * beta_c
end

If you have used WinBUGS, OpenBUGS, or JAGS, this should look familiar. Reading it line by line:

  • ~ means "is distributed as": Y[i, j] ~ dnorm(mu[i, j], tau_c) says the weight is normal with mean mu[i, j] and precision tau_c. Distributions keep their BUGS names (dnorm, dgamma, and so on).
  • = defines a deterministic quantity (BUGS uses <- for this): sigma = 1 / sqrt(tau_c) is the residual standard deviation, computed from the precision, and alpha0 is the population intercept extrapolated back to birth (age zero).
  • for loops express repetition over rats and over measurement times — the "plates" of the model. The loop bounds N and T will come from the data.

The vague dgamma(0.001, 0.001) and dnorm(0.0, 1.0e-6) priors are the standard noninformative choices from the original example. The result, rats, is a model definition: it is not tied to any data yet.

Data

The data is just a NamedTuple whose names match the variables the model expects — here the ages x, their mean xbar, the counts N and T, and the 30×5 matrix of weights Y:

data = (
    x = [8.0, 15.0, 22.0, 29.0, 36.0],
    xbar = 22,
    N = 30,
    T = 5,
    Y = [151 199 246 283 320
         145 199 249 293 354
         147 214 263 312 328
         155 200 237 272 297
         135 188 230 280 323
         159 210 252 298 331
         141 189 231 275 305
         159 201 248 297 338
         177 236 285 350 376
         134 182 220 260 296
         160 208 261 313 352
         143 188 220 273 314
         154 200 244 289 325
         171 221 270 326 358
         163 216 242 281 312
         160 207 248 288 324
         142 187 234 280 316
         156 203 243 283 317
         157 212 259 307 336
         152 203 246 286 321
         154 205 253 298 334
         139 190 225 267 302
         146 191 229 272 302
         157 211 250 285 323
         132 185 237 286 331
         160 207 257 303 345
         169 216 261 295 333
         157 205 248 289 316
         137 180 219 258 291
         153 200 244 286 324]
)

If your data lives in the R-style list() format used by the classic BUGS systems, it translates directly to a NamedTuple; see Coming from WinBUGS, OpenBUGS, and JAGS for the details.

Fit the model

Compiling the model is a single call: apply the definition to the data. Two of the three lines below are the essential steps — that call, and attaching the automatic-differentiation backend that NUTS needs. The line in between is an optional performance setting, explained in the note that follows:

model = rats(data)
model = JuliaBUGS.set_evaluation_mode(
    model, JuliaBUGS.UseGeneratedLogDensityFunction()
)
model = JuliaBUGS.BUGSModelWithGradient(model, AutoMooncake(; config=nothing))

rats(data) combines the model definition with the data and returns a compiled model, ready for inference. BUGSModelWithGradient then wraps that model with Mooncake automatic differentiation: NUTS works by following the gradient of the log posterior, so any gradient-based sampler needs this step.

What does `set_evaluation_mode` do?

Out of the box, JuliaBUGS computes a model's log density by walking the model's graph — that works for every model with no extra setup, and you can omit this line entirely. UseGeneratedLogDensityFunction() instead generates and compiles a dedicated Julia function for this model's log density. NUTS will evaluate the log density many thousands of times below, so for a model like Rats this makes sampling substantially faster. Its requirements — the default parameterization produced by compilation and a compatible AD backend such as Mooncake — are already met by the code above, and if JuliaBUGS cannot generate such a function for a model, it warns and keeps the default evaluator. See Evaluation Modes and Automatic Differentiation for the options and tradeoffs.

Now draw posterior samples with NUTS, the standard gradient-based MCMC sampler:

chain = AbstractMCMC.sample(
    model, NUTS(0.8), 3000;
    chain_type = VNChain,
    n_adapts = 1000,
    discard_initial = 1000,
)
[ Info: Found initial step size 0.00078125

This runs 3000 iterations; the first 1000 are used to tune the sampler and are discarded (n_adapts and discard_initial), leaving 2000 posterior draws. chain_type = VNChain collects the draws into a chain object keyed by variable name. Expect the run to take a few minutes.

Read the results

summarystats prints the familiar table of posterior means, standard deviations, and convergence diagnostics for every quantity in the model:

summarystats(chain)
╭─FlexiSummary (9 statistics) ─────────────────────────────────────────────────╮
│   iter    collapsed                                                          │
│   chain   collapsed                                                          │
│ ↓ stat  = [mean, std, mcse, ess_bulk, ess_tail, rhat, q5, q50, q95]          │
│                                                                              │
│ Parameters (67) ── VarName                                                   │
│  Float64  beta_tau, beta_c, alpha_tau, alpha_c, tau_c, beta[1], alpha[1],    │
│           beta[2], alpha[2], beta[3], alpha[3], beta[4], alpha[4], beta[5],  │
│           alpha[5], beta[6], alpha[6], beta[7], alpha[7], beta[8], alpha[8], │
│           beta[9], alpha[9], beta[10], alpha[10], beta[11], alpha[11],       │
│           beta[12], alpha[12], beta[13], alpha[13], beta[14], alpha[14],     │
│           beta[15], alpha[15], beta[16], alpha[16], beta[17], alpha[17],     │
│           beta[18], alpha[18], beta[19], alpha[19], beta[20], alpha[20],     │
│           beta[21], alpha[21], beta[22], alpha[22], beta[23], alpha[23],     │
│           beta[24], alpha[24], beta[25], alpha[25], beta[26], alpha[26],     │
│           beta[27], alpha[27], beta[28], alpha[28], beta[29], alpha[29],     │
│           beta[30], alpha[30], alpha0, sigma                                 │
│                                                                              │
│ Extras (13)                                                                  │
│  Float64  lp, n_steps, is_accept, acceptance_rate, log_density,              │
│           hamiltonian_energy, hamiltonian_energy_error,                      │
│           max_hamiltonian_energy_error, tree_depth, numerical_error,         │
│           step_size, nom_step_size, is_adapt                                 │
│                                                                              │
│ Summary                                                                      │
│       param      mean     std    mcse   ess_bulk   ess_tail    rhat  …       │
│    beta_tau    4.0684  1.4839  0.0382  1810.2118  1789.9816  0.9997  …       │
│      beta_c    6.1887  0.1065  0.0020  2971.5189  2341.0872  1.0007  …       │
│   alpha_tau    0.0050  0.0013  0.0000  3880.7477  2519.1729  1.0004  …       │
│     alpha_c  242.6791  2.6324  0.0466  3199.5761  2261.2037  0.9997  …       │
│       tau_c    0.0273  0.0040  0.0001  1751.2631  2255.6776  1.0001  …       │
│     beta[1]    6.0595  0.2421  0.0042  3385.0414  2021.7858  1.0005  …       │
│    alpha[1]  239.9110  2.7031  0.0389  4788.9679  2078.9660  1.0012  …       │
│     beta[2]    7.0558  0.2548  0.0046  3103.6723  2331.2257  0.9998  …       │
│    alpha[2]  247.7993  2.6849  0.0376  5139.8541  1918.9127  1.0012  …       │
│     beta[3]    6.4799  0.2571  0.0042  3824.6660  2260.5260  1.0001  …       │
│    alpha[3]  252.4721  2.7237  0.0454  3606.0013  1936.1296  0.9999  …       │
│     beta[4]    5.3469  0.2629  0.0043  3807.3101  2046.8612  1.0008  …       │
│    alpha[4]  232.5900  2.5489  0.0398  4078.8855  2219.6078  1.0007  …       │
│     beta[5]    6.5776  0.2520  0.0045  3168.7632  2113.2708  1.0036  …       │
│    alpha[5]  231.6108  2.7069  0.0456  3517.6600  2082.2048  0.9998  …       │
│     beta[6]    6.1689  0.2426  0.0044  3110.8541  2182.4328  0.9998  …       │
│    alpha[6]  249.6363  2.6940  0.0432  3909.9042  2365.4945  0.9997  …       │
│     beta[7]    5.9691  0.2485  0.0037  4662.1854  1840.5228  1.0007  …       │
│    alpha[7]  228.7205  2.6681  0.0401  4451.0770  2087.7211  1.0006  …       │
│     beta[8]    6.4202  0.2424  0.0043  3256.3058  2251.0289  0.9999  …       │
│    alpha[8]  248.4001  2.7545  0.0406  4592.2049  1929.9614  1.0011  …       │
│     beta[9]    7.0501  0.2608  0.0046  3262.2650  2197.8531  1.0018  …       │
│    alpha[9]  283.2571  2.7880  0.0448  3872.3127  2309.3797  1.0020  …       │
│    beta[10]    5.8446  0.2430  0.0037  4208.5482  2133.9734  1.0000  …       │
│   alpha[10]  219.3298  2.6626  0.0411  4195.5402  2254.0639  1.0002  …       │
│    beta[11]    6.8011  0.2517  0.0044  3235.8477  2139.4570  1.0003  …       │
│   alpha[11]  258.2283  2.6649  0.0401  4432.3213  2230.9796  1.0003  …       │
│    beta[12]    6.1264  0.2396  0.0036  4406.8446  2309.8072  1.0002  …       │
│   alpha[12]  228.1608  2.6403  0.0375  4915.7806  2332.8271  0.9999  …       │
│    beta[13]    6.1647  0.2372  0.0041  3372.1184  1985.4785  0.9998  …       │
│   alpha[13]  242.4026  2.6937  0.0440  3763.2261  1944.3483  1.0017  …       │
│    beta[14]    6.6984  0.2532  0.0040  3913.5664  2247.6174  1.0037  …       │
│   alpha[14]  268.2708  2.7060  0.0418  4189.6081  2358.7040  0.9998  …       │
│    beta[15]    5.4198  0.2551  0.0045  3208.2042  2120.8474  0.9998  …       │
│   alpha[15]  242.7472  2.7330  0.0367  5540.4667  2224.5579  1.0015  …       │
│    beta[16]    5.9185  0.2501  0.0039  4179.3308  2106.0309  0.9999  …       │
│   alpha[16]  245.3879  2.6920  0.0395  4642.5972  2333.9403  1.0003  …       │
│    beta[17]    6.2757  0.2397  0.0041  3339.7152  2369.7687  1.0010  …       │
│   alpha[17]  232.2104  2.6184  0.0414  4032.2588  2129.7956  1.0044  …       │
│    beta[18]    5.8516  0.2436  0.0041  3481.3185  2358.0950  1.0004  …       │
│   alpha[18]  240.4414  2.8164  0.0426  4375.1936  2090.1028  0.9997  …       │
│    beta[19]    6.4009  0.2434  0.0038  3989.1144  2310.9116  1.0001  …       │
│   alpha[19]  253.7874  2.6846  0.0406  4352.5914  2316.8764  0.9999  …       │
│    beta[20]    6.0549  0.2371  0.0043  3119.3924  2263.1038  1.0005  …       │
│   alpha[20]  241.6225  2.6100  0.0430  3703.1804  1967.8875  1.0014  …       │
│    beta[21]    6.4068  0.2405  0.0040  3647.9458  2220.0524  1.0004  …       │
│   alpha[21]  248.5157  2.6653  0.0416  4097.2653  1889.8868  0.9998  …       │
│    beta[22]    5.8552  0.2487  0.0039  4089.6293  2287.5985  0.9999  …       │
│   alpha[22]  225.2921  2.6750  0.0394  4643.6310  1923.7759  1.0007  …       │
│    beta[23]    5.7410  0.2497  0.0048  2672.4029  1898.2954  0.9998  …       │
│   alpha[23]  228.6189  2.6603  0.0453  3431.6172  1894.4682  1.0028  …       │
│    beta[24]    5.8942  0.2471  0.0036  4714.0048  2323.8118  0.9997  …       │
│   alpha[24]  245.0738  2.6538  0.0356  5574.9047  2433.6492  0.9997  …       │
│    beta[25]    6.9139  0.2531  0.0044  3250.3300  2383.4851  1.0004  …       │
│   alpha[25]  234.5090  2.7047  0.0481  3163.9174  1949.0999  0.9997  …       │
│    beta[26]    6.5542  0.2468  0.0035  4907.1835  2240.1595  1.0008  …       │
│   alpha[26]  253.9886  2.6879  0.0474  3207.7166  1815.7281  1.0020  …       │
│    beta[27]    5.9091  0.2384  0.0039  3707.0001  2327.0377  1.0025  …       │
│   alpha[27]  254.3232  2.6270  0.0468  3159.9917  2382.8569  1.0002  …       │
│    beta[28]    5.8433  0.2462  0.0037  4399.3630  2056.1084  1.0003  …       │
│   alpha[28]  242.9945  2.7848  0.0443  3926.2486  2128.1673  1.0002  …       │
│    beta[29]    5.6681  0.2512  0.0041  3730.2531  2007.9198  1.0009  …       │
│   alpha[29]  217.8866  2.6844  0.0350  5892.8952  2124.3662  1.0004  …       │
│    beta[30]    6.1306  0.2451  0.0038  4154.2778  1957.5784  1.0000  …       │
│   alpha[30]  241.4843  2.6080  0.0391  4422.8370  2287.5985  1.0004  …       │
│      alpha0  106.5280  3.4865  0.0640  2973.8451  2473.3347  1.0000  …       │
│       sigma    6.1003  0.4558  0.0111  1751.2631  2255.6776  1.0002  …       │
╰──────────────────────────────────────────────────────────────────────────────╯

The table has a row for each of the 30 intercepts alpha[i] and slopes beta[i], but the scientific questions concern the population-level rows:

  • beta_c, the average growth rate: about 6.2 grams per day (published value 6.186),
  • alpha0, the average weight extrapolated back to birth: about 106.6 grams (published value 106.6),
  • sigma, the residual standard deviation of the weight measurements: about 6.1 grams (published value 6.093).

Your numbers will not match the published values to every digit, and they will change slightly each time you run the sampler: posterior means estimated from 2000 draws carry a small Monte Carlo error (reported in the mcse column), so agreement to within that error is exactly what success looks like. As a quick health check, rhat should be very close to 1 for every row.

That is the whole workflow: write the model with @bugs, put the data in a NamedTuple, compile it, attach a gradient backend when the sampler needs one, sample to fit, and summarystats to read the results.

Where next

  • The Example Gallery walks through more classic BUGS models, ready to run.
  • The Seeds example treats a random-effects logistic regression in more depth, including supplying explicit initial values.
  • Initial Values explains named, partial, array-valued, and sampler-specific initialization.
  • Coming from WinBUGS, OpenBUGS, and JAGS maps your existing workflow — R list() data, initial values, CODA summaries — onto JuliaBUGS.
  • DoodleBUGS lets you build JuliaBUGS models by drawing the graph, in the spirit of DoodleBUGS from WinBUGS.