Skip to content

Commit d94c457

Browse files
perlinmpavoljuhas
andauthored
Add IdentityGate._commutes_ (#6702)
* faster commutation * add _paulis_commute * Revert "add _paulis_commute" This reverts commit 49104f4. * Revert "faster commutation" This reverts commit 05a1efe. * add IdentityGate._commutes_ * add comment * commute with gates only * fix test * fix test * Update cirq-core/cirq/ops/identity_test.py Co-authored-by: Pavol Juhas <[email protected]> * type fix * import fix * minor test change * Revert "minor test change" This reverts commit b5282da. --------- Co-authored-by: Pavol Juhas <[email protected]>
1 parent 8d8a6c5 commit d94c457

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

cirq-core/cirq/ops/identity.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,14 @@
1313
# limitations under the License.
1414
"""IdentityGate."""
1515

16-
from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, Sequence
16+
from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING, Sequence, Union
1717

1818
import numpy as np
1919
import sympy
2020

2121
from cirq import protocols, value
2222
from cirq._doc import document
23+
from cirq.type_workarounds import NotImplementedType
2324
from cirq.ops import raw_types
2425

2526
if TYPE_CHECKING:
@@ -75,6 +76,12 @@ def __pow__(self, power: Any) -> Any:
7576
return self
7677
return NotImplemented
7778

79+
def _commutes_(self, other: Any, *, atol: float = 1e-8) -> Union[bool, NotImplementedType]:
80+
"""The identity gate commutes with all other gates."""
81+
if not isinstance(other, raw_types.Gate):
82+
return NotImplemented
83+
return True
84+
7885
def _has_unitary_(self) -> bool:
7986
return True
8087

cirq-core/cirq/ops/identity_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,3 +208,9 @@ def test_identity_short_circuits_act_on():
208208
args = mock.Mock(cirq.SimulationState)
209209
args._act_on_fallback_.side_effect = mock.Mock(side_effect=Exception('No!'))
210210
cirq.act_on(cirq.IdentityGate(1)(cirq.LineQubit(0)), args)
211+
212+
213+
def test_identity_commutes():
214+
assert cirq.commutes(cirq.I, cirq.X)
215+
with pytest.raises(TypeError):
216+
cirq.commutes(cirq.I, "Gate")

0 commit comments

Comments
 (0)