StateSpaceTimeSeries#

class causalpy.pymc_models.StateSpaceTimeSeries[source]#

State-space time series model using pymc-extras.statespace.structural.

The model combines a local level/trend component with frequency-domain seasonality. When X is passed to fit, its columns (except the patsy Intercept, which the level absorbs) enter as exogenous regressors through a static-coefficient Regression component, and out-of-sample predictions use the post-period X as the forecast scenario.

Parameters:
  • level_order (int) – Order of the local level/trend component. Defaults to 2.

  • seasonal_length (int) – Seasonal period (e.g., 12 for monthly data with annual seasonality). Defaults to 12.

  • trend_component (Any | None) – Custom state-space trend component. Must be a pymc-extras structural component (e.g. pymc_extras.statespace.structural.LevelTrend). Components with non-default names introduce their own parameter names; pass matching entries in priors.

  • seasonality_component (Any | None) – Custom state-space seasonal component. Same requirements as trend_component.

  • sample_kwargs (dict[str, Any] | None) – Kwargs passed to pm.sample.

  • mode (str | None) – Pytensor compile mode used when building the state-space model. Defaults to None.

  • priors (dict[str, Prior] | None) – Dictionary mapping state-space parameter names to pymc_extras.prior.Prior objects, overriding the defaults in default_priors. The P0 covariance is parameterized through its diagonal under the key “P0_diag”. Dims are resolved from the built state-space model, so priors do not need to declare them.

  • prior_sample_kwargs (dict[str, Any] | None) – Kwargs passed to pm.sample_prior_predictive when the prior phase runs. Defaults to {"draws": 500} plus the posterior random_seed if None.

  • vs_prior_type (Optional[Literal['spike_and_slab', 'horseshoe', 'normal']]) – Variable selection prior for the exogenous regression coefficients. Requires covariates. Takes precedence over a beta_exog entry in priors.

  • vs_hyperparams (dict[str, Any] | None) – Hyperparameters for the variable selection prior. See causalpy.variable_selection_priors.VariableSelectionPrior. The defaults work without hand-tuning on roughly unit-scale data: the horseshoe sets its global shrinkage from an expected model size of min(5, p / 2) and the sample size (Piironen & Vehtari, 2017), holding the residual scale of that rule at 1, while spike-and-slab uses a Beta(2, 2) inclusion prior (prior inclusion probability centered on 0.5, no expected-model-size knob). Pass tau0 in vs_hyperparams when the residuals are not close to unit scale. The normal option is a plain Normal(0, 1) on each coefficient, with no selection. That is much tighter than the Normal(0, 50) this class puts on beta_exog when no selection prior is set, so it is not a drop-in stand-in for the default.

Examples

Covariate selection through causalpy.InterruptedTimeSeries: pass many candidate covariates in the formula and let the model select.

>>> import numpy as np
>>> import pandas as pd
>>> import causalpy as cp
>>> rng = np.random.default_rng(7)
>>> n = 60
>>> dates = pd.date_range(start="2023-01-01", periods=n, freq="D")
>>> X = rng.normal(size=(n, 3))
>>> y = 5 + 2.0 * X[:, 0] + rng.normal(0, 0.3, size=n)
>>> df = pd.DataFrame(
...     {"y": y, "x1": X[:, 0], "x2": X[:, 1], "x3": X[:, 2]}, index=dates
... )
>>> model = cp.pymc_models.StateSpaceTimeSeries(
...     level_order=1,
...     seasonal_length=7,
...     sample_kwargs={
...         "chains": 1,
...         "draws": 10,
...         "tune": 10,
...         "progressbar": False,
...     },
...     vs_prior_type="spike_and_slab",
... )
>>> import io
>>> from contextlib import redirect_stdout
>>> with redirect_stdout(io.StringIO()):  # silence the model-build table
...     result = cp.InterruptedTimeSeries(
...         data=df,
...         treatment_time=dates[45],
...         formula="y ~ 0 + x1 + x2 + x3",
...         model=model,
...     ).fit()
>>> inclusion = result.model.get_inclusion_probabilities()
>>> inclusion.index.tolist()
['x1', 'x2', 'x3']
>>> inclusion.columns.tolist()
['prob', 'selected', 'gamma_mean']

Methods

StateSpaceTimeSeries.add_coord(name[, ...])

Register a dimension coordinate with the model.

StateSpaceTimeSeries.add_coords(coords, *[, ...])

Vectorized version of Model.add_coord.

StateSpaceTimeSeries.add_named_variable(var)

Add a random graph variable to the named variables of the model.

StateSpaceTimeSeries.build([X, y, coords])

Construct the state-space graph without sampling.

StateSpaceTimeSeries.build_mapping(X, y[, ...])

Construct a specialized mapping-input graph without sampling.

StateSpaceTimeSeries.build_model([X, y, coords])

Build the PyMC state-space model.

StateSpaceTimeSeries.check_start_vals(start, ...)

Check that the logp is defined and finite at the starting point.

StateSpaceTimeSeries.compile_d2logp([vars, ...])

Compiled log probability density hessian function.

StateSpaceTimeSeries.compile_dlogp([vars, ...])

Compiled log probability density gradient function.

StateSpaceTimeSeries.compile_fn(outs, *[, ...])

Compiles a PyTensor function.

StateSpaceTimeSeries.compile_logp([vars, ...])

Compiled log probability density function.

StateSpaceTimeSeries.copy()

Clone the model.

StateSpaceTimeSeries.create_value_var(...[, ...])

Create a TensorVariable that will be used as the random variable's "value" in log-likelihood graphs.

StateSpaceTimeSeries.d2logp([vars, ...])

Hessian of the models log-probability w.r.t.

StateSpaceTimeSeries.debug([point, fn, verbose])

Debug model function at point.

StateSpaceTimeSeries.dlogp([vars, jacobian])

Gradient of the models log-probability w.r.t.

StateSpaceTimeSeries.eval_rv_shapes()

Evaluate shapes of untransformed AND transformed free variables.

StateSpaceTimeSeries.fit([X, y, coords])

Build the graph if needed, then draw smoothed posterior samples.

StateSpaceTimeSeries.fit_mapping(X, y[, coords])

Fit a specialized model that accepts mapping-valued inputs.

StateSpaceTimeSeries.get_context([...])

StateSpaceTimeSeries.get_inclusion_probabilities([...])

Posterior inclusion probabilities of the exogenous regressors.

StateSpaceTimeSeries.get_shrinkage_factors([...])

Shrinkage factors of the exogenous regressors.

StateSpaceTimeSeries.initial_point([random_seed])

Compute the initial point of the model.

StateSpaceTimeSeries.logp([vars, jacobian, sum])

Elemwise log-probability of the model.

StateSpaceTimeSeries.logp_dlogp_function([...])

Compile a PyTensor function that computes logp and gradient.

StateSpaceTimeSeries.make_obs_var(rv_var, ...)

Create a TensorVariable for an observed random variable.

StateSpaceTimeSeries.name_for(name)

Check if name has prefix and adds if needed.

StateSpaceTimeSeries.name_of(name)

Check if name has prefix and deletes if needed.

StateSpaceTimeSeries.point_logps([point, ...])

Compute the log probability of point for all random variables in the model.

StateSpaceTimeSeries.predict([X, coords, ...])

Predict data given input X.

StateSpaceTimeSeries.priors_from_data(X, y)

Generate priors dynamically based on the input data.

StateSpaceTimeSeries.profile(outs, *[, n, ...])

Compile and profile a PyTensor function which returns outs and takes values of model vars as a dict as an argument.

StateSpaceTimeSeries.register_data_var(data)

Register a data variable with the model.

StateSpaceTimeSeries.register_rv(rv_var, name, *)

Register an (un)observed random variable with the model.

StateSpaceTimeSeries.replace_rvs_by_values(...)

Clone and replace random variables in graphs with their value variables.

StateSpaceTimeSeries.require_built()

Raise unless the PyMC graph has been constructed with build().

StateSpaceTimeSeries.require_group(group)

Return the draws Dataset for group or raise an actionable error.

StateSpaceTimeSeries.sample_posterior(**kwargs)

Sample the posterior phase and attach Kalman-smoothed predictions.

StateSpaceTimeSeries.sample_prior_predictive(...)

Sample the prior predictive phase and merge it into idata.

StateSpaceTimeSeries.score([X, y, coords])

Score the Bayesian R^2 given inputs X and outputs y.

StateSpaceTimeSeries.set_data(name, values)

Change the values of a data variable in the model.

StateSpaceTimeSeries.set_dim(name, new_length)

Update a mutable dimension.

StateSpaceTimeSeries.set_initval(rv_var, initval)

Set an initial value (strategy) for a random variable.

StateSpaceTimeSeries.shape_from_dims(dims)

StateSpaceTimeSeries.table(*[, ...])

Create a rich table summarizing the model's variables and their expressions.

StateSpaceTimeSeries.to_graphviz(*[, ...])

Produce a graphviz Digraph from a PyMC model.

Attributes

basic_RVs

List of random variables the model is defined in terms of.

continuous_value_vars

All the continuous value variables in the model.

coords

Coordinate values for model dimensions.

datalogp

PyTensor scalar of log-probability of the observed variables and potential terms.

default_priors

dim_lengths

The symbolic lengths of dimensions in the model.

discrete_value_vars

All the discrete value variables in the model.

isroot

observedlogp

PyTensor scalar of log-probability of the observed variables.

parent

potentiallogp

PyTensor scalar of log-probability of the Potential terms.

prefix

root

supports_prior_predictive

The Kalman smoothing/forecast path has no prior equivalent yet; a prior phase for this backend is tracked as a follow-up (issue #1092).

unobserved_RVs

List of all random variables, including deterministic ones.

unobserved_value_vars

List of all random variables (including untransformed projections), as well as deterministics used as inputs and outputs of the model's log-likelihood graph.

value_vars

List of unobserved random variables used as inputs to the model's log-likelihood (which excludes deterministics).

varlogp

PyTensor scalar of log-probability of the unobserved random variables (excluding deterministic).

varlogp_nojac

PyTensor scalar of log-probability of the unobserved random variables (excluding deterministic) without jacobian term.

__init__(level_order=2, seasonal_length=12, trend_component=None, seasonality_component=None, sample_kwargs=None, mode=None, priors=None, prior_sample_kwargs=None, vs_prior_type=None, vs_hyperparams=None)[source]#
Parameters:
  • sample_kwargs (dict[str, Any] | None) – Dictionary of kwargs that get unpacked and passed to the pymc.sample() function. Defaults to an empty dictionary if None.

  • priors (dict[str, Prior] | None) – Dictionary of priors for the model. Defaults to None, in which case default priors are used.

  • prior_sample_kwargs (dict[str, Any] | None) – Dictionary of kwargs that get unpacked and passed to the pymc.sample_prior_predictive() function when the prior predictive phase runs. Defaults to {"draws": 500} plus the posterior random_seed if None.

  • level_order (int)

  • seasonal_length (int)

  • trend_component (Any | None)

  • seasonality_component (Any | None)

  • mode (str | None)

  • vs_prior_type (Literal['spike_and_slab', 'horseshoe', 'normal'] | None)

  • vs_hyperparams (dict[str, Any] | None)

classmethod __new__(*args, **kwargs)#