Skip to content

Commit fade070

Browse files
authored
Add support for deep=True to cirq.drop_empty_moments transformer (#5113)
- Adds support to recursively run `cirq.drop_empty_moments` transformer on circuits wrapped inside a circuit operation by setting deep=True in transformer context. - Part of #5039
1 parent cfa255a commit fade070

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

cirq-core/cirq/transformers/drop_empty_moments.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,11 @@ def drop_empty_moments(
3434
Returns:
3535
Copy of the transformed input circuit.
3636
"""
37-
return transformer_primitives.map_moments(circuit.unfreeze(False), lambda m, _: m if m else [])
37+
if context is None:
38+
context = transformer_api.TransformerContext()
39+
return transformer_primitives.map_moments(
40+
circuit.unfreeze(False),
41+
lambda m, _: m if m else [],
42+
deep=context.deep,
43+
tags_to_ignore=context.tags_to_ignore,
44+
)

cirq-core/cirq/transformers/drop_empty_moments_test.py

+27
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,30 @@ def test_drop():
2929
),
3030
cirq.Circuit(cirq.Moment([cirq.CNOT(q1, q2)])),
3131
)
32+
33+
34+
def test_drop_empty_moments():
35+
q1, q2 = cirq.LineQubit.range(2)
36+
c_nested = cirq.FrozenCircuit(
37+
cirq.Moment(),
38+
cirq.Moment(),
39+
cirq.Moment([cirq.CNOT(q1, q2)]),
40+
cirq.Moment(),
41+
)
42+
c_nested_dropped = cirq.FrozenCircuit(cirq.CNOT(q1, q2))
43+
c_orig = cirq.Circuit(
44+
c_nested,
45+
cirq.CircuitOperation(c_nested).repeat(6).with_tags("nocompile"),
46+
c_nested,
47+
cirq.CircuitOperation(c_nested).repeat(5).with_tags("preserve_tag"),
48+
c_nested,
49+
)
50+
c_expected = cirq.Circuit(
51+
c_nested_dropped,
52+
cirq.CircuitOperation(c_nested).repeat(6).with_tags("nocompile"),
53+
c_nested_dropped,
54+
cirq.CircuitOperation(c_nested_dropped).repeat(5).with_tags("preserve_tag"),
55+
c_nested_dropped,
56+
)
57+
context = cirq.TransformerContext(tags_to_ignore=("nocompile",), deep=True)
58+
cirq.testing.assert_same_circuits(cirq.drop_empty_moments(c_orig, context=context), c_expected)

0 commit comments

Comments
 (0)