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

Hi, I am trying to save the quantum circuit constructed by PennyLane into a file and back again. Is it supported by PennyLane now?

Looking forward to your suggestions.

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)

def circuit(x):
    return qml.expval(qml.PauliZ(0))

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

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

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

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

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

Does this work for what you need?

1 Like

Yes, it is exactly what I need. Thanks very much.

Awesome! I’m glad this works for you.