Repository: PennyLaneAI/pennylane
Pull request #5602 (2024-04-30 18:12:09)

BugFix: convert_to_opmath does not dequeue original op
**Context:**
Fixes latest failures in the legacy opmath tests in the plugin test matrix.

**Description of the Change:**
1. `convert_to_opmath` now dequeues the original op.
2. Skip test with `I()` when new opmath is disabled.


github-actions[bot]: Hello. You may have forgotten to update the changelog!
Please edit [`doc/releases/changelog-dev.md`](/PennyLaneAI/pennylane/blob/master/doc/releases/changelog-dev.md) with:
* A one-to-two sentence description of the change. You may include a small working example for new features.
* A link back to this PR.
* Your name (or GitHub username) in the contributors section.
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/5602?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
All modified and coverable lines are covered by tests :white_check_mark:
> :exclamation: No coverage uploaded for pull request base (`v0.36.0-rc0@0cb913e`). [Click here to learn what that means](https://docs.codecov.io/docs/error-reference?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#section-missing-base-commit).


<details><summary>Additional details and impacted files</summary>


```diff
@@              Coverage Diff               @@
##             v0.36.0-rc0    #5602   +/-   ##
==============================================
  Coverage               ?   99.69%           
==============================================
  Files                  ?      412           
  Lines                  ?    38284           
  Branches               ?        0           
==============================================
  Hits                   ?    38166           
  Misses                 ?      118           
  Partials               ?        0           
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/5602?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).


Patch:
diff --git a/pennylane/operation.py b/pennylane/operation.py
index cfd413890..d03bee24f 100644
--- a/pennylane/operation.py
+++ b/pennylane/operation.py
@@ -3043,10 +3043,14 @@ def convert_to_opmath(op):
         Operator: An operator using the new arithmetic operations, if relevant
     """
     if isinstance(op, (qml.ops.Hamiltonian, qml.ops.LinearCombination)):
+        if qml.QueuingManager.recording():
+            qml.QueuingManager.remove(op)
         c, ops = op.terms()
         ops = tuple(convert_to_opmath(o) for o in ops)
         return qml.dot(c, ops)
     if isinstance(op, Tensor):
+        if qml.QueuingManager.recording():
+            qml.QueuingManager.remove(op)
         return qml.prod(*op.obs)
     return op
 


Test patch:
diff --git a/tests/ops/op_math/test_sum.py b/tests/ops/op_math/test_sum.py
index 49e668e23..9a0cfd166 100644
--- a/tests/ops/op_math/test_sum.py
+++ b/tests/ops/op_math/test_sum.py
@@ -681,7 +681,11 @@ class TestProperties:
         assert sum_op._queue_category is None  # pylint: disable=protected-access
 
     def test_eigvals_Identity_no_wires(self):
-        """Test that the eigenvalues can be computed for a sum containing an identity with no wires."""
+        """Test that eigenvalues can be computed for a sum containing identity with no wires."""
+
+        if not qml.operation.active_new_opmath():
+            pytest.skip("Identity with no wires is not supported for legacy opmath")
+
         op1 = qml.X(0) + 2 * qml.I()
         op2 = qml.X(0) + 2 * qml.I(0)
         assert qml.math.allclose(sorted(op1.eigvals()), sorted(op2.eigvals()))
diff --git a/tests/test_operation.py b/tests/test_operation.py
index 83aaece52..911c43bec 100644
--- a/tests/test_operation.py
+++ b/tests/test_operation.py
@@ -3071,3 +3071,22 @@ def test_get_attr():
     assert (
         StatePrep is qml.operation.StatePrepBase
     )  # StatePrep imported from operation.py is an alias for StatePrepBase
+
+
+@pytest.mark.parametrize(
+    "make_op",
+    [
+        lambda: qml.Hamiltonian([1, 2], [qml.PauliX(0), qml.PauliY(1)]),
+        lambda: 1.2 * qml.PauliX(0),
+    ],
+)
+@pytest.mark.usefixtures("use_legacy_and_new_opmath")
+def test_convert_to_opmath_queueing(make_op):
+    """Tests that converting to opmath dequeues the original operation"""
+
+    with qml.queuing.AnnotatedQueue() as q:
+        original_op = make_op()
+        new_op = qml.operation.convert_to_opmath(original_op)
+
+    assert len(q.queue) == 1
+    assert q.queue[0] is new_op