Skip to content

Commit ded6cee

Browse files
committed
[FIX] ASR: use a real PSD square root in asr_calibrate
asr_calibrate computed M = linalg.sqrtm(np.real(Uavg)), which only strips a pre-existing imaginary part but does not make Uavg positive-semidefinite. If the robust average covariance Uavg has even a tiny negative eigenvalue (realistic for average-referenced / rank-deficient EEG covariance means), scipy.linalg.sqrtm of the resulting indefinite symmetric matrix returns a complex M, which then silently propagates through eigh(M) into V and the threshold matrix T. asr_process already guards against this by taking np.real() of its eigen-quantities after eigh, but asr_calibrate lacked the equivalent guard. Add _psd_sqrtm(), a real symmetric PSD square root that symmetrizes its input and clamps numerically-negative eigenvalues to zero before taking the square root, and use it in asr_calibrate. For a genuinely PSD Uavg (the normal case) this is the same principal square root sqrtm would return, so calibration is numerically unchanged; when Uavg is slightly indefinite it now yields a real M, and hence real V/T.
1 parent 107cd1b commit ded6cee

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

‎meegkit/asr.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,20 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
417417
return clean, sample_mask
418418

419419

420+
def _psd_sqrtm(A):
421+
"""Real symmetric positive-semidefinite matrix square root.
422+
423+
Symmetrizes ``A`` and clamps negative eigenvalues to zero before taking
424+
the square root, so the result stays real even for a slightly-indefinite
425+
input (where ``scipy.linalg.sqrtm`` would return a complex matrix).
426+
"""
427+
A = np.real(A)
428+
A = (A + A.T) / 2
429+
evals, evecs = linalg.eigh(A)
430+
evals = np.clip(evals, 0, None)
431+
return (evecs * np.sqrt(evals)) @ evecs.T
432+
433+
420434
def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
421435
win_overlap=0.66, max_dropout_fraction=0.1,
422436
min_clean_fraction=0.25, method="euclid", estimator="scm"):
@@ -517,7 +531,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
517531
Uavg = mean_covariance(U, metric="riemann")
518532

519533
# get the mixing matrix M
520-
M = linalg.sqrtm(np.real(Uavg))
534+
M = _psd_sqrtm(Uavg)
521535
D, Vtmp = linalg.eigh(M)
522536
# D, Vtmp = nonlinear_eigenspace(M, nc) TODO
523537
V = Vtmp[:, np.argsort(D)]

‎tests/test_asr.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,34 @@ def test_clean_windows_one_sided_zthresholds(zthresholds):
213213
assert sample_mask.dtype == bool
214214

215215

216+
def test_psd_sqrtm_real_on_indefinite():
217+
"""_psd_sqrtm stays real on a slightly indefinite matrix (unlike scipy sqrtm)."""
218+
from scipy import linalg
219+
220+
from meegkit.asr import _psd_sqrtm
221+
222+
# Build a symmetric matrix with one tiny negative eigenvalue.
223+
B = rng.standard_normal((5, 5))
224+
A = B @ B.T # PSD
225+
evals, evecs = linalg.eigh(A)
226+
evals[0] = -1e-8
227+
A_indef = (evecs * evals) @ evecs.T
228+
229+
M = _psd_sqrtm(A_indef)
230+
231+
# The result must stay real...
232+
assert np.isrealobj(M)
233+
234+
# ...and square back to the clamped PSD matrix.
235+
evals_clamped = np.clip(evals, 0, None)
236+
A_psd = (evecs * evals_clamped) @ evecs.T
237+
assert np.allclose(M @ M, A_psd, atol=1e-8)
238+
239+
# plain sqrtm(real(A)) on the indefinite matrix still returns a complex root
240+
M_bad = linalg.sqrtm(np.real(A_indef))
241+
assert np.iscomplexobj(M_bad) and not np.allclose(M_bad.imag, 0)
242+
243+
216244
@pytest.mark.parametrize(argnames="method", argvalues=("riemann", "euclid"))
217245
@pytest.mark.parametrize(argnames="reref", argvalues=(False, True))
218246
def test_asr_class(method, reref, show=False):

0 commit comments

Comments
 (0)