Repository navigation
BUG: Keep the complex-step initial state in state space results - #11113
Merged
bashtage merged 11 commits intoNov 27, 2026
Merged
Conversation
This was referenced Nov 23, 2026
bashtage
force-pushed
the
wip-ss-smooth-complex-step-init
branch
2 times, most recently
from
November 25, 2026 12:13
f5794d2 to
fce871a
Compare
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).
bashtage
force-pushed
the
wip-ss-smooth-complex-step-init
branch
from
November 27, 2026 00:32
fce871a to
01eed4f
Compare
bashtage
marked this pull request as ready for review
November 27, 2026 10:05
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 #11044, which is stacked on #11047 and #11140: merge those first (this PR adds three commits). 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. It passes
complex_stepto the filter, and its test of the derivative of the smoothed state now includes the first period. The conflicts with #11025, #11045, #11047 and #11054 are those of #11044 (therun_filter/prefixdocstring ofsmoothwith #11025, the imports and the appended test blocks); this PR adds none.BUG: Use the complex_step and smooth_method arguments of smooth()
KalmanSmoother.smooth() ignored several of its documented arguments:
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).
the model was always used.
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.
positional argument, which is filter_method. prefix was always None, but
smooth(filter_method=...) raised "TypeError: got multiple values for
argument 'filter_method'".
Changes:
(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.
prefix argument of _initialize_smoother and the unused prefix,
complex_step and results arguments of the private _smooth are removed.
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):
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.
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.
equals a model set to it.
equals a call without them; no warning without them.
BUG: Keep the complex-step initial state in state space results
With #11044,
smooth(complex_step=True)passescomplex_stepto theKalman 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-20was [-0.294, -0.064], while centralfinite differences give [0, 0.025];
smoothed_state_cov[:, :, 0]was offby up to 4.4. The derivatives of the loglikelihood and of the later
periods were right.
The cause is
FrozenRepresentation.update_representation, which theresults objects of
filterandsmoothcall after the filter has run: itinitialized 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_covof the results offilter(complex_step=True)andsmooth(complex_step=True), also had a wrong imaginary part.Changes
update_representationtakes the snapshot from the compiled statespaceobject 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
before (the filter has just initialized the object with the same
initialization).
Tests
test_smooth_complex_step(from BUG: Use the complex_step and smooth_method arguments of smooth() #11044) now checks the first period ofthe smoothed state too.
filterandsmoothwith complex step of a SARIMAX(2, 0, 0) withmeasurement error, the real part of
initial_state_covequals thestationary covariance from
scipy.linalg.solve_discrete_lyapunovandits imaginary part equals the central differences of it; for
smoothalso the first period of
smoothed_state_covagainst centraldifferences. These 4 tests fail on the base.
but is not initialized (after
simulation_smoother()) still stores thestationary covariance (passes on the base too; it covers the remaining
initialization).
DOC: Note the complex-step initial state in KalmanSmoother.smooth
The
versionchangednote of thecomplex_stepargument also says thatthe 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_covwrong.KalmanFilter.filter, whose results had thewrong
initial_state_covtoo, gets no note here because #11028, #11035and #11036 change its docstring and code next to
complex_step; therelease note covers 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 coverage audit of the state space models, writing the fix and its tests, and checking them (tests failing on the base, 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