Repository navigation
TST: Cover the remaining MLEModel and MLEResults paths - #11029
Merged
Merged
Conversation
This was referenced Nov 22, 2026
bashtage
force-pushed
the
wip-tsa-cov-c10
branch
from
November 24, 2026 16:16
2e48f2f to
c76147e
Compare
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
force-pushed
the
wip-tsa-cov-c10
branch
from
November 25, 2026 12:12
c76147e to
a327c8f
Compare
bashtage
marked this pull request as ready for review
November 25, 2026 16:32
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 #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.pythat 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 andacorr_ljungboxon the standardized residuals. The source changes are docstrings only.Changes
aicc; forecasts and their variances with a datesteps; simulations anchored by an integer, a negative integer, a date or a partial date, with a drawn or per-repetition initial state.news: revision, update and total impacts with a daterevisions_details_start,state_indexandreturn_raw; a comparison dataset with longer exog; extension of time-varying updated results, univariate and multivariate.appendwith refit, with and without fixed parameters;extendwithresults_class=FilterResults;fitfrom unconstrained start values and with extra flags;results_classorresults_wrapper_classgiven alone; low-memory predictions.summarywithdisplay_max_endog, extra rows, and the condition-number warning with a fixed parameter;plot_diagnosticswith a variable name, a truncated title, dates or integer positions, andacf_kwargs.*argsofscore/hessian; thecov_typeandcov_kwdsreferences (they pointed to methods that do not exist); parameter order; the duplicatedrngentry; return types for pandas data;use_f=Falsefor the chi-squared heteroskedasticity test; theinformation_setvalues; thePredictionResultsargument.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/hessianraise since 0.15.0; the observed information matrix with untransformed or fixed parameters;score_obswithtransformed=False(Harvey) and its defaultapprox_complex_step; univariatenewswith longer exog; numpy integersteps; smoothed predictions after a low-memory filter; listparamsinhessian/transform_jacobian; and smaller ones. Unreachable branches are left in place and listed separately.Tests
Coverage of
mlemodel.pyby 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.
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