Skip to content

Commit

Permalink
Add support for deep=True to cirq.drop_negligible_operations transf…
Browse files Browse the repository at this point in the history
…ormer (#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
  • Loading branch information
tanujkhattar committed Mar 21, 2022
1 parent fade070 commit 869d83b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cirq-core/cirq/transformers/drop_negligible_operations.py
Expand Up @@ -43,12 +43,14 @@ def drop_negligible_operations(
Returns:
Copy of the transformed input circuit.
"""
if context is None:
context = transformer_api.TransformerContext()

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

return transformer_primitives.map_operations(
circuit, map_func, tags_to_ignore=context.tags_to_ignore if context else ()
circuit, map_func, tags_to_ignore=context.tags_to_ignore, deep=context.deep
).unfreeze(copy=False)
36 changes: 36 additions & 0 deletions cirq-core/cirq/transformers/drop_negligible_operations_test.py
Expand Up @@ -59,3 +59,39 @@ def test_clears_known_empties_even_at_zero_tolerance():
cirq.Moment(),
),
)


def test_recursively_runs_inside_circuit_ops_deep():
a = cirq.NamedQubit('a')
small_op = cirq.Z(a) ** 0.000001
nested_circuit = cirq.FrozenCircuit(
cirq.X(a), small_op, small_op.with_tags(NO_COMPILE_TAG), small_op, cirq.Y(a)
)
nested_circuit_dropped = cirq.FrozenCircuit(
cirq.Moment(cirq.X(a)),
cirq.Moment(),
cirq.Moment(small_op.with_tags(NO_COMPILE_TAG)),
cirq.Moment(),
cirq.Moment(cirq.Y(a)),
)
c_orig = cirq.Circuit(
small_op,
cirq.CircuitOperation(nested_circuit).repeat(6).with_tags(NO_COMPILE_TAG),
small_op,
cirq.CircuitOperation(nested_circuit).repeat(5).with_tags("preserve_tag"),
small_op,
)
c_expected = cirq.Circuit(
cirq.Moment(),
cirq.Moment(cirq.CircuitOperation(nested_circuit).repeat(6).with_tags(NO_COMPILE_TAG)),
cirq.Moment(),
cirq.Moment(
cirq.CircuitOperation(nested_circuit_dropped).repeat(5).with_tags("preserve_tag")
),
cirq.Moment(),
)
context = cirq.TransformerContext(tags_to_ignore=[NO_COMPILE_TAG], deep=True)
cirq.testing.assert_same_circuits(
cirq.drop_negligible_operations(c_orig, context=context, atol=0.001),
c_expected,
)

0 comments on commit 869d83b

Please sign in to comment.