I have a cirq.Circuit that uses a CircuitOperation, something like:

circuit = cirq.Circuit(cirq.CircuitOperation(cirq.X.on(q), repetitions=5))

How can I flatten this circuit to remove the CircuitOperation and just have the moments?


1 Answer 1


One "hacky" way to do it is to convert it to/from qasm. For example:

import cirq
from cirq.contrib.qasm_import import circuit_from_qasm

q = cirq.NamedQubit("q")
circuit = cirq.Circuit(
    cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q)), repetitions=5),

circuit_flat = circuit_from_qasm(circuit.to_qasm())

q: ───Y───[ q: ───X─── ](loops=5)───Z───

q_0: ───Y───X───X───X───X───X───Z───


A better way is to use cirq.expand_composite:

A transformer that expands composite operations via cirq.decompose.

For each operation in the circuit, this pass examines if the operation can be decomposed. If it can be, the operation is cleared out and replaced with its decomposition using a fixed insertion strategy.

Transformation is applied using cirq.map_operations_and_unroll, which preserves the moment structure of the input circuit.

Continuing from the example above:

circuit_flat2 = cirq.expand_composite(circuit)

q: ───Y───X───X───X───X───X───Z───

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.