Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions meegkit/utils/covariances.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,5 +503,15 @@ def ehess(X, U):
problem = Problem(manifold=manifold, cost=cost, euclidean_gradient=egrad,
euclidean_hessian=ehess)
Xsol = solver.run(problem, initial_point=U0)

return S0, Xsol.point
X = Xsol.point

# The Grassmann manifold only fixes the *subspace* spanned by X, so X carries
# an arbitrary internal rotation. Diagonalise the k×k projected matrix to
# obtain proper Ritz pairs: after rotation, X.T @ L @ X is diagonal and each
# column of X is a genuine approximate eigenvector of L.
T = X.T @ L @ X
T = (T + T.T) / 2 # symmetrise against numerical noise
S, R = linalg.eigh(T)
X = X @ R

return np.real(S), np.real(X)
27 changes: 27 additions & 0 deletions tests/test_cov.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np
import pytest
from numpy.testing import assert_almost_equal

from meegkit.utils import convmtx, tscov, tsxcov
Expand Down Expand Up @@ -88,6 +89,32 @@ def test_convmtx():
])
)


def test_nonlinear_eigenspace_consistent_eigpairs():
"""Each returned eigenvalue must match the Rayleigh quotient of its column."""
pytest.importorskip("pymanopt")
from meegkit.utils.covariances import nonlinear_eigenspace

A = rng.standard_normal((6, 6))
L = A.T @ A + np.eye(6) * 1e-6

S, X = nonlinear_eigenspace(L, 6)
# X.T @ L @ X should be (near) diagonal; check the diagonal matches S
# element-wise so a permutation between S and X columns cannot slip through.
rayleigh = np.real(np.diag(X.T @ L @ X))

np.testing.assert_allclose(
S,
rayleigh,
rtol=1e-3,
atol=1e-6,
)

# Off-diagonal entries of the projected matrix should be negligible.
proj = X.T @ L @ X
off_diag = proj - np.diag(np.diag(proj))
assert np.max(np.abs(off_diag)) < 1e-6 * np.max(np.abs(np.diag(proj)))

if __name__ == "__main__":
import pytest
pytest.main([__file__])
Expand Down
Loading
Loading