This end-to-end VQE tutorial shows developers how to represent a small molecular Hamiltonian, choose a compact ansatz, optimize its parameters, and interpret results in both Qiskit and PennyLane. The examples use a local statevector simulator first, then provide a practical checklist for moving the same experiment toward cloud hardware.
Overview
The Variational Quantum Eigensolver (VQE) estimates the lowest eigenvalue of a Hamiltonian by combining a parameterized quantum circuit with a classical optimizer. In a chemistry workflow, that lowest eigenvalue is used as an estimate of a molecule’s ground-state energy after the electronic-structure problem has been mapped to qubits.
The workflow is iterative:
- Build or import a qubit Hamiltonian.
- Prepare a parameterized trial state, called an ansatz.
- Measure the expectation value of the Hamiltonian.
- Use a classical optimizer to update circuit parameters.
- Repeat until the energy stops improving or a budget is reached.
For a first implementation, separate algorithm debugging from chemistry modeling. The code below uses an illustrative two-qubit Hamiltonian that resembles a reduced molecular problem:
H = -1.0523 I + 0.3979 Z0 - 0.3979 Z1 - 0.0113 Z0Z1
These coefficients are included as a compact tutorial input, not as a universal representation of a molecule. In a production workflow, obtain the Hamiltonian from a chemistry package or a validated electronic-structure calculation, and record the geometry, basis, active space, and mapping used to produce it.
Checklist by scenario
Scenario 1: Build a local Qiskit prototype
Start with a simulator and a deliberately small ansatz. This keeps failures easy to classify: a wrong energy calculation is different from a poor optimizer setting, and both are different from hardware noise.
import numpy as np
from scipy.optimize import minimize
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector, SparsePauliOp
terms = [
("II", -1.0523),
("ZI", 0.3979),
("IZ", -0.3979),
("ZZ", -0.0113),
]
hamiltonian = SparsePauliOp.from_list(terms)
def ansatz(theta):
circuit = QuantumCircuit(2)
circuit.ry(theta[0], 0)
circuit.ry(theta[1], 1)
circuit.cx(0, 1)
return circuit
def energy(theta):
state = Statevector.from_instruction(ansatz(theta))
value = state.expectation_value(hamiltonian)
return float(np.real(value))
initial = np.zeros(2)
result = minimize(energy, initial, method="COBYLA", options={"maxiter": 200})
print("energy:", result.fun)
print("parameters:", result.x)
print("converged:", result.success)
This is a VQE-style Qiskit prototype: the statevector supplies exact expectation values, while the classical optimizer supplies new parameters. It does not model shot noise, readout error, gate error, or a hardware connectivity map. That makes it appropriate for checking Hamiltonian signs, qubit ordering, and ansatz behavior before introducing a backend.
Scenario 2: Reproduce the workflow in PennyLane
PennyLane expresses the same experiment as a differentiable quantum function. The following example uses an optimizer supplied by the framework and a local simulator device.
import pennylane as qml
from pennylane import numpy as np
coefficients = np.array([-1.0523, 0.3979, -0.3979, -0.0113])
observables = [
qml.Identity(0),
qml.PauliZ(0),
qml.PauliZ(1),
qml.PauliZ(0) @ qml.PauliZ(1),
]
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(theta):
qml.RY(theta[0], wires=0)
qml.RY(theta[1], wires=1)
qml.CNOT(wires=[0, 1])
return [qml.expval(op) for op in observables]
def energy(theta):
return np.dot(coefficients, circuit(theta))
opt = qml.AdamOptimizer(stepsize=0.05)
theta = np.array([0.0, 0.0], requires_grad=True)
for step in range(200):
theta, previous = opt.step_and_cost(energy, theta)
if step % 25 == 0:
print(step, float(energy(theta)))
print("final energy:", float(energy(theta)))
print("parameters:", theta)
Check the installed SDK documentation before running either example. Quantum SDK APIs, optimizer interfaces, and device plugins change over time, so use an isolated environment and record the package versions with the experiment.
Scenario 3: Move from simulation to hardware
Do not submit the first successful simulator run directly to hardware. Use this progression:
- Confirm the Hamiltonian and reference energy with a classical calculation when possible.
- Run the ansatz with exact statevector simulation.
- Run a finite-shot noisy simulation and inspect variance.
- Transpile or compile the circuit for the selected backend.
- Record qubit mapping, circuit depth, shots, queue or execution settings, and calibration context.
- Compare hardware results with a simulator configured as closely as possible to the submitted circuit.
Backend selection is part of the experiment, not an afterthought. Review coupling constraints and gate support in the quantum hardware connectivity guide. For broader platform decisions, compare the practical trade-offs in the IBM Quantum, AWS Braket, and Azure Quantum developer guide.
What to double-check
- Pauli ordering: Confirm which string character maps to which qubit in your SDK and Hamiltonian construction.
- Energy units: Keep track of the units inherited from the chemistry calculation. Do not compare values produced from different conventions without documenting the conversion.
- Reference state: A chemically informed initial state can outperform an all-zero state, but it must be prepared and documented correctly.
- Ansatz capacity: Too few parameters can prevent the circuit from representing a good state. Too many can make optimization unstable or increase hardware cost.
- Optimizer budget: Save the initial parameters, every energy evaluation, stopping condition, and final parameters. A final number without this trace is difficult to reproduce.
- Shots and variance: Hardware estimates are statistical. Report repeated runs or uncertainty measures rather than treating one sampled value as exact.
- Compilation effects: Compare the logical circuit with the compiled circuit. Added routing gates can materially change depth and noise exposure.
For portability between tools, exporting a circuit is only one part of the job. Hamiltonian conventions, measurement definitions, parameter order, and qubit indexing also need to travel with the circuit. The OpenQASM 3 guide provides useful context for circuit exchange.
Common mistakes
Calling any optimizer loop VQE without checking the objective. The objective must be the Hamiltonian expectation value. Optimizing an individual Pauli term or a raw bitstring probability solves a different problem.
Using a large ansatz too early. Begin with one or two layers and add expressivity only when the simpler circuit has been validated. A deeper circuit can hide a modeling error behind a plausible-looking result.
Assuming convergence proves accuracy. An optimizer can converge to a local minimum, stop because of a small parameter update, or plateau because of noise. Compare against a classical reference or exact diagonalization for small test cases.
Ignoring measurement grouping and sampling cost. A Hamiltonian is usually measured term by term or in compatible groups. The number of terms, shots, and repeated evaluations can dominate the practical runtime.
Mixing SDK examples from different releases. Installation commands and backend interfaces are release-sensitive. Keep a requirements file, test imports in a clean environment, and consult the current SDK documentation when an example fails.
Reporting only the best energy. Preserve the optimization trace. A plot of energy versus iteration often reveals oscillation, premature stopping, or sensitivity to initialization more clearly than the final value.
When to revisit
Revisit this VQE workflow whenever a quantum SDK, device plugin, simulator, compiler, or backend interface changes. As a maintenance checklist, rerun the local Qiskit and PennyLane examples in a clean environment, verify that the same Hamiltonian and ansatz are being evaluated, and compare the final energy with a stored baseline.
Before a seasonal planning cycle or a new project phase, also review whether the experiment still matches its purpose. A simulator benchmark may need finite-shot noise; a hardware study may need a new backend; and a chemistry experiment may need a more appropriate active space or ansatz. Re-run simulator-versus-hardware comparisons at a regular interval and after substantial workflow changes rather than treating an old benchmark as permanent.
Keep a small project checklist with these fields: SDK and Python versions, Hamiltonian source, qubit mapping, ansatz definition, initial parameters, optimizer and stopping rule, shot count, backend, compiled depth, mitigation settings, and reference energy. That record turns this tutorial into a reusable development workflow rather than a one-time code sample. For the next step, compare your experiment design with the simulator and hardware benchmarking guide, then expand the circuit only after the two-qubit case is reproducible.