Repository navigation
BUG: Return the input variance from constrain_stationary_multivariate - #11051
Merged
bashtage merged 13 commits intoNov 27, 2026
Merged
Conversation
bashtage
force-pushed
the
wip-ss-constrain-variance-return
branch
from
November 23, 2026 22:10
609bad8 to
3ebf9a3
Compare
4 of 5 tasks
bashtage
force-pushed
the
wip-ss-constrain-variance-return
branch
from
November 24, 2026 16:16
3ebf9a3 to
e265a8b
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 25, 2026
This branch is now stacked on statsmodels#11051, which makes constrain_stationary_multivariate (and its public Python twin) return the input variance with transform_variance=False. The private helpers of the twin still return the variance of the internal recursion, so test_python_twin_helpers_default_dimensions failed for transform_variance=False once both were merged (found by merging all open branches and running the test suite). The coefficients are compared in both cases and the variance with transform_variance=True.
bashtage
force-pushed
the
wip-ss-constrain-variance-return
branch
from
November 25, 2026 12:12
e265a8b to
dc354e4
Compare
This was referenced Nov 25, 2026
With a block initialization in which some blocks are diffuse and others known (or stationary), the CFA simulation smoother (`simulation_smoother(method="cfa")`) depended on the order in which the blocks were set. The compiled statespace resets `initialized_diffuse` for each block, so the flag describes only the block set last, and the CFA used it to treat the whole initial state as diffuse or as known: - known block set last: it inverted the full initial state covariance matrix, which is singular for the diffuse block, and raised "LinAlgError: Non-positive-definite initial state covariance matrix"; - diffuse block set last: it gave every state prior precision zero, so the known block's mean and covariance were ignored and the posterior mean, covariance and draws were silently wrong (for example 0.485 instead of the Kalman smoother's 2.091 in a two-state model with a known state of mean 3 and variance 0.5). Changes - The CFA takes the diffuse states from the diffuse part of the initial state covariance matrix (nonzero diagonal). They have prior precision zero; the precision of the other states is the inverse of their block of the initial state covariance matrix. A non-positive-definite block raises LinAlgError as before. - A whole-state diffuse or known initialization uses the same code as before. - The class docstring no longer says that diffuse initialization is not available (an exact diffuse initialization of the whole state already worked) and has a `versionchanged` note. Not changed - `initialized_diffuse` of the compiled statespace (no longer used by the CFA; nothing else reads it). Tests (test_cfa_simulation_smoothing.py) - A three-state model with two observed series, for four block layouts (diffuse block first or last, a known block of two correlated states, a diffuse block between two known ones) and for a whole-state diffuse and known initialization: the posterior mean, the draw with zero variates and the per-period blocks of the posterior covariance equal the exact diffuse Kalman smoother's smoothed state and covariance (rtol 1e-6; the two methods agree to about 1e-8 for this model). The smoother first runs with a known initialization of all states, so values left from that run would show. - A known block with a singular covariance matrix raises LinAlgError for every layout.
SmootherResults.smoothed_state_autocovariance caches its results when
extend_kwargs is None or empty, with the key (lag, t, start, end). For
lag < -1 the default end depends on whether extend_kwargs is None: without
it the last -lag - 1 autocovariances, which need the model beyond the
sample, are not computed (the result has nobs + lag + 1 periods), while
with extend_kwargs={} they are computed for a time-invariant model (nobs
periods). Both calls shared the key, so the second call returned the
result of the first, and the shape depended on the order of the calls.
The Returns section also said that for a time-invariant model and
lag < -1 the default result has nobs periods. The code returns
nobs + lag + 1 periods without extend_kwargs for time-invariant and
time-varying models alike.
Changes:
- The cache key includes whether extend_kwargs is None.
- The Returns section and the Notes describe what the code returns:
without extend_kwargs the result has nobs + lag + 1 periods, with it
nobs; extend_kwargs={} is enough for a time-invariant model, and a
time-varying model needs -lag - 1 additional matrices.
Not changed: the result of the first call in each case, so each default
keeps the result it gave when called first.
Tests (appended to test_smoothing.py): for lag -2 and -3 and both call
orders, the result without extend_kwargs has nobs + lag + 1 periods and
the result with extend_kwargs={} has nobs, and both equal Cov(alpha_t,
alpha_{t - lag}) from the joint posterior covariance of the states of the
CFA simulation smoother (in the sample) and, beyond the sample, the last
in-sample covariance times powers of the transposed transition matrix.
KalmanSmoother.smooth() ignored several of its documented arguments: - complex_step was not passed to the Kalman filter, so a stationary initialization of the state was computed as for real parameters (with a conjugating transpose). MLEModel.smooth(params, complex_step=True) passes it on, so its complex-step derivatives were wrong: for an AR(2) the imaginary part of llf / h was -9.17 instead of -10.28 (filter() and finite differences give -10.28). - smooth_method was not passed to the smoother, so the smoothing method of the model was always used. - results, run_filter and prefix had no effect. They lost their purpose when the filter and smoother were split into _filter and _smooth in 2016 (50669b1): smooth() always runs the filter and returns a new object of the model's results class, and the filter has no prefix argument. - _initialize_smoother passed its prefix to _initialize_filter as the first positional argument, which is filter_method. prefix was always None, but smooth(filter_method=...) raised "TypeError: got multiple values for argument 'filter_method'". Changes: - smooth() passes complex_step to _filter and smooth_method to _smooth. - A smooth_method that cannot smooth the output of the filter that ran (univariate smoothing without univariate filtering, or the reverse) would now raise "Invalid smoothing method". On main it was ignored and the model's method was used, so it is still ignored, with a FutureWarning that it will raise after statsmodels 0.17 is released. - _initialize_smoother calls _initialize_filter(**kwargs); the unused prefix argument of _initialize_smoother and the unused prefix, complex_step and results arguments of the private _smooth are removed. - Passing results, run_filter or prefix to smooth() now raises a FutureWarning; they will be removed after statsmodels 0.17 is released. run_filter now defaults to None so that passing it can be detected. The output does not change. Not changed: the results without complex_step or smooth_method, and all other arguments. With complex_step, the smoothed state and its covariance in the first period are still wrong: the results re-initialize the state without complex_step (in update_representation) before the smoother reads the initial state covariance again (a separate bug). Tests (appended to test_smoothing.py): - smooth(complex_step=True), through MLEModel.smooth and through KalmanSmoother.smooth, gives the complex-step derivative of the loglikelihood of filter(complex_step=True), and the derivatives of the loglikelihood and the smoothed state (after the first period) agree with central finite differences. - smooth(smooth_method=SMOOTH_UNIVARIATE) with the conventional filter, and smooth(smooth_method=SMOOTH_CONVENTIONAL) with the univariate filter, warn and give the output of the model's method; the methods that can be used do not warn. With the univariate filter, SMOOTH_UNIVARIATE overrides a model set to the conventional smoother (which raises), for that call only; the output equals the default univariate smoother and agrees with the conventional filter and smoother. - smooth(filter_method=FILTER_UNIVARIATE) uses the univariate filter and equals a model set to it. - results, run_filter and prefix warn, from the caller, and the output equals a call without them; no warning without them.
test_smooth_complex_step fails on both Azure macOS jobs (build 10564): with a step of 1e-20 the complex-step derivative of the loglikelihood is -7305 instead of -29.44 (also for filter(), on main). The stationary initialization solves the Lyapunov equation with a complex Schur decomposition (_tools.pyx.in), whose intermediate results can have imaginary parts of order one, depending on the Schur vectors that the LAPACK library returns (OpenBLAS returns real vectors here, macOS's library apparently not). Their rounding error of about 1e-16 then dominates the imaginary part of a 1e-20 step: on Windows the same happens for AR(2) models with complex roots (phi = (0.5, -0.5): 7120 instead of -28.53, also on main). With the step that MLEModel.score uses (about 1e-8), the error is 1e-8 relative and every case agrees with central differences, so the library's own scores are not affected. The test now uses h = 1e-8. It still fails with the smoother of main (5.5% difference between the derivatives of smooth() and filter()).
With statsmodels#11044, `smooth(complex_step=True)` passes `complex_step` to the Kalman filter, but the complex-step derivative of the smoothed state was still wrong in the first period. For SARIMAX(2, 0, 0) and `mod.smooth([0.5 + 1e-20j, 0.2, 1.0], complex_step=True)`, `imag(smoothed_state[:, 0]) / 1e-20` was [-0.294, -0.064], while central finite differences give [0, 0.025]; `smoothed_state_cov[:, :, 0]` was off by up to 4.4. The derivatives of the loglikelihood and of the later periods were right. The cause is `FrozenRepresentation.update_representation`, which the results objects of `filter` and `smooth` call after the filter has run: it initialized the compiled statespace object again, without `complex_step`, to take a snapshot of the initial state. That replaced the complex-step stationary initialization that the filter used, and the smoother reads the initial state covariance again in the first period. The snapshot itself, `initial_state_cov` of the results of `filter(complex_step=True)` and `smooth(complex_step=True)`, also had a wrong imaginary part. Changes - `update_representation` takes the snapshot from the compiled statespace object as the filter left it, and initializes the object only if it has not been initialized yet (a results object created directly for a model that has not been filtered). Not changed - Results without complex step: the snapshot holds the same values as before (the filter has just initialized the object with the same initialization). - The filter output and the loglikelihood, which were already right. Tests - `test_smooth_complex_step` (from statsmodels#11044) now checks the first period of the smoothed state too. - For `filter` and `smooth` with complex step of a SARIMAX(2, 0, 0) with measurement error, the real part of `initial_state_cov` equals the stationary covariance from `scipy.linalg.solve_discrete_lyapunov` and its imaginary part equals the central differences of it; for `smooth` also the first period of `smoothed_state_cov` against central differences. These 4 tests fail on the base. - A results object created for a model whose compiled statespace exists but is not initialized (after `simulation_smoother()`) still stores the stationary covariance (passes on the base too; it covers the remaining initialization).
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.
…ial_state_cov A step of 1e-20 is dominated by the rounding of the complex Schur decomposition of the stationary initialization on some LAPACK libraries (see test_smooth_complex_step, which fails on the Azure macOS jobs with it). The test still fails without the fix (2 of 2 cases).
constrain_stationary_multivariate and its Python twin constrain_stationary_multivariate_python document that the returned variance is the input variance unless transform_variance=True. With transform_variance=False they returned an internal variance instead: the Ansley-Kohn recursion is then run from a large scaled identity ((order + k_endog)**10 times the identity) and the coefficients are transformed back to the input variance at the end, but the scaled final forward variance was returned (about 7e5 for a 2 x 2 input with order 2). The coefficients were right; with the returned variance unconstrain_stationary_multivariate did not recover the unconstrained matrices. constrain_stationary_multivariate also had no docstring of its own: it reused the Python twin's, which names the argument error_variance instead of variance. Changes: - With transform_variance=False both functions return the input variance (as an array of the computed dtype for the compiled function). - constrain_stationary_multivariate has its own numpydoc docstring naming variance, so the unused Appender import is removed. Not changed: the constrained coefficients, the variance with transform_variance=True, and the callers in VARMAX and DynamicFactor (they do not use the returned variance). Tests (appended to test_tools.py): for both functions, with an array and a list of matrices and both values of transform_variance, unconstrain_stationary_multivariate with the returned variance recovers the unconstrained matrices, the input variance is not changed, and without the transformation the returned variance equals the input and is a copy of it.
bashtage
force-pushed
the
wip-ss-constrain-variance-return
branch
from
November 27, 2026 00:32
dc354e4 to
8e10bf2
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 27, 2026
This branch is now stacked on statsmodels#11051, which makes constrain_stationary_multivariate (and its public Python twin) return the input variance with transform_variance=False. The private helpers of the twin still return the variance of the internal recursion, so test_python_twin_helpers_default_dimensions failed for transform_variance=False once both were merged (found by merging all open branches and running the test suite). The coefficients are compared in both cases and the variance with transform_variance=True.
bashtage
marked this pull request as ready for review
November 27, 2026 10:04
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.
Stacked on #11113, which is stacked on #11044, #11047 and #11140: merge those first (this PR adds one commit). The stack was rebuilt on 2026-11-25 so that it merges without conflicts in this order; notes about conflicts with PRs of the same stack no longer apply.
Based on main; #11025 (the C9b coverage chunk) changes docstrings of the same files and appends to the same test files, so whichever merges second needs a rebase. With #11025:
test_tools.py, keep both blocks. It also needs a semantic fix: #11025'stest_python_twin_helpers_default_dimensionscompares the variance returned by the private Python helper (the internal variance) with that ofconstrain_stationary_multivariate, which this PR changes to the input variance, so its 4transform_variance=Falsecases fail after both merge. In that test compare the variances only iftransform_variance, and otherwise check that the returned variance equals the input. The other C9F-B PRs that append totest_tools.py(companion matrix, constrained variance, array_like inputs) conflict there too: keep every appended block.constrain_stationary_multivariate and its Python twin
constrain_stationary_multivariate_python document that the returned
variance is the input variance unless transform_variance=True. With
transform_variance=False they returned an internal variance instead: the
Ansley-Kohn recursion is then run from a large scaled identity
((order + k_endog)**10 times the identity) and the coefficients are
transformed back to the input variance at the end, but the scaled final
forward variance was returned (about 7e5 for a 2 x 2 input with order 2).
The coefficients were right; with the returned variance
unconstrain_stationary_multivariate did not recover the unconstrained
matrices.
constrain_stationary_multivariate also had no docstring of its own: it
reused the Python twin's, which names the argument error_variance instead
of variance.
Changes:
(as an array of the computed dtype for the compiled function).
variance, so the unused Appender import is removed.
Not changed: the constrained coefficients, the variance with
transform_variance=True, and the callers in VARMAX and DynamicFactor
(they do not use the returned variance).
Tests (appended to test_tools.py): for both functions, with an array and
a list of matrices and both values of transform_variance,
unconstrain_stationary_multivariate with the returned variance recovers
the unconstrained matrices, the input variance is not changed, and
without the transformation the returned variance equals the input and is
a copy of it.
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: finding the bug in a contract audit, writing the fix and its tests, and checking them (tests failing on main, 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