Skip to content

BUG: Allow non-OPG covariance matrices when every parameter is fixed - #11156

Draft
bashtage wants to merge 6 commits into
statsmodels:mainfrom
bashtage:wip-mlemodel-robust-all-fixed
Draft

bashtage wants to merge 6 commits into
statsmodels:mainfrom
bashtage:wip-mlemodel-robust-all-fixed

Conversation

@bashtage

Copy link
Copy Markdown
Member

Stacked on #11130, which is stacked on #11063: merge those first (their commits are the first ones here; this PR adds one commit). It changes the robust covariance lines that #11130 changes. No conflict in mlemodel.py with the other open PRs. Other open statespace PRs also append tests at the end of the same test file: keep both appended blocks.

REF: Remove unreachable code in mlemodel

A coverage audit of statespace/mlemodel.py found private code that no
public path can reach. It is removed; results do not change.

Changes

  • _forecasts_error_partial_derivatives: its two callers
    (observed_information_matrix and the Harvey scores) always pass the
    filter output at the parameters and a resolved approx_complex_step, and
    check that complex-step derivatives are only used with transformed
    parameters (the Harvey scores always pass transformed parameters). The
    default for approx_complex_step, the check, and the filtering when res
    is None are removed; res is a required keyword argument.
  • MLEModel.simulate, MLEModel.impulse_responses and MLEResults.simulate:
    the location of the anchor from _get_index_loc is never negative (a
    negative integer is converted to a location from the end, and dates
    before the sample raise a KeyError), so the "if iloc < 0" branches are
    removed.
  • _cov_params_robust_oim and _cov_params_robust_approx: they compute the
    OPG matrix first, which sets the rank of the covariance matrix, so their
    own "if self._rank is None" updates never ran and are removed.
  • _get_robustcov_results: the statements after "raise
    NotImplementedError" are removed.

Not changed

  • The _state_names hook, which mirrors _param_names.
  • The rank of the robust covariance matrices, which stays the rank of the
    OPG matrix.

Tests

  • A negative integer anchor in MLEModel.simulate and MLEResults.simulate
    gives the same simulations as the equivalent location, with and without
    a date index, for a model with exog (so that the simulations depend on
    the anchor). The negative anchor of impulse_responses is already tested
    in test_impulse_responses.py.
  • The removed lines were not covered by the statespace tests on main; no
    line that was covered before is missing now.

BUG: Use the rank of the robust covariance in state space summaries

The summary of state space results (MLEResults) warns that the covariance
matrix is singular when the results' _rank is below the number of free
parameters. With cov_type="robust_approx" (and "robust"/"robust_oim"),
_rank was the rank of the outer product of gradients (OPG) matrix: the
robust matrix, inv(H inv(OPG) H), computes the OPG matrix first, which
sets the rank, so the robust matrix's own rank update could never run
(#11063 removes it as unreachable). The robust matrix has the rank of H,
which can be lower. For white noise with a regressor, at the OLS
coefficient and twice the mean squared residual as variance, the Hessian
of the loglikelihood is diag(-sum(x**2) / s2, 0) (rank 1) and the OPG
matrix has rank 2; the robust_approx matrix has rank 1, but the summary
did not warn. This is the same change as #11068 for the Markov switching
models.

Changes

  • _cov_params_robust_oim and _cov_params_robust_approx set _rank to the
    rank of the robust matrix when no rank is set yet, that is when it is
    the covariance matrix of the results, as the approx, oim and opg
    matrices do for theirs. Results with another cov_type keep the rank of
    their own matrix when a robust matrix is computed later.
  • versionchanged in the cov_params_robust_oim and cov_params_robust_approx
    docstrings.

The summary of robust_approx results can now warn that the covariance
matrix is singular (or stop warning, if the OPG rank was lower). For
"robust" (Harvey's OIM matrix as H), the two ranks are equal in exact
arithmetic: a direction in which the OIM matrix is singular has zero
derivatives of the forecast errors and their variances, so every score is
zero in it and the OPG matrix is singular there too; the numerical ranks
can only differ through rounding.

Not changed

  • The covariance matrices and standard errors.
  • The rank and warning of results with cov_type "approx", "oim", "opg",
    "none" and "custom".

Tests

  • test_summary_singular_warning_follows_robust_cov_type: at the singular
    point above, robust_approx and approx results warn and the others do
    not, and the rank of cov_params() is the closed-form rank of each
    matrix (robust_approx fails on REF: Remove unreachable code in mlemodel #11063's branch and on main); after the
    other robust matrices are computed as well (rank 2 and 1), each result
    keeps the rank of its own matrix. At the MLE, all six cov types have
    rank 2 and none warns.

BUG: Allow non-OPG covariance matrices when every parameter is fixed

With every parameter of a state space model fixed (fix_params), the "oim",
"approx", "robust", "robust_oim" and "robust_approx" covariance matrices
raised "ValueError: zero-size array to reduction operation maximum", from
pinv_extended of the empty matrix of the free parameters (and from the rank
of its singular values). This affected fit and smooth with one of those
cov_type values, and the cov_params_oim, cov_params_approx and
cov_params_robust* attributes of any results. The "opg" matrix already
handled this case: it is NaN, with rank 0, so that the summary does not
warn about a singular matrix.

Stacked on #11130 (the rank of the robust covariance matrices), which
changes the same lines.

Changes

  • A helper returns the pseudo-inverse and rank of a matrix, an empty
    pseudo-inverse and rank 0 for an empty matrix. The four covariance
    methods use it, so that with every parameter fixed their matrix is NaN
    (as for "opg") and their rank 0.

Not changed

  • The "opg" covariance matrix, and the matrices with at least one free
    parameter (the same pseudo-inverse and rank as before).

Tests (test_mlemodel.py)

  • SARIMAX(1, 0, 0) with both parameters fixed, fitted with each of the
    five covariance types: the covariance matrix and standard errors are
    NaN as with "opg", the log-likelihood equals that of the "opg" fit, the
    summary marks the parameters as fixed and does not warn that the
    covariance matrix is singular, and the corresponding attribute of the
    "opg" results is NaN. All five fail on BUG: Use the rank of the robust covariance in state space summaries #11130.

  • 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: finding the bug in a coverage audit of the state space code, 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

A coverage audit of statespace/mlemodel.py found private code that no
public path can reach. It is removed; results do not change.

Changes
- _forecasts_error_partial_derivatives: its two callers
  (observed_information_matrix and the Harvey scores) always pass the
  filter output at the parameters and a resolved approx_complex_step, and
  check that complex-step derivatives are only used with transformed
  parameters (the Harvey scores always pass transformed parameters). The
  default for approx_complex_step, the check, and the filtering when `res`
  is None are removed; `res` is a required keyword argument.
- MLEModel.simulate, MLEModel.impulse_responses and MLEResults.simulate:
  the location of the anchor from _get_index_loc is never negative (a
  negative integer is converted to a location from the end, and dates
  before the sample raise a KeyError), so the "if iloc < 0" branches are
  removed.
- _cov_params_robust_oim and _cov_params_robust_approx: they compute the
  OPG matrix first, which sets the rank of the covariance matrix, so their
  own "if self._rank is None" updates never ran and are removed.
- _get_robustcov_results: the statements after "raise
  NotImplementedError" are removed.

Not changed
- The _state_names hook, which mirrors _param_names.
- The rank of the robust covariance matrices, which stays the rank of the
  OPG matrix.

Tests
- A negative integer anchor in MLEModel.simulate and MLEResults.simulate
  gives the same simulations as the equivalent location, with and without
  a date index, for a model with exog (so that the simulations depend on
  the anchor). The negative anchor of impulse_responses is already tested
  in test_impulse_responses.py.
- The removed lines were not covered by the statespace tests on main; no
  line that was covered before is missing now.
The summary of state space results (MLEResults) warns that the covariance
matrix is singular when the results' _rank is below the number of free
parameters. With cov_type="robust_approx" (and "robust"/"robust_oim"),
_rank was the rank of the outer product of gradients (OPG) matrix: the
robust matrix, inv(H inv(OPG) H), computes the OPG matrix first, which
sets the rank, so the robust matrix's own rank update could never run
(statsmodels#11063 removes it as unreachable). The robust matrix has the rank of H,
which can be lower. For white noise with a regressor, at the OLS
coefficient and twice the mean squared residual as variance, the Hessian
of the loglikelihood is diag(-sum(x**2) / s2, 0) (rank 1) and the OPG
matrix has rank 2; the robust_approx matrix has rank 1, but the summary
did not warn. This is the same change as statsmodels#11068 for the Markov switching
models.

Changes
- _cov_params_robust_oim and _cov_params_robust_approx set _rank to the
  rank of the robust matrix when no rank is set yet, that is when it is
  the covariance matrix of the results, as the approx, oim and opg
  matrices do for theirs. Results with another cov_type keep the rank of
  their own matrix when a robust matrix is computed later.
- versionchanged in the cov_params_robust_oim and cov_params_robust_approx
  docstrings.

The summary of robust_approx results can now warn that the covariance
matrix is singular (or stop warning, if the OPG rank was lower). For
"robust" (Harvey's OIM matrix as H), the two ranks are equal in exact
arithmetic: a direction in which the OIM matrix is singular has zero
derivatives of the forecast errors and their variances, so every score is
zero in it and the OPG matrix is singular there too; the numerical ranks
can only differ through rounding.

Not changed
- The covariance matrices and standard errors.
- The rank and warning of results with cov_type "approx", "oim", "opg",
  "none" and "custom".

Tests
- test_summary_singular_warning_follows_robust_cov_type: at the singular
  point above, robust_approx and approx results warn and the others do
  not, and the rank of cov_params() is the closed-form rank of each
  matrix (robust_approx fails on statsmodels#11063's branch and on main); after the
  other robust matrices are computed as well (rank 2 and 1), each result
  keeps the rank of its own matrix. At the MLE, all six cov types have
  rank 2 and none warns.
The GitHub Actions coverage job (Linux, Python 3.13) failed
test_summary_singular_warning_follows_robust_cov_type[False-approx-2-1]:
the cov_params of cov_type="approx" had rank 2, not 1. The zero entry of
the numerical Hessian at that point is the difference of two complex-step
evaluations that agree to within about one ulp, so it is 0 (locally) or
about 3e-11, 1e-12 relative to the other entry (on CI), and the numerical
rank is 1 or 2. Adding one ulp to that entry reproduces the failure.

For that case, check that the matrix is singular to the accuracy of the
finite differences (a singular value ratio below 1e-8; it is 0.3 at the
MLE) and that the summary warning follows the rank of the results' own
matrix. The robust_approx case keeps its rank 1: the robust matrix
squares the relative size of that entry (1e-24) and stays below the rank
tolerance unless the entry is off by about 3000 ulps.
With every parameter of a state space model fixed (fix_params), the "oim",
"approx", "robust", "robust_oim" and "robust_approx" covariance matrices
raised "ValueError: zero-size array to reduction operation maximum", from
pinv_extended of the empty matrix of the free parameters (and from the rank
of its singular values). This affected fit and smooth with one of those
cov_type values, and the cov_params_oim, cov_params_approx and
cov_params_robust* attributes of any results. The "opg" matrix already
handled this case: it is NaN, with rank 0, so that the summary does not
warn about a singular matrix.

Stacked on statsmodels#11130 (the rank of the robust covariance matrices), which
changes the same lines.

Changes
- A helper returns the pseudo-inverse and rank of a matrix, an empty
  pseudo-inverse and rank 0 for an empty matrix. The four covariance
  methods use it, so that with every parameter fixed their matrix is NaN
  (as for "opg") and their rank 0.

Not changed
- The "opg" covariance matrix, and the matrices with at least one free
  parameter (the same pseudo-inverse and rank as before).

Tests (test_mlemodel.py)
- SARIMAX(1, 0, 0) with both parameters fixed, fitted with each of the
  five covariance types: the covariance matrix and standard errors are
  NaN as with "opg", the log-likelihood equals that of the "opg" fit, the
  summary marks the parameters as fixed and does not warn that the
  covariance matrix is singular, and the corresponding attribute of the
  "opg" results is NaN. All five fail on statsmodels#11130.
@bashtage
bashtage force-pushed the wip-mlemodel-robust-all-fixed branch from 283cdcc to 41e12a0 Compare November 28, 2026 21:36
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