Compose circuit of different size

Hi !

I wanted to know if it is possible to compose circuits of different size in Pennylane.

For example I have two circuit, one of size 2 (the small one), and one of size 4 (the large one).

I want to construct the large one based on multiple repetition of the small one, but put on different wires.

@qml.qnode(dev)  ##2-qubits circuit
def small_circuit(phi):
    qml.RZ(- np.pi, wires=1)
    qml.CNOT([1, 0])
    return [qml.expval(qml.PauliZ(j)) for j in range(2)]

@qml.qnode(dev) ##4-qubits circuit
def circuit(phi):
    #small_circuit(phi[0])(wires=0)
    #small_circuit(phi[0])(wires=3)
    # ...
    return [qml.expval(qml.PauliZ(j)) for j in range(4)]

So that the large circuit is a composition of the small one.

How is it possible ?

Thank you very much

You make two devices:

dev4 = qml.device("default.qubit", wires=4)
dev2 = qml.device("default.qubit", wires=2)

Then make output from 4 qubit gate go to the 2 qubit gate twice. This sould work, unless you are worry about 2 vs 4 qubit entangelment.

1 Like

Hey @Maelle_T! Welcome to the forum :sunglasses:

You can totally do this in PennyLane, but how I would recommend doing it is slightly different. You can make use of quantum functions (basically python functions that aren’t decorated with @qml.qnode).

Here’s an example:

import pennylane as qml

def quantum_function(wires):
    qml.Hadamard(wires[0])
    qml.RX(0.1, wires[1]) 

I can then use quantum_function inside QNodes!

dev = qml.qnode("default.qubit", wires=4)

@qml.qnode(dev)
def qnode():
    quantum_function([0, 1])
    quantum_function([2, 3])
    return [qml.expval(qml.PauliZ(i)) for i in range(4)]

Essentially, you can think of quantum functions as building blocks just like PennyLane gates, layers, templates, etc., but you define them how you want!

Hope this helps!

1 Like

How this is awesome :slightly_smiling_face: !!
Thank you very much for your help !

1 Like

Awesome! Glad I could help :slight_smile:. If you don’t mind, could you mark my post as the solution to your question? It helps future people on the forum get the answer they need a little quicker :grin:

Sure, it’s done !
Thanks :heart_decoration:

1 Like

Thank you! :smiley: Have a great day!

1 Like

Thank you, I did not know that this was possible.

2 Likes