From f2df65e6474f4b7a39d65bb06f203b2cf678d304 Mon Sep 17 00:00:00 2001 From: albi3ro Date: Mon, 1 Apr 2024 12:12:15 -0400 Subject: [PATCH 1/2] dequeue ops in Hamiltonian.__matmul__ --- doc/releases/changelog-dev.md | 2 ++ pennylane/ops/qubit/hamiltonian.py | 3 +++ tests/ops/qubit/test_hamiltonian.py | 11 +++++++++++ 3 files changed, 16 insertions(+) diff --git a/doc/releases/changelog-dev.md b/doc/releases/changelog-dev.md index 621b094b7fb..172fc4b18c1 100644 --- a/doc/releases/changelog-dev.md +++ b/doc/releases/changelog-dev.md @@ -291,6 +291,8 @@

Bug fixes 🐛

+* Using `@` with legacy Hamiltonian instances now properly de-queues the previously existing operations. + * The `QNSPSAOptimizer` now properly handles differentiable parameters, resulting in being able to use it for more than one optimization step. [(#5439)](https://github.com/PennyLaneAI/pennylane/pull/5439) diff --git a/pennylane/ops/qubit/hamiltonian.py b/pennylane/ops/qubit/hamiltonian.py index 2f6410de261..17c6de25277 100644 --- a/pennylane/ops/qubit/hamiltonian.py +++ b/pennylane/ops/qubit/hamiltonian.py @@ -662,6 +662,9 @@ def __matmul__(self, H): coeffs1 = copy(self.coeffs) ops1 = self.ops.copy() + qml.QueuingManager.remove(H) + qml.QueuingManager.remove(self) + if isinstance(H, Hamiltonian): shared_wires = Wires.shared_wires([self.wires, H.wires]) if len(shared_wires) > 0: diff --git a/tests/ops/qubit/test_hamiltonian.py b/tests/ops/qubit/test_hamiltonian.py index 0a3ab5104d9..c88b1978a92 100644 --- a/tests/ops/qubit/test_hamiltonian.py +++ b/tests/ops/qubit/test_hamiltonian.py @@ -678,6 +678,17 @@ def circuit2(param): dev = qml.device("default.qubit", wires=2) +@pytest.mark.usefixtures("use_legacy_and_new_opmath") +def test_matmul_queuing(): + """Test that the other and self are removed during Hamiltonian.__matmul__ .""" + + with qml.queuing.AnnotatedQueue() as q: + H = 0.5 * qml.X(0) @ qml.Y(1) + + assert len(q) == 1 + assert q.queue[0] is H + + @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_deprecation_with_new_opmath(recwarn): """Test that a warning is raised if attempting to create a Hamiltonian with new operator From e5de5475625430327299bd092cb341e4b8eb900f Mon Sep 17 00:00:00 2001 From: Christina Lee Date: Mon, 1 Apr 2024 12:16:27 -0400 Subject: [PATCH 2/2] Update doc/releases/changelog-dev.md --- doc/releases/changelog-dev.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/releases/changelog-dev.md b/doc/releases/changelog-dev.md index 172fc4b18c1..5356fa8a73b 100644 --- a/doc/releases/changelog-dev.md +++ b/doc/releases/changelog-dev.md @@ -292,6 +292,7 @@

Bug fixes 🐛

* Using `@` with legacy Hamiltonian instances now properly de-queues the previously existing operations. + [(#5454)](https://github.com/PennyLaneAI/pennylane/pull/5455) * The `QNSPSAOptimizer` now properly handles differentiable parameters, resulting in being able to use it for more than one optimization step. [(#5439)](https://github.com/PennyLaneAI/pennylane/pull/5439)