In Cirq, is it possible to take a sub-circuit generator and use it as the sub_gate in a cirq.ControlledGate?

... instantiate circuit and qubits q0-q3 ...

... define sub circuit generator:
def my_layer():
    sub-circuit generator
    ref: https://github.com/quantumlib/Cirq/blob/master/docs/circuits.md
    yield CZ(q0, q1)
    yield [H(q) for q in (q0, q1, q2)]
    yield [CZ(q1, q2)]
    yield [H(q0), [CZ(q1, q2)]]

... take the sub-circuit generator and do something like:
gate = cirq.ControlledGate(sub_gate = my_layer())

In other words, how can I take a sub-circuit and make its execution conditional on a control qubit?


1 Answer 1


The following code snippet will do almost what you want:

class MyLayerGate(cirq.Gate):
    def _decompose_(self, qubits):
        a, b, c = qubits
        return my_layer(a, b, c)

    # [will be unnecessary in v0.5.0] workaround for cirq.unitary ignoring _decompose_:
    def _unitary_(self):
        return cirq.unitary(

controlled_my_layer_gate = cirq.ControlledGate(MyLayerGate())

In the future, the # workaround part won't be necessary anymore. Currently it's needed because:

1) cirq.ControlledGate doesn't implement a _decompose_ method. I've opened an issue to fix this.

2) cirq.apply_unitary and cirq.unitary should use _decompose_ when _unitary_ isn't implemented on a gate, so that circuit simulation works when using gates with nothing but a specified decomposition. There is an in-progress PR to fix that.

Also, I do like the idea of controlling the gates coming out of a method without having to define a new class. A unified cirq.control(callable_or_gate_or_operation, optional_specified_control) method would be useful. I'll also open an issue to do that.


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.