Skip to content

Commit cbc8943

Browse files
authored
[FIX] ASR: use a real PSD square root in asr_calibrate (#114)
`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, but `asr_calibrate` did not. Add `_psd_sqrtm()`, a real symmetric PSD square root that symmetrizes its input and clamps numerically-negative eigenvalues to zero before taking the 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. ### Testing Added a regression test showing `_psd_sqrtm` stays real on a slightly indefinite matrix where `sqrtm` returns complex. Full `tests/test_asr.py` passes; `ruff` clean.
1 parent f71758d commit cbc8943

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
@@ -444,6 +444,20 @@ def _rms_window_offsets(ns, N, win_overlap):
444444
return np.round(np.arange(0, ns - N, N * (1 - win_overlap))).astype(int)
445445

446446

447+
def _psd_sqrtm(A):
448+
"""Real symmetric positive-semidefinite matrix square root.
449+
450+
Symmetrizes ``A`` and clamps negative eigenvalues to zero before taking
451+
the square root, so the result stays real even for a slightly-indefinite
452+
input (where ``scipy.linalg.sqrtm`` would return a complex matrix).
453+
"""
454+
A = np.real(A)
455+
A = (A + A.T) / 2
456+
evals, evecs = linalg.eigh(A)
457+
evals = np.clip(evals, 0, None)
458+
return (evecs * np.sqrt(evals)) @ evecs.T
459+
460+
447461
def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
448462
win_overlap=0.66, max_dropout_fraction=0.1,
449463
min_clean_fraction=0.25, method="euclid", estimator="scm"):
@@ -544,7 +558,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
544558
Uavg = mean_covariance(U, metric="riemann")
545559

546560
# get the mixing matrix M
547-
M = linalg.sqrtm(np.real(Uavg))
561+
M = _psd_sqrtm(Uavg)
548562
D, Vtmp = linalg.eigh(M)
549563
# D, Vtmp = nonlinear_eigenspace(M, nc) TODO
550564
V = Vtmp[:, np.argsort(D)]

‎tests/test_asr.py‎

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

216216

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

0 commit comments

Comments
 (0)