Repository navigation
[FEAT] Unified error distributions across the StatsForecast suite (ETS, CES, Theta + shared C++/Python infra) - #1116
Merged
Merged
Conversation
Saul (nasaul)
marked this pull request as ready for review
April 27, 2026 14:56
Spec for extending non-normal error distribution fitting (ARIMA, ETS) to AutoCES and AutoTheta via shared C++ header and Python distributions module.
# Conflicts: # python/statsforecast/utils.py
- Create python/statsforecast/distributions.py: re-exports Distribution, ArimaMethod, _quantiles, _calculate_intervals from utils.py and adds dist_init_params, extract_dist_params, distribution_n_extra_params, switch_distribution, aic_bic_aicc helpers shared by ARIMA/ETS/CES/Theta. - Add tests/test_distributions.py with base tests (test_switch_distribution_maps_all is deferred until Task 3 adds _ets.Distribution C++ binding). - Fix Distribution.__str__ in utils.py to return value string on Python 3.11+.
…vior change) Replace local Distribution enum with dist::Distribution from distributions.h; swap inline per-distribution NLL math in ObjectiveFunctionDist with calls to dist::negloglik_* (adding sumlog_adj for multiplicative errors); update the pybind enum binding to bind dist::Distribution. In ets.py, delete local switch_distribution and replace inline dist_init/extract/AIC blocks with the four shared helpers: switch_distribution, dist_init_params, extract_dist_params, aic_bic_aicc.
Point arima.py's ArimaMethod, Distribution, _VALID_DISTRIBUTIONS, _quantiles imports at the shared distributions.py hub (re-exports) instead of utils.py directly. No numeric or behavioral change.
… intervals Add distribution-aware CES fitting (ces_target_fn_dist, optimize_dist, Distribution binding in C++) with one-pass joint optimization over smoothing + dist params. Thread distribution="normal" through cesmodel/auto_ces/AutoCES; rewire _simulate_pred_intervals to use sample_errors with fitted distribution. Add error_params_from_model helper to distributions.py.
Add cross-method key-contract matrix (4 models × 5 distributions) and heavy-tailed AIC sanity test (ETS t-dist < normal on Student-t AR(1) data).
…validation messages - simulation.py: use d.value instead of str(d) to build _SUPPORTED_SIMULATION_DISTRIBUTIONS - models.py: render clean value tuples in AutoCES/AutoTheta distribution validation error messages - distributions.py: add : str type annotation to distribution_n_extra_params parameter
…istribution factory - Replace _quantiles body with one-line delegation to frozen_error_distribution(1.0, ...) - Remove now-unused scipy.stats imports (norm, laplace_dist, t_dist, skewnorm_dist, gennorm_dist) from utils.py - Update ETS _calculate_intervals call to pass error_params_from_model(model) instead of raw model dict - Update both ARIMA _quantiles call sites to pass error_params_from_model(model/self.model_.model) - Add error_params_from_model to distributions imports in ets.py and arima.py - Laplace analytic intervals now use scale=sigma/sqrt(2) (consistent with MC); no test value changes needed
…a factory Replace the explicit if/elif parametric dispatch (lines 225-278) in sample_errors with a single frozen_error_distribution().rvs() call. This fixes the sigma=scale vs sigma=SD mismatch for t, skew-normal, and ged distributions — the old code incorrectly rescaled sigma to match SD rather than using it directly as the scipy scale parameter. Add MC scale test (test_sample_errors_uses_sigma_as_scale) that verifies empirical p97.5 matches the analytic PPF within 2% for all three parametric distributions at sigma=2.0. Update two existing validation tests whose error-message assertions targeted the old custom dispatch: invalid-df/invalid-shape now raise ValueError via scipy's domain check rather than hand-rolled messages.
…h (sigma2=scale^2)
…bution Replace the per-distribution elif ladder in _compute_pred_intervals with a single frozen_error_distribution() call driven by error_params_from_model(), removing the direct scipy.stats imports from ets.py. Distributionally equivalent to the prior branches (verified scale factors match).
Replace the per-distribution elif ladder in _compute_pred_intervals with the shared statsforecast.simulation.sample_errors() helper, matching how CES (_simulate_pred_intervals) and Theta (compute_pi_samples) already sample errors. Drops the direct scipy.stats imports from ets.py and swaps the global np.random.seed(1) for a local np.random.default_rng(1), so all three models share one sampling path (params via error_params_from_model, residual-fit for normal/laplace when params is None).
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.
Summary
This PR began as "add non-normal error distributions for fitting ETS" but its scope has expanded into unified error-distribution infrastructure across the StatsForecast suite. It introduces a single C++ header and a single Python module that own all distribution math and MLE-fitting helpers, then wires four models — ARIMA, ETS, AutoCES, and AutoTheta — through them.
Supported distributions:
normal,laplace,t,skew-normal,ged.Motivation
PR #1113 added distribution-aware MLE fitting to ARIMA, and the original version of this PR added it to ETS — independently, duplicating the C++ likelihood math and splitting the Python distribution utilities between
utils.pyandsimulation.py. This PR consolidates that into shared layers so each future method (and each future distribution) is a small, single-recipe extension rather than another copy of the math.What's included
Shared infrastructure
include/statsforecast/distributions.h— single C++ source of truth: theDistributionenum and per-observation negative-log-likelihood cores (negloglik_laplace/t/skewnorm/ged).python/statsforecast/distributions.py— single Python hub: re-exports theDistributionenum / quantile utilities and adds shared fitting helpers (switch_distribution,dist_init_params,extract_dist_params,aic_bic_aicc,error_params_from_model).Model integration
distributions.py); no numeric change.optimize_distinces.cpp), distribution-aware prediction intervals, anddistribution=threaded throughcesmodel/auto_ces/AutoCES.optimize_distintheta.cpp) with AIC-based model selection; normal path unchanged.distribution=threaded throughthetamodel/auto_theta/AutoTheta.Simulation
.simulate()now defaultserror_distributionto the fittedmodel_["distribution"]and emits aUserWarningon an explicit mismatch (it still proceeds).SUPPORTED_DISTRIBUTIONSkept as a deprecated alias.Tests
tests/test_distributions.py— unified parametrized suite covering the model-dict key contract across ARIMA/ETS/CES/Theta, scipy quantile/log-likelihood cross-checks, prediction-interval ordering, and the simulate-mismatch warning.Notes / limitations
auto_ces/auto_thetaselect only the structural type (seasontype / modeltype), not the distribution.likis the concentratedn·log(SSE), while the non-normal objective is a full-2logL; these are not comparable across distributions — fine because the distribution is fixed per fit.x0, C++ runs a single Nelder-Mead.Out of scope (future PRs)
Checklist