Repository navigation
REF: Remove dead Cython statespace code, mark unreachable hooks no cover - #11073
Merged
Merged
Conversation
Univariate filtering (filter_univariate=True, the exact diffuse periods, and the fallback of the conventional filter when the forecast error covariance is singular) diagonalizes a non-diagonal obs_cov with the LDL decomposition in _tools.pyx.in. Its check of definiteness was wrong: - It tested the sign of the original diagonal element A[j, j] instead of the pivot d(j) after the update, so a negative pivot (an indefinite matrix) went unnoticed: [[1, 2], [2, 1]] gave a loglikelihood of -8.07e34 with univariate filtering, and -2.55e14 with the conventional filter, which falls back to it. - It reported a negative first diagonal element as info = -j = 0, that is, as positive definite: [[-1, 0.5], [0.5, 1]] gave -51454. - A zero diagonal element was taken as a zero pivot whatever the rest of its column, and the "zero the column" statement had no assignment: [[1, 0.5], [0.5, 0]] and [[0, 1], [1, 1]], both indefinite, only warned that the matrix is positive semi-definite, and gave -204 and -241. - A rank-deficient positive semi-definite matrix did not warn, and an exactly singular one such as u u' with u = (1, 2, 3) raised ZeroDivisionError (0 / 0 in the update of the column). Changes - A pivot is compared with the original diagonal element, with the relative tolerance 1e-10, instead of comparing the diagonal element with the absolute tolerance 1e-15. - A negative diagonal element, or a pivot below -1e-10 * A[j, j], means that the matrix is indefinite: info = -(j + 1), which raises the existing LinAlgError "Invalid value in LDL factorization of observation covariance matrix". - A pivot with |d(j)| <= 1e-10 * A[j, j] whose column below, after the update, is below 1e-10 * sqrt(A[i, i] * A[j, j]) is a zero pivot: that column is set to zero (a positive pivot itself is kept), and the existing positive semi-definite warning is issued. - If the column below such a pivot is not small, a zero or negative pivot means that the matrix is indefinite, and a positive one is used as an ordinary pivot (an ill-conditioned positive definite matrix). - The Notes of set_filter_method describe the warning and the error (versionchanged 0.15.1). Not changed - Positive definite matrices keep their results. Their pivots are processed with the same operations in the same order as before, also for ill-conditioned ones: L D L' with L = [[1, 0, 0], [0.3, 1, 0], [0.2, 5e5, 1]] and D = diag(1, 1e-12, 0.75) (condition number 2e12) gives the same loglikelihood, without a warning. The exception is a pivot below 1e-10 times its diagonal element whose column below is also below the tolerance (condition number above about 1e10): such a matrix now warns that it is positive semi-definite. If the pivot is the last one, the result is unchanged; otherwise the small column is set to zero, and the factorization still reproduces the matrix to about 1e-10 (relative). Only matrices too ill-conditioned for double precision (condition number above about 1e16) can come out indefinite and raise; before, these mostly produced a negative variance. - The texts of the warning and of the LinAlgError. Tests - test_univariate_psd_obs_cov: rank-1 (2x2 and 3x3) and rank-2 matrices, among them three u u' with u of shape (3, 2) whose last pivot rounds to about -1e-15 times its diagonal element (main gave the conventional loglikelihood for them, without a warning), a matrix with a zero row, and [[1, 1], [1, 1 + 1e-12]]: univariate filtering warns and gives the loglikelihood of the conventional filter, which does not decompose obs_cov, with float64 and with complex-step (complex128) filtering. All but the zero row fail on main. - test_univariate_pd_obs_cov: positive definite matrices, including [[1, 1], [1, 1 + 1e-8]] and [[1e-11, 1e-9], [1e-9, 1]] (the tolerance is relative), do not warn and give the conventional loglikelihood, as on main. - test_univariate_ill_conditioned_pd_obs_cov: the L D L' example above gives main's loglikelihood (-297.21603787944184) without a warning or an error, and agrees with the conventional filter to the precision its conditioning allows. - test_univariate_small_last_pivot_kept: a positive definite obs_cov whose last pivot (5e-11) is below the tolerance warns and keeps the pivot. That matters here, because the states add little variance in that direction (setting the pivot to zero would change the loglikelihood by 4%); it agrees with the conventional filter. It fails on main, which does not warn. - test_univariate_indefinite_obs_cov_raises: a negative pivot, a negative first or second diagonal element, a zero diagonal element, and zero pivots with a nonzero column (2x2, 3x3, and a rescaled 3x3) raise the LinAlgError. All but the negative second diagonal element, which raised on main, fail on main. - The existing tests of a non-diagonal obs_cov use X X' with X of rank 2, so univariate filtering warns for it now; they expect the warning.
Collapsed filtering (filter_collapsed=True) replaces the observation vector
by a vector with k_states elements, which needs the inverse of
Z_t' H_t^{-1} Z_t: in each period with more observed series than states,
the rows of the design matrix that belong to the observed series must have
full column rank. When they did not, filtering raised "LinAlgError:
Non-positive-definite ZHZ matrix encountered at period 0", which did not
say what was wrong. For example, DynamicFactor(endog, k_factors=1,
factor_order=2) with ssm.filter_collapsed = True raised it for any
parameters, because the lagged factor is a state with a zero column in the
design matrix. The requirement was not documented.
Changes
- The error names the requirement: "Collapsed filtering requires a design
matrix of full column rank, but the design matrix of the observed series
is not of full column rank (Z' H^{-1} Z is not positive definite) at
period t". It is still a LinAlgError, which is a ValueError, so code
that catches either keeps working.
- The FILTER_COLLAPSED entry in the Notes of set_filter_method, and the
filter_collapsed attribute, document the requirement (versionchanged
0.15.1).
Not changed
- Models whose design matrix has full column rank.
- Where the error is raised: in the compiled filter, at the decomposition
that fails. A check in Python before filtering
(KalmanFilter._initialize_filter) would also run for unconditional
simulation, impulse responses and the creation of a simulation smoother,
which do not collapse and work with such a design matrix on main. The
compiled check covers time-varying design matrices, missing data and the
simulation smoother at no extra cost.
- subset_design, the Cython hook that would collapse only the first
k_posdef states, stays unused.
Tests
- DynamicFactor(k_factors=1, factor_order=2) with filter_collapsed raises
the error at period 0.
- A model with 4 series and 2 states, whose second state loads only on the
second series, raises it at period 10, where the second series is
missing and the other 3 are observed.
- When the periods in which the design matrix of the observed series has
rank 1 have no more observed series than states, nothing is collapsed in
those periods, and the loglikelihood equals that of the conventional
filter.
- The two tests of the error fail on main (other message).
A line coverage measurement of the compiled statespace code (Linux, Cython
line tracing) found float64 template lines that nothing can reach: methods
without a caller, statements that cannot run, the code under three Cython
API flags that nothing in Python sets, and LAPACK error branches that no
input reaches. This removes the first two kinds and marks the other two
"pragma: no cover". All edits are in the .pyx.in templates (and the .pxd
declarations, _stl.pyx).
Changes
- Removed, because nothing calls them:
- the cdef methods _forecasting, _inversion, _updating,
_calculate_loglikelihood and _prediction of KalmanFilter (their calls
in __next__ were commented out), with their declarations in
_kalman_filter.pxd;
- the Cython Statespace.initialize_stationary (the Python
Representation.initialize_stationary goes through Initialization);
- the module-level cpdef wrappers sldl, dldl, cldl and zldl in _tools,
with their declarations in _tools.pxd (the cdef _ldl stays).
- Removed statements that cannot run:
- in KalmanFilter.__next__, the re-raise when the filter was already
univariate: the univariate inversion is a no-op that cannot raise;
- in KalmanFilter.check_convergence, the return for t = 0 with filtered
timing: the enclosing test requires t >= nobs_diffuse + 1;
- in Statespace.transform_generalized_collapse, the check
k_endog < k_states: the collapse only runs with more observed series
than states (and KalmanFilter.set_filter_method raises first);
- in arma_innovations_algo_fast, a continue: for n >= m the loop already
starts at k = n + 1 - q;
- in _is_pos_int of STL, a try/except around a comparison that only runs
for integers.
- "# pragma: no cover" on the traced lines:
- under the subset_design, companion_transition and identity_transition
flags (hooks of the Cython API that nothing in Python sets), including
companion_predicted_state and companion_predicted_state_cov, which
only run under companion_transition;
- of the LAPACK error branches that cannot be reached: illegal-argument
codes of ?potrf, ?getrf, ?trtrs, ?potrs, ?getrs and ?pbtrf, a singular
factor reported by ?trtrs after a successful ?potrf or for a unit
diagonal, and the ?potrf of the inverse of a positive definite matrix;
and of two defensive ones, a failure of ?gees in the Lyapunov solver
and of ?pbtrf for the joint CFA posterior;
- of the callbacks that ?gees requires but never calls with sort='N'.
Cython.Coverage excludes only the line that carries the pragma, not the
block below it, so every traced line has its own (including the
continuation line of a multi-line raise, where the % formatting is
traced).
- The Cython validate_matrix_shape printed the actual number of columns
twice and had no space before "got".
Not changed
- Results. The statespace, innovations, STL and ARIMA tests pass, and 116
outputs of representative models (loglikelihoods, filtered and smoothed
states and covariances, forecasts and their covariances, KFS simulation
smoother draws, the CFA posterior mean and draw, ARMA innovations, STL
components) are bitwise identical to those of the base build, covering
the conventional, univariate, exact diffuse, collapsed, Chandrasekhar
and concentrated filters, filtered timing, the Cholesky and LU
inversions and the conventional, univariate, alternative and classical
smoothers.
- The nobs checks of the Cython validate_matrix_shape and
validate_vector_shape: Statespace.__init__ passes nobs, so they are
reachable through the Cython API (the Python layer validates first).
- The max shift of the order-0 logsumexp in the Hamilton filter, which
statsmodels#11001 changes.
Tests
- No new tests (refactoring). Linux coverage build (WSL, Python 3.12,
Cython 3.3.1, Cython.Coverage), with the statespace, innovations, STL
and ARIMA tests (4049 passed, before and after): the 19 measured .pyx
files have 16971 traced lines with 8659 missed before, and 16400 with
8126 missed after. All 328 generated lines that carry the pragma (82
template lines, 4 dtypes each) are excluded, none of them is reported
as missed, and no other line is excluded. For float64, the only covered
lines that disappear are removed ones.
- Windows: the same tests pass, and the outputs listed above are bitwise
identical to those of the base build.
This was referenced Nov 23, 2026
bashtage
marked this pull request as ready for review
November 23, 2026 21:13
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 #11072, which is stacked on #11071: merge those first (their commits are the first two of the three here). #11026 (
_simulation_smoother.pyx.in) and #11027 (_tools.pyx.in) change the same templates and merge cleanly. #11028 (the C9a chunk) also appends totest_collapsed.py: keep both appended blocks.BUG: Detect indefinite observation covariances in the univariate LDL
Univariate filtering (filter_univariate=True, the exact diffuse periods, and
the fallback of the conventional filter when the forecast error covariance
is singular) diagonalizes a non-diagonal obs_cov with the LDL decomposition
in _tools.pyx.in. Its check of definiteness was wrong:
the pivot d(j) after the update, so a negative pivot (an indefinite
matrix) went unnoticed: [[1, 2], [2, 1]] gave a loglikelihood of -8.07e34
with univariate filtering, and -2.55e14 with the conventional filter,
which falls back to it.
as positive definite: [[-1, 0.5], [0.5, 1]] gave -51454.
its column, and the "zero the column" statement had no assignment:
[[1, 0.5], [0.5, 0]] and [[0, 1], [1, 1]], both indefinite, only warned
that the matrix is positive semi-definite, and gave -204 and -241.
exactly singular one such as u u' with u = (1, 2, 3) raised
ZeroDivisionError (0 / 0 in the update of the column).
Changes
tolerance 1e-10, instead of comparing the diagonal element with the
absolute tolerance 1e-15.
that the matrix is indefinite: info = -(j + 1), which raises the existing
LinAlgError "Invalid value in LDL factorization of observation covariance
matrix".
update, is below 1e-10 * sqrt(A[i, i] * A[j, j]) is a zero pivot: that
column is set to zero (a positive pivot itself is kept), and the existing
positive semi-definite warning is issued.
means that the matrix is indefinite, and a positive one is used as an
ordinary pivot (an ill-conditioned positive definite matrix).
(versionchanged 0.15.1).
Not changed
with the same operations in the same order as before, also for
ill-conditioned ones: L D L' with L = [[1, 0, 0], [0.3, 1, 0],
[0.2, 5e5, 1]] and D = diag(1, 1e-12, 0.75) (condition number 2e12)
gives the same loglikelihood, without a warning. The exception is a
pivot below 1e-10 times its diagonal element whose column below is also
below the tolerance (condition number above about 1e10): such a matrix
now warns that it is positive semi-definite. If the pivot is the last
one, the result is unchanged; otherwise the small column is set to zero,
and the factorization still reproduces the matrix to about 1e-10
(relative). Only matrices too ill-conditioned for double precision
(condition number above about 1e16) can come out indefinite and raise;
before, these mostly produced a negative variance.
Tests
among them three u u' with u of shape (3, 2) whose last pivot rounds to
about -1e-15 times its diagonal element (main gave the conventional
loglikelihood for them, without a warning), a matrix with a zero row, and
[[1, 1], [1, 1 + 1e-12]]: univariate filtering warns and gives the
loglikelihood of the conventional filter, which does not decompose
obs_cov, with float64 and with complex-step (complex128) filtering. All
but the zero row fail on main.
[[1, 1], [1, 1 + 1e-8]] and [[1e-11, 1e-9], [1e-9, 1]] (the tolerance is
relative), do not warn and give the conventional loglikelihood, as on
main.
gives main's loglikelihood (-297.21603787944184) without a warning or an
error, and agrees with the conventional filter to the precision its
conditioning allows.
last pivot (5e-11) is below the tolerance warns and keeps the pivot. That
matters here, because the states add little variance in that direction
(setting the pivot to zero would change the loglikelihood by 4%); it
agrees with the conventional filter. It fails on main, which does not
warn.
first or second diagonal element, a zero diagonal element, and zero
pivots with a nonzero column (2x2, 3x3, and a rescaled 3x3) raise the
LinAlgError. All but the negative second diagonal element, which raised
on main, fail on main.
so univariate filtering warns for it now; they expect the warning.
BUG: Name the full column rank requirement of collapsed filtering
Collapsed filtering (filter_collapsed=True) replaces the observation vector
by a vector with k_states elements, which needs the inverse of
Z_t' H_t^{-1} Z_t: in each period with more observed series than states,
the rows of the design matrix that belong to the observed series must have
full column rank. When they did not, filtering raised "LinAlgError:
Non-positive-definite ZHZ matrix encountered at period 0", which did not
say what was wrong. For example, DynamicFactor(endog, k_factors=1,
factor_order=2) with ssm.filter_collapsed = True raised it for any
parameters, because the lagged factor is a state with a zero column in the
design matrix. The requirement was not documented.
Changes
matrix of full column rank, but the design matrix of the observed series
is not of full column rank (Z' H^{-1} Z is not positive definite) at
period t". It is still a LinAlgError, which is a ValueError, so code
that catches either keeps working.
filter_collapsed attribute, document the requirement (versionchanged
0.15.1).
Not changed
that fails. A check in Python before filtering
(KalmanFilter._initialize_filter) would also run for unconditional
simulation, impulse responses and the creation of a simulation smoother,
which do not collapse and work with such a design matrix on main. The
compiled check covers time-varying design matrices, missing data and the
simulation smoother at no extra cost.
k_posdef states, stays unused.
Tests
the error at period 0.
second series, raises it at period 10, where the second series is
missing and the other 3 are observed.
rank 1 have no more observed series than states, nothing is collapsed in
those periods, and the loglikelihood equals that of the conventional
filter.
REF: Remove dead Cython statespace code, mark unreachable hooks no cover
A line coverage measurement of the compiled statespace code (Linux, Cython
line tracing) found float64 template lines that nothing can reach: methods
without a caller, statements that cannot run, the code under three Cython
API flags that nothing in Python sets, and LAPACK error branches that no
input reaches. This removes the first two kinds and marks the other two
"pragma: no cover". All edits are in the .pyx.in templates (and the .pxd
declarations, _stl.pyx).
Changes
_calculate_loglikelihood and _prediction of KalmanFilter (their calls
in next were commented out), with their declarations in
_kalman_filter.pxd;
Representation.initialize_stationary goes through Initialization);
with their declarations in _tools.pxd (the cdef _ldl stays).
univariate: the univariate inversion is a no-op that cannot raise;
timing: the enclosing test requires t >= nobs_diffuse + 1;
k_endog < k_states: the collapse only runs with more observed series
than states (and KalmanFilter.set_filter_method raises first);
starts at k = n + 1 - q;
for integers.
flags (hooks of the Cython API that nothing in Python sets), including
companion_predicted_state and companion_predicted_state_cov, which
only run under companion_transition;
codes of ?potrf, ?getrf, ?trtrs, ?potrs, ?getrs and ?pbtrf, a singular
factor reported by ?trtrs after a successful ?potrf or for a unit
diagonal, and the ?potrf of the inverse of a positive definite matrix;
and of two defensive ones, a failure of ?gees in the Lyapunov solver
and of ?pbtrf for the joint CFA posterior;
Cython.Coverage excludes only the line that carries the pragma, not the
block below it, so every traced line has its own (including the
continuation line of a multi-line raise, where the % formatting is
traced).
twice and had no space before "got".
Not changed
outputs of representative models (loglikelihoods, filtered and smoothed
states and covariances, forecasts and their covariances, KFS simulation
smoother draws, the CFA posterior mean and draw, ARMA innovations, STL
components) are bitwise identical to those of the base build, covering
the conventional, univariate, exact diffuse, collapsed, Chandrasekhar
and concentrated filters, filtered timing, the Cholesky and LU
inversions and the conventional, univariate, alternative and classical
smoothers.
validate_vector_shape: Statespace.init passes nobs, so they are
reachable through the Cython API (the Python layer validates first).
BUG: Avoid underflow in the log-sum-exp of the Hamilton filter #11001 changes.
Tests
No new tests (refactoring). Linux coverage build (WSL, Python 3.12,
Cython 3.3.1, Cython.Coverage), with the statespace, innovations, STL
and ARIMA tests (4049 passed, before and after): the 19 measured .pyx
files have 16971 traced lines with 8659 missed before, and 16400 with
8126 missed after. All 328 generated lines that carry the pragma (82
template lines, 4 dtypes each) are excluded, none of them is reported
as missed, and no other line is excluded. For float64, the only covered
lines that disappear are removed ones.
Windows: the same tests pass, and the outputs listed above are bitwise
identical to those of the base build.
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: finding the unreachable code in a coverage audit, removing it, and checking that the results do not change.
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