Skip to main content

07 - Variational Quantum Eigensolver (VQE) for Chemistry

VQE on the H2 molecule in four qubits, simulated in numpy and checked against the PySCF FCI energy, with the measurement cost expressed in shots.

What do you think about this article?

07 - Variational Quantum Eigensolver (VQE) for Chemistry
Quantum Computingfedericocalo.dev

At a Glance

VQE on the H2 molecule in four qubits, simulated in numpy and checked against the PySCF FCI energy, with the measurement cost expressed in shots.

Computing the lowest energy of a molecule is one of the problems where the idea of using a quantum machine has an obvious physical motivation: the state of n electrons in m orbitals lives in a space that grows exponentially, and a quantum machine already has that space. The Variational Quantum Eigensolver (VQE) is the attempt to use this idea on today's noisy machines: the quantum processor prepares a state that depends on a few parameters and measures its energy, and a classical optimiser moves the parameters until the energy stops going down.

Here you build the circuit and run it in numpy for the hydrogen molecule H2, on four qubits, and compare the result with a classical chemistry calculation (PySCF) and with a second, independent calculation. The example is deliberately honest: H2 is solved in microseconds even on a laptop, so there is no advantage to show here. What there is, instead, is the whole cycle of the algorithm, in a form you can read and rerun, including its measurement cost. You start from the gates of article 02; the previous article, on Shor's algorithm, serves only as a contrast: Shor requires a machine with error correction, while VQE was born to reduce the demands on coherence, as the abstract of the paper that proposes it says.

The variational principle: why minimising is enough

For any normalised state |ψ⟩, the mean energy ⟨ψ|H|ψ⟩ never falls below the ground-state energy E0 of the Hamiltonian H. Anyone who has used a one-parameter model already knows this: if you try to guess the shape of a wave function and look for the parameter that gives the lowest energy, you get an upper bound on the true energy, never a value below it. For VQE this turns an eigenvalue problem into a minimisation problem: you do not need to compute E0, you need to find the parameters θ that minimise E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩.

The loop has three components, each with a precise task:

  • the ansatz, the circuit that prepares |ψ(θ)⟩ and decides which states can be reached;
  • the measurement, which estimates E(θ) from many single-qubit outcomes;
  • the classical optimiser, which proposes the next θ.

The three choices are not independent: an ansatz that is too poor prevents reaching E0 whatever optimiser you use, while one that is too expressive makes the search hard, as discussed further on under barren plateaus. The variational principle also has a limit: it guarantees that the energy found is an upper bound, but it does not say how far it is from E0.

From the molecule to four qubits

H2 has two electrons. In a minimal basis (STO-3G) there are two spatial orbitals, one bonding and one antibonding, and each orbital hosts one electron with spin up or down: four spin-orbitals, hence four qubits, one per spin-orbital, equal to 1 if occupied. The electronic Hamiltonian in second quantisation combines a one-body term (kinetic energy and attraction of the nuclei) and a two-body term (repulsion between electrons). The coefficients are the integrals that PySCF computes; the Jordan-Wigner map translates the creation and annihilation operators into Pauli matrices, with a chain of Z on the preceding qubits that preserves the antisymmetry of the electrons.

In the listing, annichilatore builds that map, integrali asks PySCF for the Hartree-Fock calculation and the integrals in the molecular basis, hamiltoniana assembles them into a 16 × 16 matrix and pauli decomposes it into Pauli strings with the trace product. The __main__ part is the test: it compares the minimum of H in the two-electron sector with the PySCF FCI energy (full configuration interaction, the exact solution in the chosen basis) and with the Hartree-Fock energy. The three listings of the article are three files in the same folder: save the first as h2.py, the second as vqe.py and the third as shots.py, because the second imports h2 and the third imports h2 and vqe.

import itertools
import numpy as np
from pyscf import ao2mo, fci, gto, scf

I2, X = np.eye(2), np.array([[0, 1], [1, 0]])
Y, Z = np.array([[0, -1j], [1j, 0]]), np.diag([1.0, -1.0])
CREA = np.array([[0, 0], [1, 0]])        # |0> -> |1> on the single mode

def kron(ops):
    m = ops[0]
    for o in ops[1:]:
        m = np.kron(m, o)
    return m

def annichilatore(p, n):
    """Jordan-Wigner: a_p = Z...Z (qubits < p) * sigma^- (qubit p) * I...I."""
    return kron([Z] * p + [CREA.T] + [I2] * (n - p - 1))

def integrali(distanza):
    mol = gto.M(atom=f"H 0 0 0; H 0 0 {distanza}", basis="sto-3g", unit="Angstrom", verbose=0)
    mf = scf.RHF(mol).run()
    c = mf.mo_coeff
    h1 = c.T @ mf.get_hcore() @ c
    eri = ao2mo.restore(1, ao2mo.kernel(mol, c), 2)       # (pq|rs), chemists' notation
    return mol, mf, h1, eri

def hamiltoniana(distanza):
    mol, mf, h1, eri = integrali(distanza)
    n = 4                                                  # spin-orbital p = 2*i + spin
    a = [annichilatore(p, n) for p in range(n)]
    ad = [m.conj().T for m in a]
    H = mol.energy_nuc() * np.eye(2**n, dtype=complex)
    for p, q in itertools.product(range(n), repeat=2):
        if p % 2 == q % 2:
            H += h1[p // 2, q // 2] * ad[p] @ a[q]
    for p, q, r, s in itertools.product(range(n), repeat=4):
        if p % 2 == q % 2 and r % 2 == s % 2:
            H += 0.5 * eri[p // 2, q // 2, r // 2, s // 2] * ad[p] @ ad[r] @ a[s] @ a[q]
    return H, a, mf

def pauli(H):
    """Decomposition H = sum c_P P over the 4^n Pauli strings."""
    n = int(np.log2(H.shape[0]))
    out = {}
    for lettere in itertools.product("IXYZ", repeat=n):
        P = kron([{"I": I2, "X": X, "Y": Y, "Z": Z}[l] for l in lettere])
        c = np.trace(P @ H).real / 2**n
        if abs(c) > 1e-8:
            out["".join(lettere)] = c
    return out

if __name__ == "__main__":
    H, a, mf = hamiltoniana(0.74)
    n_el = np.array([bin(s).count("1") for s in range(16)])
    w = np.linalg.eigvalsh(H)
    sett = np.linalg.eigvalsh(H[np.ix_(n_el == 2, n_el == 2)])
    print("Hermitian:", np.allclose(H, H.conj().T))
    print(f"Lowest E, 2-electron sector: {sett[0]:.8f} Ha")
    print(f"PySCF FCI energy:                 {fci.FCI(mf).kernel()[0]:.8f} Ha")
    print(f"Hartree-Fock energy:              {mf.e_tot:.8f} Ha")
    print("The minimum over the whole Fock space lies in the 2-electron sector:", bool(np.isclose(w[0], sett[0])))
    termini = pauli(H)
    print("Pauli strings with nonzero coefficient:", len(termini))
    for k, v in sorted(termini.items(), key=lambda kv: -abs(kv[1]))[:5]:
        print(f"  {k}  {v:+.6f}")

# Output:
# Hermitian: True
# Lowest E, 2-electron sector: -1.13728383 Ha
# PySCF FCI energy:                 -1.13728383 Ha
# Hartree-Fock energy:              -1.11675931 Ha
# The minimum over the whole Fock space lies in the 2-electron sector: True
# Pauli strings with nonzero coefficient: 15
#   IIIZ  -0.223432
#   IIZI  -0.223432
#   IIZZ  +0.174413
#   IZII  +0.171413
#   ZIII  +0.171413

The minimum of the hand-built matrix coincides with the PySCF FCI to eight decimal places (-1.13728383 hartree), which confirms the map, the factors of 1/2 and the order of the operators in the two-body term. An error in any one of those three points would immediately shift the energy. The Hartree-Fock energy is -1.11675931: the difference, about 20.5 millihartree, is the correlation energy that VQE has to recover. The line on the two-electron sector must be read carefully: the four qubits also represent states with 0, 1, 3 or 4 electrons, and here the global minimum happens to fall in the right sector; this cannot be taken for granted in general, and it is the reason why the ansatz must conserve the number of particles.

There are 15 non-zero Pauli strings, one of which is the identity (a constant). This number matters because the processor does not measure H in one shot: it measures Pauli strings, and E(θ) = Σ c_P ⟨P⟩ is reconstructed by summing the mean values weighted with the coefficients.

The ansatz: a single double excitation

The starting state is Hartree-Fock, with the electrons in qubits 0 and 1 (|1100⟩, index 0b1100 in the code). The UCC (unitary coupled cluster) ansatz transforms it with exp(θ(T - T†)), where T = a†₂ a†₃ a₁ a₀ moves the pair of electrons from the bonding orbital to the antibonding one. The operator T - T† is anti-Hermitian, so its exponential is unitary; and since T conserves the number of electrons, the state never leaves the right sector. The advantage over a generic "hardware-efficient" circuit, made of rotations and CNOTs chosen for the convenience of the hardware, is exactly this: the chemical structure restricts the search space and keeps it inside the physically sensible sector.

The space to explore should not be widened more than necessary. McClean and collaborators showed that for a broad class of parametrised circuits inspired by random circuits the probability that the gradient is non-zero to a fixed precision is exponentially small in the number of qubits: this is the phenomenon of barren plateaus, and for VQE it is an argument in favour of structured ansätze. We will come back to it when discussing learning in article 09. The following listing minimises E(θ) in two steps: a scan over 721 points to find the right valley, then a bounded optimisation around the minimum (minimize_scalar with an interval of ±0.05).

import numpy as np
from scipy.linalg import expm
from scipy.optimize import minimize_scalar
from pyscf import fci
from h2 import hamiltoniana

def prepara(distanza):
    H, a, mf = hamiltoniana(distanza)
    T = a[2].conj().T @ a[3].conj().T @ a[1] @ a[0]     # double excitation 01 -> 23
    G = T - T.conj().T                                  # anti-Hermitian: exp(theta*G) is unitary
    hf = np.zeros(16, dtype=complex)
    hf[0b1100] = 1                                      # electrons in qubits 0 and 1
    return H, G, hf, mf

def energia(theta, H, G, hf):
    psi = expm(theta * G) @ hf
    return float((psi.conj() @ H @ psi).real)

if __name__ == "__main__":
    for d in (0.5, 0.74, 1.5):
        H, G, hf, mf = prepara(d)
        griglia = np.linspace(-np.pi, np.pi, 721)
        e = [energia(t, H, G, hf) for t in griglia]
        t0 = griglia[int(np.argmin(e))]
        ris = minimize_scalar(lambda t: energia(t, H, G, hf), bounds=(t0 - 0.05, t0 + 0.05), method="bounded",
                              options={"xatol": 1e-10})
        e_fci = fci.FCI(mf).kernel()[0]
        # second, independent calculation: diagonalise H in the subspace {HF, double}
        doppia = expm((np.pi / 2) * G) @ hf
        B = np.stack([hf, doppia], axis=1)
        e_2x2 = np.linalg.eigvalsh(B.conj().T @ H @ B)[0]
        print(f"d={d:.2f} Å: theta*={ris.x:+.4f}  E(theta=0)={energia(0, H, G, hf):.6f}  "
              f"E_HF={mf.e_tot:.6f}  E_VQE={ris.fun:.6f}  E_FCI={e_fci:.6f}  E_2x2={e_2x2:.6f}  "
              f"VQE=FCI within 1e-9: {abs(ris.fun - e_fci) < 1e-9}")

# Output:
# d=0.50 Å: theta*=-0.0719  E(theta=0)=-1.042996  E_HF=-1.042996  E_VQE=-1.055160  E_FCI=-1.055160  E_2x2=-1.055160  VQE=FCI within 1e-9: True
# d=0.74 Å: theta*=-0.1128  E(theta=0)=-1.116759  E_HF=-1.116759  E_VQE=-1.137284  E_FCI=-1.137284  E_2x2=-1.137284  VQE=FCI within 1e-9: True
# d=1.50 Å: theta*=-0.3633  E(theta=0)=-0.910874  E_HF=-0.910874  E_VQE=-0.998149  E_FCI=-0.998149  E_2x2=-0.998149  VQE=FCI within 1e-9: True

The first two columns say that E(θ = 0) coincides with Hartree-Fock to six decimals, as it must, because at θ = 0 the ansatz returns the starting state. Then E_VQE reaches E_FCI with a difference of less than one billionth of a hartree, for all three distances. This is not a merit of the optimiser but a property of H2 in a minimal basis: in the two-electron sector with the right symmetry, the exact state is a combination of just two determinants, Hartree-Fock and the double excitation. The third calculation, E_2x2, confirms it: it diagonalises H in the subspace of those two states with no optimisation at all and finds the same value. For a larger molecule one parameter is no longer enough, and you have to decide which excitations to include.

The optimal parameter θ* grows from -0.07 to -0.11 to -0.36 radians with the distance, and the correction with respect to Hartree-Fock from about 12 to 21 to 87 millihartree. As the bond is stretched the two electrons stop sitting "together" in the bonding orbital, and the single-determinant description gets worse: here VQE recovers exactly what Hartree-Fock loses. The negative sign of θ* depends only on the convention chosen for T - T†.

How much it costs to measure the energy

So far the simulator has computed ⟨ψ|H|ψ⟩ with linear algebra, which a real processor cannot do: it obtains only random outcomes of Pauli-string measurements, each +1 or -1. The mean value of a string is estimated with the frequency of the outcomes, and the error falls as 1/√shots. The listing simulates this procedure: for each of the 14 non-trivial strings it draws the number of +1 outcomes from a binomial distribution, repeats the energy estimate 200 times and compares the standard deviation with the theoretical formula √(Σ c² (1 - ⟨P⟩²) / shots).

import numpy as np
from scipy.linalg import expm
from h2 import hamiltoniana, pauli, kron, I2, X, Y, Z
from vqe import prepara

H, G, hf, mf = prepara(0.74)
theta = -0.1128                                          # value found by vqe.py
psi = expm(theta * G) @ hf
termini = pauli(H)
mat = {"I": I2, "X": X, "Y": Y, "Z": Z}
valori = {k: float((psi.conj() @ kron([mat[l] for l in k]) @ psi).real) for k in termini}
esatta = sum(c * valori[k] for k, c in termini.items())
print(f"energy as sum c*<P>: {esatta:.6f} Ha")

rng = np.random.default_rng(2024)
for colpi in (100, 1000, 10000):
    stime = []
    for _ in range(200):
        E = termini["IIII"]                              # the identity term is not measured
        for k, c in termini.items():
            if k != "IIII":
                uni = rng.binomial(colpi, (1 + valori[k]) / 2)   # +1 outcomes out of `colpi` measurements
                E += c * (2 * uni / colpi - 1)
        stime.append(E)
    teorica = np.sqrt(sum(c**2 * (1 - valori[k] ** 2) for k, c in termini.items() if k != "IIII") / colpi)
    print(f"{colpi:>6} shots per string: mean={np.mean(stime):.4f}  "
          f"measured std. dev.={np.std(stime):.4f}  theoretical={teorica:.4f}")

# Output:
# energy as sum c*<P>: -1.137284 Ha
#    100 shots per string: mean=-1.1368  measured std. dev.=0.0123  theoretical=0.0125
#   1000 shots per string: mean=-1.1374  measured std. dev.=0.0039  theoretical=0.0040
#  10000 shots per string: mean=-1.1374  measured std. dev.=0.0013  theoretical=0.0013

The sum c·⟨P⟩ reproduces the FCI energy, so the Pauli decomposition is correct. The measured standard deviation (0.0123, 0.0039, 0.0013 hartree) coincides with the theoretical one and scales as the square root of the number of shots: to halve the uncertainty you need four times as many. With 10,000 shots per string you get to a little over one millihartree, and 14 × 10,000 shots were used for a single evaluation of the energy. An optimiser that requires a hundred evaluations then consumes of the order of 107 shots for a four-qubit molecule; it is an order of magnitude based on that assumed hundred, not a measurement. Strings that commute can be measured together to reduce the cost: here this was not done, and it is one of the research topics indicated in the review by Tilly and collaborators.

What can go wrong

The perfect simulator hides almost all the practical problems. Those that the code above lets you name are four, and the listing reproduces two of them, the first and the third:

  • an ansatz that is too weak fixes an energy floor above E0, and no optimiser lowers it;
  • leaving the particle sector, with a generic circuit, produces states with the wrong number of electrons, whose energy does not correspond to H2 (here it does not go below E0, because the global minimum falls in the right sector, but in general this is not guaranteed);
  • measurement noise makes the function to minimise stochastic, and a minimum that is too "flat" gets lost in the noise;
  • local minima and gradient plateaus make the optimiser stop far from the bottom.

The difference between the first and the third point is useful: the first is a representation limit, visible in the perfect simulator, the third is a measurement limit, which appears only with a finite number of shots. Hardware noise, which is not simulated here, adds to this and shifts the energy systematically, not just randomly. In a theoretical paper of 2015, McClean and collaborators propose derivative-free optimisers, because with noisy measurements computing the gradient is expensive; in their abstract they speak of computational savings of up to three orders of magnitude compared with the techniques used previously.

On real hardware the picture is more modest than the name of the algorithm suggests. The first experiment, on a photonic processor, computed the energy of the HeH+ ion within chemical accuracy; a later experiment, on superconducting qubits, obtained the dissociation energy of H2 with the same accuracy, with UCC and VQE. They are tiny molecules. The review by Tilly and collaborators points out that the multiplicative factors of various components of the algorithm might be too large to obtain an advantage over classical methods: it states this as an open question, and that is how it should be read here.

What you can do now

You can go from a molecule to a qubit Hamiltonian and check it against an FCI calculation, prepare a state with an ansatz that conserves the number of electrons and minimise the energy down to the exact result. You can estimate how many shots are needed for a given precision and explain why a result from the perfect simulator does not transfer directly to hardware. The next step changes the problem: no longer the molecule but a combinatorial optimisation problem, with the same hybrid architecture, in QAOA. The complete sequence is on the series page.

Frequently asked questions

What does VQE compute?

The ground-state energy of a Hamiltonian. A quantum processor prepares a state with parameters and measures its energy, a classical optimiser changes the parameters to lower it, and the variational principle guarantees that the value found is an upper bound on the true energy.

Why are four qubits and one parameter enough for H2?

In a minimal basis H2 has four spin-orbitals, hence four qubits. The exact state in the right sector is a combination of just two determinants, Hartree-Fock and the double excitation, and an ansatz with a single rotation reaches both: in simulation it coincides with the FCI.

Does VQE beat classical chemistry methods?

It has not been shown. The published experiments concern tiny molecules, exactly solvable on a laptop, and the reviews indicate that the measurement cost might cancel any advantage.

Sources

The three listings were run twice with Python 3.14, numpy 2.5.4, scipy 1.18.1 and PySCF 2.15.0, with identical outputs; shots.py uses a fixed seed. The outputs reported are the real ones. The simulator does not include hardware noise.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects