From 74c05b87af5038233fa3eeae2e79435ed6e27075 Mon Sep 17 00:00:00 2001 From: Ryosuke Noro <64354442+RyosukeNORO@users.noreply.github.com> Date: Fri, 5 Jul 2024 18:02:44 -0400 Subject: [PATCH] fixed the ordering of the matrix in takagi with diagonal matrix added test to trigger both svd_order=True and False in takagi with diagonal matrix --- thewalrus/decompositions.py | 7 ++++--- thewalrus/tests/test_decompositions.py | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/thewalrus/decompositions.py b/thewalrus/decompositions.py index a8ae2d3e..df490513 100644 --- a/thewalrus/decompositions.py +++ b/thewalrus/decompositions.py @@ -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) diff --git a/thewalrus/tests/test_decompositions.py b/thewalrus/tests/test_decompositions.py index 5da07ac0..1a9e9b82 100644 --- a/thewalrus/tests/test_decompositions.py +++ b/thewalrus/tests/test_decompositions.py @@ -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( @@ -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)