What is PennyLane?
PennyLane provides a powerful framework for creating and executing quantum circuits in quantum machine learning (QML) projects. It is a cross-platform Python library for differentiable programming of quantum computers. This means that you can use PennyLane to access quantum computers from different providers, while making it easy to write and run quantum computing programs.
Quantum Circuits
Every computation has three elements: data, operations, and results. For quantum circuits:
- Data = qubits
- Operations = quantum gates
- Results = measurements
Defining a Quantum Circuit
import pennylane as qml
def my_quantum_circuit(x, y):
qml.RZ(x, wires=0) # applies RZ rotation (by x radians) gate
# to qubit on wire 0
qml.CNOT(wires=[0,1]) # applies a CNOT gate between two qubits
# wire 0 is control qubit
# and wire 1 is target qubit
qml.RY(y, wires=1) # applies RY rotation (by y radians) gate
# to qubit on wire 1
return qml.expval(qml.PauliZ(1)) # measures the expectation value
# of the Pauli Z operator on wire 1
This function describes a simple quantum circuit with rotations and a CNOT gate, followed by a measurement.
For most standard quantum devices, each wire represents a single qubit.
Creating a Quantum Device
Before running your circuit, you need to specify a quantum device:
dev = qml.device('default.qubit', wires=2)This creates a simulator with two qubits. You can easily switch to other devices, including hardware backends, by changing the device name.
Note that the choice of a device significantly determines the speed of your computation. PennyLane offers some basic devices such as the ‘default.qubit’, ‘default.mixed’, lightning.qubit, ‘default.gaussian’, ‘default.clifford’, and ‘default.tensor’ simulators.
Quantum Node (QNode)
A quantum node is used to declare the quantum circuit, and also ties the computation to a specific device that executes it. To execute the quantum circuit, wrap it in a QNode:
# Step 1: Choose a device
dev = qml.device('default.qubit', wires=2) # creating a quantum device
# Step 2: Define the quantum circuit with qnode decorator
@qml.qnode(dev) # qnode decorator converts function to a runnable QNode circuit
def circuit(x):
qml.RZ(x, wires=0)
qml.CNOT(wires=[0,1])
qml.RY(x, wires=1)
return qml.expval(qml.PauliZ(1))
result = circuit(0.543)
The QNode connects your quantum function to the specified device. Now you can run the circuit to get your result.References
PennyLane Documentation