Skip to content

Commit 869d83b

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

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: cirq-core/cirq/transformers/drop_negligible_operations.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,14 @@ def drop_negligible_operations(
4343
Returns:
4444
Copy of the transformed input circuit.
4545
"""
46+
if context is None:
47+
context = transformer_api.TransformerContext()
4648

4749
def map_func(op: 'cirq.Operation', _: int) -> 'cirq.OP_TREE':
4850
return (
4951
op if protocols.is_measurement(op) or protocols.trace_distance_bound(op) > atol else []
5052
)
5153

5254
return transformer_primitives.map_operations(
53-
circuit, map_func, tags_to_ignore=context.tags_to_ignore if context else ()
55+
circuit, map_func, tags_to_ignore=context.tags_to_ignore, deep=context.deep
5456
).unfreeze(copy=False)

Diff for: cirq-core/cirq/transformers/drop_negligible_operations_test.py

+36
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,39 @@ def test_clears_known_empties_even_at_zero_tolerance():
5959
cirq.Moment(),
6060
),
6161
)
62+
63+
64+
def test_recursively_runs_inside_circuit_ops_deep():
65+
a = cirq.NamedQubit('a')
66+
small_op = cirq.Z(a) ** 0.000001
67+
nested_circuit = cirq.FrozenCircuit(
68+
cirq.X(a), small_op, small_op.with_tags(NO_COMPILE_TAG), small_op, cirq.Y(a)
69+
)
70+
nested_circuit_dropped = cirq.FrozenCircuit(
71+
cirq.Moment(cirq.X(a)),
72+
cirq.Moment(),
73+
cirq.Moment(small_op.with_tags(NO_COMPILE_TAG)),
74+
cirq.Moment(),
75+
cirq.Moment(cirq.Y(a)),
76+
)
77+
c_orig = cirq.Circuit(
78+
small_op,
79+
cirq.CircuitOperation(nested_circuit).repeat(6).with_tags(NO_COMPILE_TAG),
80+
small_op,
81+
cirq.CircuitOperation(nested_circuit).repeat(5).with_tags("preserve_tag"),
82+
small_op,
83+
)
84+
c_expected = cirq.Circuit(
85+
cirq.Moment(),
86+
cirq.Moment(cirq.CircuitOperation(nested_circuit).repeat(6).with_tags(NO_COMPILE_TAG)),
87+
cirq.Moment(),
88+
cirq.Moment(
89+
cirq.CircuitOperation(nested_circuit_dropped).repeat(5).with_tags("preserve_tag")
90+
),
91+
cirq.Moment(),
92+
)
93+
context = cirq.TransformerContext(tags_to_ignore=[NO_COMPILE_TAG], deep=True)
94+
cirq.testing.assert_same_circuits(
95+
cirq.drop_negligible_operations(c_orig, context=context, atol=0.001),
96+
c_expected,
97+
)

0 commit comments

Comments
 (0)