Regime-Switching SSMs with RSSSM (K = 2)¶
The HMM-DDM tutorial, rebuilt with HSSM's regime-switching class
This tutorial reproduces the HMM with DDM emissions tutorial with hssm.RSSSM. That tutorial builds a regime-switching DDM by hand in PyMC: the forward algorithm, the label-switching constraint, the two emission backends and the regime recovery. Here RSSSM provides each of them: the forward algorithm is built in, and the rest are arguments or methods.
Everything else stays the same, so the two notebooks can be read side by side: the simulated data, the priors, the sampler settings and the figures. Parts 1–8 match the parts with the same numbers in the original. Parts 9–11 go beyond it: using the recovered regimes, LOO model comparison and regime-specific lapse rates.
Model overview.
- Latent regimes: $s_t \mid s_{t-1} \sim \text{Categorical}(P_{s_{t-1}, \cdot})$, where $P$ is a $K \times K$ transition matrix.
- Emissions: $(rt_t, \text{response}_t) \mid s_t = k \sim \text{DDM}(v_k, a, z, t)$. The drift rate $v$ switches across regimes, while $a$, $z$ and $t$ are shared.
- Inference: the discrete regime sequence is marginalized out with the forward algorithm (in log space), which leaves only continuous parameters for NUTS. The regimes are recovered afterwards.
Run this tutorial¶
On Colab, uncomment and run the installation cell below once, then restart the runtime. For local setup, GPU extras, and troubleshooting see the Installation guide.
# %pip install hssm
Part 1: Setup¶
Unlike the original, this notebook imports neither PyMC nor PyTensor: RSSSM builds the PyMC model itself.
# --- Core scientific Python ---
import arviz as az # Bayesian inference diagnostics and plotting
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# --- HSSM ---
import hssm
Part 2: Simulate Regime-Switching DDM Data¶
We generate synthetic data from a 2-regime HMM-DDM where the drift rate $v$ switches between regimes while all other parameters are shared. This gives us ground-truth labels to evaluate regime recovery later. The simulator, the true parameters and the seed are copied unchanged from the original, so this is the same dataset.
def simulate_hmm_ddm_data(
n_trials,
regime_params,
P,
pi0,
seed=42,
):
"""Simulate data from a regime-switching DDM.
Parameters
----------
n_trials : int
Number of trials.
regime_params : dict[int, dict]
DDM parameters per regime, e.g. {0: {"v": 0.5, ...}, 1: {"v": -0.5, ...}}.
P : np.ndarray
(K, K) transition matrix.
pi0 : np.ndarray
(K,) initial regime distribution.
seed : int
Random seed.
Returns
-------
data : np.ndarray
(n_trials, 2) array of [rt, response].
regimes : np.ndarray
(n_trials,) ground-truth regime labels.
"""
rng = np.random.default_rng(seed)
K = len(regime_params)
# Step 1: Generate the latent regime sequence from the Markov chain.
# The first regime is drawn from the initial distribution pi0,
# and each subsequent regime is drawn from row P[s_{t-1}] of the transition matrix.
regimes = np.empty(n_trials, dtype=int)
regimes[0] = rng.choice(K, p=pi0)
for t in range(1, n_trials):
regimes[t] = rng.choice(K, p=P[regimes[t - 1]])
# Step 2: Simulate DDM data for each regime using HSSM's built-in simulator.
# We batch-simulate all trials belonging to the same regime at once for efficiency.
rts, responses = [], []
for k in range(K):
mask = regimes == k
n_k = int(mask.sum())
if n_k == 0:
continue
sims = hssm.simulate_data(
model="ddm",
theta=regime_params[k], # DDM parameters for regime k
size=n_k,
random_state=seed + k,
output_df=False, # Return raw numpy array instead of DataFrame
)
rts.append(sims[:, 0])
responses.append(sims[:, 1])
# Step 3: Place simulated RTs and responses back into trial order.
data = np.empty((n_trials, 2))
for k in range(K):
mask = regimes == k
data[mask, 0] = rts[k]
data[mask, 1] = responses[k]
return data, regimes
# --- Ground-truth parameters for our simulation ---
N_TRIALS = 500 # Total number of trials
K = 2 # Number of hidden regimes
# DDM parameters per regime.
# Both regimes share the same boundary (a), starting point (z), and
# non-decision time (t).
# Only drift rate (v) differs: regime 0 has high drift (attentive),
# regime 1 has low drift (distracted).
TRUE_PARAMS = {
0: {"v": 1.5, "a": 0.8, "z": 0.5, "t": 0.3}, # attentive: fast, accurate
1: {"v": 0.2, "a": 0.8, "z": 0.5, "t": 0.3}, # distracted: slow, noisy
}
# Transition matrix: high diagonal = regimes are "sticky" (participants tend to stay
# in the same state). P[i, j] = probability of transitioning from regime i to regime j.
TRUE_P = np.array(
[
[0.95, 0.05], # From attentive: 95% stay, 5% switch to distracted
[0.10, 0.90], # From distracted: 10% switch to attentive, 90% stay
]
)
# Initial regime distribution: 80% chance of starting in the attentive regime
TRUE_PI0 = np.array([0.8, 0.2])
# Generate the synthetic dataset
data, true_regimes = simulate_hmm_ddm_data(
N_TRIALS,
TRUE_PARAMS,
TRUE_P,
TRUE_PI0,
seed=42,
)
print(f"Data shape: {data.shape}")
print(f"Regime counts: {np.bincount(true_regimes)}")
mean_rts = [f"{data[true_regimes == k, 0].mean():.3f}" for k in range(K)]
print(f"Mean RT by regime: {mean_rts}")
Data shape: (500, 2) Regime counts: [328 172] Mean RT by regime: ['0.811', '0.939']
fig, axes = plt.subplots(2, 1, gridspec_kw={"height_ratios": [1, 2]})
# --- Top panel: color-coded regime sequence ---
# Each contiguous block of trials in the same regime gets a colored background band.
ax = axes[0]
regime_colors = {0: "#4CAF50", 1: "#F44336"} # green = attentive, red = distracted
t_axis = np.arange(N_TRIALS)
start = 0
for t in range(1, N_TRIALS):
if true_regimes[t] != true_regimes[t - 1] or t == N_TRIALS - 1:
end = t if t < N_TRIALS - 1 else N_TRIALS
ax.axvspan(start, end, alpha=0.4, color=regime_colors[true_regimes[start]])
start = t
ax.set_xlim(0, N_TRIALS - 1)
ax.set_ylabel("Regime")
ax.set_yticks([])
ax.set_title("Ground-Truth Regime Sequence")
# --- Bottom panel: signed RT scatter plot ---
# "Signed RT" = RT * response, so upper-boundary responses are positive and
# lower-boundary responses are negative. This makes it easy to see both RT
# magnitude and choice direction in one plot.
ax = axes[1]
for k, label in enumerate(["Attentive (v=1.5)", "Distracted (v=0.2)"]):
mask = true_regimes == k
ax.scatter(
t_axis[mask],
data[mask, 0] * data[mask, 1],
s=8,
alpha=0.6,
color=regime_colors[k],
label=label,
)
ax.set_xlabel("Trial")
ax.set_ylabel("Signed RT (positive = upper)")
ax.legend(loc="upper right", fontsize=9)
ax.set_xlim(0, N_TRIALS - 1)
ax.set_title("Reaction Times Colored by Regime")
fig.tight_layout()
plt.show()
RSSSM takes a data frame with one row per trial, in trial order, and rt and response columns. With a single participant no participant column is needed: RSSSM treats all rows as one session.
df = pd.DataFrame(data, columns=["rt", "response"])
df.head()
| rt | response | |
|---|---|---|
| 0 | 0.880135 | 1.0 |
| 1 | 0.419972 | 1.0 |
| 2 | 0.673736 | 1.0 |
| 3 | 1.494165 | 1.0 |
| 4 | 0.583225 | 1.0 |
Part 3: Analytical HMM-DDM Model¶
The original builds this model in a 110-line function. With RSSSM it is one constructor call, and each part of the hand-built model maps to an argument:
| Hand-built model (original) | RSSSM argument |
|---|---|
Sticky Dirichlet prior on each row of $P$ (sticky_diag=20, sticky_offdiag=2) |
transition_prior={"sticky_diag": 20.0, "sticky_offdiag": 2.0} |
Uniform initial regime distribution (log_pi0) |
initial_distribution="uniform" |
| One drift rate per regime; shared $a$, $z$, $t$ | switching_params=["v"] |
Priors pm.Normal("v", mu=0.0, sigma=3.0, ...), pm.HalfNormal("a", sigma=2.0), ... |
v={"name": "Normal", "mu": 0.0, "sigma": 3.0}, a={"name": "HalfNormal", "sigma": 2.0}, ... |
pm.Potential("v_order", ...) enforcing $v_0 > v_1$ |
ordering={"name": "v", "direction": "desc"} |
DDM.dist(...) and pm.logp(...) for each regime |
model="ddm", loglik_kind="analytical" |
Forward algorithm in pytensor.scan, added as a pm.Potential |
built in |
The transition prior and the initial distribution above are RSSSM's defaults. They are spelled out here so that the correspondence is visible.
Label switching. The original penalizes every draw with $v_0 \le v_1$. RSSSM instead puts PyMC's ordered transform on the drift rate, so draws with the regime labels swapped can't occur at all; the target posterior is the same. By default RSSSM orders the regimes from the lowest to the highest drift. direction="desc" keeps the original's convention that regime 0 is the high-drift, attentive regime. To do this, RSSSM samples v_ordered $= -v$ in ascending order, which is why the model graph below has a v_ordered node.
How the HMM-DDM Likelihood Works¶
RSSSM computes the same likelihood as the original, with the forward algorithm:
- Local DDM densities: for every trial $t$ and regime $k$, the log-likelihood of the observed response time and choice under that regime's DDM parameters.
- State filtering: a forward pass tracks $\alpha_t(k) = p(y_{1:t}, s_t = k)$, the probability of the data up to trial $t$ and of being in regime $k$ at trial $t$.
- Recursive update: each step combines the previous trial's $\alpha$ with the transition matrix $P$ and the current trial's DDM density.
- Total likelihood: summing $\alpha$ over regimes at the final trial $N$ gives the marginal likelihood of the whole session, which
RSSSMadds to the model as a singlepm.Potential.
The one difference is numerical. RSSSM rescales $\alpha_t$ to sum to one at every trial and adds the logs of the scale factors back up. This gives the same marginal likelihood without underflow on long sessions.
# Everything except the emission likelihood. Part 6 reuses this dictionary
# unchanged, so the two models differ only in their likelihood.
rsssm_kwargs = dict(
data=df,
model="ddm",
K=K,
switching_params=["v"], # v switches across regimes; a, z, t are shared
transition_prior={"sticky_diag": 20.0, "sticky_offdiag": 2.0},
initial_distribution="uniform",
ordering={"name": "v", "direction": "desc"}, # v[0] > v[1]
# Priors, as in the original
v={"name": "Normal", "mu": 0.0, "sigma": 3.0}, # one drift per regime
a={"name": "HalfNormal", "sigma": 2.0}, # boundary separation (shared)
z={"name": "Beta", "alpha": 10, "beta": 10}, # starting point bias (shared)
t={"name": "HalfNormal", "sigma": 0.5}, # non-decision time (shared)
)
model_analytical = hssm.RSSSM(**rsssm_kwargs, loglik_kind="analytical")
model_analytical.graph()
No participant column found; treating all rows as a single participant.
RSSSM model initialized successfully.
Part 4: NUTS Sampling (Analytical)¶
RSSSM.sample() calls pm.sample on the model that RSSSM built, with the same arguments as the original. nuts_sampler="numpyro" is RSSSM's default, because the forward recursion compiles to JAX; it is passed here to match the original.
# Same settings as the original: 2 chains of 1000 draws after 1000 tuning
# steps, target_accept=0.9, NumPyro's NUTS (JAX backend), random_seed=42.
idata_analytical = model_analytical.sample(
draws=1000,
tune=1000,
chains=2,
target_accept=0.9,
nuts_sampler="numpyro",
random_seed=42,
)
NUTS[numpyro]: [P, v_ordered, a, z, t]
<environment>/site-packages/pymc/sampling/jax.py:463: UserWarning: There are not enough devices to run parallel chains: expected 2 but got 1. Chains will be drawn sequentially. If you are running MCMC in CPU, consider using `numpyro.set_host_device_count(2)` at the beginning of your program. You can double-check how many devices are available in your system using `jax.local_device_count()`. pmap_numpyro = MCMC(
We recommend running at least 4 chains for robust computation of convergence diagnostics
Diagnostics and Posterior Summary¶
az.summary(idata_analytical, var_names=["v", "a", "z", "t", "P"])
| mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd | |
|---|---|---|---|---|---|---|---|---|---|
| v[0] | 1.17 | 0.177 | 0.91 | 1.5 | 1016 | 1132 | 1.00 | 0.0056 | 0.0049 |
| v[1] | -0.01 | 0.22 | -0.39 | 0.32 | 1627 | 1278 | 1.00 | 0.0055 | 0.0055 |
| a | 0.804 | 0.0222 | 0.77 | 0.84 | 1206 | 1223 | 1.00 | 0.00064 | 0.00049 |
| z | 0.5276 | 0.0175 | 0.5 | 0.56 | 1289 | 1156 | 1.00 | 0.00049 | 0.00042 |
| t | 0.3114 | 0.0081 | 0.3 | 0.32 | 1203 | 1363 | 1.00 | 0.00024 | 0.00018 |
| P[0, 0] | 0.92 | 0.036 | 0.86 | 0.97 | 1235 | 1176 | 1.00 | 0.001 | 0.001 |
| P[0, 1] | 0.08 | 0.036 | 0.032 | 0.14 | 1235 | 1176 | 1.00 | 0.001 | 0.001 |
| P[1, 0] | 0.128 | 0.054 | 0.053 | 0.22 | 1464 | 1178 | 1.00 | 0.0014 | 0.0014 |
| P[1, 1] | 0.872 | 0.054 | 0.78 | 0.95 | 1464 | 1178 | 1.00 | 0.0014 | 0.0014 |
print("True values for reference:")
print(f" v = [{TRUE_PARAMS[0]['v']}, {TRUE_PARAMS[1]['v']}]")
print(f" a = {TRUE_PARAMS[0]['a']}")
print(f" z = {TRUE_PARAMS[0]['z']}")
print(f" t = {TRUE_PARAMS[0]['t']}")
print(f" P = {TRUE_P.tolist()}")
True values for reference: v = [1.5, 0.2] a = 0.8 z = 0.5 t = 0.3 P = [[0.95, 0.05], [0.1, 0.9]]
az.plot_trace_dist(idata_analytical, var_names=["v", "a", "z", "t"])
plt.tight_layout()
plt.show()
Posterior Pair Plot (Analytical)¶
Pair plots help reveal correlations and trade-offs between DDM parameters across regimes.
az.plot_pair(
idata_analytical,
var_names=["v", "a", "z", "t"],
)
plt.suptitle("Posterior Pair Plot (Analytical DDM)", fontsize=13, y=1.01)
plt.show()
Part 5: Regime Recovery via Forward-Filter Backward-Sample (FFBS)¶
NUTS sampled only the continuous parameters, because the forward algorithm summed the regime sequence out. To recover which regime was active on each trial, the original writes Forward-Filter Backward-Sample (FFBS) by hand. RSSSM.infer_regimes() runs the same algorithm for a set of posterior draws:
Forward filter: the recursion of Part 3, keeping $\alpha_t(k)$ for every trial. On its own, $\alpha_t$ uses only the data up to trial $t$.
Backward sample: draw the regime of the last trial from $\alpha_N$, then go backwards, drawing each $s_t$ from
$$p(s_t = k \mid s_{t+1}, y_{1:N}) \propto \alpha_t(k) \cdot P_{k,\, s_{t+1}}.$$
The sampled sequences are consistent with both the data and the Markov dynamics, which picking $\arg\max_k \alpha_t(k)$ trial by trial would not be.
Repeating this for many posterior draws gives a distribution over regime sequences that also carries the uncertainty in the parameters. As in the original, we use 200 posterior draws. infer_regimes compiles the model's emission density itself, so there is no logp_ddm to compile by hand.
n_ffbs_draws = 200
# One FFBS regime sequence for each of 200 randomly selected posterior draws.
regimes_analytical = model_analytical.infer_regimes(
idata_analytical, n_draws=n_ffbs_draws, seed=123
)
# `regime_sample_frequency` has dimensions (participant, trial, regime): for each
# trial, the share of the sampled sequences in each regime, i.e. the posterior
# probability of that regime.
regimes_analytical.posterior_regimes["regime_sample_frequency"]
<xarray.DataArray 'regime_sample_frequency' (participant: 1, trial: 500,
regime: 2)> Size: 8kB
array([[[0.72 , 0.28 ],
[0.77 , 0.23 ],
[0.735, 0.265],
[0.67 , 0.33 ],
[0.595, 0.405],
[0.395, 0.605],
[0.375, 0.625],
[0.2 , 0.8 ],
[0.15 , 0.85 ],
[0.2 , 0.8 ],
[0.22 , 0.78 ],
[0.16 , 0.84 ],
[0.135, 0.865],
[0.205, 0.795],
[0.465, 0.535],
[0.69 , 0.31 ],
[0.815, 0.185],
[0.835, 0.165],
[0.815, 0.185],
[0.745, 0.255],
...
[0.12 , 0.88 ],
[0.095, 0.905],
[0.115, 0.885],
[0.225, 0.775],
[0.29 , 0.71 ],
[0.29 , 0.71 ],
[0.36 , 0.64 ],
[0.37 , 0.63 ],
[0.53 , 0.47 ],
[0.72 , 0.28 ],
[0.8 , 0.2 ],
[0.835, 0.165],
[0.875, 0.125],
[0.875, 0.125],
[0.875, 0.125],
[0.88 , 0.12 ],
[0.81 , 0.19 ],
[0.68 , 0.32 ],
[0.72 , 0.28 ],
[0.755, 0.245]]])
Coordinates:
* participant (participant) int64 8B 0
* trial (trial) int64 4kB 0 1 2 3 4 5 6 ... 493 494 495 496 497 498 499
* regime (regime) int64 16B 0 1Regime Recovery Visualization¶
We plot the posterior probability of each regime alongside the ground truth. The lower panel is RSSSM.plot_regime_recovery(); the upper panel adds the ground-truth bands, as in the original.
def plot_regime_recovery(model, regimes_idata, true_regimes, title_suffix=""):
"""Ground-truth regime bands above RSSSM's posterior regime probabilities."""
N = len(true_regimes)
fig, axes = plt.subplots(2, 1, gridspec_kw={"height_ratios": [1, 2]})
# --- Top panel: ground-truth regime bands ---
ax = axes[0]
start = 0
for t_idx in range(1, N):
if true_regimes[t_idx] != true_regimes[t_idx - 1] or t_idx == N - 1:
end = t_idx if t_idx < N - 1 else N
ax.axvspan(start, end, alpha=0.4, color=regime_colors[true_regimes[start]])
start = t_idx
ax.set_xlim(0, N - 1)
ax.set_ylabel("True")
ax.set_yticks([])
ax.set_title("Ground-Truth Regimes")
# --- Bottom panel: posterior regime probabilities (stacked area) ---
# The stacked area shows how confident the model is about each regime, with
# the true regime as a step line. Colour the areas like the bands above.
ax = axes[1]
ax.set_prop_cycle(color=[regime_colors[k] for k in range(model.K)])
model.plot_regime_recovery(regimes_idata, true_regimes=true_regimes, ax=ax)
ax.set_title(f"Posterior Regime Probabilities{title_suffix}")
fig.tight_layout()
plt.show()
plot_regime_recovery(
model_analytical, regimes_analytical, true_regimes, title_suffix=" (Analytical DDM)"
)
Part 6: Approx Differentiable HMM-DDM (LAN via ONNX)¶
The original swaps the analytical DDM for HSSM's approximate differentiable DDM: a pre-trained Likelihood Approximation Network (LAN) that HSSM provides as an ONNX model. The rest of the HMM is unchanged. With RSSSM the swap is the loglik_kind argument, and everything else is the rsssm_kwargs dictionary from Part 3.
backend="pytensor" matches the original, which built the LAN distribution with make_distribution_for_supported_model(..., backend="pytensor"); RSSSM's default LAN backend is "jax". The same call fits SSMs that have no analytical likelihood, such as angle or levy: change model= and keep loglik_kind="approx_differentiable".
model_approx = hssm.RSSSM(
**rsssm_kwargs, loglik_kind="approx_differentiable", backend="pytensor"
)
model_approx.graph()
No participant column found; treating all rows as a single participant.
RSSSM model initialized successfully.
Sampling the Approx Differentiable Model¶
Same sampling settings as the analytical model, so that the two posteriors can be compared directly.
idata_approx = model_approx.sample(
draws=1000,
tune=1000,
chains=2,
target_accept=0.9,
nuts_sampler="numpyro",
random_seed=42,
)
NUTS[numpyro]: [P, v_ordered, a, z, t]
<environment>/site-packages/pymc/sampling/jax.py:463: UserWarning: There are not enough devices to run parallel chains: expected 2 but got 1. Chains will be drawn sequentially. If you are running MCMC in CPU, consider using `numpyro.set_host_device_count(2)` at the beginning of your program. You can double-check how many devices are available in your system using `jax.local_device_count()`. pmap_numpyro = MCMC(
We recommend running at least 4 chains for robust computation of convergence diagnostics
az.summary(idata_approx, var_names=["v", "a", "z", "t", "P"])
| mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd | |
|---|---|---|---|---|---|---|---|---|---|
| v[0] | 1.19 | 0.2 | 0.9 | 1.5 | 811 | 1016 | 1.00 | 0.007 | 0.0051 |
| v[1] | 0.05 | 0.218 | -0.31 | 0.38 | 1679 | 1182 | 1.00 | 0.0053 | 0.0045 |
| a | 0.781 | 0.023 | 0.75 | 0.82 | 1121 | 1062 | 1.00 | 0.00068 | 0.00051 |
| z | 0.5296 | 0.018 | 0.5 | 0.56 | 1443 | 1318 | 1.00 | 0.00048 | 0.00036 |
| t | 0.3151 | 0.0091 | 0.3 | 0.33 | 1162 | 1294 | 1.00 | 0.00027 | 0.00019 |
| P[0, 0] | 0.916 | 0.04 | 0.84 | 0.97 | 1058 | 966 | 1.00 | 0.0012 | 0.001 |
| P[0, 1] | 0.084 | 0.04 | 0.031 | 0.16 | 1058 | 966 | 1.00 | 0.0012 | 0.001 |
| P[1, 0] | 0.118 | 0.05 | 0.05 | 0.21 | 1295 | 1173 | 1.00 | 0.0013 | 0.0012 |
| P[1, 1] | 0.882 | 0.05 | 0.79 | 0.95 | 1295 | 1173 | 1.00 | 0.0013 | 0.0012 |
az.plot_trace_dist(idata_approx, var_names=["v", "a", "z", "t"])
plt.tight_layout()
plt.show()
Posterior Pair Plot (LAN)¶
az.plot_pair(
idata_approx,
var_names=["v", "a", "z", "t"],
)
plt.suptitle("Posterior Pair Plot (LAN DDM)", fontsize=13, y=1.01)
plt.show()
Regime Recovery (LAN)¶
The original recovers the regimes of the LAN fit with the analytical density, because that was the NumPy function it had compiled for FFBS. infer_regimes uses the fitted model's own emission, so here FFBS runs on the LAN density that was used for sampling. To reproduce the original's shortcut exactly, pass idata_approx to model_analytical.infer_regimes: the two posteriors have the same parameter names.
regimes_approx = model_approx.infer_regimes(
idata_approx, n_draws=n_ffbs_draws, seed=456
)
plot_regime_recovery(
model_approx, regimes_approx, true_regimes, title_suffix=" (LAN DDM)"
)
Part 7: Comparing Analytical vs. Approx Differentiable Posteriors¶
Let's overlay the posterior distributions from both backends to assess how closely the LAN approximation tracks the analytical solution. The posteriors of both RSSSM fits contain the original's variables (v, a, z, t and P), so the plotting code below is the original's, unchanged.
# --- Compare posterior distributions: Analytical vs. LAN ---
# For each DDM parameter, we overlay histograms from both backends.
# If the LAN approximation is accurate, the two distributions should overlap closely.
# The black dashed line shows the true parameter value used to generate the data.
params_to_compare = {
"v[0]": {"true": TRUE_PARAMS[0]["v"]},
"v[1]": {"true": TRUE_PARAMS[1]["v"]},
"a": {"true": TRUE_PARAMS[0]["a"]},
"z": {"true": TRUE_PARAMS[0]["z"]},
"t": {"true": TRUE_PARAMS[0]["t"]},
}
fig, axes = plt.subplots(1, 5)
for ax, (param_name, info) in zip(axes, params_to_compare.items()):
base_name = param_name.split("[")[0]
# Plot histogram from each backend
for idata, label, color in [
(idata_analytical, "Analytical", "#1976D2"),
(idata_approx, "LAN", "#FF7043"),
]:
samples = idata.posterior[base_name].values.flatten()
if "[" in param_name:
# For indexed parameters like v[0], extract the right index
idx = int(param_name.split("[")[1].rstrip("]"))
samples = idata.posterior[base_name].values[:, :, idx].flatten()
ax.hist(samples, bins=40, alpha=0.5, density=True, color=color, label=label)
ax.axvline(info["true"], color="k", linestyle="--", linewidth=1.5, label="True")
ax.set_title(param_name, fontsize=11)
ax.set_xlabel("")
ax.set_yticks([])
axes[0].legend(fontsize=8)
fig.suptitle("Posterior Comparison: Analytical vs. LAN", fontsize=13, y=1.02)
fig.tight_layout()
plt.show()
Transition Matrix Recovery¶
# --- Compare transition matrix posteriors: Analytical vs. LAN ---
# Each subplot shows one entry P[i, j] of the 2x2 transition matrix.
# The diagonal entries (P[0,0] and P[1,1]) represent regime persistence ("stickiness").
fig, axes = plt.subplots(2, 2)
for i in range(K):
for j in range(K):
ax = axes[i, j]
for idata, label, color in [
(idata_analytical, "Analytical", "#1976D2"),
(idata_approx, "LAN", "#FF7043"),
]:
samples = idata.posterior["P"].values[:, :, i, j].flatten()
ax.hist(samples, bins=40, alpha=0.5, density=True, color=color, label=label)
ax.axvline(TRUE_P[i, j], color="k", linestyle="--", linewidth=1.5, label="True")
ax.set_title(f"P[{i},{j}] (true={TRUE_P[i, j]:.2f})", fontsize=10)
ax.set_yticks([])
axes[0, 0].legend(fontsize=8)
fig.suptitle("Transition Matrix Posterior", fontsize=13, y=1.01)
fig.tight_layout()
plt.show()
RT Distributions by Regime¶
The observed signed RTs of each ground-truth regime. The attentive regime is faster, and its responses are more consistently positive.
# --- RT distributions by ground-truth regime ---
# "Signed RT" = RT * response direction, so we can visualize both speed and
# choice in a single histogram. The attentive regime should show tighter,
# more positive RTs (higher drift -> faster, more accurate responses).
fig, axes = plt.subplots(1, 2)
for k, (label, color) in enumerate(
[("Regime 0 (Attentive)", "#4CAF50"), ("Regime 1 (Distracted)", "#F44336")]
):
ax = axes[k]
mask = true_regimes == k
signed_rt = data[mask, 0] * data[mask, 1]
ax.hist(signed_rt, bins=40, density=True, alpha=0.7, color=color, label="Observed")
ax.set_title(label, fontsize=11)
ax.set_xlabel("Signed RT")
ax.set_ylabel("Density")
ax.legend(fontsize=9)
fig.suptitle("RT Distributions by Ground-Truth Regime", fontsize=13, y=1.02)
fig.tight_layout()
plt.show()
Part 8: Summary and Extensions¶
What we demonstrated¶
- One constructor call:
hssm.RSSSMreplaced the hand-built PyMC model. The sticky transition prior, the regime-specific drift, the ordering constraint and the priors are arguments; the forward algorithm is built in. - Plug-and-play emissions: the analytical DDM and the LAN were swapped with
loglik_kindandbackend, with the rest of the arguments unchanged. - Regime recovery:
infer_regimes()ran FFBS for 200 posterior draws, andplot_regime_recovery()plotted the result. - NumPyro backend: both models were sampled with
nuts_sampler="numpyro", which isRSSSM's default because it compiles the forward recursion to JAX.
Interpretation tips¶
- Label switching: the
orderedtransform makes swapped labels impossible, so the chains should agree with each other. Withordering="none"the transform is gone, and the posterior has one mode for each labelling of the regimes. - Sticky prior: the Dirichlet concentration (
sticky_diag=20) strongly favours self-transitions. This is a useful inductive bias for cognitive data, where regime switches are rare; adjust it for your domain withtransition_prior. - Number of regimes: we fixed $K=2$. Part 10 below gets LOO scores from
RSSSMfits, and the K = 3 tutorial uses them to choose $K$. LOO can be tricky for HMMs, because the trials are not independent.
The original's extensions, with RSSSM¶
- More switching parameters: list them in
switching_params, e.g.switching_params=["v", "a"]. - Hierarchical structure: with several participants,
pooling="none"fits independent DDM parameters per participant and one transition matrix for all of them. Partial pooling across participants isn't inRSSSMyet. - Covariate-driven transitions: not in
RSSSMyet. - More complex SSMs: change
model=to another SSM that HSSM supports, e.g.model="angle", withloglik_kind="approx_differentiable"when it has no analytical likelihood. - Duration-dependent HMMs: not in
RSSSMyet.
Beyond the original¶
The parts below go beyond the hand-built tutorial: what to do with the recovered regimes, then two features of RSSSM that the original doesn't have.
Part 9: Using the Recovered Regimes¶
Parts 5 and 6 recovered the posterior probability of each regime on every trial. Two things to do with it:
- On simulated data, measure how often the most probable regime is the true one. This puts a number on the recovery plots.
- On real data, where there is no ground truth, assign each trial to its most probable regime and compare the behaviour in each regime. Part 7 split the RTs by the true regime; the same figure by recovered regime is the one you can make with real data. Here the true split is drawn as an outline for comparison.
def most_probable_regime(regimes_idata):
"""Return each trial's most probable regime from `infer_regimes` output."""
freq = regimes_idata.posterior_regimes["regime_sample_frequency"].values[0]
return freq.argmax(axis=1) # (n_trials,)
map_analytical = most_probable_regime(regimes_analytical)
map_approx = most_probable_regime(regimes_approx)
for label, map_regime in [("Analytical", map_analytical), ("LAN", map_approx)]:
accuracy = (map_regime == true_regimes).mean()
print(
f"{label}: the most probable regime is the true one on {accuracy:.1%} of trials"
)
Analytical: the most probable regime is the true one on 82.6% of trials LAN: the most probable regime is the true one on 84.0% of trials
# --- RT distributions by recovered regime (analytical fit) ---
# Part 7's figure, with each trial assigned to its most probable regime instead
# of its true one. The black outline is the split by true regime.
signed_rt_all = data[:, 0] * data[:, 1]
bins = np.histogram_bin_edges(signed_rt_all, bins=40)
fig, axes = plt.subplots(1, 2)
for k, (label, color) in enumerate(
[("Regime 0 (Attentive)", "#4CAF50"), ("Regime 1 (Distracted)", "#F44336")]
):
ax = axes[k]
recovered = map_analytical == k
ax.hist(
signed_rt_all[recovered],
bins=bins,
density=True,
alpha=0.7,
color=color,
label=f"Recovered (n={recovered.sum()})",
)
ax.hist(
signed_rt_all[true_regimes == k],
bins=bins,
density=True,
histtype="step",
color="k",
label=f"True (n={(true_regimes == k).sum()})",
)
ax.set_title(label, fontsize=11)
ax.set_xlabel("Signed RT")
ax.set_ylabel("Density")
ax.legend(fontsize=9)
fig.suptitle("RT Distributions by Recovered Regime", fontsize=13, y=1.02)
fig.tight_layout()
plt.show()
The recovered split is close to the true one: the regime sizes differ by only a few trials (see the legends), and in each panel the two histograms nearly coincide, even though about one trial in six is assigned to the wrong regime. Most attentive-regime responses are at the upper boundary, while the distracted regime's are split between the two boundaries, as expected from its low drift rate.
Part 10: Model Comparison with LOO¶
RSSSM adds the HMM likelihood to the model as one number for the whole session, so sampling stores no per-trial log-likelihood, which az.loo needs. compute_log_likelihood() rebuilds it from the posterior: for each draw it reruns the forward filter and splits the marginal likelihood into one term per trial. (sample(..., include_log_likelihood=True) does the same right after sampling.)
Both fits are of the same model and data, so their LOO scores should be statistically indistinguishable: this is a consistency check, not a model choice. The per-trial terms are one-step-ahead predictions that depend on each other, so treat LOO for HMMs as a relative score rather than an exact leave-one-out.
model_analytical.compute_log_likelihood(idata_analytical)
model_approx.compute_log_likelihood(idata_approx)
az.compare({"analytical": idata_analytical, "LAN": idata_approx})
Reconstructing per-trial log-likelihood over 2000 draws (2 chains x 1000) for 1 participants; this can be slow on large posteriors.
Reconstructing per-trial log-likelihood over 2000 draws (2 chains x 1000) for 1 participants; this can be slow on large posteriors.
| rank | elpd_diff | dse | p_worse | diag_diff | diag_elpd | p | elpd | se | weight | |
|---|---|---|---|---|---|---|---|---|---|---|
| LAN | 0 | 0.0 | 0.0 | NaN | 6.0 | -400.0 | 24.0 | 1.0 | ||
| analytical | 1 | -1.0 | 0.5 | 0.94 | |elpd_diff| < 4 | 6.1 | -400.0 | 24.0 | 0.0 |
The two fits' scores differ by about 1 elpd point, and az.compare marks the difference with |elpd_diff| < 4, its flag for models that make similar predictions.
Part 11: Regime-Specific Lapses¶
Real data contain lapses: fast guesses or attention failures that the DDM can't explain, and a distracted regime may lapse more often than an attentive one. Adding p_outlier to switching_params gives each regime its own lapse rate: the emission of regime $k$ becomes the mixture $(1 - p_k)\,\text{DDM}(\theta_k) + p_k\,\text{Uniform}(0, 20)$ over RT.
We simulate a new session from the same process and turn each attentive trial into a lapse with probability 0.03, and each distracted trial with probability 0.30. A lapse has an RT drawn from Uniform(0, 20) and a random choice. Then we fit the Part 3 model with p_outlier switching as well.
data_lapse, true_regimes_lapse = simulate_hmm_ddm_data(
N_TRIALS, TRUE_PARAMS, TRUE_P, TRUE_PI0, seed=5
)
TRUE_P_OUTLIER = np.array([0.03, 0.30]) # regime 0 (attentive), regime 1 (distracted)
rng_lapse = np.random.default_rng(7)
is_lapse = rng_lapse.random(N_TRIALS) < TRUE_P_OUTLIER[true_regimes_lapse]
data_lapse[is_lapse, 0] = rng_lapse.uniform(0.0, 20.0, size=is_lapse.sum()) # RT
data_lapse[is_lapse, 1] = rng_lapse.choice([-1.0, 1.0], size=is_lapse.sum()) # choice
print(f"Lapse trials: {is_lapse.sum()} of {N_TRIALS}")
model_lapse = hssm.RSSSM(
**{
**rsssm_kwargs,
"data": pd.DataFrame(data_lapse, columns=["rt", "response"]),
"switching_params": ["v", "p_outlier"], # a lapse rate per regime
},
loglik_kind="analytical",
p_outlier={"name": "Beta", "alpha": 1, "beta": 8},
)
Lapse trials: 51 of 500 No participant column found; treating all rows as a single participant.
RSSSM model initialized successfully.
idata_lapse = model_lapse.sample(
draws=1000,
tune=1000,
chains=2,
target_accept=0.9,
nuts_sampler="numpyro",
random_seed=42,
)
NUTS[numpyro]: [P, v_ordered, a, z, t, p_outlier]
<environment>/site-packages/pymc/sampling/jax.py:463: UserWarning: There are not enough devices to run parallel chains: expected 2 but got 1. Chains will be drawn sequentially. If you are running MCMC in CPU, consider using `numpyro.set_host_device_count(2)` at the beginning of your program. You can double-check how many devices are available in your system using `jax.local_device_count()`. pmap_numpyro = MCMC(
We recommend running at least 4 chains for robust computation of convergence diagnostics
summary_lapse = az.summary(idata_lapse, var_names=["v", "p_outlier"])
summary_lapse.insert(
0,
"true",
[TRUE_PARAMS[0]["v"], TRUE_PARAMS[1]["v"], *TRUE_P_OUTLIER],
)
summary_lapse
| true | mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd | |
|---|---|---|---|---|---|---|---|---|---|---|
| v[0] | 1.5 | 1.641 | 0.139 | 1.4 | 1.9 | 1226 | 1427 | 1.00 | 0.004 | 0.0026 |
| v[1] | 0.2 | 0.12 | 0.25 | -0.3 | 0.51 | 1653 | 1421 | 1.00 | 0.0063 | 0.0055 |
| p_outlier[0] | 0.03 | 0.0487 | 0.0204 | 0.018 | 0.084 | 1994 | 984 | 1.00 | 0.00043 | 0.00046 |
| p_outlier[1] | 0.3 | 0.349 | 0.063 | 0.25 | 0.46 | 1803 | 1368 | 1.00 | 0.0015 | 0.0013 |
Both lapse rates are recovered: the true values (0.03 for the attentive regime, 0.30 for the distracted one) fall inside the 89% intervals. So do the true drift rates, although 51 of the 500 trials were replaced by lapses.
Where to go next¶
- The K = 3 tutorial fits three regimes, and uses LOO to choose the number of regimes.
- The
RSSSMAPI reference documents every argument and method used here. - The HMM with DDM emissions tutorial builds the model by hand, which is the starting point for an HMM that
RSSSMdoesn't cover.