0
$\begingroup$

Say, I have a list of operations which are pennylane gates, can I create a circuit from it?

I tried:

import pennylane as qml
operations=[qml.Hadamard(wires=2),qml.PauliX(wires=[2]),qml.PauliX(wires=[3]),qml.CNOT(wires=[1, 2])]
def circuit():
    operations[0]
    for op in operations:
       op
    qml.Hadamard(wires=[3])
    return qml.expval(qml.PauliZ(0))

dev=qml.device('default.qubit',wires=4)
circuit=qml.QNode(circuit, dev)
print(qml.draw(circuit)())

This seems not to work. Only the Hadamard on wire 3 is drawn. I do not understand what difference it makes whether I write the gate directly into the circuit or first in a list and then insert it into the circuit.

Is there another way to do this?

$\endgroup$

2 Answers 2

1
$\begingroup$

PennyLane uses queuing under the hood so the issue in your code is that the operations have been instantiated outside of the circuit but haven't been applied to the circuit. You can fix this by simply using qml.apply(op). So you can keep everything as is, but within the for loop you change op to qml.apply(op).

The last Hadamard is already applied because it's instantiated within the circuit.

You can also use qml.draw_mpl() if you want to get nicer drawings of your circuit.

Catalina from PennyLane

$\endgroup$
2
$\begingroup$

Since the operations were already instantiated in list outside of the circuit context, you will have to use qml.apply(operations[0]) and qml.apply(op) instead of just operations[0] or op in the circuit in order for these to be properly picked up.

(under the hood, when you create ops in the circuit function context, some tricks are used to capture this implicitly into your circuit; if you create them outside of the circuit function context, you'll have to explicitly say to apply them)

$\endgroup$
1
  • $\begingroup$ Thank you to both of you. Especially, for including some explanation for the behavior. Unfortunately, I can only mark one of the answers as 'the answer'. $\endgroup$ Sep 28, 2022 at 7:50

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.