Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for deep=True to cirq.drop_negligible_operations transformer #5114

Merged
merged 3 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cirq-core/cirq/transformers/drop_negligible_operations.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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,
)