Skip to content

Commit c35ed72

Browse files
p51leepavoljuhas
andauthored
Preserve max moment of control key while appending to circuit (#7626)
Control operations sharing the same control key could be assigned an earlier moment index, causing later measurements to appear before earlier controls. This change updates `ckey_indices` to keep the maximum moment index seen so far, preventing reordering of classical controls and measurements. Fixes #7622, fixes #7623 --------- Co-authored-by: Pavol Juhas <juhas@google.com>
1 parent c334f75 commit c35ed72

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

cirq-core/cirq/circuits/circuit.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3002,13 +3002,15 @@ def get_earliest_accommodating_moment_index(
30023002
mop_index = last_conflict + 1
30033003

30043004
# Update our dicts with data from this `mop` placement. Note `mop_index` will always be greater
3005-
# than the existing value for all of these, by construction.
3005+
# than the existing value for qubits and measurement keys, by construction.
30063006
for qubit in mop_qubits:
30073007
qubit_indices[qubit] = mop_index
30083008
for key in mop_mkeys:
30093009
mkey_indices[key] = mop_index
3010+
# For control keys, keep the maximum moment index seen so far because ops with the same control
3011+
# keys can commute past each other.
30103012
for key in mop_ckeys:
3011-
ckey_indices[key] = mop_index
3013+
ckey_indices[key] = max(mop_index, ckey_indices.get(key, -1))
30123014

30133015
return mop_index
30143016

cirq-core/cirq/circuits/circuit_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,24 @@ def test_append_control_key() -> None:
208208
assert len(c) == 1
209209

210210

211+
def test_append_control_key_before_measure() -> None:
212+
c = cirq.Circuit()
213+
q1, q2 = cirq.LineQubit.range(2)
214+
c.append(cirq.X(q1))
215+
c.append(cirq.X(q1))
216+
c.append(cirq.X(q1).with_classical_controls('a'))
217+
c.append(cirq.X(q2).with_classical_controls('a'))
218+
c.append(cirq.measure(q2, key='a'))
219+
assert c == cirq.Circuit(
220+
[
221+
cirq.Moment(cirq.X(q1), cirq.X(q2).with_classical_controls('a')),
222+
cirq.Moment(cirq.X(q1)),
223+
cirq.Moment(cirq.X(q1).with_classical_controls('a')),
224+
cirq.Moment(cirq.measure(q2, key='a')),
225+
]
226+
)
227+
228+
211229
def test_append_multiple() -> None:
212230
a = cirq.NamedQubit('a')
213231
b = cirq.NamedQubit('b')

0 commit comments

Comments
 (0)