Tutorial 1: a first look at ProbPipe¶
This sequence of tutorials introduces ProbPipe by walking through an example statistical analysis. We consider modeling the size of a moose population, using data collected by an annual survey conducted between 1967 and 1988.
This first tutorial walks through a simple Bayesian analysis: defining a prior and likelihood, fitting the model, and generating predictions. The goal is to get a general sense of a ProbPipe workflow, rather than explain how any particular line of code works.
# @title Setup: install ProbPipe on Colab (run this first)
# On Google Colab, install ProbPipe and download the data; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
import os
import urllib.request
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet 'probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main'
os.makedirs('data', exist_ok=True)
urllib.request.urlretrieve(
'https://raw.githubusercontent.com/TARPS-group/prob-pipe/main/'
'docs/tutorials/data/moose.csv',
'data/moose.csv',
)
import warnings
import arviz as az
import jax
import jax.numpy as jnp
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from probpipe import (
Beta,
LogNormal,
Poisson,
conditional_distribution,
condition_on,
quantile,
workflow_run,
summarize,
)
# TensorFlow Probability warns that JAX runs in 32-bit precision, which these models use.
warnings.filterwarnings('ignore', message=r'Explicitly requested dtype float64')
# Cleaner printing for floats
np.set_printoptions(precision=3, suppress=True)
# set random seed for reproducibility
workflow_run.set_default(seed=532431)
1. The Dataset¶
The data come from the course materials of Michael Dietze's environmental statistics course. They are a time series of annual moose counts.
data = pd.read_csv('data/moose.csv')
years = data['year'].to_numpy()
observed_counts = jnp.asarray(data['count'], dtype=jnp.float32)
n_years = observed_counts.shape[0]
print('years:', years[0], 'to', years[-1])
print('number of counts:', n_years)
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(years, observed_counts, 'o-', color='black')
ax.set(xlabel='year', ylabel='moose counted')
plt.show()
years: 1967 to 1988 number of counts: 22
2. A Population Model¶
Let's model the counts with a classical population model: the Ricker model. This model describes a population $N_t$ that grows at rate $r$ when the population is small, and stops growing at the carrying capacity $K$:
$$ N_{t+1} = N_t \exp\left(r\left(1 - \frac{N_t}{K}\right)\right). $$
We fix the population of 1966, the year before the first count, at $N_0 = 50$ moose.
The below code implements a function that simulates this model over a given number of annual timesteps. This is just Python/JAX — no ProbPipe code yet. This is by design: users should feel like they're just writing normal Python code!
# population model
def ricker(r: jax.Array, K: jax.Array, n0: float, years: int) -> jax.Array:
"""The population in each of the *years* after the year of *n0*."""
def step(N: jax.Array, _: None) -> tuple[jax.Array, jax.Array]:
N_next = N * jnp.exp(r * (1.0 - N / K))
return N_next, N_next
_, N = jax.lax.scan(step, jnp.asarray(n0, dtype=jnp.float32), None, length=years)
return N
3. A Statistical Model¶
Next, we'll wrap a statistical observation model around the Ricker population model. Adopting a Bayesian approach, we'll also assign prior distributions to each parameter in the model.
Observation Model¶
The observed count $y_t$ in year $t$ will generally underestimate $N_t$. We thus introduce a parameter $\phi$
representing the probability that the surveyor finds each moose. In other words, the expected count in year $t$
is $\phi N_t$. This can be represented with a Poisson likelihood with rate parameter $\phi N_t$:
$$
p(y \mid K, r, \phi) = \prod_{t} \mathrm{Poisson}(y_t \mid \phi N_t),
$$
where $N_t$ is computed from the Ricker model above, and depends on $K$ and $r$.
Parameter Model¶
A Bayesian model also requires prior distributions on each parameter. In this example, we assume priors of the form $$ p_{\mathrm{prior}}(K, r, \phi) = \mathrm{LogNormal}(K) \cdot \mathrm{LogNormal}(r) \cdot \mathrm{Beta}(\phi), $$ with the particular parameters of these distributions specified in the code below.
The Full Model¶
The complete Bayesian model is assembled by multiplying the likelihood and the prior. This is a joint distribution over all of the variables:
$$ p(y, K, r, \phi) = p(y \mid K, r, \phi) \cdot p_{\mathrm{prior}}(K, r, \phi). $$
Implementing this in ProbPipe¶
This model can be implemented in a handful of lines of ProbPipe code, mimicking how the math
is written above. We use the merge operator & to combine probability distributions into
joint distributions.
# prior model
prior = LogNormal('K', jnp.log(350.0), 0.4) & LogNormal('r', jnp.log(0.4), 0.4) & Beta('phi', 2.0, 2.0)
# observation model
@conditional_distribution(given_spec=prior.event_spec)
def likelihood(K: jax.Array, r: jax.Array, phi: jax.Array, n0: float = 50.0) -> Poisson:
return Poisson('y', phi * ricker(r, K, n0, n_years))
# the full model
model = likelihood & prior
print(model)
likelihood(y | K, r, phi, n0=50.0)·LogNormal(K)·LogNormal(r)·Beta(phi)
4. Fitting the Model¶
A Bayesian model is fit by conditioning on observed data to obtain the posterior distribution: $$ p_{\mathrm{post}}(K, r, \phi) = p(K, r, \phi \mid y = y_{\mathrm{obs}}). $$
This is typically the hardest step in a Bayesian workflow, requiring the choice of a suitable
inference algorithm such as Markov chain Monte Carlo (MCMC). In ProbPipe, conditioning on
observed data is done with the condition_on operator, which conveniently chooses a default
inference algorithm for you if you don't specify one yourself. Future tutorials will go into
detail on this matter; for now, we'll just show the basic commands.
# observed data
observed = {'y': observed_counts}
# assign a shorter label, for brevity
model = model.with_label('model')
# condition on observation
posterior = condition_on(model, observed).with_label('posterior')
print(posterior)
posterior(K, r, phi; y)
The condition_on command returns a distribution, in this case representing the posterior $p(K, r, \phi \mid y = y_{\mathrm{obs}})$.
The below commands provide quick numeric and visual summaries of the posterior.
# summary of the posterior distribution
summary = summarize(posterior)
print(summary)
# visual summary of the posterior distribution
az.plot_pair(posterior.annotations['arviz'])
plt.show()
mean sd median q10 q90 r_hat ess_bulk ess_tail K 412.571 31.019 410.147 374.029 452.715 1.004 927.318 1315.21 r 0.222 0.016 0.221 0.202 0.241 1.003 1050.228 1352.989 phi 0.673 0.057 0.673 0.601 0.748 1.004 876.222 1181.785
5. Predicting with the Fit Model¶
To close out this first glance at ProbPipe, let's generate some probabilistic predictions with our fit model. This is done by feeding posterior samples through the observation model to generate predictions of the moose counts. A bit more precisely, the quantity we're after here is the posterior predictive distribution $$ p_{\mathrm{pred}}(y_{\mathrm{pred}}) = p(y_{\mathrm{pred}} \mid K, r, \phi) \cdot p_{\mathrm{post}}(K, r, \phi). $$
This is quite easy to do in ProbPipe, again using the merge operator.
predictive = likelihood.rename(y='y_pred') & posterior
print(predictive)
likelihood(y_pred | K, r, phi, n0=…)·posterior(K, r, phi; y)
The result predictive is simply another distribution, so we could once again summarize it with
the summarize operation used above. However, this is a distribution over $y_{\mathrm{pred}}$,
which has 22 entries. A more succinct way to visualize this distribution is by plotting the
quantiles of each entry of $y_{\mathrm{pred}}$. This is easy to do with the quantile operator.
levels = jnp.array([0.05, 0.5, 0.95])
# quantiles of predictive distribution
low, med, high = quantile(predictive['y_pred'], levels)
# print the median of each entry
med
NumericArray('ℚ[y_pred ~ likelihood·posterior][quantile=1]', shape=(22,), dtype=float32)
[ 40. 49. 59. 70. 82. 96. 113. 127. 144. 160. 175. 189. 203. 216.
226. 236. 243. 249. 254. 259. 263. 265.]
# plot the predictive quantiles
fig, ax = plt.subplots(figsize=(7, 3))
ax.fill_between(years, low.raw, high.raw, color='tab:blue', alpha=0.3, label='90% prediction band')
ax.plot(years, med.raw, color='tab:blue', label='median prediction')
ax.plot(years, observed_counts, 'o', color='black', label='observed counts')
ax.set(xlabel='year', ylabel='count', title='Posterior predictions of moose counts')
ax.legend()
plt.show()
6. Reviewing the Modeling Steps¶
As modeling workflows grow in complexity, you may find yourself asking: what were the sequence of steps that led to this result? By default, ProbPipe automatically records this information in the provenance attribute of any ProbPipe object.
Let's see how the provenance of posterior is reported. There are a few things to notice:
- The numbers refer to the objects produced from previous steps. For example,
model = condition_on(2, given)tells us thatmodelwas produced by conditioning the object from step 2 on a given value. - Re-labeling an object gets treated as a recorded operation, in addition to the more significant operations.
- The righthand column gives additional information about how an operation was computed. Don't worry about the specifics for now, but note that this is telling us that a particular MCMC algorithm was deployed to approximate the posterior.
print(posterior.provenance)
1. likelihood & (LogNormal & LogNormal & Beta) 2. model = with_label(1) 3. model = condition_on(2, given) route inference_methods, method blackjax_nuts, approximate 4. with_label(3)
We can also print the provenance of other objects, such as the predictive distribution or the median of the predictive distribution.
print(predictive.provenance)
1. likelihood = rename(likelihood) 2. likelihood & (LogNormal & LogNormal & Beta) 3. model = with_label(2) 4. model = condition_on(3, given) route inference_methods, method blackjax_nuts, approximate 5. posterior = with_label(4) 6. 1 & 5
print(med.provenance)
1. likelihood = rename(likelihood) 2. likelihood & (LogNormal & LogNormal & Beta) 3. model = with_label(2) 4. model = condition_on(3, given) route inference_methods, method blackjax_nuts, approximate 5. posterior = with_label(4) 6. 1 & 5 7. quantile(6['y_pred'], q, given) route monte_carlo, approximate
Summary¶
This tutorial provided a first glance at building probabilistic workflows in ProbPipe. In particular, we saw how:
- the merge operator
&makes it easy to build up a probabilistic model using notation that echoes the mathematical notation. - the
condition_onoperation provides a consistent, algorithm-agnostic interace for doing Bayesian inference. - operations like
summarizeandquantilemake it easy to query information about a distribution. - provenance tracking shows you the sequence of steps used to construct a ProbPipe object.
Tutorial 2 continues introducing ProbPipe using the same moose count example.
References¶
- Ricker, W. E. (1954). Stock and recruitment. Journal of the Fisheries Research Board of Canada, 11(5), 559–623.
- Dietze, M. C. (2017). Ecological Forecasting. Princeton University Press. The moose counts are from the course materials of Boston University's EE509 Applied Environmental Statistics course.
Human-validated by Andrew Roberts on 2026-10-27.