# how to flatten a cirq.Circuit with CircuitOperation

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?

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.Y(q),
cirq.CircuitOperation(cirq.FrozenCircuit(cirq.X(q)), repetitions=5),
cirq.Z(q)
)

circuit_flat = circuit_from_qasm(circuit.to_qasm())

print(circuit)
print(circuit_flat)

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

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


EDIT:

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)

print(circuit_flat2)

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