Skip to content

BUG: Fit random effects with two zero variance components - #879

Open
soodoku wants to merge 3 commits into
bashtage:mainfrom
finite-sample:fix/random-effects-zero-variance
Open

soodoku wants to merge 3 commits into
bashtage:mainfrom
finite-sample:fix/random-effects-zero-variance

Conversation

@soodoku

@soodoku soodoku commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

On current main d7980a7, the public random-effects estimator fails when both variance components are exactly zero. This includes an all-zero dependent variable with full-rank regressors and ample residual degrees of freedom. The share of variance due to the effects (rho) and the quasi-demeaning factor (theta) both divide by zero before a result can be returned. The documented contract introduced in #814 is that an undefined R-squared is NaN without an error or warning.

import numpy as np
import pandas as pd
from linearmodels.panel import RandomEffects

idx = pd.MultiIndex.from_product([range(40), range(6)])
x = pd.DataFrame(np.random.default_rng(0).normal(size=(240, 2)), index=idx)
x["const"] = 1.0
fit = RandomEffects(pd.Series(0.0, index=idx), x).fit()

On Linux arm64 with Python 3.13 and the exact NumPy 2.2.6 / SciPy 1.15.3 / pandas 2.3.3 pins used by the project's Python 3.13 Azure job, this raises ZeroDivisionError: float division by zero. On macOS arm64 with NumPy 2.5.5 / SciPy 1.18.1 / pandas 3.1.1, it emits invalid-division warnings and raises ValueError: array must not contain infs or NaNs. A constant outcome of 0.1 also fails on that Mac. The Linux solver produces tiny positive variances for 0.1, so the existing 0.1 test passes there.

The patch handles exactly two zero estimated variances. It chooses pooled least squares (theta zero), consistent with the existing zero-random-effect interpretation. The reported share of effects is zero, matching the convention in PanelOLS when total residual variance is zero. The residual and effect variance estimates themselves remain zero. The parameter covariance is zero and R-squared is NaN for the all-zero example. The choice of reported share is a convention because its underlying ratio is undefined; the updated docstring makes that explicit in the behavior.

Both added regression cases failed against the parent. The patched wheel passed 507 tests in the zero-total-sum-of-squares, random-effects variance and random-effects degrees-of-freedom modules on both the Linux pins and the Mac stack. The full installed-package suite on macOS passed with 23,688 passed, 2,476 skipped, and 47 expected failures. The new test uses an unbalanced panel and exercises both small_sample settings with warnings promoted to errors.

Hosted test replay

The Linux Python 3.12 job in Azure build 1204 had one failing test, IVSystemGMM's comparison of coefficients obtained from equivalent formula and array specifications with random weights. The build recorded 23,391 passed, 2,473 skipped and 47 xfailed in that job. The other nine matrix jobs passed.

I repeated the individual test on Linux x86_64 with Python 3.12.16, NumPy 2.0.2, SciPy 1.13.1, pandas 2.2.3, statsmodels 0.14.6, pytest 9.2.0 and pytest-randomly 5.1.0. With one BLAS thread, both builds gave the same results:

pytest-randomly seed Parent d7980a7 PR 7e16f18
480777500 (hosted seed) Failed, max relative difference 1.51567353e-6 Failed, max relative difference 1.51567353e-6
3 Passed Passed

Both local failures had 6 of 18 coefficients outside the default tolerance of 1e-7. The hosted job reported 2.51e-6. To reproduce from the source root, using the same test node ID preserves pytest-randomly’s per-test seed.

OPENBLAS_NUM_THREADS=1 python -m pytest --randomly-seed=480777500 'linearmodels/tests/system/test_gmm.py::test_formula_equivalence_weights[steps:1,robust]'

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T23:13:30.390116Z f8e4b4f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (65f4054) to head (f8e4b4f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #879   +/-   ##
=======================================
  Coverage   99.69%   99.69%           
=======================================
  Files         207      207           
  Lines       39478    39494   +16     
  Branches     2541     2542    +1     
=======================================
+ Hits        39357    39373   +16     
  Misses         52       52           
  Partials       69       69           
Flag Coverage Δ
adder 99.68% <100.00%> (+<0.01%) ⬆️
subtractor 99.68% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks. Handling the exact 0/0 makes test_constant_dependent_variable_panel[RandomEffects-0.1] independent of the platform, and an all-zero y now gives the pooled estimates with no warning. As you found, the red Linux job is test_formula_equivalence_weights[steps:1,robust], which is flaky on main; it is not from this PR.

Please add a .. versionchanged:: 7.2 next to the new sentence in the fit docstring, and a 7.2 note under "Bug fixes":

- ``RandomEffects.fit`` returns the pooled estimates, with ``theta`` and the share of the
  variance due to the effects set to 0, when both estimated variance components are 0,
  which happens when the regressors fit the dependent variable exactly. 7.1 divided 0
  by 0 and raised a ``ValueError`` or a ``ZeroDivisionError``, depending on the platform
  (:issue:`879`).

Add a versionchanged entry to RandomEffects.fit and a 7.2 bug-fix note,
as requested in review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@soodoku

soodoku commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — added the versionchanged:: 7.2 note in RandomEffects.fit and your "Bug fixes" entry in 28daed0.

@bashtage

bashtage commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Could you rebase on main to resolve the merge conflicts.

@bashtage

bashtage commented Dec 3, 2026 •

Copy link
Copy Markdown
Owner

To add to my comment above: the only conflict with main is in doc/source/changes/7.0.rst, where #885 and #864 added bullets in the same place under "Bug fixes". Rebasing or merging main both work; please keep all of the bullets, with yours after the one for #864. I couldn't resolve it myself, since maintainers can't push to branches of forks that belong to an organization. With that resolved, this is ready to merge.

@soodoku

soodoku commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Kevin. I merged main into the PR branch, kept all the bug-fix entries, and placed #879 immediately after #864. GitHub now shows the conflict is resolved. All 220 tests in test_rsquared_zero_tss.py passed locally.

This branch has not been deployed

No deployments
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.

2 participants