Skip to content

TST: Cover the statespace representation, Kalman filter and initialization - #11028

Merged
bashtage merged 5 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c9a
Nov 24, 2026
Merged

bashtage merged 5 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c9a

Conversation

@bashtage

Copy link
Copy Markdown
Member

Close the coverage gaps of tsa/statespace/representation.py, kalman_filter.py and initialization.py through 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 in stl/tests/results. The source changes are docstrings only.

Changes

  • Representation: the "known" initialization keywords and errors, invalid initialization names, clone dimension and time-varying errors, extend with default, negative and 1-dim arguments, the extend, diff_endog and bind errors, an incomplete Initialization, and FrozenRepresentation without an initialization.
  • FilterResults and PredictionResults: 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.
  • KalmanFilter options: INVERT_CHOLESKY and INVERT_LU on 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 with k_posdef=0; the filter timing keywords and fixed_scale; options passed to filter.
  • Initialization: the from_components errors, all-diffuse components, the approximate diffuse variance, a constant with exact diffuse initialization, unset of an empty index, and the __call__ stationarity check.
  • innovations_algo with a negative rtol. 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 compiled stl-fixed.f90; R's stl uses a different partial sort for the robustness weights, so it is not a reference for robust STL).
  • Docstrings: the k_endog shapes, k_posdef (transition equation), statespace_classes, clone/extend/diff_endog; the set_* examples (they ran on a range and showed wrong bitmasks), the defaults and Returns of filter, random_state in simulate, impulse response shapes and rows; the FilterResults and PredictionResults attributes, and the Initialization examples and set.

Not changed

No behaviour changes. Bugs found in the audit are fixed separately, and no test asserts the current behaviour of those paths: filter_timing and tolerance passed to filter are swapped; inversion and filter methods passed to filter are not reflected in the results; filtered_forecasts_error_cov/smoothed_forecasts_error_cov return None when read first; npredictions is negative; initial_variance is never set; impulse_responses rejects numpy integers and ignores direct; diff_endog with a 1-dim array; Initialization.set with an Initialization object for all states.

Tests

  • statsmodels/tsa/statespace and tsa/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.py 95.2% to 99.5% lines and 88.6% to 98.1% branches; kalman_filter.py 96.9% to 99.7% and 87.9% to 98.5%; initialization.py 95.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=true build): 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.pyx and stl/_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.

  • No AI tools were used to develop this pull request.
  • AI tools were 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

…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
bashtage marked this pull request as ready for review November 24, 2026 00:41
@bashtage
bashtage merged commit 7a4c633 into statsmodels:main Nov 24, 2026
10 of 11 checks passed
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
bashtage deleted the wip-tsa-cov-c9a branch November 24, 2026 15:56
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant