Skip to content

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

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

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

Conversation

@soodoku

@soodoku soodoku commented Nov 21, 2026 •

Copy link
Copy Markdown

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-11-21T07:41:12.208419Z 7e16f18 PR opened
ℹ️ 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 (d7980a7) to head (7e16f18).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #879   +/-   ##
=======================================
  Coverage   99.69%   99.69%           
=======================================
  Files         202      202           
  Lines       38871    38887   +16     
  Branches     2501     2502    +1     
=======================================
+ Hits        38752    38768   +16     
  Misses         51       51           
  Partials       68       68           
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.

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.

1 participant