Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve sum op equals #7681

Merged
merged 8 commits into from
Mar 10, 2022
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