Skip to content

Commit

Permalink
Update sporadically failing Hermitian test (#4258)
Browse files Browse the repository at this point in the history
* update test

* fix comments

* see if this fixes mocking

* Add pytest fixture Hermitian._eigs={} before each test

* Update tests/ops/qubit/test_observables.py

Co-authored-by: Matthew Silverman <matthews@xanadu.ai>

---------

Co-authored-by: Matthew Silverman <matthews@xanadu.ai>
  • Loading branch information
lillian542 and timmysilv authored Jun 16, 2023
1 parent e102fe2 commit 81b1c65
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion tests/ops/qubit/test_observables.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@
H,
)


@pytest.fixture(autouse=True)
def run_before_tests():
qml.Hermitian._eigs = {}
yield


# Standard observables, their matrix representation, and eigenvalues
OBSERVABLES = [
(qml.PauliX, X, [1, -1]),
Expand Down Expand Up @@ -304,17 +311,28 @@ def test_hermitian_eigvals_eigvecs_same_observable_twice(
assert len(qml.Hermitian._eigs) == 1

@pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA)
def test_hermitian_diagonalizing_gates(self, observable, eigvals, eigvecs, tol):
def test_hermitian_diagonalizing_gates(self, observable, eigvals, eigvecs, tol, mocker):
"""Tests that the diagonalizing_gates method of the Hermitian class returns the correct results."""

# check calling `diagonalizing_gates` when `observable` is not in `_eigs` adds expected entry to `_eigs`
spy = mocker.spy(np.linalg, "eigh")

qubit_unitary = qml.Hermitian(observable, wires=[0]).diagonalizing_gates()

assert spy.call_count == 1

key = tuple(observable.flatten().tolist())
assert np.allclose(qml.Hermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0)
assert np.allclose(qml.Hermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0)

assert np.allclose(qubit_unitary[0].data, eigvecs.conj().T, atol=tol, rtol=0)
assert len(qml.Hermitian._eigs) == 1

# calling it again doesn't recalculate or add anything to _eigs (uses cached value)
_ = qml.Hermitian(observable, wires=[0]).diagonalizing_gates()
assert spy.call_count == 1
assert len(qml.Hermitian._eigs) == 1

def test_hermitian_compute_diagonalizing_gates(self, tol):
"""Tests that the compute_diagonalizing_gates method of the
Hermitian class returns the correct results."""
Expand Down

0 comments on commit 81b1c65

Please sign in to comment.