Skip to content

REF: Use array_like for hand-rolled checks in tsa - #11254

Merged
bashtage merged 1 commit into
statsmodels:mainfrom
bashtage:wip-array-like-tsa
Nov 26, 2026
Merged

bashtage merged 1 commit into
statsmodels:mainfrom
bashtage:wip-array-like-tsa

Conversation

@bashtage

@bashtage bashtage commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Companion of #11250 and #11251 (merged).

Several functions and methods in tsa convert an argument with np.asarray
or np.array and then check its ndim or shape by hand. This replaces the
conversion and the dimension check with a single array_like call from
statsmodels.tools.validation. Results do not change for any input. Inputs
that were rejected are still rejected with a ValueError, in most cases now
with array_like's message. The calls are written so that array_like checks
exactly what the old code checked: shape=(None,) * k without ndim, because
ndim pads and squeezes axes instead of rejecting them; maxdim where ndim's
padding of a 1-d input is wanted but squeezing is not; mindim=0 where a
scalar was rejected; dtype=None where the old code did not convert to
float. Checks of a length against the model or another argument stay as
they were. This builds on the change that makes array_like return a
base-class ndarray, as np.asarray does, so matrix and masked-array input
behave as before.

Changes

  • _lagselect.nested_lag_ols (behind adfuller's autolag, pacf_ols,
    zivot_andrews, VAR.select_order and ardl_select_order): exog uses
    array_like(exog, "exog", dtype=None, shape=(None, None)); the check of the
    number of rows stays. start uses array_like(start, "start", dtype=int,
    mindim=0, shape=(None,)); the check that it is a nondecreasing sequence of
    len(lags) + 1 integers stays.
  • MarkovSwitching.initialize_known: probabilities uses
    array_like(probabilities, "probabilities", dtype=None, shape=(None,))
    followed by a copy, which np.array made before, so that the model does
    not share the caller's array. A scalar is still a vector with one
    element (np.array(..., ndmin=1) before). The length check stays.
  • Representation.initialize_known (and so MLEModel.initialize_known):
    constant uses array_like(constant, "constant", dtype=None, mindim=0,
    shape=(None,), order="F") and stationary_cov uses
    array_like(stationary_cov, "stationary_cov", dtype=None,
    shape=(None, None), order="F"). dtype=None keeps complex values. The
    checks against k_states stay.
  • MLEResults.news, when a comparison dataset is extended to a longer
    exog: comparison uses array_like(comparison, "comparison", dtype=None,
    maxdim=2, ndim=2). A 1-d comparison is still a single column. The check
    of the number of columns stays.
  • stattools.leybourne: x uses array_like(x, "x", dtype=None, maxdim=2,
    ndim=2, shape=(None, 1)), which also replaces the reshape to a column.
  • varma_process.varfilter: x uses array_like(x, "x", dtype=None,
    mindim=0, maxdim=2); a 1-d x is still made a column by hand, because
    ndim=2 would also turn a scalar into a 1 x 1 series. dtype=None keeps
    integer x giving integer results.
  • var_model.forecast: coefs uses array_like(coefs, "coefs", dtype=None,
    shape=(None, None, None)).

Error messages that change (all ValueError):

  • nested_lag_ols: an exog that is not 2-d gave "exog must have shape
    (nobs, k_exog)" and now gives "exog must have 2 dimensions, but has
    ..."; a 2-d exog with the wrong number of rows keeps the old message. A
    start that is not 1-d gave "start must be a nondecreasing sequence of
    len(lags) + 1 integers starting at 0" and now gives "start must have 1
    dimension, but has ..."; other invalid start values keep the old
    message.
  • MarkovSwitching.initialize_known: probabilities with two or more
    dimensions gave "Initial probabilities must be a vector of shape
    (k_regimes,)." and now give "probabilities must have 1 dimension, but
    has 2" (or 3); a scalar or a vector of the wrong length keeps the old
    message.
  • Representation.initialize_known: a constant that is not 1-d gave
    "Invalid dimensions for constant state vector. Requires shape (k,), got
    ..." and now gives "constant must have 1 dimension, but has ..."; a
    stationary_cov that is not 2-d gave "Invalid dimensions for stationary
    covariance matrix. ..." and now gives "stationary_cov must have 2
    dimensions, but has ...". Wrong lengths keep the old messages. Both
    arguments are converted before either length is checked, so a constant
    of the wrong length together with a stationary_cov of the wrong number
    of dimensions now reports stationary_cov.
  • MLEResults.news: a comparison with more than 2 dimensions gave "Invalid
    shape for comparison. Must contain k columns." and now gives
    "comparison must have ndim <= 2"; the wrong number of columns keeps the
    old message.
  • leybourne: "LM: x must be a 1d array or a 2d array with a single column"
    becomes "x is required to have shape (*, 1) but has shape (n, k)" for a
    2-d x and "x must have ndim <= 2" for an x with more dimensions.
  • varfilter: "x array has to be 1d or 2d" becomes "x must have ndim <= 2".
    A scalar x still fails with "not enough values to unpack".
  • var_model.forecast: "coefs must be an array with 3 dimensions" becomes
    "coefs must have 3 dimensions, but has ...".

Not changed

  • KalmanFilter.impulse_responses impulse: the code squeezes all singleton
    axes before the check, so a (1, k_posdef) row and a (1, k_posdef, 1)
    array are accepted. array_like(ndim=1) only squeezes trailing axes and
    would reject them.
  • LocalProjection exog: the only check compares the number of rows with
    endog. exog has already gone through array_like(exog, "exog", ndim=2,
    dtype=float) at the top of init, so the np.asarray before the check
    does nothing.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form or a published value: the fits
of nested_lag_ols with a start against lstsq order by order, the known
initial probabilities of a Markov switching model, the first predicted
state and covariance of a SARIMAX with a known initialization, the news
of a VARX(1) against its forecasts by hand, the Leybourne-McCabe
statistic of the BAA series against Matlab, varfilter against explicit
loops, and VAR(2) forecasts by hand. Each input that was rejected before
(a column, a row, a 3-d or 4-d array, a scalar, a trailing axis of length
one) is still rejected, matching the new message where it changed. The
cases that need mindim=0, maxdim, shape instead of ndim, dtype=None and
the copy of the Markov probabilities each fail if that part of the call
is dropped. MarkovSwitching keeps a copy of the probabilities,
Representation keeps a complex constant and varfilter keeps integer data.
nested_lag_ols is tested directly, as in the rest of test_lagselect.py,
because its callers only pass the 2-d arrays they build. One existing
test that matched the old message is updated (test_exceptions in
tsa/tests/test_lagselect.py).

  • 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 hand-rolled checks with an AST scan, replacing them, writing the tests, and checking that only error messages change (probes with NumPy 1.23.5 and 2.5, mutation check, the tsa test suite with NumPy 1.23.5, 1.26.4 and 2.5).
    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

Several functions and methods in tsa convert an argument with np.asarray
or np.array and then check its ndim or shape by hand. This replaces the
conversion and the dimension check with a single array_like call from
statsmodels.tools.validation. Results do not change for any input. Inputs
that were rejected are still rejected with a ValueError, in most cases now
with array_like's message. The calls are written so that array_like checks
exactly what the old code checked: shape=(None,) * k without ndim, because
ndim pads and squeezes axes instead of rejecting them; maxdim where ndim's
padding of a 1-d input is wanted but squeezing is not; mindim=0 where a
scalar was rejected; dtype=None where the old code did not convert to
float. Checks of a length against the model or another argument stay as
they were. This builds on the change that makes array_like return a
base-class ndarray, as np.asarray does, so matrix and masked-array input
behave as before.

Changes

- _lagselect.nested_lag_ols (behind adfuller's autolag, pacf_ols,
  zivot_andrews, VAR.select_order and ardl_select_order): exog uses
  array_like(exog, "exog", dtype=None, shape=(None, None)); the check of the
  number of rows stays. start uses array_like(start, "start", dtype=int,
  mindim=0, shape=(None,)); the check that it is a nondecreasing sequence of
  len(lags) + 1 integers stays.
- MarkovSwitching.initialize_known: probabilities uses
  array_like(probabilities, "probabilities", dtype=None, shape=(None,))
  followed by a copy, which np.array made before, so that the model does
  not share the caller's array. A scalar is still a vector with one
  element (np.array(..., ndmin=1) before). The length check stays.
- Representation.initialize_known (and so MLEModel.initialize_known):
  constant uses array_like(constant, "constant", dtype=None, mindim=0,
  shape=(None,), order="F") and stationary_cov uses
  array_like(stationary_cov, "stationary_cov", dtype=None,
  shape=(None, None), order="F"). dtype=None keeps complex values. The
  checks against k_states stay.
- MLEResults.news, when a comparison dataset is extended to a longer
  exog: comparison uses array_like(comparison, "comparison", dtype=None,
  maxdim=2, ndim=2). A 1-d comparison is still a single column. The check
  of the number of columns stays.
- stattools.leybourne: x uses array_like(x, "x", dtype=None, maxdim=2,
  ndim=2, shape=(None, 1)), which also replaces the reshape to a column.
- varma_process.varfilter: x uses array_like(x, "x", dtype=None,
  mindim=0, maxdim=2); a 1-d x is still made a column by hand, because
  ndim=2 would also turn a scalar into a 1 x 1 series. dtype=None keeps
  integer x giving integer results.
- var_model.forecast: coefs uses array_like(coefs, "coefs", dtype=None,
  shape=(None, None, None)).

Error messages that change (all ValueError):

- nested_lag_ols: an exog that is not 2-d gave "exog must have shape
  (nobs, k_exog)" and now gives "exog must have 2 dimensions, but has
  ..."; a 2-d exog with the wrong number of rows keeps the old message. A
  start that is not 1-d gave "start must be a nondecreasing sequence of
  len(lags) + 1 integers starting at 0" and now gives "start must have 1
  dimension, but has ..."; other invalid start values keep the old
  message.
- MarkovSwitching.initialize_known: probabilities with two or more
  dimensions gave "Initial probabilities must be a vector of shape
  (k_regimes,)." and now give "probabilities must have 1 dimension, but
  has 2" (or 3); a scalar or a vector of the wrong length keeps the old
  message.
- Representation.initialize_known: a constant that is not 1-d gave
  "Invalid dimensions for constant state vector. Requires shape (k,), got
  ..." and now gives "constant must have 1 dimension, but has ..."; a
  stationary_cov that is not 2-d gave "Invalid dimensions for stationary
  covariance matrix. ..." and now gives "stationary_cov must have 2
  dimensions, but has ...". Wrong lengths keep the old messages. Both
  arguments are converted before either length is checked, so a constant
  of the wrong length together with a stationary_cov of the wrong number
  of dimensions now reports stationary_cov.
- MLEResults.news: a comparison with more than 2 dimensions gave "Invalid
  shape for `comparison`. Must contain k columns." and now gives
  "comparison must have ndim <= 2"; the wrong number of columns keeps the
  old message.
- leybourne: "LM: x must be a 1d array or a 2d array with a single column"
  becomes "x is required to have shape (*, 1) but has shape (n, k)" for a
  2-d x and "x must have ndim <= 2" for an x with more dimensions.
- varfilter: "x array has to be 1d or 2d" becomes "x must have ndim <= 2".
  A scalar x still fails with "not enough values to unpack".
- var_model.forecast: "coefs must be an array with 3 dimensions" becomes
  "coefs must have 3 dimensions, but has ...".

Not changed

- KalmanFilter.impulse_responses impulse: the code squeezes all singleton
  axes before the check, so a (1, k_posdef) row and a (1, k_posdef, 1)
  array are accepted. array_like(ndim=1) only squeezes trailing axes and
  would reject them.
- LocalProjection exog: the only check compares the number of rows with
  endog. exog has already gone through array_like(exog, "exog", ndim=2,
  dtype=float) at the top of __init__, so the np.asarray before the check
  does nothing.

Tests

For each changed function, list and pandas inputs give the same result as
an ndarray, checked against a closed form or a published value: the fits
of nested_lag_ols with a start against lstsq order by order, the known
initial probabilities of a Markov switching model, the first predicted
state and covariance of a SARIMAX with a known initialization, the news
of a VARX(1) against its forecasts by hand, the Leybourne-McCabe
statistic of the BAA series against Matlab, varfilter against explicit
loops, and VAR(2) forecasts by hand. Each input that was rejected before
(a column, a row, a 3-d or 4-d array, a scalar, a trailing axis of length
one) is still rejected, matching the new message where it changed. The
cases that need mindim=0, maxdim, shape instead of ndim, dtype=None and
the copy of the Markov probabilities each fail if that part of the call
is dropped. MarkovSwitching keeps a copy of the probabilities,
Representation keeps a complex constant and varfilter keeps integer data.
nested_lag_ols is tested directly, as in the rest of test_lagselect.py,
because its callers only pass the 2-d arrays they build. One existing
test that matched the old message is updated (test_exceptions in
tsa/tests/test_lagselect.py).
@bashtage
bashtage marked this pull request as ready for review November 26, 2026 23:27
@bashtage
bashtage merged commit 5da858e into statsmodels:main Nov 26, 2026
11 of 13 checks passed
@bashtage
bashtage deleted the wip-array-like-tsa branch November 26, 2026 23:28
bashtage added a commit that referenced this pull request Nov 27, 2026
Stacked on #11254.

When the comparison passed to `MLEResults.news` is a dataset and `exog`
has more periods than it, `_get_previous_updated` extends the dataset
with missing values and wraps it in a DataFrame whose columns are
`self.model.endog_names`. For a univariate model `endog_names` is a str
such as "y", which pandas rejects, so
`SARIMAX(endog[:15], exog=exog[:15], order=(1, 0, 0)).smooth(params)
.news(endog, exog=exog[:17], impact_date=16)` raised `TypeError:
Index(...) must be called with a collection of some kind, 'y' was
passed`, for an ndarray, a list or a Series. Passing the equivalent
updated results object worked.

Changes
- The columns are `np.atleast_1d(self.model.endog_names)`, so a
  univariate model gets one column named after its endog.
- A versionchanged note for `comparison`.

Not changed
- Multivariate models, comparisons that are results objects, and
  comparisons whose length matches `exog`.

Tests
- `test_news_univariate_comparison_with_longer_exog`, for a 1-d array,
  an (n, 1) column, a list and a Series: for a regression with AR(1)
  errors and fixed parameters, the previous and updated forecasts of the
  impact date and the total impact equal the closed forms
  `beta * x[16] + phi**2 * u[14]` and `beta * x[16] + phi * u[15]` with
  `u = y - beta * x`, and the news equals the news computed from the
  updated results object. All four cases fail on the base with the
  TypeError and pass here. `test_mlemodel.py` and `test_news.py` pass on
  the oldest, mid and latest dependency sets.
bashtage added a commit that referenced this pull request Nov 27, 2026
Stacked on #11254.

`MarkovSwitching.initialize_known` set `self._initialization = "known"`
before it checked the probabilities. When a check failed (a vector of
the wrong length or dimension, or probabilities that do not sum to one)
the ValueError left the model with known initialization but without
initial probabilities, or with those of an earlier call. A model that
used the steady-state initialization could then no longer compute its
initial probabilities: `initial_probabilities()`, and so `loglike` and
`fit`, raised `TypeError: '>=' not supported between instances of
'NoneType' and 'float'`.

Changes
- The initialization is set to "known" only after the checks pass,
  together with the probabilities, so that a failed call keeps the
  previous initialization.
- A versionchanged note in a new Notes section.

Not changed
- The checks and their messages, and the result of a successful call.

Tests
- `test_initialize_known_failure_keeps_initialization`, for probabilities
  that do not sum to one, a vector that is too long and a 2-d array, after
  the default steady-state initialization and after an earlier
  `initialize_known([0.3, 0.7])`: the call raises the ValueError and the
  initial probabilities are still the steady state of the transition
  matrix (2/3 and 1/3 for p[0->0] = 0.9 and p[1->0] = 0.2, by hand) or
  [0.3, 0.7]. The three steady-state cases fail on the base with the
  TypeError and pass here. The `regime_switching` tests pass on the
  oldest, mid and latest dependency sets.
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