Repository navigation
TST: Cover the statespace representation, Kalman filter and initialization - #11028
Merged
Merged
Conversation
This was referenced Nov 22, 2026
bashtage
force-pushed
the
wip-tsa-cov-c9a
branch
from
November 23, 2026 19:14
e6fc816 to
958ba1d
Compare
…ation Close the coverage gaps of tsa/statespace/representation.py, kalman_filter.py and initialization.py through public paths, and the float64 filter options of the compiled filter that no test reached. Every assertion compares with an independent value: another filter method on the same model, a closed form, or the reference Fortran STL. - Representation: the "known" initialization keywords and errors, invalid initialization names, clone with the current dimensions and the errors for other dimensions or time-varying matrices, extend with the default and negative start and end and a 1-dim endog (against the concatenated data), the extend, diff_endog and bind errors, a 1-dim observation in bind, an incomplete Initialization, and FrozenRepresentation of a model without an initialization. - FilterResults: update_representation(only_options=True); kalman_gain without a stored gain against the gain the filter stores (complete, partially and entirely missing observations); forecasts of partially missing and collapsed observations when only the mean or only the covariance is stored, against Z a_t + d, Z P_t Z' + H, the filter's own values and the conventional filter of the uncollapsed series. - PredictionResults: the signal covariances read before the signals, the filtered and smoothed forecasts, against Z a_t (+ d) and Z P_t Z' (+ H); a time-varying intercept with static, dynamic and out-of-sample periods. - KalmanFilter: impulse responses for a column impulse against Z T^h R impulse and the time-varying error; the filter timing keywords; fixed_scale without a concentrated filter; options passed to filter against the same options set on the model. - Compiled filter options: INVERT_CHOLESKY and INVERT_LU on their own, for one and two series, filtered and smoothed, and with memory conservation, against SOLVE_CHOLESKY and SOLVE_LU; invalid inversion and filter methods; the collapsed-filter errors (fewer series than states, a concentrated likelihood, an observation intercept, a negative observation variance); filtered timing with exact diffuse initialization; a negative forecast variance in an exact diffuse period is set to zero; stationary initialization with k_posdef=0 against the closed form and the known initialization. - Initialization: the from_components errors and an all-diffuse initialization, the approximate diffuse variance for all states and for a block, a constant with exact diffuse initialization (warning, and the same loglikelihood as without it), unset of an empty index, and the stationarity check of __call__. - innovations_algo with a negative rtol. - STL: a cycle-subseries with one value and robust STL with an outlier block longer than the trend window (with and without jumps), against the stl-fixed.f90 reference; robust weights when the fit is exact at most points, against the non-robust fit.
… code - Representation and KalmanFilter: the shapes of an ndarray `k_endog` (a 1-dim array is one observation), `k_posdef` describes the transition equation (also in FrozenRepresentation and FilterResults), the `statespace_classes` parameter and the `constant`/`stationary_cov` spellings of the known initialization. - Representation.clone needs an ndarray endog; extend's `start` and `end` select the data as well as time-varying matrices, `end` is excluded and both may be negative; diff_endog needs an ndarray shaped (nobs, k_endog). - KalmanFilter: the examples of the set_* methods ran on a range, which SARIMAX rejects, and showed wrong bitmask values; the stale SciPy 0.16 note; set_filter_timing's argument and keywords; the defaults of filter are the model's settings, and its Returns section; the second `rng` of simulate is `random_state`; simulate and impulse_responses need a SimulationSmoother; the impulse shapes, the unused `direct` and the number of rows of impulse_responses for time-varying models. - FilterResults: `initialization` is an Initialization, the `llf` and `scale` attributes, and update_filter takes the compiled filter. - PredictionResults: `nforecast` counts out-of-sample forecasts. - Initialization: there is no 'exact_diffuse' type, the block examples used a one-state block for two values and lacked continuation prompts, set accepts a slice, and the default approximate diffuse variance is that of the object.
bashtage
force-pushed
the
wip-tsa-cov-c9a
branch
from
November 23, 2026 21:45
958ba1d to
725090f
Compare
bashtage
marked this pull request as ready for review
November 24, 2026 00:41
4 of 5 tasks
bashtage
added a commit
that referenced
this pull request
Nov 24, 2026
The docstring of `FilterResults.predict` said that "the last prediction will be at end", but `end` is excluded, as the end of a slice: for a model with 20 observations, `predict(start=2, end=5)` returns the 3 predictions for periods 2, 3 and 4, `predict()` (whose default `end` is the number of observations) returns the 20 in-sample predictions, and `predict(start=18, end=22)` returns 2 in-sample predictions and 2 out-of-sample forecasts. The `end` parameter and attribute of `PredictionResults`, which receive this `end`, and the private `_check_dynamic` had the same mistake. Changes - The `end` parameter of `FilterResults.predict` says that it is excluded, with its default. - The same for the `end` parameter and attribute of `PredictionResults`, and for `end` of `_check_dynamic`. Not changed - The code. (`nforecast` of `PredictionResults` is documented as the number of in-sample forecasts, but #11028 already fixes that.)
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 25, 2026
The `versionchanged` note of the `complex_step` argument also says that the results no longer initialize the state again without complex step, which made the derivatives of the first period of the smoothed state and of `initial_state_cov` wrong. `KalmanFilter.filter`, whose results had the wrong `initial_state_cov` too, gets no note here because statsmodels#11028, statsmodels#11035 and statsmodels#11036 change its docstring and code next to `complex_step`; the release note covers it.
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 25, 2026
The `versionchanged` note of the `complex_step` argument also says that the results no longer initialize the state again without complex step, which made the derivatives of the first period of the smoothed state and of `initial_state_cov` wrong. `KalmanFilter.filter`, whose results had the wrong `initial_state_cov` too, gets no note here because statsmodels#11028, statsmodels#11035 and statsmodels#11036 change its docstring and code next to `complex_step`; the release note covers it.
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 27, 2026
The `versionchanged` note of the `complex_step` argument also says that the results no longer initialize the state again without complex step, which made the derivatives of the first period of the smoothed state and of `initial_state_cov` wrong. `KalmanFilter.filter`, whose results had the wrong `initial_state_cov` too, gets no note here because statsmodels#11028, statsmodels#11035 and statsmodels#11036 change its docstring and code next to `complex_step`; the release note covers it.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Close the coverage gaps of
tsa/statespace/representation.py,kalman_filter.pyandinitialization.pythrough public paths, test the float64 filter options of the compiled filter that no test reached (found by a Cython coverage audit), and align the docstrings with what the code does. The tests compare with references independent of the code: another filter method on the same model (INVERT vs SOLVE inversions, collapsed vs conventional filtering, the stored vs the recomputed Kalman gain), closed forms (Z a + d, Z P Z' + H, Z T^h R impulses, the stationary mean and covariance), and the Fortran STL instl/tests/results. The source changes are docstrings only.Changes
clonedimension and time-varying errors,extendwith default, negative and 1-dim arguments, theextend,diff_endogandbinderrors, an incomplete Initialization, andFrozenRepresentationwithout an initialization.update_representation(only_options=True); the Kalman gain when it is not stored; the forecasts of partially missing and collapsed observations when only the mean or only the covariance is stored; the signal covariances read before the signals; time-varying intercepts with dynamic and out-of-sample periods.INVERT_CHOLESKYandINVERT_LUon their own (one and two series, smoothing, memory conservation); invalid inversion and filter methods; the collapsed-filter errors, and filtered timing with exact diffuse initialization; clipping of a negative forecast variance in a diffuse period; stationary initialization withk_posdef=0; the filter timing keywords andfixed_scale; options passed tofilter.from_componentserrors, all-diffuse components, the approximate diffuse variance, a constant with exact diffuse initialization,unsetof an empty index, and the__call__stationarity check.innovations_algowith a negativertol. STL with a one-value cycle-subseries, robust weights for an exact fit, and blocks of outliers longer than the trend window (references from the compiledstl-fixed.f90; R'sstluses a different partial sort for the robustness weights, so it is not a reference for robust STL).k_endogshapes,k_posdef(transition equation),statespace_classes,clone/extend/diff_endog; theset_*examples (they ran on arangeand showed wrong bitmasks), the defaults and Returns offilter,random_stateinsimulate, impulse response shapes and rows; the FilterResults and PredictionResults attributes, and the Initialization examples andset.Not changed
No behaviour changes. Bugs found in the audit are fixed separately, and no test asserts the current behaviour of those paths:
filter_timingandtolerancepassed tofilterare swapped; inversion and filter methods passed tofilterare not reflected in the results;filtered_forecasts_error_cov/smoothed_forecasts_error_covreturn None when read first;npredictionsis negative;initial_varianceis never set;impulse_responsesrejects numpy integers and ignoresdirect;diff_endogwith a 1-dim array;Initialization.setwith an Initialization object for all states.Tests
statsmodels/tsa/statespaceandtsa/tests/test_stattools.py: 4943 passed, no warnings. The new STL tests pass on a current build of_stl(Linux, Python 3.12).Coverage:
representation.py95.2% to 99.5% lines and 88.6% to 98.1% branches;kalman_filter.py96.9% to 99.7% and 87.9% to 98.5%;initialization.py95.4% to 100% and 90.7% to 99.3%. What remains is unreachable, or reachable only through the bugs above.Cython (measured together with TST: Cover the statespace smoothers, simulation smoothers and tools #11025 on a
-Dcython-coverage=truebuild): the tests of the two PRs reach 143 lines of the compiled filters, smoothers, tools, innovations and STL that the full TSA test suite did not; this PR's share is mainly_filters/_inversions.pyx(+36),_kalman_filter.pyxandstl/_stl.pyx.Mutation check: 41 single-line changes to the covered code, each caught by a new test.
tests added / passed.
code/documentation is well formatted.
properly formatted commit message. See
NumPy's guide.
AI Disclosure
Contributions must comply with the statsmodels AI Policy.
Tick exactly one of the following. If AI tools were used, replace the
<...>placeholders in the second option with the tool name(s) and how the tool's output was
used.
Tool(s): Claude Code (Claude Opus 5.5).
Used for: auditing the coverage gaps and docstrings of the statespace representation, Kalman filter and initialization, writing the tests and docstring fixes, and checking them (coverage, mutation check).
I have personally read, understood, and can explain every line of this diff, and
have verified the statistical/numerical correctness of the change.
🤖 Generated with Claude Code