Skip to content

Commit

Permalink
bugfix: substraction works with new opmath (#4441)
Browse files Browse the repository at this point in the history
* bugfix: substraction works with new opmath

* changelog

* add test when not implemented

* use s_prod in Operator.__sub__
  • Loading branch information
timmysilv authored Aug 9, 2023
1 parent e3e85aa commit a025e29
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,9 @@ array([False, False])
and `var` measurements.
[(#4426)](https://github.com/PennyLaneAI/pennylane/pull/4426)

* Subtracting a `Prod` from another operator now works as expected.
[(#4441)](https://github.com/PennyLaneAI/pennylane/pull/4441)

<h3>Contributors ✍️</h3>

This release contains contributions from (in alphabetical order):
Expand Down
4 changes: 3 additions & 1 deletion pennylane/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,9 @@ def __matmul__(self, other):

def __sub__(self, other):
"""The subtraction operation of Operator-Operator objects and Operator-scalar."""
if isinstance(other, (Operator, TensorLike)):
if isinstance(other, Operator):
return self + qml.s_prod(-1, other)
if isinstance(other, TensorLike):
return self + (qml.math.multiply(-1, other))
return NotImplemented

Expand Down
14 changes: 14 additions & 0 deletions tests/test_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,14 @@ def test_sub_rsub_and_neg_dunder_methods(self):
neg_op = -qml.PauliX(0)
assert np.allclose(a=neg_op.matrix(), b=np.array([[0, -1], [-1, 0]]), rtol=0)

def test_sub_obs_from_op(self):
"""Test that __sub__ returns an SProd to be consistent with other Operator dunders."""
op = qml.S(0) - qml.PauliX(1)
assert isinstance(op, Sum)
assert isinstance(op[1], SProd)
assert qml.equal(op[0], qml.S(0))
assert qml.equal(op[1], SProd(-1, qml.PauliX(1)))

def test_mul_with_scalar(self):
"""Test the __mul__ dunder method with a scalar value."""
sprod_op = 4 * qml.RX(1, 0)
Expand Down Expand Up @@ -2489,6 +2497,7 @@ def test_composed(self):
(qml.S(0), qml.PauliX(0)),
(qml.PauliX(0), qml.S(0)),
(qml.PauliX(0), qml.PauliY(0)),
(qml.PauliZ(0), qml.prod(qml.PauliX(0), qml.PauliY(1))),
]


Expand Down Expand Up @@ -2522,6 +2531,11 @@ def test_sub_operators(self, op0, op1):
assert op[1].scalar == -1
assert qml.equal(op[1].base, op1)

def test_sub_with_unknown_not_supported(self):
"""Test subtracting an unexpected type from an Operator."""
with pytest.raises(TypeError, match="unsupported operand type"):
_ = qml.S(0) - "foo"

def test_op_with_scalar(self):
"""Tests adding/subtracting ops with scalars."""
x0 = qml.PauliX(0)
Expand Down

0 comments on commit a025e29

Please sign in to comment.