Skip to content

Fix: Allow subtraction of IdentityGate in PauliSum.__sub__ #7276

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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
5 changes: 4 additions & 1 deletion cirq-core/cirq/ops/linear_combinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,7 +798,10 @@ def __isub__(self, other):

def __sub__(self, other):
if not isinstance(other, (numbers.Complex, PauliString, PauliSum)):
return NotImplemented
if hasattr(other, 'gate') and isinstance(other.gate, identity.IdentityGate):
other = PauliString(other)
else:
return NotImplemented
result = self.copy()
result -= other
return result
Expand Down
16 changes: 16 additions & 0 deletions cirq-core/cirq/ops/pauli_string_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2137,3 +2137,19 @@ def test_resolve(resolve_fn):
pst = cirq.PauliString({q: 'x'}, coefficient=t)
ps1 = cirq.PauliString({q: 'x'}, coefficient=1j)
assert resolve_fn(pst, {'t': 1j}) == ps1


def test_pauli_ops_identity_gate_operation():
q = cirq.LineQubit(0)
paulis = (cirq.I(q), cirq.X(q), cirq.Y(q), cirq.Z(q))
for p1 in paulis:
for p2 in paulis:
# TODO: Issue #7280 - Support addition and subtraction of identity gate operations.
if p1 == cirq.I(q) and p2 == cirq.I(q):
continue
assert isinstance(
p1 + p2, (cirq.PauliSum, cirq.PauliString)
), f"Addition failed for {p1} + {p2}"
assert isinstance(
p1 - p2, (cirq.PauliSum, cirq.PauliString)
), f"Subtraction failed for {p1} - {p2}"