Skip to content

Commit 3ec2d1b

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 3721224 commit 3ec2d1b

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
@@ -399,6 +399,20 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
399399
return clean, sample_mask
400400

401401

402+
def _psd_sqrtm(A):
403+
"""Real symmetric positive-semidefinite matrix square root.
404+
405+
Symmetrizes ``A`` and clamps negative eigenvalues to zero before taking
406+
the square root, so the result stays real even for a slightly-indefinite
407+
input (where ``scipy.linalg.sqrtm`` would return a complex matrix).
408+
"""
409+
A = np.real(A)
410+
A = (A + A.T) / 2
411+
evals, evecs = linalg.eigh(A)
412+
evals = np.clip(evals, 0, None)
413+
return (evecs * np.sqrt(evals)) @ evecs.T
414+
415+
402416
def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
403417
win_overlap=0.66, max_dropout_fraction=0.1,
404418
min_clean_fraction=0.25, method="euclid", estimator="scm"):
@@ -492,7 +506,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
492506
Uavg = mean_covariance(U, metric="riemann")
493507

494508
# get the mixing matrix M
495-
M = linalg.sqrtm(np.real(Uavg))
509+
M = _psd_sqrtm(Uavg)
496510
D, Vtmp = linalg.eigh(M)
497511
# D, Vtmp = nonlinear_eigenspace(M, nc) TODO
498512
V = Vtmp[:, np.argsort(D)]

‎tests/test_asr.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,34 @@ def test_asr_functions(show=False, method="riemann"):
171171
plt.show()
172172

173173

174+
def test_psd_sqrtm_real_on_indefinite():
175+
"""_psd_sqrtm stays real on a slightly indefinite matrix (unlike scipy sqrtm)."""
176+
from scipy import linalg
177+
178+
from meegkit.asr import _psd_sqrtm
179+
180+
# Build a symmetric matrix with one tiny negative eigenvalue.
181+
B = rng.standard_normal((5, 5))
182+
A = B @ B.T # PSD
183+
evals, evecs = linalg.eigh(A)
184+
evals[0] = -1e-8
185+
A_indef = (evecs * evals) @ evecs.T
186+
187+
M = _psd_sqrtm(A_indef)
188+
189+
# The result must stay real...
190+
assert np.isrealobj(M)
191+
192+
# ...and square back to the clamped PSD matrix.
193+
evals_clamped = np.clip(evals, 0, None)
194+
A_psd = (evecs * evals_clamped) @ evecs.T
195+
assert np.allclose(M @ M, A_psd, atol=1e-8)
196+
197+
# plain sqrtm(real(A)) on the indefinite matrix still returns a complex root
198+
M_bad = linalg.sqrtm(np.real(A_indef))
199+
assert np.iscomplexobj(M_bad) and not np.allclose(M_bad.imag, 0)
200+
201+
174202
@pytest.mark.parametrize(argnames="method", argvalues=("riemann", "euclid"))
175203
@pytest.mark.parametrize(argnames="reref", argvalues=(False, True))
176204
def test_asr_class(method, reref, show=False):

0 commit comments

Comments
 (0)