hssm.RSSSM
Experimental
hssm.RSSSM is new in HSSM 0.6.0 and experimental: its interface may
change in a later release without a deprecation period.
Use the hssm.RSSSM class to fit a regime-switching sequential sampling
model: each trial belongs to one of K hidden regimes that evolve as a Markov
chain, and within a regime the (rt, response) emission is a standard SSM (e.g.
DDM) with regime-specific switching parameters. The discrete regimes are
marginalised out by the forward algorithm, so only continuous parameters remain
for NUTS. After sampling, infer_regimes reconstructs the latent regime
trajectories (Forward-Filter Backward-Sample) and compute_log_likelihood
produces the per-trial log-likelihood needed for arviz.loo.
hssm.RSSSM ¶
RSSSM(
data: DataFrame,
model: str | BaseModelConfig | None = None,
K: int | None = None,
switching_params: list[str] | None = None,
*,
model_config: RSSSMConfig | None = None,
transition_prior: Any = None,
initial_distribution: Any = None,
loglik_kind: "LoglikKind" | None = None,
backend: Literal["jax", "pytensor"] | None = None,
participant_col: str = "participant_id",
ordering: Any = None,
pooling: Any = None,
missing_data: bool | float = False,
deadline: bool | str = False,
p_outlier: float | dict | Prior | None = None,
lapse: float | dict | Prior | None = None,
**kwargs: Any,
)
Bases: HSSMBase
Regime-Switching Sequential Sampling Model.
Experimental: the interface of this class may change in a later release without a deprecation period.
Parameters:
-
data(DataFrame) –Long-format trial data, sorted by
(participant, trial). Panels may be unbalanced. Must contain the emission columns (rt,response) and, for multi-participant data,participant_col. -
model(str | BaseModelConfig | None, default:None) –SSM identifier (e.g.
"ddm") or a pre-builtBaseModelConfig. Required. The emission is always resolved from the registry entry named by the identifier (model.model_namefor a config), so a config must name a registered SSM; it may overridelist_params/bounds/loglik_kind, but a customloglikis rejected rather than silently discarded. -
K(int | None, default:None) –Number of hidden regimes (
>= 2). -
switching_params(list[str] | None, default:None) –SSM parameters inferred per regime.
-
model_config(RSSSMConfig | None, default:None) –Pre-built
RSSSMConfig(advanced path). Mutually exclusive with the granular args above. -
transition_prior(Any, default:None) –Spec inputs (dataclass, HSSM-style dict, or shorthand) for the Markov chain structure and label-switching.
-
initial_distribution(Any, default:None) –Spec inputs (dataclass, HSSM-style dict, or shorthand) for the Markov chain structure and label-switching.
-
ordering(Any, default:None) –Spec inputs (dataclass, HSSM-style dict, or shorthand) for the Markov chain structure and label-switching.
-
pooling(Any, default:None) –Spec inputs (dataclass, HSSM-style dict, or shorthand) for the Markov chain structure and label-switching.
-
loglik_kind('LoglikKind' | None, default:None) –"analytical"(Phase 2) or"approx_differentiable"(Phase 3). -
participant_col(str, default:'participant_id') –Column identifying participants. Synthesised as a constant when absent.
-
**kwargs(Any, default:{}) –Per-parameter input specs (the three-mode rule):
v=0.5shares a scalar,v=[0.5, 1.5]fixes per regime,v={"name": "Normal", ...}infers with that prior.
Methods:
-
sample–Sample the model via
pm.sampleon the directly-built graph. -
infer_regimes–Recover the latent regime sequences from the posterior via FFBS.
-
compute_log_likelihood–Attach the post-hoc per-trial log-likelihood group (§5.6).
-
plot_regime_recovery–Stacked-area plot of the posterior regime probabilities over trials.
-
graph–Render the PyMC model graph via graphviz.
Attributes:
-
pymc_model(Model) –The directly-built PyMC model (no bambi).
hssm.RSSSM.sample ¶
sample(
draws: int = 1000,
tune: int = 1000,
chains: int = 4,
nuts_sampler: Literal["blackjax", "numpyro", "nutpie", "pymc"] = "numpyro",
include_log_likelihood: bool = False,
*,
sampler: Any = None,
**kwargs: Any,
) -> DataTree
Sample the model via pm.sample on the directly-built graph.
Defaults to nuts_sampler="numpyro" (decision 10.1.10): the forward
pytensor.scan JIT-compiles to jax.lax.scan under numpyro, which
is dramatically faster than the PyMC NUTS default on the batched
recursion. All other pm.sample kwargs pass through.
Note
This signature deliberately differs from :meth:HSSM.sample: RSSSM
builds the PyMC model directly and calls pm.sample rather than
bambi.Model.fit, so the sampler is selected with nuts_sampler=
(not sampler=) and the bambi-specific init / initvals /
include_response_params arguments are not accepted. sampler=
is accepted only to raise a clear error. The positional order also
differs — :meth:HSSM.sample takes sampler first while this method
takes draws first — so always pass these arguments by keyword.
Parameters:
-
sampler(Any, default:None) –Not supported; present only so that
sampler="numpyro"raises a clearTypeErrorpointing atnuts_sampler=instead of leaking an internal PyMC error. -
include_log_likelihood(bool, default:False) –When
True, attach the per-triallog_likelihoodgroup via :meth:compute_log_likelihood(needed forarviz.loo). Defaults toFalse: unlike a standard HSSM model whose per-trial logp is vectorised, RSSSM reconstructs it post-hoc with a pure-NumPy forward filter over every draw (O(chains·draws·N·T)), which is costly on large posteriors — so it is opt-in here (callcompute_log_likelihoodlater instead if preferred).
Notes
HSSMBase._clean_posterior_group is intentionally not applied: it
prunes bambi trial-wise deterministics, of which the directly-built RSSSM
graph has none, and it would risk dropping the descending-anchor
Deterministic (OrderByParam(direction="desc")).
hssm.RSSSM.infer_regimes ¶
infer_regimes(
idata: DataTree | None = None, n_draws: int = 200, seed: int | None = None
) -> DataTree
Recover the latent regime sequences from the posterior via FFBS.
NUTS marginalises the discrete regimes out at sampling time, so the
posterior holds only theta, P, pi0. infer_regimes runs
Forward-Filter Backward-Sample for n_draws posterior draws, drawing
one regime sequence per participant per draw (§5.5).
Parameters:
-
idata(DataTree | None, default:None) –Posterior to use; defaults to the model's own
traces. -
n_draws(int, default:200) –Number of posterior draws to run FFBS on.
-
seed(int | None, default:None) –Seed for draw selection and the backward sampling.
Returns:
-
DataTree–A
posterior_regimesgroup withregimes(draw, participant, trial)andregime_sample_frequency(participant, trial, regime).
hssm.RSSSM.compute_log_likelihood ¶
Attach the post-hoc per-trial log-likelihood group (§5.6).
The sampler graph contributes only the scalar marginal (§3.4), so the
log_likelihood group needed by arviz.loo is
reconstructed here from the saved posterior: per draw, the forward
filter's running log-evidence yields delta_t = logZ_t - logZ_{t-1},
whose per-participant sum equals the marginal the sampler used.
The per-trial terms are one-step-ahead predictives and are serially
dependent within a participant, so the arviz.loo estimate
is an approximate leave-one-out (use it as a relative comparison score,
not an exact LOO). This recomputes the forward filter for every
posterior draw, so it can be slow on large posteriors.
Parameters:
-
idata(DataTree | None, default:None) –Posterior to use; defaults to the model's own
traces. Thelog_likelihoodgroup is added to it in place and returned.
hssm.RSSSM.plot_regime_recovery ¶
plot_regime_recovery(
regimes_idata: DataTree | None = None,
participant: int = 0,
true_regimes: Any = None,
ax: Any = None,
n_draws: int = 200,
seed: int | None = None,
)
Stacked-area plot of the posterior regime probabilities over trials.
Parameters:
-
regimes_idata(DataTree | None, default:None) –Output of :meth:
infer_regimes; computed on the fly (viainfer_regimes) whenNone. -
participant(int, default:0) –Index of the participant to plot.
-
true_regimes(Any, default:None) –Optional ground-truth regime sequence to overlay as a step line. Regime
kis drawn atk / (K - 1). -
ax(Any, default:None) –Optional matplotlib axis; created when
None. -
n_draws(int, default:200) –Forwarded to :meth:
infer_regimeswhenregimes_idata is None. -
seed(int, default:200) –Forwarded to :meth:
infer_regimeswhenregimes_idata is None.
Returns:
-
Axes–
hssm.RSSSM.graph ¶
Render the PyMC model graph via graphviz.
The signature matches :meth:HSSM.graph, but only formatting is
honoured: the direct-build path renders the PyMC model itself rather
than a bambi model, so the figure-saving arguments (name /
figsize / dpi / fmt) are ignored with a warning. Save the
returned graphviz object yourself if you need a file.
Parameters:
-
formatting–One of
"plain"or"plain_with_params". Defaults to"plain". -
name–Accepted for signature compatibility with :meth:
HSSM.graphand ignored with a warning when set to anything other than the default. -
figsize–Accepted for signature compatibility with :meth:
HSSM.graphand ignored with a warning when set to anything other than the default. -
dpi–Accepted for signature compatibility with :meth:
HSSM.graphand ignored with a warning when set to anything other than the default. -
fmt–Accepted for signature compatibility with :meth:
HSSM.graphand ignored with a warning when set to anything other than the default.
Returns:
-
Graph–The graph.