Skip to content

Commit

Permalink
Make order of traversal deterministic in merge_operations primitive (
Browse files Browse the repository at this point in the history
…#4764)

This PR fixes the iteration order of operations in a single moment in the `merge_operations` transformer primitive by iterating over operations in sorted order, sorted based on `op.qubits`.
  • Loading branch information
tanujkhattar authored Jan 19, 2022
1 parent 7ffc77c commit 745ee1b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cirq-core/cirq/transformers/transformer_primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def apply_merge_func(op1: ops.Operation, op2: ops.Operation) -> Optional[ops.Ope
ret_circuit = circuits.Circuit()
for current_moment in circuit:
new_moment = ops.Moment()
for op in current_moment:
for op in sorted(current_moment.operations, key=lambda op: op.qubits):
op_qs = set(op.qubits)
idx = ret_circuit.prev_moment_operating_on(tuple(op_qs))
if idx is not None and op_qs.issubset(ret_circuit[idx][op_qs].operations[0].qubits):
Expand Down
23 changes: 23 additions & 0 deletions cirq-core/cirq/transformers/transformer_primitives_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,29 @@ def merge_func(op1, op2):
)


@pytest.mark.parametrize('qubit_order', ([0, 1], [1, 0]))
def test_merge_operations_deterministic_order(qubit_order):
q = cirq.LineQubit.range(2)
c_orig = cirq.Circuit(cirq.identity_each(*q), cirq.H.on_each(q[i] for i in qubit_order))
cirq.testing.assert_has_diagram(
c_orig,
'''
0: ───I───H───
1: ───I───H───''',
)
c_new = cirq.merge_operations(
c_orig, lambda op1, op2: op2 if isinstance(op1.gate, cirq.IdentityGate) else None
)
cirq.testing.assert_has_diagram(
c_new,
'''
0: ───H───────
1: ───────H───''',
)


@pytest.mark.parametrize("op_density", [0.1, 0.5, 0.9])
def test_merge_operations_complexity(op_density):
prng = cirq.value.parse_random_state(11011)
Expand Down

0 comments on commit 745ee1b

Please sign in to comment.