Skip to content

BUG: Use exog centroid as center in rainbow test use_distance (#9103) - #9903

Merged
bashtage merged 2 commits into
statsmodels:mainfrom
Leonard013:fix/9103-rainbow-centroid
Aug 7, 2026
Merged

bashtage merged 2 commits into
statsmodels:mainfrom
Leonard013:fix/9103-rainbow-centroid

Conversation

@Leonard013

@Leonard013 Leonard013 commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

closes #9103

Why

linear_rainbow(res, use_distance=True) is supposed to order the observations by
their multivariate distance from the center of the design, so the "central
subset" used by the rainbow test is chosen automatically and the result does
not depend on the order in which the rows happen to be stored.

The current implementation instead uses an arbitrary, order-dependent point as the
center (statsmodels/stats/diagnostic.py):

center = int(nobs) // 2 if center is None else center
...
center_obs = exog[center:center+1]          # the nobs//2-th ROW of the data
try:
    err = exog - center_obs
    vi = np.linalg.inv(err.T @ err / nobs)  # 2nd moment about that one row
except np.linalg.LinAlgError:
    err = exog - exog.mean(0)
    vi = np.linalg.inv(err.T @ err / nobs)
dist = cdist(exog, center_obs, metric="mahalanobis", VI=vi)

Two problems follow:

  1. Order dependence (the reported bug). exog[nobs // 2] is whatever
    observation sits in the middle row, and the covariance VI is the second
    moment about that single point. Permuting the rows changes the center, hence
    the distances, hence the central subset, hence the statistic.
  2. Crashes with a constant column. For a model with an intercept, the constant
    column of exog - center_obs is exactly zero, so err.T @ err is singular and
    np.linalg.inv raises LinAlgError. The except branch subtracts
    exog.mean(0), also zero on the constant column, so it raises again. So
    use_distance=True fails outright for the most common case (a model with a
    constant).

The multivariate analogue of "central observations" is distance from the data
centroid (the multivariate mean), per Utts (1982), The rainbow test for lack
of fit in regression
. R's lmtest::raintest also centers on the mean. This was
confirmed in the issue thread by @josef-pkt ("I agree that there is a problem with
the current code ... R uses the mean") and the reporter @SvenSerneels ("use the
mean for both univariate and multivariate cases").

Reproduction (before)

Same data, 5 random row permutations, use_distance=True:

original order      : F=1.1276196497  p=0.2765704447
permutation 0       : F=1.5185224719  p=0.0198496219
permutation 4       : F=1.7777827002  p=0.0023765099

The conclusion flips from clearly non-significant (p=0.28) to significant (p=0.002)
purely from the row order. With a constant column the same call raises
LinAlgError: Singular matrix.

What

Measure the Mahalanobis distances from the exog centroid, with a deterministic
tie-break:

center_obs = exog.mean(0, keepdims=True)
err = exog - center_obs
vi = np.linalg.pinv(err.T @ err / nobs)
dist = cdist(exog, center_obs, metric="mahalanobis", VI=vi)
# dist is the primary key; the exog columns break exact ties deterministically
idx = np.lexsort((*exog.T[::-1], dist.ravel()))
  • Centroid center. The centroid is order invariant, so the ordering (and the
    statistic) no longer depends on row order. This follows Utts (1982) and R's
    lmtest::raintest. (The subset itself remains the middle band of the distance
    ranks — the same [lowidx:uppidx] slice shared with the order_by path — not
    Utts' "closest frac" subset; that pre-existing slicing is unchanged.)
  • Deterministic tie-break (argsort → lexsort). With the centroid fix alone,
    the default np.argsort (non-stable quicksort) still left the result order
    dependent whenever Mahalanobis distances tie and the tied rows straddle the
    subset boundary — common with discrete or duplicated regressors. np.lexsort
    keys on distance (primary) and the exog columns (secondary), so ties are broken
    by regressor values, a property of the observation rather than its position.
    endog is deliberately not a tie-break key: breaking ties by the response
    would make subset membership depend on y, a statistical defect. Among exactly
    equidistant points any deterministic choice is valid.
  • Covariance / inv → pinv. The covariance is the sample covariance about
    the mean (what the old except branch already computed). The try/except —
    whose purpose @josef-pkt noted he could not recall — is removed. On a constant
    column the pseudo-inverse contributes 0 to the distance (the constant equals its
    own mean), so the typical intercept model runs instead of raising. pinv equals
    inv for a full-rank covariance, so relative to the centroid approach the
    ordering for models without a constant is unchanged (it of course differs from
    the old middle-row center, which was the bug).
  • center keyword no longer has a meaning under the corrected definition, so it
    is deprecated: passing it emits a FutureWarning and is otherwise ignored.

After

continuous, 5 permutations : spread 8.9e-16 (floating-point noise)
constant-column model      : F=1.3847543113 (no longer raises; spread 2.2e-16)
discrete lattice, 100 perms: 1 distinct F, spread 6.7e-16 (argsort before: 69 distinct, spread 0.17)

Tests

test_rainbow_smoke_centered was smoke-only and is replaced by real regression
tests in statsmodels/stats/tests/test_diagnostic.py:

  • test_rainbow_use_distance_order_invariant[False|True] — continuous data,
    statistic identical across permutations, with/without a constant (the constant
    case also exercises the former LinAlgError). Targets the centroid fix.
  • test_rainbow_use_distance_order_invariant_discrete — discrete integer-lattice
    design (every exog row distinct but many exact distance ties), invariant across
    permutations. Targets the lexsort tie-break; fails with argsort even after
    the centroid fix.
  • test_rainbow_use_distance_matches_manual_ordering — equals ordering by
    Mahalanobis distance to the centroid (recomputed independently) via the standard
    order_by path.
  • test_rainbow_center_deprecated — passing center warns and doesn't change the
    result.

All fail on main; pytest statsmodels/stats/tests/test_diagnostic.py -q → 138 passed. The value-asserting test_rainbow uses use_distance=False (untouched),
so no reference values change.

Notes for the maintainer (scope / decisions to confirm)

  1. center disposition. Deprecated (non-breaking) rather than removed — it has
    no coherent meaning once the center is the centroid. You may prefer to remove it
    (no test coverage / documented users) or repurpose it — see (2). Left in
    place so that door stays open.
  2. Mean vs. median. @josef-pkt suggested a median might be "more in the spirit
    of central observations." I implemented the mean, matching Utts (1982), R's
    raintest, and @SvenSerneels. center could become a center={"mean","median"}
    selector in a follow-up (another reason I deprecated rather than deleted it).
  3. Constant-column fix via pinv. Fixing the order-dependence alone (mean +
    inv) would leave the LinAlgError in place. pinv resolves both. Happy to
    split if you'd rather scope this strictly to order-dependence — but they share
    the same lines.
  4. Tie-break residual. The lexsort tie-break is order-invariant for tied
    distances from discrete/duplicated regressors, with one honest exception: two
    rows with identical exog but different endog straddling the subset boundary
    can't be disambiguated without ordering by the response (which we must not),
    so they keep input order. Rare, documented in Notes. A different key order is a
    one-line change.
  5. Robust covariance / Mahalanobis (ENH: Outlier robust covariance - rebased #8129) intentionally out of scope.
  6. Independent reference. Tests pin against an independent re-derivation of the
    centroid ordering, not R (unavailable here). A hard lmtest::raintest cross-check
    value could be added if you want one.

Conventions

  • flake8 clean; docstring parses under numpydoc.
  • No release-notes file edited — statsmodels generates notes from merged PRs, so
    this BUG:-prefixed PR under the 0.15 milestone is picked up automatically.

linear_rainbow(res, use_distance=True) ordered the observations by their
Mahalanobis distance to an arbitrary middle-indexed observation
(exog[nobs // 2]) and built the covariance from the deviations around
that single point. Both depend on the raw row order of the data, so the
same data supplied in a different order produced a different F-statistic
and p-value. In addition, the covariance was singular whenever exog
contained a constant column, which raised a LinAlgError for the typical
regression model.

Measure the Mahalanobis distances from the exog centroid (the
multivariate mean) instead, following Utts (1982) and matching R's
lmtest::raintest. The centroid is order invariant, so the statistic no
longer depends on the row order, and using the pseudo-inverse of the
covariance handles a constant (or otherwise rank-deficient) column
gracefully. Order the observations with a deterministic lexsort keyed on
the distance (primary) and the exog values (tie-break) rather than the
non-stable argsort, so that exact distance ties from discrete or
duplicated regressors do not reintroduce order dependence; endog is
never used as a tie-break key. The center keyword no longer has any
effect; it is deprecated and now emits a FutureWarning.

Add regression tests that assert order invariance for continuous data
(with and without a constant column) and for a discrete integer-lattice
design (which ties distances and exercises the tie-break), equivalence
to ordering manually by the centroid distance, and the center
deprecation warning. The previous test_rainbow_smoke_centered test was
smoke-only and is superseded.

closes #9103

This change was drafted with the assistance of Claude (Anthropic).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes linear_rainbow(..., use_distance=True) so that observation ordering is based on Mahalanobis distance to the exog centroid, making the rainbow test invariant to row order and robust to singular covariance structures (e.g., intercept/constant columns).

Changes:

  • Update linear_rainbow to center Mahalanobis distances on the exog centroid, use pinv, and apply deterministic tie-breaking via lexsort.
  • Deprecate and ignore the center keyword when use_distance=True, emitting a FutureWarning.
  • Replace the prior smoke test with regression tests that assert order invariance (continuous + discrete/ties), manual ordering equivalence, and deprecation behavior.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
statsmodels/stats/diagnostic.py Reworks use_distance=True ordering to use centroid + pinv and deterministic tie-breaking; adds documentation and center deprecation warning.
statsmodels/stats/tests/test_diagnostic.py Adds targeted regression tests for order invariance, tie handling, manual ordering equivalence, and center deprecation warning.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 1184 to +1187
center : {float, int}, default None
If a float, the value must be in [0, 1] and the center is center *
nobs of the ordered data. If an integer, must be in [0, nobs) and
is interpreted as the observation of the ordered data to use.
Deprecated and ignored. The center used to order the observations
when ``use_distance`` is True is always the exog centroid (the
multivariate mean). Passing a value emits a ``FutureWarning``.
Comment on lines +1252 to +1262
if center is not None:
warnings.warn(
"The center keyword is deprecated and no longer has any "
"effect. The Mahalanobis distances used to order the "
"observations are now measured from the exog centroid (the "
"multivariate mean) rather than from an individual "
"observation, so that the rainbow test no longer depends on "
"the order of the observations (Utts, 1982).",
FutureWarning,
stacklevel=2,
)
@bashtage bashtage added this to the 0.15 milestone Jul 23, 2026
@bashtage

bashtage commented Aug 6, 2026

Copy link
Copy Markdown
Member

@copilot please fix the merge conflicts in this pull request.

@bashtage

bashtage commented Aug 7, 2026

Copy link
Copy Markdown
Member

Thanks. LGTM.

@bashtage
bashtage merged commit 071a14d into statsmodels:main Aug 7, 2026
1 check was pending
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.

Error estimating mean in rainbow test

3 participants