-
-
Notifications
You must be signed in to change notification settings - Fork 69
Multivariate Structural Statespace Components #529
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jessegrabowski
wants to merge
61
commits into
pymc-devs:main
Choose a base branch
from
jessegrabowski:multivariate-structural
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,933
−2,052
Open
Changes from all commits
Commits
Show all changes
61 commits
Select commit
Hold shift + click to select a range
a70b733
Reorganize structural model module
jessegrabowski b970a6c
Allow combination of components with different numbers of observed st…
jessegrabowski 7cae487
Allow multiple observed in LevelTrend component
jessegrabowski bba8431
Allow multiple observed states in measurement error component
jessegrabowski 0a84576
Allow multiple observed in AutoRegressive component
jessegrabowski 480f4fb
Fix typo in docstrings
AlexAndorra a898eb6
Allow multiple observed in Cycle component
aandorra-mia 62d0750
Fix Cycle docstring examples
AlexAndorra 152e962
Use pytensor block_diag for Cycle
AlexAndorra 7e9bb07
1. updated level_trend component coord/param labels
Dekermanjian c0a4a47
1. removed incorrectly comitted file test_structural.py
Dekermanjian 1f3dc3a
removed incorrectly committed file structural.py
Dekermanjian 530f530
Merge pull request #3 from Dekermanjian/multivariate-structural
jessegrabowski 0c4590e
Always count names to determine k_endog
jessegrabowski 3c5124d
LevelTrend state/shock names depend on component name
jessegrabowski b932255
Update tests to new names
jessegrabowski 6debd23
More test updates
jessegrabowski fbc61a1
Delay dropping data names from states/coords until `.build`
jessegrabowski 85b78fe
Remove docstring typo
jessegrabowski a6327b7
Update autoregressive component and tests
jessegrabowski 5630256
1. updated regression component to revert to univariate shape schema …
Dekermanjian 0b20dbc
Add component name to shock state names
jessegrabowski a8564b7
Allow multiple observed in TimeSeasonality component
jessegrabowski bf38a4c
updated coord dimension names in regression component to always use t…
Dekermanjian 46e4a39
updated level_trend component so that component name is added as a pr…
Dekermanjian 7581f04
Allow multiple observed in FrequencySeasonality component
jessegrabowski a102e3c
Propagate static shape information in join_tensors_by_dim_labels wher…
jessegrabowski c694646
Regression component bugfix and tests
jessegrabowski f584e79
update default name in test
jessegrabowski 92eae7a
merged resolved conflicts
Dekermanjian ab98abe
Improve cycle code with Jesse's feedback
AlexAndorra 08818ad
Explicitly test matrices in test_cycle
AlexAndorra 505b7d0
Add test addition of two Cycles with different observed names
AlexAndorra 4fc8db2
Make code for state cov when no innov clearer
AlexAndorra 4b6ffcb
1. updated coords for level trend component and regression component
Dekermanjian 1085e24
1. added seasonality params coords fix from Alex Andorra
Dekermanjian 669bd10
1. updated param dims in regression component
Dekermanjian 486fa14
Add exog names to shock_names in LevelTrend
jessegrabowski de143ad
Update tests to respect new naming convention
jessegrabowski d0b6fd6
added multivariate forecast with exogenous variables test
Dekermanjian d123987
Merge branch 'multivariate-structural' of https://github.com/Dekerman…
Dekermanjian 7ca00d7
level_trend shock coords should be base_shock_names, not self.shock_n…
jessegrabowski 1c8b61a
Merge branch 'multivariate-structural' of https://github.com/Dekerman…
Dekermanjian c9458e7
Merge pull request #4 from Dekermanjian/multivariate-structural
jessegrabowski c15f965
Save static shape of last data dim
jessegrabowski f8e7729
More static shapes
jessegrabowski d38c71b
Broken test of decomposition with multiple observed
jessegrabowski ce14343
Don't use `pad`
jessegrabowski 503eec5
fix decompose test
jessegrabowski 77c27f4
updated leveltrend, seasonal, cycle components to adhere to naming sc…
Dekermanjian 08085c7
Merge pull request #5 from Dekermanjian/multivariate-structural
jessegrabowski 083e786
Delete notebook
jessegrabowski 66e0252
Use nwe name order in autoregressive component
jessegrabowski 21c64c6
Improve docstrings
AlexAndorra b94c9a3
Refactor test_regression to cover innotations = True
AlexAndorra ec98064
Fix comment in test_cycle
AlexAndorra 124e1c3
Add docstrings to core and measurement_error
AlexAndorra 9c14472
Improve cycle and seasonal docstrings
AlexAndorra 16761c7
Fix shape of AR params
AlexAndorra b71354a
Some other AR dims fixes
AlexAndorra fafc4c2
fix: handle numpy arrays and missing return cases in _combine_property
AlexAndorra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from pymc_extras.statespace.models.structural.components.autoregressive import ( | ||
AutoregressiveComponent, | ||
) | ||
from pymc_extras.statespace.models.structural.components.cycle import CycleComponent | ||
from pymc_extras.statespace.models.structural.components.level_trend import LevelTrendComponent | ||
from pymc_extras.statespace.models.structural.components.measurement_error import MeasurementError | ||
from pymc_extras.statespace.models.structural.components.regression import RegressionComponent | ||
from pymc_extras.statespace.models.structural.components.seasonality import ( | ||
FrequencySeasonality, | ||
TimeSeasonality, | ||
) | ||
|
||
__all__ = [ | ||
"LevelTrendComponent", | ||
"MeasurementError", | ||
"AutoregressiveComponent", | ||
"TimeSeasonality", | ||
"FrequencySeasonality", | ||
"RegressionComponent", | ||
"CycleComponent", | ||
] |
Empty file.
188 changes: 188 additions & 0 deletions
188
pymc_extras/statespace/models/structural/components/autoregressive.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
import numpy as np | ||
import pytensor.tensor as pt | ||
|
||
from pymc_extras.statespace.models.structural.core import Component | ||
from pymc_extras.statespace.models.structural.utils import order_to_mask | ||
from pymc_extras.statespace.utils.constants import AR_PARAM_DIM | ||
|
||
|
||
class AutoregressiveComponent(Component): | ||
r""" | ||
Autoregressive timeseries component | ||
|
||
Parameters | ||
---------- | ||
order: int or sequence of int | ||
|
||
If int, the number of lags to include in the model. | ||
If a sequence, an array-like of zeros and ones indicating which lags to include in the model. | ||
|
||
name: str, default "auto_regressive" | ||
A name for this autoregressive component. Used to label dimensions and coordinates. | ||
|
||
observed_state_names: list[str] | None, default None | ||
List of strings for observed state labels. If None, defaults to ["data"]. | ||
|
||
Notes | ||
----- | ||
An autoregressive component can be thought of as a way o introducing serially correlated errors into the model. | ||
The process is modeled: | ||
|
||
.. math:: | ||
x_t = \sum_{i=1}^p \rho_i x_{t-i} | ||
|
||
Where ``p``, the number of autoregressive terms to model, is the order of the process. By default, all lags up to | ||
``p`` are included in the model. To disable lags, pass a list of zeros and ones to the ``order`` argumnet. For | ||
example, ``order=[1, 1, 0, 1]`` would become: | ||
|
||
.. math:: | ||
x_t = \rho_1 x_{t-1} + \rho_2 x_{t-1} + \rho_4 x_{t-1} | ||
|
||
The coefficient :math:`\rho_3` has been constrained to zero. | ||
|
||
.. warning:: This class is meant to be used as a component in a structural time series model. For modeling of | ||
stationary processes with ARIMA, use ``statespace.BayesianSARIMA``. | ||
|
||
Examples | ||
-------- | ||
Model a timeseries as an AR(2) process with non-zero mean: | ||
|
||
.. code:: python | ||
|
||
from pymc_extras.statespace import structural as st | ||
import pymc as pm | ||
import pytensor.tensor as pt | ||
|
||
trend = st.LevelTrendComponent(order=1, innovations_order=0) | ||
ar = st.AutoregressiveComponent(2) | ||
ss_mod = (trend + ar).build() | ||
|
||
with pm.Model(coords=ss_mod.coords) as model: | ||
P0 = pm.Deterministic('P0', pt.eye(ss_mod.k_states) * 10, dims=ss_mod.param_dims['P0']) | ||
intitial_trend = pm.Normal('initial_trend', sigma=10, dims=ss_mod.param_dims['initial_trend']) | ||
ar_params = pm.Normal('ar_params', dims=ss_mod.param_dims['ar_params']) | ||
sigma_ar = pm.Exponential('sigma_ar', 1, dims=ss_mod.param_dims['sigma_ar']) | ||
|
||
ss_mod.build_statespace_graph(data) | ||
idata = pm.sample(nuts_sampler='numpyro') | ||
|
||
""" | ||
|
||
def __init__( | ||
self, | ||
order: int = 1, | ||
name: str = "auto_regressive", | ||
observed_state_names: list[str] | None = None, | ||
): | ||
if observed_state_names is None: | ||
observed_state_names = ["data"] | ||
|
||
k_posdef = k_endog = len(observed_state_names) | ||
|
||
order = order_to_mask(order) | ||
ar_lags = np.flatnonzero(order).ravel().astype(int) + 1 | ||
k_states = len(order) | ||
|
||
self.order = order | ||
self.ar_lags = ar_lags | ||
|
||
super().__init__( | ||
name=name, | ||
k_endog=k_endog, | ||
k_states=k_states * k_endog, | ||
k_posdef=k_posdef, | ||
measurement_error=True, | ||
combine_hidden_states=True, | ||
observed_state_names=observed_state_names, | ||
obs_state_idxs=np.tile(np.r_[[1.0], np.zeros(k_states - 1)], k_endog), | ||
) | ||
|
||
def populate_component_properties(self): | ||
k_states = self.k_states // self.k_endog # this is also the number of AR lags | ||
|
||
self.state_names = [ | ||
f"L{i + 1}[{state_name}]" | ||
for state_name in self.observed_state_names | ||
for i in range(k_states) | ||
] | ||
|
||
self.shock_names = [f"{self.name}[{obs_name}]" for obs_name in self.observed_state_names] | ||
self.param_names = [f"params_{self.name}", f"sigma_{self.name}"] | ||
self.param_dims = {f"params_{self.name}": (f"lag_{self.name}",)} | ||
self.coords = {f"lag_{self.name}": self.ar_lags.tolist()} | ||
|
||
if self.k_endog > 1: | ||
self.param_dims[f"params_{self.name}"] = ( | ||
f"endog_{self.name}", | ||
AR_PARAM_DIM, | ||
) | ||
self.param_dims[f"sigma_{self.name}"] = (f"endog_{self.name}",) | ||
|
||
self.coords[f"endog_{self.name}"] = self.observed_state_names | ||
|
||
self.param_info = { | ||
f"params_{self.name}": { | ||
"shape": (k_states,) if self.k_endog == 1 else (self.k_endog, k_states), | ||
"constraints": None, | ||
"dims": (AR_PARAM_DIM,) | ||
if self.k_endog == 1 | ||
else ( | ||
f"endog_{self.name}", | ||
f"lag_{self.name}", | ||
), | ||
}, | ||
f"sigma_{self.name}": { | ||
"shape": () if self.k_endog == 1 else (self.k_endog,), | ||
"constraints": "Positive", | ||
"dims": None if self.k_endog == 1 else (f"endog_{self.name}",), | ||
}, | ||
} | ||
|
||
def make_symbolic_graph(self) -> None: | ||
k_endog = self.k_endog | ||
k_states = self.k_states // k_endog | ||
k_posdef = self.k_posdef | ||
|
||
k_nonzero = int(sum(self.order)) | ||
ar_params = self.make_and_register_variable( | ||
f"params_{self.name}", shape=(k_nonzero,) if k_endog == 1 else (k_endog, k_nonzero) | ||
) | ||
sigma_ar = self.make_and_register_variable( | ||
f"sigma_{self.name}", shape=() if k_endog == 1 else (k_endog,) | ||
) | ||
|
||
if k_endog == 1: | ||
T = pt.eye(k_states, k=-1) | ||
ar_idx = (np.zeros(k_nonzero, dtype="int"), np.nonzero(self.order)[0]) | ||
T = T[ar_idx].set(ar_params) | ||
|
||
else: | ||
transition_matrices = [] | ||
|
||
for i in range(k_endog): | ||
T = pt.eye(k_states, k=-1) | ||
ar_idx = (np.zeros(k_nonzero, dtype="int"), np.nonzero(self.order)[0]) | ||
T = T[ar_idx].set(ar_params[i]) | ||
transition_matrices.append(T) | ||
T = pt.specify_shape( | ||
pt.linalg.block_diag(*transition_matrices), (self.k_states, self.k_states) | ||
) | ||
|
||
self.ssm["transition", :, :] = T | ||
|
||
R = np.eye(k_states) | ||
R_mask = np.full((k_states), False) | ||
R_mask[0] = True | ||
R = R[:, R_mask] | ||
|
||
self.ssm["selection", :, :] = pt.specify_shape( | ||
pt.linalg.block_diag(*[R for _ in range(k_endog)]), (self.k_states, self.k_posdef) | ||
) | ||
|
||
Z = pt.zeros((1, k_states))[0, 0].set(1.0) | ||
self.ssm["design", :, :] = pt.specify_shape( | ||
pt.linalg.block_diag(*[Z for _ in range(k_endog)]), (self.k_endog, self.k_states) | ||
) | ||
AlexAndorra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
cov_idx = ("state_cov", *np.diag_indices(k_posdef)) | ||
self.ssm[cov_idx] = sigma_ar**2 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.