This VQE tutorial in Python shows how to build a small variational quantum eigensolver from first principles, measure an energy expectation value, optimize circuit parameters, and validate the result. The workflow is designed as a reusable checklist for experiments in quantum chemistry, combinatorial optimization, and other hybrid quantum-classical applications.
Overview
The variational quantum eigensolver (VQE) estimates the lowest eigenvalue of a Hamiltonian. In chemistry, that value can represent a ground-state energy after the physical problem has been mapped to qubits. More generally, VQE can optimize any objective that can be written as the expectation value of a Hermitian operator.
VQE alternates between two components:
- A quantum circuit prepares a parameterized state, often called an ansatz.
- A classical optimizer changes the circuit parameters to reduce the measured expectation value.
If the Hamiltonian is written as a weighted sum of Pauli operators, the objective has the form:
E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩
where θ is the parameter vector and H is the Hamiltonian. A useful first experiment is a two-qubit Hamiltonian with a known reference energy. This keeps the implementation small enough to debug while preserving the structure of a production VQE workflow.
Minimal Python example
The example below uses NumPy and SciPy to make the data flow explicit. It evaluates the ansatz state with a statevector simulator, computes the exact expectation value, and uses a classical optimizer. The same objective can later be replaced by shot-based measurements or an SDK primitive.
import numpy as np
from scipy.optimize import minimize
I = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)
kron = np.kron
# H = c0 I⊗I + c1 Z⊗I + c2 I⊗Z + c3 X⊗X
terms = [
("II", -0.042),
("ZI", 0.177),
("IZ", 0.177),
("XX", 0.170),
]
paulis = {"I": I, "X": X, "Y": Y, "Z": Z}
H = sum(c * kron(paulis[p[0]], paulis[p[1]]) for p, c in terms)
def ry(theta):
return np.array([
[np.cos(theta / 2), -np.sin(theta / 2)],
[np.sin(theta / 2), np.cos(theta / 2)]
], dtype=complex)
def ansatz(theta):
# Product rotations followed by a CNOT-like entangling layer.
state = kron(ry(theta[0]), ry(theta[1])) @ np.array([1, 0, 0, 0], dtype=complex)
entangler = np.array([
[1, 0, 0, 0], [0, 1, 0, 0],
[0, 0, 0, 1], [0, 0, 1, 0]
], dtype=complex)
return entangler @ state
def energy(theta):
state = ansatz(theta)
return float(np.real(np.vdot(state, H @ state)))
history = []
def objective(theta):
value = energy(theta)
history.append(value)
return value
result = minimize(objective, x0=np.array([0.1, 0.1]), method="COBYLA",
options={"maxiter": 300, "rhobeg": 0.2, "tol": 1e-7})
print("Energy:", result.fun)
print("Parameters:", result.x)
print("Converged:", result.success)
print("Evaluations:", result.nfev)This is a simulator-based VQE, not a hardware execution. It is valuable because it separates algorithmic errors from sampling noise and device effects. When moving to Qiskit, Cirq, PennyLane, or another quantum SDK, retain the same interfaces: an ansatz function, an expectation-value function, an optimizer loop, and a validation routine. SDK syntax and primitive interfaces change over time, so check the installed version's documentation before adapting the circuit.
Checklist by scenario
For a first VQE experiment
- Define the operator: list every Pauli term and its coefficient. Confirm qubit ordering before constructing tensor products.
- Choose a small ansatz: begin with one rotation layer and one entangling layer. Increase depth only when the circuit cannot represent a sufficiently good state.
- Set an initialization: use a reproducible starting vector, such as small angles or a problem-informed reference state.
- Record every objective evaluation: an energy history makes stagnation, oscillation, and unexpected increases visible.
- Set a stopping rule: use both an iteration limit and an energy-change tolerance. One criterion alone can stop too early or run unnecessarily long.
For a chemistry-style Hamiltonian
- Document how the physical model was reduced and mapped to qubits.
- Separate constant energy offsets from Pauli expectation terms.
- Compare the optimized energy with a classical or exact small-system reference when available.
- Check whether the ansatz preserves known symmetries, such as particle number, rather than relying on optimization to discover them.
- Estimate the effect of measurement noise separately from the ideal expectation value.
For a shot-based or hardware run
- Replace exact statevector expectations with measurements for each Pauli group.
- Use enough shots to make optimizer decisions meaningful, but treat shot count as an experimental variable rather than a guarantee of accuracy.
- Repeat selected evaluations to estimate uncertainty.
- Start with a noiseless simulator, then a noisy simulator if available, and only then compare with hardware.
- Keep backend and transpilation settings in the experiment record. Backend selection can materially affect circuit depth and measurement behavior; use the quantum cloud platform backend checklist when choosing an execution target.
Parameter checklist
| Parameter | Starting choice | What to inspect |
|---|---|---|
| Ansatz depth | One shallow layer | Expressibility versus circuit depth |
| Initial angles | Small, reproducible values | Whether gradients or objective changes are effectively zero |
| Optimizer | Derivative-free for noisy objectives | Stability, evaluation count, and sensitivity to scale |
| Maximum evaluations | Finite experiment budget | Whether the run stops before meaningful progress |
| Convergence tolerance | Relative to expected energy precision | Whether the tolerance is tighter than measurement noise |
| Shots | Increase after the ideal test passes | Variance and repeatability of each expectation value |
What to double-check
Hamiltonian construction: Verify the matrix is Hermitian and that each Pauli string acts on the intended qubit. A reversed tensor-product order can produce a plausible but incorrect result.
Ansatz and reference state: Confirm that the circuit actually changes when parameters change. Test several parameter vectors and inspect the resulting state or measurement probabilities. For state-preparation diagnostics, see the quantum state debugging guide.
Expectation values: The exact simulator objective should be real, even when floating-point arithmetic creates a tiny imaginary component. Taking the real part is appropriate only after confirming that the operator and state calculation are correct.
Convergence: A final optimizer flag is not enough. Inspect the energy trace, the final parameter vector, the number of evaluations, and the change in energy over the last several evaluations. A flat trace may indicate convergence, but it can also indicate a barren plateau, an ineffective ansatz, or a broken parameter binding.
Validation: Compare against exact diagonalization for small Hamiltonians. For larger systems, compare with a classical approximation, a known bound, or multiple ansätze. A lower energy is not automatically a correct result if the operator or units were defined incorrectly.
Once the ideal workflow is reliable, package the experiment so that its Hamiltonian, ansatz, optimizer, seed, backend, and results are saved together. The reproducible quantum software project template provides a useful structure for moving from a notebook to a repeatable experiment.
Common mistakes
- Starting with a deep ansatz: More layers can increase expressibility but also make optimization and hardware execution harder. Add depth only when a shallow circuit fails a controlled test.
- Using one optimizer without a baseline: Optimizers respond differently to noisy, flat, or discontinuous objectives. Compare a small set of methods with the same initialization and evaluation budget.
- Confusing low energy with successful chemistry: The energy target depends on the Hamiltonian, mapping, constant terms, and physical assumptions. Validate each stage independently.
- Ignoring shot noise: An optimizer can chase random fluctuations when expectation values are estimated from too few shots. Track repeated evaluations and uncertainty.
- Declaring a barren plateau too quickly: First test parameter binding, gradient or finite-difference changes, circuit depth, initialization, and observable scaling. Flat behavior has several possible causes.
- Changing several variables at once: Keep the Hamiltonian, ansatz, optimizer, and backend fixed while diagnosing one issue. Use circuit unit tests and golden results where possible; the quantum circuit testing guide covers practical patterns.
- Skipping measurement validation: For hardware-oriented VQE, confirm that each Pauli term is measured in the correct basis and that qubit and bit ordering are handled consistently. The quantum program debugging checklist is a useful pre-run review.
When to revisit
Return to this checklist whenever the underlying inputs change. Before a new experiment, confirm the Hamiltonian, qubit mapping, ansatz, parameter initialization, optimizer settings, and validation reference. When switching from a statevector simulator to shot-based execution, revisit convergence tolerances, measurement grouping, shot budgets, and uncertainty handling.
Review the implementation after a major quantum SDK release because primitive APIs, optimizer interfaces, transpilation behavior, and supported backends may change. Preserve the dependency versions used for published or benchmarked results, then run a small regression test against a known Hamiltonian before updating them.
For the next practical step, run the example with several initial vectors, plot history, and compare the optimized energy with the smallest eigenvalue from numpy.linalg.eigvalsh(H). Then change exactly one element—ansatz depth, optimizer, or shot-based measurement—and record whether the result, convergence speed, and reproducibility improve. If your target is a constrained combinatorial objective rather than an eigenvalue problem, the related QAOA in Python tutorial provides the corresponding variational workflow.