Repository navigation
BUG: Reject singular or non-positive-definite sigma in system GLS - #885
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 677f5c58cd
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| vals = np.linalg.eigvalsh((sigma + sigma.T) / 2) | ||
| if not (vals[-1] > 0 and vals[0] > k * np.finfo(float).eps * vals[-1]): |
There was a problem hiding this comment.
Preserve diagonal GLS for equations on different scales
When equations have residual variances such as 1 and 1e16, this test rejects even an exactly diagonal, positive-definite covariance: the smallest eigenvalue is 1, while the cutoff is about 4.44. Consequently, fit(method='gls', full_cov=False) now fails solely because the equations use different measurement units, although the independent diagonal inversions are numerically safe. Test singularity on a diagonally normalized covariance, and keep the inverse-square-root and user-sigma guards consistent, so rescaling an equation does not invalidate an otherwise estimable system.
Useful? React with 👍 / 👎.
| "sigma must be a square matrix with dimensions " | ||
| "equal to the number of equations" | ||
| ) | ||
| self._sigma = self._validate_sigma(sigma, len(self._equations)) |
There was a problem hiding this comment.
Preserve semidefinite covariance support in system GMM
For IVSystemGMM(..., weight_type='unadjusted'), sigma itself need not be invertible: HomoskedasticWeightMatrix.weight_matrix constructs Z' (sigma ⊗ I) Z, which is what _blocked_gmm inverts. For example, sigma=np.ones((2, 2)) with orthogonal one-column instrument sets produces a positive-definite diagonal moment weight matrix; result finalization also supports this case because _system_r2 inverts only sigma's diagonal and skips its singular inverse square root. Since GMM calls this shared constructor, the new validation rejects these previously estimable models before fitting. Restrict strict positive-definiteness to GLS, allowing positive-semidefinite sigma for GMM and checking its actual moment weight matrix instead.
Useful? React with 👍 / 👎.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #885 +/- ##
=======================================
Coverage 99.69% 99.69%
=======================================
Files 203 203
Lines 38941 39033 +92
Branches 2503 2512 +9
=======================================
+ Hits 38822 38914 +92
Misses 51 51
Partials 68 68
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ccf6ba38b7
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if np.max(np.abs(sigma_arr - sigma_arr.T)) > 1e-8 * scale: | ||
| raise ValueError("sigma must be symmetric.") | ||
| sigma_arr = 0.5 * sigma_arr + 0.5 * sigma_arr.T | ||
| if not covariance_is_definite(sigma_arr, allow_singular=allow_singular): |
There was a problem hiding this comment.
Defer strict sigma validation until full_cov is applied
When a user supplies a semidefinite covariance and requests diagonal GLS, for example SUR(eqs, sigma=np.ones((2, 2))).fit(method='gls', full_cov=False), construction now raises before the fitting mode is known. This previously worked because _gls_estimate discards the off-diagonal entries, making the effective covariance the identity. Accept semidefinite inputs at construction and enforce strict definiteness through the existing post-diagonalization _check_sigma_invertible call so that full_cov=False remains usable with singular supplied covariances whose diagonal entries are positive.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55e231168b
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| vecs, roots, _ = np.linalg.svd(np.linalg.cholesky(s)) | ||
| out = (vecs / roots) @ vecs.T |
There was a problem hiding this comment.
Preserve small roots when decomposing differently scaled covariances
For correlated equations on very different scales, the unscaled Cholesky-factor SVD can lose the smaller singular value. For example, np.array([[1., 2.**53], [2.**53, 2.**108]]) has correlation eigenvalues 0.5 and 1.5 and passes the definiteness check, but LAPACK's bidiagonalization can round the Cholesky factor's trailing pivot to zero. The subsequent division by roots then produces NaN/inf instead of the finite inverse square root obtainable from the previous eigendecomposition. Since GLS uses this routine for weighted residuals and McElroy R², a valid supplied covariance can now produce invalid results solely because of equation units. Use a scale-robust decomposition rather than an SVD of the unscaled factor.
Useful? React with 👍 / 👎.
bashtage
left a comment
There was a problem hiding this comment.
Thanks, this fixes a real problem: a singular residual covariance, for example in a share system that keeps all of the share equations, or with more equations than observations, was inverted and gave arbitrary GLS estimates, often without a warning. GLS here agrees with a direct GLS on the stacked system to 6e-14, and the estimates and covariances of valid input are unchanged.
-
Coverage.
if np.any(variances < 0): return Falseincovariance_is_definiteis reachable (SUR(eqs, sigma=[[-1, 0], [0, 1]])) but not tested, andif not np.isfinite(corr).all(): return Falsecan't be reached through a public path: sigma is finite by then, and |corr| <= 1 for positive semidefinite input. -
The tolerance isn't tested: in both singular tests the smallest eigenvalue of the correlation matrix is already <= 0, so
tol = 0passes them. With seeds 2 and 4 oftest_sur_singular_sigma_more_equations_than_obsit is a small positive number, so running that test over several seeds makes it depend on the tolerance.Both changes:
--- a/linearmodels/system/_utility.py +++ b/linearmodels/system/_utility.py @@ -229,8 +229,6 @@ def covariance_is_definite( return False scales = np.sqrt(np.where(zero, 1.0, variances)) corr = s / scales[:, None] / scales - if not np.isfinite(corr).all(): - return False vals = np.linalg.eigvalsh(corr) tol = len(s) * np.finfo(float).eps * vals[-1] return bool(vals[0] >= -tol if allow_singular else vals[0] > tol) --- a/linearmodels/tests/system/test_sur.py +++ b/linearmodels/tests/system/test_sur.py @@ -1093,8 +1093,9 @@ def test_sur_contraint_with_value(): assert_allclose(result.params, result_without_q.params) -def test_sur_singular_sigma_more_equations_than_obs(): - rng = np.random.default_rng(0) +@pytest.mark.parametrize("seed", range(6)) +def test_sur_singular_sigma_more_equations_than_obs(seed): + rng = np.random.default_rng(seed) nobs = 4 eqs = { f"e{i}": { @@ -1146,6 +1147,7 @@ def test_sur_singular_sigma_collinear_equations(): (np.array([[1.0, np.nan], [np.nan, 1.0]]), "missing or infinite"), (np.array([[1.0, 0.5], [0.0, 1.0]]), "symmetric"), (np.array([[1.0, 2.0], [2.0, 1.0]]), "positive semidefinite"), + (np.array([[-1.0, 0.0], [0.0, 1.0]]), "positive semidefinite"), ], ) def test_sur_invalid_user_sigma(bad_sigma, match):
-
Docs. The
sigmaparameter ofSUR,IV3SLSandIVSystemGMM(and of thefrom_formulamethods) should say what is accepted:sigma : array_like, optional Prespecified residual covariance to use in GLS estimation, with shape (nequations, nequations). If not provided, FGLS is implemented based on an estimate of sigma. It must be finite, symmetric and positive semidefinite. .. versionchanged:: 7.2 A ``ValueError`` is raised if sigma is not finite, symmetric and positive semidefinite.and
fitneeds aRaisesentry:numpy.linalg.LinAlgError If ``method`` is "gls" and the residual covariance that GLS inverts (``sigma``, or its estimate, or only their diagonal if ``full_cov`` is False) is singular. -
Release notes, one bullet in each of three sections:
.. "Bug fixes" - GLS estimation of ``SUR`` and ``IV3SLS`` raises a ``LinAlgError`` when the residual covariance that it inverts is singular, as it is when there are more equations than observations or when the residuals of some equations are linearly dependent, for example share equations that sum to one. The check uses the correlation matrix, so it does not depend on the units of the equations. 7.1 inverted the rounding error and returned arbitrary estimates, at most with a ``RuntimeWarning`` (:issue:`885`). .. "Backward-incompatible changes" - ``SUR``, ``IV3SLS`` and ``IVSystemGMM`` raise a ``ValueError`` if ``sigma`` contains missing or infinite values or is not symmetric and positive semidefinite. 7.1 accepted it, also when it was not used, as with ``method="ols"``, ``full_cov=False`` or a GMM weight type other than "unadjusted" (:issue:`885`). .. "Changes that alter results" - The McElroy R-squared of the system models is computed when the residual variances of the equations differ by a factor of about 1e15 or more, where 7.1 reported NaN. The weighted residuals of GLS and the McElroy R-squared are more accurate when the equations have very different scales, and change by rounding error otherwise (:issue:`885`).
On the last Codex comment: it is right that [[1, 2**53], [2**53, 2**108]] gives NaN, but those scales aren't realistic, and for realistic differences in scale the new inv_matrix_sqrt is more accurate than eigh was. No change needed.
Optional: test_sur_singular_sigma_more_equations_than_obs only checks that the OLS, diagonal-GLS and sigma=np.eye(5) estimates are finite. All three equal equation-by-equation OLS, so assert_allclose against the OLS estimates would be a real check.
- Drop the unreachable finiteness check on the correlation matrix and test the negative-variance branch through SUR(sigma=...). - Run the more-equations-than-observations test over six seeds, so that it depends on the eigenvalue tolerance (tol = 0 fails two of them), and compare the OLS, diagonal-GLS and sigma=I estimates with each other instead of only checking that they are finite. - Document what sigma must be in SUR, IV3SLS and IVSystemGMM, and the LinAlgError that GLS raises for a singular covariance. - Add 7.2 notes under bug fixes, backward-incompatible changes and changes that alter results. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks for the detailed review — all four points are in f1f789c: your coverage/tolerance diff (with |
|
Thanks. |
Summary
sigmais numerically positive definite before inverting it in_SystemModelBase._gls_estimate, using eigenvalues after scaling each equation to unit variance.sigmain_SystemModelBase.__init__for finiteness and symmetry. Full GLS requires positive definite covariance. Diagonal GLS checks the diagonal it actually inverts, so a singular input with positive variances remains usable. System GMM accepts positive semidefinite covariance when the instrument-weighted moment matrix is invertible.linearmodels.system._utility.inv_matrix_sqrtagainst non-positive-definite inputs (raisingnp.linalg.LinAlgError, matchinglinearmodels.shared.linalg.inv_sqrth), preventing silentRuntimeWarning: divide by zeroandNaNpropagation.Why
When a system has more equations than observations ($M > T$ ) or linearly dependent residuals (e.g., identical equations or zero-variance residuals), the sample residual covariance $\hat{\Sigma} = \frac{1}{T}\hat{\varepsilon}^\top\hat{\varepsilon}$ is mathematically singular, yet IEEE-754 roundoff leaves a tiny positive smallest eigenvalue ($\sim 10^{-17}$ ). Calling $\sim 10^{17}$ ) and returns arbitrary GLS parameter estimates and standard errors with no warning or error.
numpy.linalg.inv(sigma)without a rank/eigenvalue check silently inverts floating-point noise (condition numberExample before this fix:
With this fix:
SUR(eqs).fit(method="gls")raisesnp.linalg.LinAlgErrorexplaining thatsigmais singular (and notingmethod='ols',full_cov=False, or a user-supplied positive definitesigmaas alternatives).method="ols",full_cov=False(when diagonal entries are positive), and a valid user-suppliedsigmacontinue to work unchanged.Verification
pytest linearmodels/tests/system/: 2821 passed, including diagonal GLS with a singular supplied covariance, variances in different units, and system GMM with a rank-one covariance and orthogonal instruments.ruff checkandruff format --checkpass cleanly on all modified files.