Skip to content

Commit 504bdbb

Browse files
authored
Fix behavior of MergeInteractions for tagged partial CZ gates (#4288)
* Add test for the failing case with a tagged operation * Fix merge interactions for tagged operation
1 parent c80e463 commit 504bdbb

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

cirq-core/cirq/optimizers/merge_interactions.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,9 @@ def optimization_at(
5555

5656
switch_to_new = False
5757
switch_to_new |= any(
58-
len(old_op.qubits) == 2 and not isinstance(old_op.gate, ops.CZPowGate)
58+
len(old_op.qubits) == 2 and not self._may_keep_old_op(old_op)
5959
for old_op in old_operations
6060
)
61-
if not self.allow_partial_czs:
62-
switch_to_new |= any(
63-
isinstance(old_op, ops.GateOperation)
64-
and isinstance(old_op.gate, ops.CZPowGate)
65-
and old_op.gate.exponent != 1
66-
for old_op in old_operations
67-
)
6861

6962
# This point cannot be optimized using this method
7063
if not switch_to_new and old_interaction_count <= 1:
@@ -89,6 +82,13 @@ def optimization_at(
8982
new_operations=new_operations,
9083
)
9184

85+
def _may_keep_old_op(self, old_op: 'cirq.Operation') -> bool:
86+
"""Returns True if the old two-qubit operation may be left unchanged
87+
without decomposition."""
88+
if self.allow_partial_czs:
89+
return isinstance(old_op.gate, ops.CZPowGate)
90+
return isinstance(old_op.gate, ops.CZPowGate) and old_op.gate.exponent == 1
91+
9292
def _op_to_matrix(
9393
self, op: ops.Operation, qubits: Tuple['cirq.Qid', ...]
9494
) -> Optional[np.ndarray]:

cirq-core/cirq/optimizers/merge_interactions_test.py

+10
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,16 @@ def test_optimizes_single_iswap():
163163
assert len([1 for op in c.all_operations() if len(op.qubits) == 2]) == 2
164164

165165

166+
def test_optimizes_tagged_partial_cz():
167+
a, b = cirq.LineQubit.range(2)
168+
c = cirq.Circuit((cirq.CZ ** 0.5)(a, b).with_tags('mytag'))
169+
assert_optimization_not_broken(c)
170+
cirq.MergeInteractions(allow_partial_czs=False).optimize_circuit(c)
171+
assert (
172+
len([1 for op in c.all_operations() if len(op.qubits) == 2]) == 2
173+
), 'It should take 2 CZ gates to decompose a CZ**0.5 gate'
174+
175+
166176
@pytest.mark.parametrize(
167177
'circuit',
168178
(

0 commit comments

Comments
 (0)