3
$\begingroup$

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?

$\endgroup$
1

1 Answer 1

2
$\begingroup$

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───
$\endgroup$

Your Answer

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

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