Skip to content

Commit

Permalink
BugFix in cirq.merge_moments to correctly handle new empty moments. (
Browse files Browse the repository at this point in the history
…quantumlib#5013)

Fixes a bug where `cirq.merge_moments` would treat a newly merged empty `cirq.Moment()` as the case where we return `None` to indicate that two moments cannot be merged.
  • Loading branch information
tanujkhattar authored and rht committed May 1, 2023
1 parent e6c41e3 commit ddec75b
Show file tree
Hide file tree
Showing 2 changed files with 15 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 @@ -392,7 +392,7 @@ def merge_moments(
merged_moments: List[circuits.Moment] = [circuit[0]]
for current_moment in circuit[1:]:
merged_moment = merge_func(merged_moments[-1], current_moment)
if not merged_moment:
if merged_moment is None:
merged_moments.append(current_moment)
else:
merged_moments[-1] = merged_moment
Expand Down
14 changes: 14 additions & 0 deletions cirq-core/cirq/transformers/transformer_primitives_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,20 @@ def mul(op1, op2):
)


def test_merge_moments_empty_moment_as_intermediate_step():
q = cirq.NamedQubit("q")
c_orig = cirq.Circuit([cirq.X(q), cirq.Y(q), cirq.Z(q)] * 2, cirq.X(q) ** 0.5)

def merge_func(m1: cirq.Moment, m2: cirq.Moment):
gate = cirq.single_qubit_matrix_to_phxz(cirq.unitary(cirq.Circuit(m1, m2)), atol=1e-8)
return cirq.Moment(gate.on(q) if gate else [])

c_new = cirq.merge_moments(c_orig, merge_func)
assert len(c_new) == 1
assert isinstance(c_new[0][q].gate, cirq.PhasedXZGate)
cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(c_orig, c_new, atol=1e-8)


def test_merge_moments_empty_circuit():
def fail_if_called_func(*_):
assert False
Expand Down

0 comments on commit ddec75b

Please sign in to comment.