Skip to content

Add IdentityGate._commutes_ #6702

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

Merged
merged 14 commits into from
Aug 19, 2024
9 changes: 8 additions & 1 deletion cirq-core/cirq/ops/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
# limitations under the License.
"""IdentityGate."""

from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, Sequence
from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, Sequence, Union

import numpy as np
import sympy

from cirq import protocols, value
from cirq._doc import document
from cirq.type_workarounds import NotImplementedType
from cirq.ops import raw_types

if TYPE_CHECKING:
Expand Down Expand Up @@ -75,6 +76,12 @@ def __pow__(self, power: Any) -> Any:
return self
return NotImplemented

def _commutes_(self, other: Any, *, atol: float = 1e-8) -> Union[bool, NotImplementedType]:
"""The identity gate commutes with all other gates."""
if not isinstance(other, raw_types.Gate):
return NotImplemented
return True

def _has_unitary_(self) -> bool:
return True

Expand Down
6 changes: 6 additions & 0 deletions cirq-core/cirq/ops/identity_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,9 @@ def test_identity_short_circuits_act_on():
args = mock.Mock(cirq.SimulationState)
args._act_on_fallback_.side_effect = mock.Mock(side_effect=Exception('No!'))
cirq.act_on(cirq.IdentityGate(1)(cirq.LineQubit(0)), args)


def test_identity_commutes():
assert cirq.commutes(cirq.I, cirq.X)
with pytest.raises(TypeError):
cirq.commutes(cirq.I, "Gate")