Skip to content

Commit

Permalink
Improve sum op equals (#7681)
Browse files Browse the repository at this point in the history
* Enable PauliSumOp comparison with single PauliOp

* Also fix the commutative case where equals is called on PauliOp

* Add reno release note for PauliSumOp equals

Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
  • Loading branch information
towynlin and ikkoham committed Mar 10, 2022
1 parent 99d89ab commit 9f867e9
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
12 changes: 9 additions & 3 deletions qiskit/opflow/primitive_ops/pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,16 @@ def adjoint(self) -> "PauliOp":
return PauliOp(self.primitive, coeff=self.coeff.conjugate())

def equals(self, other: OperatorBase) -> bool:
if not isinstance(other, PauliOp) or not self.coeff == other.coeff:
return False
if isinstance(other, PauliOp) and self.coeff == other.coeff:
return self.primitive == other.primitive

return self.primitive == other.primitive
# pylint: disable=cyclic-import
from .pauli_sum_op import PauliSumOp

if isinstance(other, PauliSumOp):
return other == self

return False

def _expand_dim(self, num_qubits: int) -> "PauliOp":
return PauliOp(Pauli("I" * num_qubits).expand(self.primitive), coeff=self.coeff)
Expand Down
5 changes: 5 additions & 0 deletions qiskit/opflow/primitive_ops/pauli_sum_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ def adjoint(self) -> "PauliSumOp":
def equals(self, other: OperatorBase) -> bool:
self_reduced, other_reduced = self.reduce(), other.reduce()

if isinstance(other_reduced, PauliOp):
other_reduced = PauliSumOp(
SparsePauliOp(other_reduced.primitive, coeffs=[other_reduced.coeff])
)

if not isinstance(other_reduced, PauliSumOp):
return False

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
:class:`~qiskit.opflow.PauliSumOp` equality tests now handle the case when
one of the compared items is a single :class:`~qiskit.opflow.PauliOp`.
For example, ``0 * X + I == I`` now evaluates to True, whereas it was
False prior to this release.
2 changes: 2 additions & 0 deletions test/python/opflow/test_pauli_sum_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ def test_equals(self):

self.assertNotEqual((X ^ X) + (Y ^ Y), X + Y)
self.assertEqual((X ^ X) + (Y ^ Y), (Y ^ Y) + (X ^ X))
self.assertEqual(0 * X + I, I)
self.assertEqual(I, 0 * X + I)

theta = ParameterVector("theta", 2)
pauli_sum0 = theta[0] * (X + Z)
Expand Down

0 comments on commit 9f867e9

Please sign in to comment.