How can I save the quantum circuit into disk and load from disk in PennyLane

Hi @Yang, it’s good to see you in the Forum!

You could use to_openqasm and from_qasm to do what you need.

import pennylane as qml

dev = qml.device("lightning.qubit",wires=1)

@qml.qnode(dev)
def circuit(x):
    qml.RX(x,wires=0)
    return qml.expval(qml.PauliZ(0))

circuit.construct([0.5], {})
# Convert to QASM (str)
t = circuit.qtape.to_openqasm()
print(t)

# Remove the measurement
t_cut = t[:-23]
print(t_cut) 

This gives you a string that you can send to someone. The other person can then use the following code:

my_circuit = qml.from_qasm(t_cut) # Create a template

@qml.qnode(dev)
def new_circuit(y):
    # You can add new things to the circuit
    qml.RY(y, wires=0)
    # Add your old circuit
    my_circuit(wires=[0])
    return qml.expval(qml.PauliZ(0))

#Draw
drawer = qml.draw(new_circuit)
print(drawer(y = 0.3))

Does this work for what you need?

2 Likes