Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch positive definite error #24

Merged
merged 2 commits into from Aug 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/xarray_einstats/stats.py
Expand Up @@ -5,6 +5,7 @@

import numpy as np
import xarray as xr
from numpy.linalg import LinAlgError
from scipy import stats

from .linalg import cholesky, eigh
Expand Down Expand Up @@ -363,7 +364,12 @@ def rvs(self, mean=None, cov=None, dims=None, *, size=1, rv_dims=None, random_st
mean, cov, dims = self._process_inputs(mean, cov, dims)
dim1, dim2 = dims

cov_chol = cholesky(cov, dims=dims)
try:
cov_chol = cholesky(cov, dims=dims)
except LinAlgError:
k = len(cov[dim1])
eye = xr.DataArray(np.eye(k), dims=list(dims))
cov_chol = cholesky(cov + 1e-10 * eye, dims=dims)
std_norm = XrContinuousRV(stats.norm, xr.zeros_like(mean.rename({dim1: dim2})), 1)
samples = std_norm.rvs(size=size, dims=rv_dims, random_state=random_state)
return mean + xr.dot(cov_chol, samples, dims=dim2)
Expand Down