Skip to content

Commit

Permalink
fixed the ordering of the matrix in takagi with diagonal matrix
Browse files Browse the repository at this point in the history
added test to trigger both svd_order=True and False in takagi with diagonal matrix
  • Loading branch information
RyosukeNORO committed Jul 5, 2024
1 parent cf82481 commit 74c05b8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 4 additions & 3 deletions thewalrus/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,14 @@ def takagi(A, svd_order=True):
# If the matrix is diagonal, Takagi decomposition is easy
if np.allclose(A, np.diag(np.diag(A)), rtol=1e-16):
d = np.diag(A)
U = np.diag(np.exp(1j * 0.5 * np.angle(d)))
l = np.abs(d)
idx = np.argsort(l)
d = d[idx]
l = l[idx]
U = U[idx]
U = np.diag(np.exp(1j * 0.5 * np.angle(d)))
U = U[::-1, :]
if svd_order:
return l[::-1], U[::-1, :]
return l[::-1], U[:, ::-1]
return l, U

u, d, v = np.linalg.svd(A)
Expand Down
5 changes: 3 additions & 2 deletions thewalrus/tests/test_decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,8 @@ def test_takagi_error():
takagi(A)


def test_takagi_diagonal_matrix():
@pytest.mark.parametrize("svd_order", [True, False])
def test_takagi_diagonal_matrix(svd_order):
"""Test the takagi decomposition works well for a specific matrix that was not decomposed accurately in a previous implementation.
See more info in PR #393 (https://github.com/XanaduAI/thewalrus/pull/393)"""
A = np.array(
Expand All @@ -356,7 +357,7 @@ def test_takagi_diagonal_matrix():
],
]
)
d, U = takagi(A)
d, U = takagi(A, svd_order=svd_order)
assert np.allclose(A, U @ np.diag(d) @ U.T)
assert np.allclose(U @ np.conjugate(U).T, np.eye(len(U)))
assert np.all(d >= 0)
Expand Down

0 comments on commit 74c05b8

Please sign in to comment.