Skip to content

ENH/BUG: add min_diag option to cov_nearest for zero or negative diagonal - #9898

Merged
bashtage merged 3 commits into
statsmodels:mainfrom
vsaraikin:fix/cov-nearest-min-diag
Aug 3, 2026
Merged

bashtage merged 3 commits into
statsmodels:mainfrom
vsaraikin:fix/cov-nearest-min-diag

Conversation

@vsaraikin

Copy link
Copy Markdown
Contributor

Summary

Closes #9675. cov_nearest returns a matrix full of nan when the input covariance has a zero (or negative) element on the diagonal:

>>> cov_nearest(np.array([[2.0, 0.0], [0.0, 0.0]]))
[[ 2. nan]
 [nan nan]]

The cause is the conversion to a correlation matrix (cov2corr), which divides by std = sqrt(diag(cov)); a zero variance divides by zero and a negative variance takes sqrt of a negative number, so the result is nan and every downstream step propagates it.

This adds an opt-in min_diag parameter, following the approach @josef-pkt outlined in the issue: when min_diag is a positive float, diagonal elements below it are raised to min_diag before the correlation conversion, and a SpecificationWarning is issued. This fixes both zero and negative diagonals:

>>> cov_nearest(np.array([[2.0, 0.0], [0.0, 0.0]]), min_diag=1e-8)
[[2.e+00 0.e+00]
 [0.e+00 1.e-08]]

which matches the magnitude of R's Matrix::nearPD on the same input.

Default behavior is unchanged (min_diag=None), so existing callers are unaffected — the nan result is only corrected when the caller opts in. I kept it opt-in rather than picking a non-None default; happy to change the default or the 1e-8 example value if you'd prefer a specific one.

Testing

  • Added test_cov_nearest_min_diag, parametrized over both method="clipped" and method="nearest", asserting: default still returns nan (no behavior change), min_diag removes the nan, the result equals [[2, 0], [0, 1e-8]] and is PSD, a negative diagonal is corrected, the input array is not mutated, and no warning fires when the diagonal is already above min_diag.
  • Full statsmodels/stats/tests/test_corrpsd.py passes (22 passed, 3 skipped) on Python 3.13 / macOS arm64.
  • flake8 clean on both changed files.

@vsaraikin
vsaraikin marked this pull request as ready for review July 9, 2026 16:04
Comment on lines +232 to +233
SpecificationWarning,
)

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.

Suggested change
SpecificationWarning,
)
SpecificationWarning,
stacklevel=2,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks! Applied the stacklevel=2 suggestion. On the CI failure: the full test_corrpsd.py suite passes locally (22 passed, 3 skipped) including under -W error, and codecov is green. The Azure failure looks unrelated/systemic — it's also red on other current PRs (e.g. #9894) — so I believe it's not from this change, but happy to dig further if you spot something specific.

@Aniketsy Aniketsy 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.

@vsaraikin thanks for the work ❤️ . i haven't gone through the changes in depth, i've suggested one changes as i looked into ci fail.

I will look into this if you say 😸

@vsaraikin
vsaraikin force-pushed the fix/cov-nearest-min-diag branch from 692f82b to b8890bf Compare August 2, 2026 14:59

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Two small changes then LGTM.

Comment thread statsmodels/stats/correlation_tools.py Outdated

def cov_nearest(cov, method="clipped", threshold=1e-15, n_fact=100, return_all=False):
def cov_nearest(cov, method="clipped", threshold=1e-15, n_fact=100,
return_all=False, min_diag=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

New keyword should be keyword only, so , *, min_diag=None.

Comment thread statsmodels/stats/correlation_tools.py Outdated
diag = np.diag(cov)
if np.any(diag < min_diag):
warnings.warn(
"Diagonal elements below min_diag=%r have been raised to "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you rebase on main, and then run the latest ruff? This file will fail the current CI checks. The only CI checks we now have are ruff and flake8.

@vsaraikin
vsaraikin force-pushed the fix/cov-nearest-min-diag branch from b8890bf to ee4eafb Compare August 3, 2026 09:03
@bashtage

bashtage commented Aug 3, 2026

Copy link
Copy Markdown
Member

Thanks

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM.

@bashtage
bashtage merged commit 6d35d3b into statsmodels:main Aug 3, 2026
3 checks passed
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.

cov_nearest cannot not handle matrices with zero in the diagonal

3 participants