Skip to content

TST: Cover the remaining MLEModel and MLEResults paths - #11029

Merged
bashtage merged 4 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c10
Nov 25, 2026
Merged

bashtage merged 4 commits into
statsmodels:mainfrom
bashtage:wip-tsa-cov-c10

Conversation

@bashtage

@bashtage bashtage commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Stacked on #11114, which is stacked on #11064 and #11056: merge those first (this PR adds two 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.

Adds tests for the paths of statsmodels/tsa/statespace/mlemodel.py that the TSA tests did not reach, and corrects the docstrings where they disagree with the code. Each test checks against an independent value: closed forms for an AR(1) and a VARX(1), another derivative method on the same model, an extension or refit against the whole sample, or scipy and acorr_ljungbox on the standardized residuals. The source changes are docstrings only.

Changes

  • Closed forms for the AR(1): the likelihood, the Harvey scores per observation and the Harvey information matrix (complex step, forward and centered differences); the outer product of gradients and the Hessian (complex step and finite differences); the covariance matrix from finite differences and its description; aicc; forecasts and their variances with a date steps; simulations anchored by an integer, a negative integer, a date or a partial date, with a drawn or per-repetition initial state.
  • The complex-step filter and smoother against finite differences. Impulse responses of a model with a time-varying transition, and of a regression with a random-walk coefficient beyond the sample.
  • news: revision, update and total impacts with a date revisions_details_start, state_index and return_raw; a comparison dataset with longer exog; extension of time-varying updated results, univariate and multivariate.
  • append with refit, with and without fixed parameters; extend with results_class=FilterResults; fit from unconstrained start values and with extra flags; results_class or results_wrapper_class given alone; low-memory predictions.
  • summary with display_max_endog, extra rows, and the condition-number warning with a fixed parameter; plot_diagnostics with a variable name, a truncated title, dates or integer positions, and acf_kwargs.
  • Error and warning paths.
  • Docstrings: Returns sections; the flag-style *args of score/hessian; the cov_type and cov_kwds references (they pointed to methods that do not exist); parameter order; the duplicated rng entry; return types for pandas data; use_f=False for the chi-squared heteroskedasticity test; the information_set values; the PredictionResults argument.

Not changed

No code changes. Bugs found in the audit are fixed separately, and no test asserts the current behaviour of those paths: positional flags in loglike/score/hessian raise since 0.15.0; the observed information matrix with untransformed or fixed parameters; score_obs with transformed=False (Harvey) and its default approx_complex_step; univariate news with longer exog; numpy integer steps; smoothed predictions after a low-memory filter; list params in hessian/transform_jacobian; and smaller ones. Unreachable branches are left in place and listed separately.

Tests

  • Coverage of mlemodel.py by the TSA tests: lines 93.2% to 99.1%, branches 85.4% to 97.5%.

  • Mutation check: 60 single-line changes to newly covered lines, all caught except a finite-difference step size that the 10% tolerance (the accuracy of the centered finite-difference Hessian) cannot catch, and one change with no public effect.

  • statsmodels/tsa/statespace: 3522 passed, no leaked warnings; the test file also passes on pandas 2.3.3.

  • 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 mlemodel.py, 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

This was referenced Nov 22, 2026
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 24, 2026
MLEModel.score_obs with transformed=False gave wrong scores in two cases.

- The "harvey" method dropped `transformed` and treated the untransformed
  parameters as transformed. For SARIMAX(1, 0, 0) with a trend on the
  macrodata inflation series, at the untransformed values of
  [1, 0.5, 4], the scores summed to [532.1, 3413.7, 1202.9]; the score
  is [49.7, -178.3, 84.5].
- The check that rejects complex-step derivatives with transformed=False
  ran before the default of approx_complex_step was resolved, so by
  default the complex step was applied through transform_params. That is
  only right for transformations that are complex differentiable. For a
  VAR(1) with a constant on GDP and consumption growth, 5 of the 9
  summed scores were wrong (for example -70.12 instead of -13.27).

Changes
- With transformed=False, the "harvey" method and complex-step
  differentiation compute the scores with respect to the transformed
  parameters, as with transformed=True, and multiply them by the Jacobian
  of the transformation (centered differences), as score and hessian do.
- With the default complex step, the result for models whose
  transformation is complex differentiable (for example SARIMAX) is that
  of 0.15.0 to about 1e-10 relative.
- The docstring says so, with a versionchanged note.

Not changed
- Finite differences with the "approx" method still differentiate
  loglikeobs through the transformation, so their results are unchanged.
- An explicit approx_complex_step=True with transformed=False still
  raises (as statsmodels#11029 tests).
- With fixed parameters and includes_fixed=False, all of the paths of
  score_obs with transformed=False evaluate the likelihood with the fixed
  values transformed as if they were unconstrained, and return a column
  for each parameter. That is a separate bug and is left as it is; the
  new paths agree with the finite differences there.

Tests
- For SARIMAX(2, 0, 1), a VAR(2), a dynamic factor model and an AR(1),
  the "approx" and "harvey" scores with the default and with finite
  differences match centered differences of loglikeobs with respect to
  the untransformed parameters, and sum to score. The harvey cases for all
  models and the default for the VAR(2) and the dynamic factor model fail
  on main.
- The default and harvey results are the chain rule applied to the
  results for the transformed parameters, to 1e-8 (for SARIMAX, this is
  main's default result).
- The "approx" finite differences are unchanged, and with
  includes_fixed=True and fixed parameters the scores are those of the
  model without fixed parameters.
Add tests of the paths of statespace/mlemodel.py that the TSA test suite
did not reach, each checked against an independent value:

- closed forms for an AR(1) model with the stationary initialization:
  loglikelihood, Harvey scores per observation, the Harvey (1989)
  information matrix (complex step, forward and centered finite
  differences), the outer product of gradients, the Hessian (complex step
  and finite differences), the finite difference covariance matrix and its
  description, aicc, forecasts and their variances with a date `steps`,
  simulations from an anchor given as an integer, a negative integer, a
  date and a partial date (a slice of dates), with an initial state drawn
  from the predicted state, and with one initial state per repetition;
- complex-step filtering and smoothing of a bivariate model against
  centered finite differences of the loglikelihood;
- impulse responses of a model with a time-varying transition from an
  anchor, and of a regression with a random walk coefficient beyond the
  sample, with the new exog of the extended model;
- news: impacts of a revision and an update against the AR(1) closed
  forms with a date `revisions_details_start` and `state_index`, the raw
  output, a comparison dataset with a longer exog (VARX closed forms), and
  time-varying models whose updated results are extended, univariate and
  multivariate;
- append with refit, with and without fixed parameters, extend of a model
  that only filters (results_class=FilterResults), fit from unconstrained
  start parameters and with extra flags, results_class or
  results_wrapper_class alone, low memory predictions;
- summary with display_max_endog against acorr_ljungbox, the breakvar
  test and scipy's Jarque-Bera, skew and kurtosis of the standardized
  residuals; the condition number of the free parameters in the warning of
  a singular covariance matrix with a fixed parameter; plot_diagnostics
  with a variable name, a truncated title, dates or integer positions and
  acf_kwargs;
- the errors: a flag given positionally and by keyword, complex-step
  derivatives with complex data or unconstrained parameters, anchors
  outside the sample, out-of-sample exog, invalid `state_index` and
  comparison shapes, Lütkepohl criteria with a time-varying state
  covariance, news without the smoother, and the warnings of an
  unsupported index and of ignored exog.

Coverage of mlemodel.py by the TSA tests goes from 93.2% to 99.1% of the
lines and from 85.4% to 97.5% of the branches.
Fix the docstrings of statespace/mlemodel.py where they disagree with the
code. No code changes.

- MLEModel.fit returns an array if `return_params` is True; `callback` is
  a callable.
- filter and smooth: the covariance options are those of MLEModel.fit
  (there is no MLEResults.fit or get_robustcov_results); parameters in the
  order of the signature; Returns sections.
- loglike, loglikeobs, observed_information_matrix and
  opg_information_matrix: Returns sections. score and hessian: `*args`
  and `**kwargs` are the flags (positionally in a fixed order, as a
  dictionary from fit, or by keyword with `method` as an alias), not
  arguments of loglike; the notes say when complex-step, finite
  difference or Harvey derivatives are used.
- handle_params, prepare_data, initialize_known and
  initialize_approximate_diffuse: their parameters and returns.
- simulate (model and results): `rng` was documented twice, the
  deprecation of `random_state` now belongs to `rng`; `**kwargs`; the
  result is a Series or DataFrame for Pandas data. impulse_responses
  returns a Series or DataFrame for Pandas data, and the `anchor` and
  `exog` of MLEResults.impulse_responses are keyword arguments.
- MLEResults: `results` and `filter_results` are filter or smoother
  results, `nobs` is an int; info_criteria and test_normality get
  Returns sections; test_heteroskedasticity gives the chi-squared test
  with `use_f=False`, not True; the parameters of test_serial_correlation,
  append and apply in the order of the signature; the values of
  `information_set`; news returns the raw output with `return_raw`; a
  duplicated line in the example of apply.
- PredictionResults takes the results object, not the model.
bashtage added a commit to bashtage/statsmodels that referenced this pull request Nov 25, 2026
MLEModel.score_obs with transformed=False gave wrong scores in two cases.

- The "harvey" method dropped `transformed` and treated the untransformed
  parameters as transformed. For SARIMAX(1, 0, 0) with a trend on the
  macrodata inflation series, at the untransformed values of
  [1, 0.5, 4], the scores summed to [532.1, 3413.7, 1202.9]; the score
  is [49.7, -178.3, 84.5].
- The check that rejects complex-step derivatives with transformed=False
  ran before the default of approx_complex_step was resolved, so by
  default the complex step was applied through transform_params. That is
  only right for transformations that are complex differentiable. For a
  VAR(1) with a constant on GDP and consumption growth, 5 of the 9
  summed scores were wrong (for example -70.12 instead of -13.27).

Changes
- With transformed=False, the "harvey" method and complex-step
  differentiation compute the scores with respect to the transformed
  parameters, as with transformed=True, and multiply them by the Jacobian
  of the transformation (centered differences), as score and hessian do.
- With the default complex step, the result for models whose
  transformation is complex differentiable (for example SARIMAX) is that
  of 0.15.0 to about 1e-10 relative.
- The docstring says so, with a versionchanged note.

Not changed
- Finite differences with the "approx" method still differentiate
  loglikeobs through the transformation, so their results are unchanged.
- An explicit approx_complex_step=True with transformed=False still
  raises (as statsmodels#11029 tests).
- With fixed parameters and includes_fixed=False, all of the paths of
  score_obs with transformed=False evaluate the likelihood with the fixed
  values transformed as if they were unconstrained, and return a column
  for each parameter. That is a separate bug and is left as it is; the
  new paths agree with the finite differences there.

Tests
- For SARIMAX(2, 0, 1), a VAR(2), a dynamic factor model and an AR(1),
  the "approx" and "harvey" scores with the default and with finite
  differences match centered differences of loglikeobs with respect to
  the untransformed parameters, and sum to score. The harvey cases for all
  models and the default for the VAR(2) and the dynamic factor model fail
  on main.
- The default and harvey results are the chain rule applied to the
  results for the transformed parameters, to 1e-8 (for SARIMAX, this is
  main's default result).
- The "approx" finite differences are unchanged, and with
  includes_fixed=True and fixed parameters the scores are those of the
  model without fixed parameters.
@bashtage
bashtage marked this pull request as ready for review November 25, 2026 16:32
@bashtage
bashtage merged commit 6142e45 into statsmodels:main Nov 25, 2026
10 checks passed
@bashtage
bashtage deleted the wip-tsa-cov-c10 branch November 27, 2026 10:02
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