Quantum Chemistry Lab¶
Introduction¶
This notebook is concerned with a question: given a molecule, what is its ground-state energy?
The ground-state energy is the central quantity of chemistry. Almost every chemical property can be traced back to it or to differences between it and the energies of other states. Reaction energies and equilibrium constants are differences between ground-state energies of reactants and products. Bond strengths, molecular geometries, and vibrational frequencies follow from the shape of the ground-state energy as a function of nuclear positions. Reaction rates depend on the energies of transition states, which are themselves stationary points on the same energy surface. If the ground-state energy could be computed exactly for any molecule, it would give us most of what we need to predict how chemical reactions behave — how much energy they release, how fast they proceed, and which products form.
The question is simple to state but difficult to answer. The reason is not that the relevant physics is unknown. The Hamiltonian of a molecule — the operator whose eigenvalues are its allowed energies — is known in closed form. The difficulty lies in extracting its lowest eigenvalue. For small systems this can be done exactly, but for larger ones it rapidly becomes intractable by classical means, and this is the setting in which quantum computers are expected to have advantage.
The purpose of this introduction is to set out the basic objects and equations that the rest of the lab uses, so that the individual runs can be read as concrete instances of a single pipeline.
1. The electronic Hamiltonian¶
We work within the Born–Oppenheimer approximation, in which the nuclei are treated as fixed at positions $\mathbf{R}_A$ and only the electrons are treated quantum mechanically. The electronic (or fermionic) Hamiltonian for a molecule is then
$$ \hat H \;=\; \underbrace{\sum_{A<B}\frac{Z_A Z_B}{|\mathbf{R}_A-\mathbf{R}_B|}}_{E_\text{nuc}} \;+\; \underbrace{\sum_i\left(-\tfrac12\nabla_i^2-\sum_A\frac{Z_A}{|\mathbf{r}_i-\mathbf{R}_A|}\right)}_{\text{one-electron terms}} \;+\; \underbrace{\sum_{i<j}\frac{1}{|\mathbf{r}_i-\mathbf{r}_j|}}_{\text{two-electron terms}} . $$
In this expression, $A$ and $B$ label the nuclei and $i$ and $j$ label the electrons. $Z_A$ is the charge of nucleus $A$ (its atomic number), $\mathbf{R}_A$ is its position, and $\mathbf{r}_i$ is the position of electron $i$. The symbol $\nabla_i^2$ is the Laplacian with respect to the coordinates of electron $i$, so the term $-\tfrac12\nabla_i^2$ is the kinetic energy of that electron. All quantities are in atomic units, in which $\hbar$, the electron mass and the elementary charge are set to 1.
The three terms of this Hamiltonian are, respectively, the repulsion between nuclei, the kinetic energy and nuclear attraction of each electron, and the repulsion between electrons. Every term is known analytically. The nuclear positions are the only input that comes from outside the theory, either from experiment or from a geometry optimisation. For a diatomic molecule such as H₂, the nuclear positions reduce to a single number — the H–H bond distance.
2. Molecular integrals¶
This electronic Hamiltonian contains differential operators that cannot be used directly in a computation. It must first be represented in a finite set of functions, called a basis set. The idea is to write each one-electron orbital as a fixed linear combination of a small number of chosen functions, and then to compute how the Hamiltonian acts on those functions rather than on continuous space. The result is a finite array of numbers, which a computer can handle.
For H₂ — the example used throughout this notebook to demonstrate the different techniques for estimating the ground-state energy — the smallest such choice is the basis set known as STO-3G (from Slater-type orbital, approximated by three Gaussians). STO-3G is a minimal basis set: it assigns exactly one basis function to each orbital that is occupied in the free atom. A hydrogen atom has one electron, which occupies the 1s orbital (lowest shell with spherically symmetrical shape), so each hydrogen atom contributes one 1s function. This function in the STO-3G construction is a fixed sum of three Gaussians, chosen to approximate the shape of Slater-type orbital (function of the form $r^{n-1}e^{-\zeta r}$ that approximates the exact atomic orbitals). These two 1s functions (one on each hydrogen atom), represented in the STO-3G basis, then combine into two molecular orbitals, the bonding orbital $\sigma_g$ and the antibonding orbital $\sigma_u^*$. The electronic Hamiltonian is then expanded in this two-function basis, and the expansion produces the molecular integrals:
$$ h_{pq}=\int \phi_p^*(\mathbf r)\Big(-\tfrac12\nabla^2-\sum_A\frac{Z_A}{|\mathbf r-\mathbf R_A|}\Big)\phi_q(\mathbf r)\,d\mathbf r, $$
$$ (pq|rs)=\iint\frac{\phi_p^*(\mathbf r_1)\phi_q(\mathbf r_1)\,\phi_r^*(\mathbf r_2)\phi_s(\mathbf r_2)}{|\mathbf r_1-\mathbf r_2|}\,d\mathbf r_1\,d\mathbf r_2 . $$
The one-electron integrals (first equation) are evaluated for every pair of basis functions $(p,q)$, and each evaluation involves a three-dimensional integration; the two-electron integrals (second equation) are evaluated for every quartet $(p,q,r,s)$ and each involves six dimensions. The choice of basis set matters for accuracy and for cost: larger basis sets give more accurate energies but require more functions, more qubits, and more integrals. This cost is the reason why basis functions are usually chosen to be Gaussians, for which both types of integral have closed-form expressions.
3. Second quantisation¶
Once the integrals have been computed for this molecular geometry and basis, the electronic Hamiltonian can be written in a compact operator form using creation and annihilation operators. The operator $a^\dagger_{p\sigma}$ creates an electron in spin orbital $p$ with spin $\sigma$, and $a_{p\sigma}$ removes one. Taken together, these operators describe how electrons move between molecular orbitals: a product such as $a^\dagger_{p\sigma} a_{q\sigma}$ removes an electron from orbital $q$ and places it in orbital $p$, so the pair of operators represents a single move of one electron from one orbital to another. The coefficient in front of each such product, taken from the integrals, gives the amplitude for that move.
In this formalism the Hamiltonian is expressed as:
$$ \hat H \;=\; E_\text{nuc} \;+\; \sum_{pq,\sigma} h_{pq}\, a^\dagger_{p\sigma} a_{q\sigma} \;+\; \tfrac12 \sum_{pqrs,\sigma\tau} (pq|rs)\, a^\dagger_{p\sigma} a^\dagger_{r\tau} a_{s\tau} a_{q\sigma} . $$
The meaning of the three groups of terms can be read directly:
| Term | Operator | Interpretation |
|---|---|---|
| constant | $E_\text{nuc}$ | nuclear repulsion, a fixed number |
| one-body | $a^\dagger_{p} a_{q}$ | moves one electron from $q$ to $p$; for $p=q$ it counts the occupation of $p$ |
| two-body | $a^\dagger_{p} a^\dagger_{r} a_{s} a_{q}$ | moves two electrons simultaneously, representing their mutual repulsion |
The structure of this expression is the same for every molecule. What differs between molecules is only the numerical content — the values of $h_{pq}$, $(pq|rs)$ and $E_\text{nuc}$ — which are computed from the geometry and the basis set. In this lab, that computation is performed by PySCF in R1 and R2.
For H₂ the integral computation is trivial, but the number of two-electron integrals scales nominally as $N^4$, so a brute-force calculation becomes infeasible for large molecules. In practice most integrals are negligibly small, and larger systems are handled by integral screening and by local or fragment-based methods, which treat the molecule in pieces rather than as a whole.
4. The Schrödinger's Equation¶
The allowed energies of the molecule are the eigenvalues of $\hat H$. They satisfy the time-independent Schrödinger equation (TISE):
$$ \hat H\,|\psi_n\rangle \;=\; E_n\,|\psi_n\rangle, \qquad E_0 < E_1 < E_2 < \cdots $$
The lowest eigenvalue $E_0$ is the ground-state energy, and its eigenstate $|\psi_0\rangle$ is the ground state. This equation is the central object of the notebook: every run is, in one way or another, an attempt to determine $E_0$.
It is worth noting that this equation contains no time. Time would enter through the separate time-dependent Schrödinger equation (TDSE),
$$ i\hbar\,\partial_t|\psi\rangle \;=\; \hat H\,|\psi\rangle , $$
whose solution is the unitary operator $e^{-i\hat H t/\hbar}$. This operator advances a state from one moment to the next: a state prepared at time $t=0$ becomes $e^{-i\hat H t/\hbar}|\psi(0)\rangle$ at time $t$.
What this operator does depends on the state it acts on. For a general state, it produces a new state. For an eigenstate $|\psi_n\rangle$ with eigenvalue $E_n$, however, the action is particularly simple. Because $\hat H|\psi_n\rangle = E_n|\psi_n\rangle$, the operator $e^{-i\hat H t/\hbar}$ leaves the eigenstate unchanged except for a phase factor:
$$ e^{-i\hat H t/\hbar}\,|\psi_n\rangle \;=\; e^{-iE_n t/\hbar}\,|\psi_n\rangle . $$
The energy $E_n$ appears in this phase, and quantum phase estimation (QPE) algorithm uses that fact directly: it measures the accumulated phase and from it determines the energy of that eigenstate, $E_n$.
Thus, both the eigenvalue equation and the time-dependent equation describe the same system in different ways. The eigenvalue equation is static and concerns energies and eigenstates; the time-dependent equation describes how states change in time.
Finally, we can substitute real time $t$ with imaginary time $\tau = it$ in the time-dependent Schrödinger equation to obtain imaginary-time Schrödinger equation (ITSE), which is the foundation of the QC-AFQMC method:
$$ -\partial_\tau |\psi(\tau)\rangle = \hat{H} |\psi(\tau)\rangle $$
where $|\psi(\tau)\rangle$ is a general quantum state that is continuously changing. The solution to this equation is an exponential decay operator:
$$ |\psi(\tau)\rangle = e^{-\hat{H}\tau/\hbar} |\psi(0)\rangle $$
If we expand our initial state in the eigenstates of the Hamiltonian (instead of computational basis states), $|\psi(0)\rangle = \sum_n c_n |\psi_n\rangle$, we get:
$$ |\psi(\tau)\rangle = \sum_n c_n e^{-E_n\tau/\hbar} |\psi_n\rangle $$
Notice the exponent. The higher the energy $E_n$, the faster that term decays as $\tau$ increases. This means imaginary time acts as a filter. As $\tau \to \infty$, the excited states decay away exponentially, leaving only the lowest-energy term: the ground state $|\psi_0\rangle$.
This is exactly how the Monte Carlo part of QC-AFQMC works. While QPE uses real-time phases to measure the energy, QC-AFQMC uses imaginary time to project the system into the ground state. (In practice, we shift the exponent by a reference energy to prevent the wavefunction from decaying to zero entirely).
5. Configurations¶
Each molecular orbital can hold at most two electrons, one with spin up ($\alpha$) and one with spin down ($\beta$). A molecular orbital is a spatial orbital — it depends only on position, not on spin — and combining it with a spin label gives a spin orbital. For H₂ in STO-3G there are two spatial orbitals, $\sigma_g$ and $\sigma_u^*$, and therefore four spin orbitals: $\sigma_g\alpha$, $\sigma_g\beta$, $\sigma_u^*\alpha$ and $\sigma_u^*\beta$.
In the standard mapping used here, each spin orbital is either empty or occupied, and a qubit is either ∣0⟩ or ∣1⟩. The two are therefore in one-to-one correspondence, and each spin orbital is represented by one qubit. H₂ has four spin orbitals and so requires four qubits.
A configuration (Slater determinant) is one specific occupation pattern of the spin orbitals — which ones hold an electron and which are empty. For H₂ in STO-3G, the configuration $|0101\rangle$ denotes both electrons occupying $\sigma_g$, and $|1010\rangle$ denotes both occupying $\sigma_u^*$.
Together, the configurations span the many-electron state space, so the exact ground state is, in general, a superposition of all configurations:
$$ |\psi_0\rangle \;=\; \sum_k c_k\,|\text{config}_k\rangle , \qquad c_k\in\mathbb{C}. $$
The coefficients $c_k$ are complex amplitudes. Determining them is equivalent to determining the ground state, and it is the task that both classical and quantum methods address.
These configurations form the basis in which the Hamiltonian is represented. The entries of the Hamiltonian matrix built in the configuration basis are the energies of each configuration (diagonal) and the couplings between them (off-diagonal), and diagonalising this matrix gives the exact energies, the lowest of which is the ground-state energy that all the methods below aim to compute.
6. Algorithmic families for finding the ground-state energy¶
There are several distinct algorithmic strategies for determining $E_0$, and they differ in how they use the quantum computer. For the purposes of this lab, four families are worth distinguishing, alongside the exact classical method that serves as the reference.
The variational family (VQE). A parameterised trial state $|\psi(\theta)\rangle$ is prepared on the quantum computer, and the expectation value $\langle\psi(\theta)|\hat H|\psi(\theta)\rangle$ is measured. Because this expectation value is always greater than or equal to $E_0$, a classical optimiser can vary $\theta$ to drive the trial state toward the ground state. This is the variational quantum eigensolver (VQE). It is designed for near-term noisy hardware, but its accuracy is limited by measurement statistics, gate noise, and the expressiveness of the ansatz. It is the method used in this lab.
The sampling-and-diagonalisation family (SQD). The quantum computer is used as a sampler: it prepares a state and measures bitstrings, which correspond to electron configurations. A classical computer then projects the Hamiltonian onto the subspace spanned by the sampled configurations and diagonalises it there. Sample-based quantum diagonalisation (SQD) is also a hybrid strategy designed for near-term hardware, but is robust to noise and avoids the optimisation loop of VQE.
The phase-estimation family (QPE). Quantum phase estimation estimates the phase accumulated by an eigenstate under time evolution $e^{-i\hat H t}$, and that phase encodes the energy directly. QPE can in principle reach the ground-state energy with exponential precision and without a classical optimisation loop, but it requires deep, fault-tolerant circuits and error-corrected quantum computers.
The trial-state / quantum Monte Carlo family (QC-AFQMC). A fourth strategy uses the quantum computer to prepare a correlated trial wavefunction, which is then handed to a classical Auxiliary-Field Quantum Monte Carlo (AFQMC) algorithm. The classical algorithm simulates an imaginary-time random walk and repeatedly queries the quantum device to measure overlaps with the trial state. These overlaps are used to control the fermionic sign problem during propagation. This avoids the iterative loop of VQE and the deep circuits of QPE, though the classical post-processing can be demanding.
Classical diagonalisation (FCI). For completeness, the exact classical route is to construct the Hamiltonian matrix in the basis of all configurations and diagonalise it. This is full configuration interaction (FCI). It is exact within the chosen basis, but the dimension of the matrix grows exponentially with the number of orbitals, so it is feasible only for small systems.
The methods above represent genuinely different computational strategies and their implementation details are described in this lab.
7. Mapping to qubits¶
To run any quantum algorithm that operates on a qubit Hamiltonian (including VQE, QPE, and SQD), the fermionic Hamiltonian must first be translated into operators that act on qubits. This is typically done with the Jordan–Wigner transformation:
$$ a_j \;=\; Z_0 Z_1\cdots Z_{j-1}\,\frac{X_j+iY_j}{2}, \qquad a_j^\dagger \;=\; Z_0\cdots Z_{j-1}\,\frac{X_j-iY_j}{2}, $$
which expresses each creation and annihilation operator as a product of Pauli matrices. For H₂ in STO-3G the result is a Hamiltonian of 15 Pauli strings acting on 4 qubits. The transformation is exact: R3 verifies that the qubit Hamiltonian reproduces the FCI energy to within $10^{-10}$ Ha, so no physical information is lost in the mapping.
The sequence of steps described above can be summarised as follows:
$$ \underbrace{\text{geometry and basis}}_{\text{chosen}} \;\longrightarrow\; \underbrace{h_{pq},\ (pq|rs),\ E_\text{nuc}}_{\text{computed by PySCF}} \;\longrightarrow\; \underbrace{\hat H\text{ in }a^\dagger,\,a}_{\text{second quantisation}} \;\longrightarrow\; \underbrace{\hat H\text{ in }X,\,Y,\,Z}_{\text{Jordan–Wigner}} \;\longrightarrow\; \underbrace{E_0}_{\text{FCI, VQE, QPE or SQD}} . $$
We should note that QC-AFQMC shares the same construction of the qubit Hamiltonian but diverges at the last step of the conceptual pipeline above: the quantum device prepares a trial state and measures its overlaps, and a classical Monte Carlo algorithm uses those measurements to estimate the energy.
Each subsequent section of the notebook implements one part of this chain for the hydrogen molecule, and then examines how the final step using different approaches behaves under conditions that resemble real quantum hardware.
Overview of the Notebook¶
This experiment investigates how quantum computers can compute molecular energies, how precise those calculations can be, and which hardware limitations currently constrain their accuracy.
To address these questions, the ground-state energy of the hydrogen molecule is computed using different methods:
- Classically, with standard quantum-chemistry methods: Hartree–Fock and exact FCI (Full Configuration Interaction).
- With quantum algorithms: Variational Quantum Eigensolver (VQE), Sample-based Quantum Diagonalization (SQD), Quantum Phase Estimation (QPE) and Quantum-Classical Auxiliary-Field Quantum Monte Carlo (QC-AFQMC) using a simulated quantum computer.
Pipeline¶
The Introduction set out the conceptual pipeline. The version below shows how it is implemented in this notebook, with the runs that perform each step: steps 1–6 are common to every method discussed here, while the steps specific to a particular method are described separately.
1. molecule (H–H, with bond length R)
2. classical SCF (PySCF) to solve Hartree-Fock
3. orbital integrals h_pq, (pq|rs)
4. fermionic Hamiltonian
5. Jordan–Wigner mapping of fermions to qubits
6. qubit Hamiltonian (15 Pauli terms, 4 qubits)
↓
method-specific final stage
Notation. Throughout the notebook, the calculations are labelled R1, R2, … . Each label identifies one run — a single calculation performed by the cell or cells beneath it. Runs are grouped into stages, each corresponding to one part of the pipeline; a stage may consist of a single run or several. The labels and stages are used in the tables and text to refer to these calculations.
Conventions. The zero of energy is defined as all nuclei and electrons at infinite separation and at rest. The HF and FCI energies reported in R1 are relative to this reference, which is why they are negative.
Note on geometries. The single-point calculations in this section use H–H = 0.735 Å, close to the experimental bond length of 0.741 Å.
The common stages¶
The first three stages are common to every method discussed here and are described in this section. The final stage — extraction of the ground-state energy from the qubit Hamiltonian — differs between methods and is described separately in each method's section.
| Stage | Runs | What happens | Why it matters | Passes if |
|---|---|---|---|---|
| Molecule | R1 | Place two H atoms 0.735 Å apart; compute the classical Hartree–Fock and exact FCI energies | Establishes the answer key; shows that HF misses chemically decisive energy | HF and FCI are both computed |
| Integrals | R2 | Compute the integrals that describe the electrons' kinetic energies, nuclear attraction and mutual repulsion | Supplies the Hamiltonian inputs | Integrals match the expected values |
| Qubit Hamiltonian | R3 | Translate the fermionic Hamiltonian into qubits by Jordan–Wigner → 15 Pauli terms; check the result against the exact energy | Confirms that the translation to qubits loses nothing | Qubit Hamiltonian reproduces HF and FCI exactly |
These three stages establish two things: that Hartree–Fock is insufficiently accurate, and that the translation to qubits is exact. Both are prerequisites for every method that follows. Once R3 is complete, the qubit Hamiltonian is fixed, and the methods differ only in the final stage.
R1–R3 are entirely classical computations, performed with PySCF, NumPy and Qiskit's SparsePauliOp. The quantum simulation begins only in the method-specific sections that follow.
Constants used in this notebook¶
The table below lists the physical constants and fixed parameters that recur throughout the notebook.
| Constant | Value | Meaning | Used in |
|---|---|---|---|
| Hartree to eV | 27.211386 | 1 Ha = 27.211386 eV | R1, R7 |
| Hartree to kcal/mol | 627.5095 | 1 Ha = 627.5095 kcal/mol | R1 |
| Hartree to cm⁻¹ | 219474.63 | 1 Ha = 219474.63 cm⁻¹ | R7 |
| Bohr to Å | 0.529177210903 | 1 bohr = 0.529177 Å | R7 |
| Atomic mass unit | 1822.888486 mₑ | 1 amu = 1822.888 electron masses | R7 |
| Hydrogen atomic mass | 1.00782503 amu | mass of the hydrogen atom, used for the H₂ reduced mass | R7 |
| Chemical accuracy | 1.6 mHa | 1 kcal/mol, rounded; the accuracy target for the lab | R1, R6, R8, R9 |
| Reference bond length $R_\text{eq}$ | 0.735 Å | H–H distance for the single-point calculations | R1–R6, R8–R9 |
| Thermal energy $k_BT$ at 298 K | 0.944 mHa | thermal energy at room temperature | R1 |
The first three are unit conversions: they translate between atomic units used for simulations (hartree, bohr, electron mass) and the units more familiar in chemistry (eV, kcal/mol, cm⁻¹, Å, amu).
The next two are length and mass conversions: the first expresses the bond lengths in atomic units (bohr) for the curvature fit, so that the force constant comes out in hartree per bohr²; the second expresses the hydrogen mass in electron masses, so that the reduced mass can be formed in atomic units. Both are needed in R7, where the vibrational frequency of H₂ is obtained from the curvature of the energy curve and the reduced mass.
Next, hydrogen atomic mass, 1.00782503 amu, is used to form the reduced mass of the H₂ molecule, $\mu = m_H/2$; for a different diatomic molecule, the mass would be different, so this value is specific to H₂ rather than to the unit system.
The last three are parameters of the calculation rather than physical constants: the accuracy target, the geometry at which the single-point calculations are performed, and the thermal energy used to interpret an energy error as a change in a rate or equilibrium constant.
# ── R0 · Environment check and imports ─────────────────────────────────────
import sys, time, warnings
try:
import numpy as np
import matplotlib.pyplot as plt
import scipy
import qiskit_algorithms
import qiskit, qiskit_aer, pyscf
except ImportError as e:
raise ImportError(
f"{e}\n\nRun `uv sync` (or `pip install -e .`) in the repo root, "
"then restart the kernel."
) from None
from scipy.optimize import minimize
from pyscf import gto, scf, fci, ao2mo
from qiskit import QuantumCircuit, transpile
from qiskit.circuit import Parameter
from qiskit.circuit.library import PauliEvolutionGate, real_amplitudes
from qiskit.quantum_info import SparsePauliOp, Statevector
from qiskit.primitives import StatevectorEstimator
from qiskit_aer.primitives import EstimatorV2 as AerEstimator
from qiskit_aer.noise import NoiseModel, depolarizing_error
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", module="scipy.sparse")
# ── Physical constants ────────────────────────────────────────────────────────
HARTREE_TO_EV = 27.211386 # 1 Ha = 27.211386 eV
HARTREE_TO_KCAL = 627.5095 # 1 Ha = 627.5095 kcal/mol
HARTREE_TO_CM = 219474.63 # 1 Ha = 219474.63 cm⁻¹
BOHR_TO_ANGSTROM = 0.529177210903 # 1 bohr = 0.529177 Å
AMU_TO_ME = 1822.888486 # 1 amu = 1822.888 electron masses
# ── Lab-specific parameters ───────────────────────────────────────────────────
CHEM_ACC = 1.6e-3 # chemical accuracy: 1 kcal/mol ≈ 1.6 mHa
R_EQ = 0.735 # H–H distance in Å used for the single-point runs
# ── Plot style (colour-blind-validated palette; one colour per method) ───────
COL = {"HF": "#2a78d6", "FCI": "#eb6834", "VQE": "#1baf7a", # methods
"Compact": "#4a3aa7", "HEA": "#e87ba4", "raw": "#4a3aa7", # ansätze / unmitigated
"muted": "#898781", "grid": "#e1e0d9"}
plt.rcParams.update({
"figure.dpi": 110, "font.size": 10, "axes.edgecolor": "#c3c2b7", "axes.labelcolor": "#52514e",
"axes.grid": True, "grid.color": COL["grid"], "grid.linewidth": 0.6, "axes.spines.top": False,
"axes.spines.right": False, "xtick.color": "#52514e", "ytick.color": "#52514e",
"lines.linewidth": 2, "legend.frameon": False,
})
print(f"Python {sys.version.split()[0]} | qiskit {qiskit.__version__} | qiskit-aer {qiskit_aer.__version__} | "
f"pyscf {pyscf.__version__} | numpy {np.__version__}")
Python 3.12.8 | qiskit 2.4.2 | qiskit-aer 0.17.2 | pyscf 2.15.0 | numpy 2.4.6
R1 · Classical reference: Hartree–Fock and Full CI energies¶
In the STO-3G basis each H atom contributes one 1s function. These two functions combine into two molecular orbitals,
$$ \sigma_g \propto 1s_A + 1s_B \quad (\text{bonding}), \qquad \sigma_u^* \propto 1s_A - 1s_B \quad (\text{antibonding}). $$
Each orbital can hold one $\alpha$ and one $\beta$ electron, giving four spin orbitals, and later four qubits.
The correlation energy is the energy recovered by going from a single configuration to the full mixture of configurations. Operationally it is measured as
$$ E_\text{corr} = E_\text{FCI} - E_\text{HF} < 0, $$
because HF is the best single configuration and FCI is the full mixture: the difference between them is exactly the energy that mixing recovers. It is negative because FCI is always lower than HF by the variational principle.
"Exact" here means exact within STO-3G. FCI solves the electronic Schrödinger equation exactly for the basis it is given, so the value it produces is the best answer STO-3G can give. But STO-3G is a small basis — one function per hydrogen, built from three Gaussians — and it cannot describe the true orbitals perfectly. The near-exact non-relativistic energy of H₂, obtained with a much larger basis, is −1.1745 Ha. The difference between that value and the FCI result is therefore a basis-set error, not an algorithm error: no method, classical or quantum, can remove it without a larger basis. The lab uses STO-3G deliberately, to separate the correlation problem the methods are meant to solve from the basis-set error that comes with the basis itself.
The code defines the H₂ molecule at R_EQ = 0.735 Å with PySCF and computes the two reference values E_HF and E_FCI:
- restricted Hartree–Fock (
scf.RHF); - full CI (
fci.FCI); this is $E_0$, the target for the methods that follow.
It then derives the correlation energy $E_\text{corr}$, in mHa and kcal/mol, together with its thermal interpretation. The quantity kT is local to R1 and used only for the rate-factor estimate.
The correlation energy is the part of the energy that Hartree–Fock misses, and although it is only about 1.8% of the total, it governs chemical behaviour — which is why every method that follows in this lab is judged by how well it recovers it. At room temperature, an error of 20.3 mHa would change a predicted reaction rate by about a billion times.
# ── R1 · The molecule and its classical reference energies ────────────────────
def classical_h2(R, basis="sto-3g"):
"""Build H2 at bond length R (Å); return HF and exact (FCI) results plus the objects needed later."""
mol = gto.M(atom=f"H 0 0 0; H 0 0 {R}", basis=basis, unit="Angstrom", verbose=0)
mf = scf.RHF(mol).run() # Hartree–Fock: best single Slater determinant
e_fci = fci.FCI(mf).kernel()[0] # Full CI: exact answer inside this basis set
return {"R": R, "mol": mol, "mf": mf, "E_nuc": mol.energy_nuc(), "E_HF": mf.e_tot, "E_FCI": e_fci}
ref = classical_h2(R_EQ)
E_HF, E_FCI = ref["E_HF"], ref["E_FCI"]
E_corr = E_FCI - E_HF
print(f"H2 at R = {R_EQ} Å, basis STO-3G")
print(f" atomic orbitals : {ref['mol'].nao} electrons: {ref['mol'].nelectron}")
print(f" orbital energies (Ha): {np.round(ref['mf'].mo_energy, 6)} (σg occupied, σu* empty)")
print(f" nuclear repulsion : {ref['E_nuc']: .6f} Ha")
print(f" E_HF : {E_HF: .6f} Ha")
print(f" E_FCI (exact) : {E_FCI: .6f} Ha")
print(f" correlation energy : {E_corr*1e3: .3f} mHa = {E_corr*HARTREE_TO_KCAL: .2f} kcal/mol (difference between FCI and HF)")
print(f" chemical accuracy : {CHEM_ACC*1e3:.1f} mHa -> HF misses it by a factor {abs(E_corr)/CHEM_ACC:.0f}")
# ── Interpretation: what an energy error means for chemistry at room temperature ──
kT = 3.166811563e-6 * 298.15 # Boltzmann constant (Ha/K) × 298.15 K
print(f"\nThermal energy kT at 298 K (room temperature or 25°C): {kT*1e3:.3f} mHa")
for label, err in [("chemical accuracy", CHEM_ACC), ("HF error = missing correlation", abs(E_corr))]:
print(f" error {err*1e3:6.2f} mHa -> rate / equilibrium constant off by a factor ≈ {np.exp(err/kT):<9.3g} ({label})")
print(f"\nHF fraction of FCI energy : {E_HF/E_FCI:.1%} (correlation is {abs(E_corr/E_FCI):.1%} of the total)")
H2 at R = 0.735 Å, basis STO-3G atomic orbitals : 2 electrons: 2 orbital energies (Ha): [-0.580629 0.676336] (σg occupied, σu* empty) nuclear repulsion : 0.719969 Ha E_HF : -1.116999 Ha E_FCI (exact) : -1.137306 Ha correlation energy : -20.307 mHa = -12.74 kcal/mol (difference between FCI and HF) chemical accuracy : 1.6 mHa -> HF misses it by a factor 13 Thermal energy kT at 298 K (room temperature or 25°C): 0.944 mHa error 1.60 mHa -> rate / equilibrium constant off by a factor ≈ 5.44 (chemical accuracy) error 20.31 mHa -> rate / equilibrium constant off by a factor ≈ 2.19e+09 (HF error = missing correlation) HF fraction of FCI energy : 98.2% (correlation is 1.8% of the total)
Interpretation¶
- The correlation energy, or the energy recovered by going from a single configuration to the full mixture of configurations (in our case the difference between FCI and HF) is small in absolute terms but chemically significant. It is about 1.8% of the total energy, yet 13 times larger than chemical accuracy.
- Chemistry is governed by energy differences. Reaction energies, barriers and bond strengths enter rates and equilibria exponentially, as $e^{-\Delta E/k_BT}$. At room temperature $k_BT = 0.944$ mHa, so an error of 1.6 mHa already changes a prediction by a factor of 5.44, and the 20.307 mHa that HF misses changes it by about nine orders of magnitude (two billion times). This is why the lab asks for the chemical accuracy of 1.6 mHa.
Conclusion. Hartree–Fock recovers about 98.2% of the total energy but misses the correlation energy of 20.3 mHa, which is what governs chemical behavior.
The target for the following methods is to recover this missing 20.3 mHa to within 1.6 mHa.
In the next step R2 we will compute the integrals from which the Hamiltonian, and hence those energies, are built.
R2 · Molecular-orbital integrals — the Hamiltonian inputs¶
R2 computes the one- and two-electron integrals $h_{pq}$ and $(pq∣rs)$ - defined in the Introduction - from which the Hamiltonian is built.
But before computing the integrals, it is worth seeing why this difference (correlation energy) has the value of 20.3 mHa.
The true ground state is not the HF configuration alone: it is a mixture of the ground configuration and the doubly-excited one. How much of the excited configuration appears is set by the ratio of two quantities: the energy gap between the configurations, which suppresses the mixing of these two configurations, and the coupling between them — the off-diagonal matrix element of the Hamiltonian, given by $\langle 1010|\hat H|0101\rangle$, which increases that mixing. When the gap is much larger than the coupling, the mixture is dominated by the ground configuration, with only a small admixture of the excited one, and the energy gained by the mixing of these two configruations — the correlation energy — is small.
For H₂ the antibonding orbital $\sigma_u^*$ lies about 1.26 Ha above $\sigma_g$, so the doubly-excited configuration lies about 1.59 Ha ($\Delta$) above the ground configuration — the extra 0.33 Ha comes from the electron–electron repulsion when both electrons occupy $\sigma_u^*$. The coupling between the two configurations is 0.18 Ha ($K$), the exchange integral $(01|01)$: it is the coefficient of the only term in $\hat H$ that moves both electrons from $\sigma_g$ to $\sigma_u^*$, and therefore equals the off-diagonal matrix element between the two configurations. The ratio of the coupling to the gap ($K/\Delta$) is small, about 0.11, so the ground state is close to the HF configuration. The energy gained by the mixing is $E_\text{corr} \approx -K^2/\Delta \approx -20.4$ mHa, close to the exact value of 20.3 mHa. R7 shows that the configuration gap closes as the bond is stretched, the mixing becomes large, and the correlation energy grows to hundreds of mHa, as happens when the molecule dissociates.
The code evaluates the matrix elements $\langle\phi_p|\hat h|\phi_q\rangle$ — the one-electron integrals defined in the Introduction, now computed for the two molecular orbitals of H₂ — and stores them together with the corresponding two-electron integrals, where both will be needed to build the Hamiltonian. For H₂ the result is the $2 \times 2$ matrix printed above, whose entries are the energies of an electron in $\sigma_g$ and $\sigma_u^*$ and the (vanishing) coupling between them.
# ── R2 · Molecular-orbital integrals: the ingredients of the Hamiltonian ──────
def mo_integrals(ref):
mol, mf = ref["mol"], ref["mf"]
C = mf.mo_coeff # AO -> MO transformation
h1 = C.T @ mf.get_hcore() @ C # one-electron integrals h_pq (kinetic + nuclear attraction)
g = ao2mo.restore(1, ao2mo.kernel(mol, C), C.shape[1]) # two-electron integrals (pq|rs), chemist notation
return h1, g
h1, g = mo_integrals(ref)
n_orb = h1.shape[0]
np.set_printoptions(precision=6, suppress=True)
print(f"Spatial orbitals: {n_orb} -> spin orbitals / qubits: {2*n_orb}\n")
print("One-electron integrals h_pq (Ha):\n", h1, "\n")
print("Distinct two-electron integrals (pq|rs) (Ha):")
for (p, q, r, s), label in [
((0,0,0,0), "(00|00) Coulomb, both electrons in σg "),
((1,1,1,1), "(11|11) Coulomb, both electrons in σu* "),
((0,0,1,1), "(00|11) Coulomb, one in σg and one in σu* "),
((0,1,0,1), "(01|01) Exchange, mixes the two configurations"),
]:
print(f" {label:<46} {g[p,q,r,s]: .6f}")
Spatial orbitals: 2 -> spin orbitals / qubits: 4 One-electron integrals h_pq (Ha): [[-1.256339 0. ] [ 0. -0.471896]] Distinct two-electron integrals (pq|rs) (Ha): (00|00) Coulomb, both electrons in σg 0.675710 (11|11) Coulomb, both electrons in σu* 0.698574 (00|11) Coulomb, one in σg and one in σu* 0.664582 (01|01) Exchange, mixes the two configurations 0.180931
Interpretation¶
- The zero off-diagonal entries of the one-electron matrix reflect the inversion symmetry of H₂. Because the two atoms are identical, the molecule has a centre of inversion at the midpoint of the bond, and inverting every point through that centre swaps the two nuclei. A molecular orbital that is unchanged by this operation is called gerade ($\sigma_g \propto 1s_A + 1s_B$) and one that changes sign is called ungerade ($\sigma_u^* \propto 1s_A - 1s_B$). The one-electron operator is itself symmetric under inversion, so it cannot connect an orbital of one parity to an orbital of the other - that is, move an electron between them; hence $h_{01} = 0$. This same symmetry causes whole classes of terms to vanish from the Hamiltonian.
- $(01|01)$ — the matrix element $\langle 1010|\hat H|0101\rangle$ — is the exchange integral between the two configurations. Of the four distinct two-electron integrals, it is the only one that couples the ground configuration $|0101\rangle$ to the doubly-excited configuration $|1010\rangle$; the three Coulomb integrals act within a single configuration. A nonzero value is what allows the ground state to be a mixture rather than a single configuration, and therefore what allows a correlation energy to appear.
- The repulsion integrals are large (about 0.66–0.70 Ha each) and of the same order of magnitude as the one-electron integrals $h_{00}$ and $h_{11}$ (1.26 and 0.47 Ha) — not small compared with them. Electron–electron repulsion is not a small correction, so averaging it, as HF does, is the source of the error.
- The number of integrals needed for H–H is six. For a molecule with $N$ orbitals, the two-electron integrals grow polynomially as $N^4$, which is why the Hamiltonian becomes much larger for bigger molecules.
Conclusion. These six numbers — two nonzero one-electron integrals and four distinct two-electron integrals — fully specify H₂ in the STO-3G basis set. Inversion symmetry already tells us that correlation will come from one double excitation (the one in which both electrons have moved from $\sigma_g$ to $\sigma_u^*$), controlled by the exchange integral $(01|01) = 0.181$ Ha.
R3 · Jordan–Wigner mapping to the qubit Hamiltonian¶
The Introduction section defined the second-quantized Hamiltonian and the Jordan–Wigner mapping. Here they are applied to H₂: the results of the integrals from R2 are used into the Hamiltonian formula, the fermionic (creation and annihilation) operators are mapped to Pauli operators by Jordan-Wigner and the resulting qubit Hamiltonian is converted to a matrix and diagonalised. The result is checked in two ways: the lowest eigenvalue must equal $E_{FCI}$, and the diagonal entry for $|0101\rangle$ — read from the matrix before diagonalisation — must equal $E_{HF}$.
Jordan-Wigner¶
Jordan-Wigner mapping transforms the fermionic annihilation ($a_j$) and creation ($a_j^\dagger$) operators as Pauli operators:
$$ a_j = Z_0 Z_1 \cdots Z_{j-1}\,\frac{X_j + iY_j}{2}, \qquad a_j^\dagger = Z_0 \cdots Z_{j-1}\,\frac{X_j - iY_j}{2}. $$
The factor $(X+iY)/2 = |0\rangle\langle1|$ empties the orbital: it maps occupied $|1\rangle$ to empty $|0\rangle$, and gives zero if the orbital is already empty. Its adjoint $(X-iY)/2 = |1\rangle\langle0|$ does the reverse, filling the orbital. The string of Pauli $Z$ operators on all earlier qubits supplies the fermionic sign — the minus sign that fermions acquire when two of them are exchanged.
Qubit-orbital assignment¶
The four spin orbitals defined in the Introduction are assigned to the four qubits — all α first, then all β:
| Qubit | Spin orbital |
|---|---|
| q0 | $\sigma_g\alpha$ |
| q1 | $\sigma_u^*\alpha$ |
| q2 | $\sigma_g\beta$ |
| q3 | $\sigma_u^*\beta$ |
Qiskit writes states as $|q_3 q_2 q_1 q_0\rangle$, with the highest-index qubit on the left. Hartree–Fock puts both electrons in the lowest orbital, $\sigma_g$ — one with spin α (q0) and one with spin β (q2). So q0 = 1 and q2 = 1, with q1 = q3 = 0, which in the order $|q_3 q_2 q_1 q_0\rangle$ is $|0101\rangle$.
This assignment is what allows the results below to be read in chemical terms: which entry is the HF energy, which is the ground-state energy, and which configurations are coupled.
Steps¶
The code will encode the electronic Hamiltonian from R2 иnto qubits using the Jordan–Wigner transform and verify the ground-state energy through the quantum encoding against R1's exact values.
- Builds Jordan–Wigner annihilation operators $a_j$ as
SparsePauliOp - Assembles $\hat H = E_\text{nuc} + \sum h_{pq} a^\dagger a + \frac{1}{2}\sum(pq|rs) a^\dagger a^\dagger a a$.
- Diagonalises the 16×16 matrix to obtain its eigenvalues.
- Checks the mapping in two ways: the lowest eigenvalue must equal $E_\text{FCI}$, and the diagonal entry of the HF bitstring $|0101\rangle$ — read from the matrix before diagonalisation — must equal $E_\text{HF}$.
- Shows that the problem reduces to two configurations — $|0101\rangle$ (both electrons in $\sigma_g$) and $|1010\rangle$ (both in $\sigma_u^*$), where all other configurations have the wrong electron number, spin or parity, so they cannot mix with the ground state.
# ── R3 · Second quantisation + Jordan–Wigner mapping -> qubit Hamiltonian ─────
N_QUBITS = 2 * n_orb # 4 qubits: [q0 q1 | q2 q3] = [α0 α1 | β0 β1]
def spin_orbital(p, spin): # block ordering: all α first, then all β
return p + n_orb * spin
def annihilation(j, n=N_QUBITS):
"""Jordan–Wigner: a_j = Z_0 … Z_{j-1} (X_j + iY_j)/2 (Qiskit labels are right-to-left)."""
idx = [j] + list(range(j))
return SparsePauliOp.from_sparse_list([("X" + "Z"*j, idx, 0.5), ("Y" + "Z"*j, idx, 0.5j)], num_qubits=n)
a = [annihilation(j) for j in range(N_QUBITS)]
ad = [op.adjoint() for op in a] # creation operators a†_j
def qubit_hamiltonian(E_nuc, h1, g):
"""H = E_nuc + Σ h_pq a†_p a_q + ½ Σ (pq|rs) a†_pσ a†_rτ a_sτ a_qσ, mapped to Pauli strings."""
H = SparsePauliOp.from_sparse_list([("", [], E_nuc)], num_qubits=N_QUBITS)
rng = range(n_orb)
# ── One-electron terms: sum over spin s and orbital pair (p, q) ──────────
for s in (0, 1):
for p in rng:
for q in rng:
if abs(h1[p, q]) > 1e-12:
H += h1[p, q] * ad[spin_orbital(p, s)].dot(a[spin_orbital(q, s)])
# ── Two-electron terms: sum over spins (s, t) and orbitals (p, q, r, u) ─
for s in (0, 1):
for t in (0, 1):
for p in rng:
for q in rng:
for r in rng:
for u in rng:
v = g[p, q, r, u]
if abs(v) > 1e-12:
H += 0.5 * v * (ad[spin_orbital(p, s)].dot(ad[spin_orbital(r, t)])
.dot(a[spin_orbital(u, t)]).dot(a[spin_orbital(q, s)]))
return H.simplify(atol=1e-10)
H = qubit_hamiltonian(ref["E_nuc"], h1, g)
print(f"Qubit Hamiltonian: {len(H)} Pauli terms on {H.num_qubits} qubits\n")
for label, c in sorted(zip(H.paulis.to_labels(), H.coeffs.real), key=lambda t: -abs(t[1])):
print(f" {c:+.6f} · {label}")
# ── Checks: exact diagonalisation must reproduce FCI; |0101> must give E_HF ──
Hmat = H.to_matrix() # converts the SparsePauliOp (the 15 Pauli terms) into a 16×16 matrix in the computational basis
evals = np.linalg.eigvalsh(Hmat) # diagonalises that matrix and returns its eigenvalues, sorted in ascending order, evals[0] will be the losest eigenvalue
HF_BITSTRING = "0101" # q3 q2 q1 q0 : α0 (q0) and β0 (q2) occupied
E_hf_state = Hmat[int(HF_BITSTRING, 2), int(HF_BITSTRING, 2)].real
print(f"\nLowest eigenvalue of H : {evals[0]: .10f} Ha (FCI {E_FCI: .10f})")
print(f"<{HF_BITSTRING}|H|{HF_BITSTRING}> : {E_hf_state: .10f} Ha (HF {E_HF: .10f})")
# ── Which configurations can mix with |0101>? ────────────────────────────────
# The ground state has two electrons (one α, one β) and is gerade. Only
# configurations sharing these three properties can have a nonzero matrix
# element with it. The bitstring is written |q3 q2 q1 q0>, so:
# alpha orbitals: q0, q1 -> string positions 3, 2
# beta orbitals: q2, q3 -> string positions 1, 0
# σg orbitals: q0, q2 -> string positions 3, 1
# σu* orbitals: q1, q3 -> string positions 2, 0
def electron_number(bits):
return bits.count("1")
def spin_counts(bits):
return int(bits[3]) + int(bits[2]), int(bits[1]) + int(bits[0]) # (n_alpha, n_beta)
def parity(bits):
n_u = int(bits[2]) + int(bits[0]) # occupied σu* orbitals
return (-1) ** n_u # +1 = gerade, -1 = ungerade
ground = HF_BITSTRING
ground_idx = int(ground, 2)
candidates = []
for k in range(2 ** N_QUBITS):
bits = format(k, f"0{N_QUBITS}b")
if (electron_number(bits) == electron_number(ground)
and spin_counts(bits) == spin_counts(ground)
and parity(bits) == parity(ground)):
candidates.append((k, bits))
print("\nConfigurations with the same electron number, spin and parity as |0101>:")
for k, bits in candidates:
print(f" |{bits}> (index {k})")
mixing = [(k, bits) for k, bits in candidates
if k != ground_idx and abs(Hmat[ground_idx, k]) > 1e-12]
print("\nOf these, the ones that actually couple to |0101>:")
for k, bits in mixing:
print(f" |{bits}> coupling = {Hmat[ground_idx, k].real:+.6f} Ha")
# ── 2×2 block built from the identified configurations ───────────────────────
two = [ground_idx] + [k for k, _ in mixing]
H_eff = Hmat[np.ix_(two, two)].real
print(f"\nEffective {len(two)}×{len(two)} Hamiltonian in the basis "
f"{{{', '.join('|'+format(k, f'0{N_QUBITS}b')+'>' for k in two)}}} (Ha):")
print(H_eff)
print("its eigenvalues:", np.round(np.linalg.eigvalsh(H_eff), 8), " -> the lower one is E_FCI")
Qubit Hamiltonian: 15 Pauli terms on 4 qubits
-0.225753 · IIZI
-0.225753 · ZIII
+0.174643 · ZIZI
+0.172184 · IIIZ
+0.172184 · IZII
+0.168928 · IZIZ
+0.166145 · ZIIZ
+0.166145 · IZZI
+0.120913 · IIZZ
+0.120913 · ZZII
-0.090579 · IIII
+0.045233 · YYYY
+0.045233 · XXYY
+0.045233 · YYXX
+0.045233 · XXXX
Lowest eigenvalue of H : -1.1373060358 Ha (FCI -1.1373060358)
<0101|H|0101> : -1.1169989968 Ha (HF -1.1169989968)
Configurations with the same electron number, spin and parity as |0101>:
|0101> (index 5)
|1010> (index 10)
Of these, the ones that actually couple to |0101>:
|1010> coupling = +0.180931 Ha
Effective 2×2 Hamiltonian in the basis {|0101>, |1010>} (Ha):
[[-1.116999 0.180931]
[ 0.180931 0.474751]]
its eigenvalues: [-1.137306 0.495058] -> the lower one is E_FCI
Interpretation¶
- The lowest eigenvalue of the matrix is the ground-state energy, the diagonal entry for $|0101\rangle$ is the Hartree–Fock energy, and the configurations that can mix with the ground state are those with the same electron number, spin and parity as $|0101\rangle$.
- The lowest eigenvalue agrees with $E_\text{FCI}$ and the $|0101\rangle$ entry with $E_\text{HF}$, both to $10^{-10}$ Ha. The Jordan-Wigner mapping therefore preserves the predictions of the model, so any later error comes from the quantum algorithm, sampling or noise, and not from the encoding.
- Out of 15 total Hamiltonian terms, the 11 $I/Z$ terms only assign an energy to each bitstring and cannot change the electrons' arrangement. The 4 $X/Y$ terms are the only ones that move electrons from $\sigma_g$ to $\sigma_u^*$ or back. Each carries a coefficient of 0.045233, and their sum is $(01|01) = 0.180931$ — the exchange integral of R2.
- The 2×2 block reproduces the correlation energy: the off-diagonal $0.181$ Ha lowers the lower eigenvalue by $K^2/\Delta \approx 20.6$ mHa, matching the $20.3$ mHa from R1.
- For H₂ the matrix is only 16×16, so diagonalisation is easy. But in general the matrix grows as $2^N$ (where $N$ is the number of qubits) — about $6.7 \times 10^7$ entries for water in a modest basis (R10) — so diagonalization becomes impossible for real molecules.
Conclusion. The molecule is now a 15-term operator on 4 qubits, verified exactly against R1. All of H₂'s correlation comes from one coupling, $(01|01) = 0.181$ Ha, between $|0101\rangle$ and $|1010\rangle$. The ground state therefore lies in a two-dimensional subspace, a fact each of the methods below can exploit in its own way.
Variational Quantum Eigensolver (VQE)¶
Introduction to VQE¶
VQE determines the ground-state energy of a Hamiltonian with a hybrid quantum-classical algorithm architecture. The quantum computer prepares a trial state $|\psi(\theta)\rangle$ and measures its energy; the classical optimiser adjusts $\theta$ to lower that energy. By the variational principle, the measured energy is always at least $E_0$, so minimising it drives the trial state toward the ground state.
The loop has three parts:
$$ \underbrace{|\psi(\theta)\rangle}_{\text{ansatz}} \;\longrightarrow\; \underbrace{\langle\psi(\theta)|\hat H|\psi(\theta)\rangle}_{\text{estimator}} \;\longleftrightarrow\; \underbrace{\theta \leftarrow \text{optimiser}}_{\text{classical}} \;\longrightarrow\; E_\text{VQE} $$
The diagram shows the VQE loop. The ansatz prepares a trial state, and the estimator measures its energy. The optimiser and the estimator then exchange information repeatedly (denoted with double-arrow line): the optimiser uses the measured energy to choose the next θ, and the circuit uses that θ to prepare the next trial state. Once the energy stops decreasing, the result is $E_\text{VQE}$.
For H₂, R3 established that the qubit Hamiltonian has 15 Pauli terms and that the ground state lies in the two-dimensional subspace spanned by $|0101\rangle$ and $|1010\rangle$. VQE therefore has to search a very small space — which is what makes the comparison between the three circuits (ansätze) in R4 interesting: they differ in how many gates the use to cover that same space.
R4 · Trial circuits (ansätze)¶
R4 builds three parameterised circuits that can all prepare the same two-dimensional ground-state space, at very different hardware costs.
VQE starts from a trial state and improves it, so it needs a reference. Here the reference is the HF configuration, $|0101\rangle$: it is the best single configuration, already 98 % of the ground state, so the circuit only has to add the small admixture of $|1010\rangle$. This reference will be used as the starting point for the trial state.
- UCC-D — the physics-derived unitary coupled-cluster circuit, truncated to the double excitation $e^{\theta(T_2 - T_2^\dagger)}|\text{HF}\rangle$, since for H₂ single excitations are forbidden by symmetry and triple excitations are impossible. One parameter, 44 CNOTs after transpilation.
- Compact — a hand-tailored 3-CNOT circuit, built from R3's result that only $|0101\rangle \leftrightarrow |1010\rangle$ matters. One parameter.
- Hardware-efficient —
real_amplitudeswith two repetitions: generic $R_y$ rotations and a linear CNOT ladder, which make no use of the molecular structure found in R3. 12 parameters.
The three ansätze differ in how much they know about the problem. The compact circuit is short because R3 established that only two configurations matter, so a single rotation and three CNOTs suffice. UCC-D is long because it is general: it is written as the exponential of a fermionic operator, which the Jordan–Wigner mapping expands into eight Pauli strings, and those into 44 CNOTs — it does not exploit the fact that H₂ is simple. The hardware-efficient circuit is short in gates but long in parameters: it makes no use of the molecular structure found in R3, so we have to optimize its 12 angles.
The code builds the three circuits, prints their parameter, CNOT and depth counts, and draws the compact and hardware-efficient ones. The VQE loop here is implemented explicitly rather than through Qiskit's high-level VQE class. This makes each stage visible and modifiable. A later cell repeats the same calculation with the packaged class for the comparison.
# ── R4 · Three trial circuits (ansätze) ──────────────────────────────────────
theta = Parameter("θ")
def hf_circuit():
qc = QuantumCircuit(N_QUBITS)
qc.x([0, 2]) # occupy α0 and β0 -> |0101>
return qc
# (A) Unitary coupled-cluster, doubles only (UCC-D): exp(θ (a†_{α1} a†_{β1} a_{β0} a_{α0} − h.c.))
T2 = ad[spin_orbital(1, 0)].dot(ad[spin_orbital(1, 1)]).dot(a[spin_orbital(0, 1)]).dot(a[spin_orbital(0, 0)])
G = (1j * (T2 - T2.adjoint())).simplify() # Hermitian generator, exp(−iθG)
BASIS_GATES = ["cx", "rz", "sx", "x"]
ucc = hf_circuit()
ucc.append(PauliEvolutionGate(G, time=theta), range(N_QUBITS))
ucc = transpile(ucc, basis_gates=BASIS_GATES, optimization_level=3, seed_transpiler=7) # PauliEvolutionGate must be decomposed into elementary gates
# (B) Compact, symmetry-aware circuit: cos φ|1010> + sin φ|0101>-type state with 3 CNOTs (φ = π/2 is HF)
phi = Parameter("φ")
compact = QuantumCircuit(N_QUBITS)
compact.ry(2 * phi, 0)
compact.x([1, 3])
compact.cx(0, 2); compact.cx(0, 1); compact.cx(0, 3)
# (C) Hardware-efficient: HF start + RY layers and a linear CNOT ladder (no chemistry built in)
hea = hf_circuit().compose(real_amplitudes(N_QUBITS, reps=2, entanglement="linear"))
ANSATZE = {"UCC-D": ucc, "Compact": compact, "Hardware-efficient": hea}
print("Generator G of the UCC double excitation:", [f"{c.real:+.3f}·{l}" for l, c in zip(G.paulis.to_labels(), G.coeffs)])
print()
print(f"{'Ansatz':<20}{'parameters':>11}{'CNOTs':>7}{'depth':>7}")
for name, qc in ANSATZE.items():
tq = transpile(qc, basis_gates=BASIS_GATES, optimization_level=1)
print(f"{name:<20}{qc.num_parameters:>11}{tq.count_ops().get('cx', 0):>7}{tq.depth():>7}")
print("\nCompact ansatz:")
print(compact.draw(output="text"))
print("Hardware-efficient ansatz:")
print(transpile(hea, basis_gates=["x", "ry", "cx"]).draw(output="text", fold=110))
Generator G of the UCC double excitation: ['-0.125·XYXX', '-0.125·XXXY', '-0.125·YYXY', '+0.125·YXXX', '-0.125·XYYY', '+0.125·XXYX', '+0.125·YYYX', '+0.125·YXYY']
Ansatz parameters CNOTs depth
UCC-D 1 44 83
Compact 1 3 7
Hardware-efficient 12 6 19
Compact ansatz:
┌─────────┐
q_0: ┤ Ry(2*φ) ├──■────■────■──
└──┬───┬──┘ │ ┌─┴─┐ │
q_1: ───┤ X ├─────┼──┤ X ├──┼──
└───┘ ┌─┴─┐└───┘ │
q_2: ───────────┤ X ├───────┼──
┌───┐ └───┘ ┌─┴─┐
q_3: ───┤ X ├─────────────┤ X ├
└───┘ └───┘
Hardware-efficient ansatz:
┌───┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
q_0: ───┤ X ├────┤ Ry(θ[0]) ├──■──┤ Ry(θ[4]) ├─────────────────■──────┤ Ry(θ[8]) ├─────────────────────────
┌──┴───┴───┐└──────────┘┌─┴─┐└──────────┘┌──────────┐ ┌─┴─┐ └──────────┘┌──────────┐
q_1: ┤ Ry(θ[1]) ├────────────┤ X ├─────■──────┤ Ry(θ[5]) ├───┤ X ├─────────■──────┤ Ry(θ[9]) ├─────────────
└──┬───┬───┘┌──────────┐└───┘ ┌─┴─┐ └──────────┘┌──┴───┴───┐ ┌─┴─┐ └──────────┘┌───────────┐
q_2: ───┤ X ├────┤ Ry(θ[2]) ├────────┤ X ├─────────■──────┤ Ry(θ[6]) ├───┤ X ├─────────■──────┤ Ry(θ[10]) ├
┌──┴───┴───┐└──────────┘ └───┘ ┌─┴─┐ ├──────────┤ └───┘ ┌─┴─┐ ├───────────┤
q_3: ┤ Ry(θ[3]) ├────────────────────────────────┤ X ├────┤ Ry(θ[7]) ├───────────────┤ X ├────┤ Ry(θ[11]) ├
└──────────┘ └───┘ └──────────┘ └───┘ └───────────┘
Interpretation¶
The compact circuit is short because it uses knowledge of this specific molecule — R3 told us that only two configurations matter. That knowledge is not available for a molecule one does not yet understand, so a real application for a larger molecule must choose between a systematic ansatz like UCC-D, which is reliable but expensive, and a problem-specific ansatz, which is cheap but requires insight that may not exist. Much current work — adaptive ansätze such as ADAPT-VQE, symmetry-preserving circuits — tries to obtain the reliability of the systematic ansatz at the cost of the problem-specific one.
R5 · Explicit VQE optimisation loop¶
R5 runs the full VQE algorithm for all three ansätze: the quantum side prepares a trial state and measures its energy with StatevectorEstimator; the classical side passes the result to SciPy's function minimize, which chooses the next parameters.
The two optimisers are chosen for the corresponding circuits. UCC-D and Compact have a single parameter, so they use COBYLA optimizer, a derivative-free method that needs no gradient and works well on a one-dimensional landscape. Hardware-efficient has 12 parameters and uses L-BFGS-B optimizer, which does use gradients: without gradients, the optimiser would have to search a 12-dimensional space blindly.
That difference has a direct cost. L-BFGS-B estimates the gradient by finite differences, so each optimiser step requires one circuit evaluation per parameter plus one for the energy — 13 for the 12-parameter circuit. Each evaluation is a full run of the circuit, and on hardware each run costs its full shot budget. The number of evaluations therefore multiplies directly into the total number of shots, which is why the evaluation counts reported below matter as much as the energies themselves.
The code:
- defines
run_vqe, which records every circuit evaluation and then callsscipy.optimize.minimize; - runs UCC-D and Compact with COBYLA (gradient-free), and Hardware-efficient with L-BFGS-B (finite-difference gradients);
- prints final energies, errors against FCI, evaluation counts and times, and plots convergence on a log scale.
Note on hardware execution. This run uses a local simulator, where sessions are neither needed nor supported. If the same loop were run on IBM hardware, each estimator call would be queued separately, and the queue time between iterations would make the optimisation impractically slow. A session avoids this by reserving the QPU for the whole loop, so the iterative calls run in one dedicated window without re-queuing.
# ── R5 · VQE: let a classical optimiser drive the quantum circuit ─────────────
estimator = StatevectorEstimator()
def run_vqe(circuit, hamiltonian, x0, method="COBYLA", options=None):
history = [] # energy at every circuit evaluation
def cost(x):
e = estimator.run([(circuit, hamiltonian, x)]).result()[0].data.evs
history.append(e)
return e
t0 = time.perf_counter()
res = minimize(cost, x0, method=method, options=options or {})
return {"E": res.fun, "x": res.x, "nfev": len(history), "history": np.array(history),
"seconds": time.perf_counter() - t0}
rng = np.random.default_rng(seed=42)
runs = {
"UCC-D": run_vqe(ucc, H, [0.0], "COBYLA", {"rhobeg": 0.2, "tol": 1e-10}),
"Compact": run_vqe(compact, H, [0.5], "COBYLA", {"rhobeg": 0.2, "tol": 1e-10}),
"Hardware-efficient": run_vqe(hea, H, rng.uniform(-0.1, 0.1, hea.num_parameters), "L-BFGS-B"),
}
def evals_to(r, tol):
"""Number of evaluations until the best energy so far is within tol (Ha) of FCI."""
best = np.minimum.accumulate(r["history"]) - E_FCI # using the running minimum
return int(np.argmax(best < tol)) + 1
print(f"{'Ansatz':<20}{'E_VQE (Ha)':>14}{'error (mHa)':>13}{'evaluations':>13}{'to 1.6 mHa':>12}{'time (s)':>10}{'ms/eval':>9}")
for name, r in runs.items():
print(f"{name:<20}{r['E']:>14.8f}{(r['E']-E_FCI)*1e3:>13.2e}{r['nfev']:>13}"
f"{evals_to(r, CHEM_ACC):>12}{r['seconds']:>10.2f}{r['seconds']/r['nfev']*1e3:>9.2f}")
theta_star = runs["UCC-D"]["x"][0]
print(f"\nOptimal UCC angle θ* = {theta_star:+.4f} rad")
# Where the 20.3 mHa comes from: coupling gain (linear in the amplitude) vs excitation penalty (its square)
print(f"Amplitudes: HF {np.cos(theta_star):+.5f}, doubly excited {np.sin(theta_star):+.5f}")
print(f"Ground state: |ψ0⟩ = {np.cos(theta_star):+.5f}·|0101⟩ {np.sin(theta_star):+.5f}·|1010⟩")
composition = Statevector(ucc.assign_parameters([theta_star])).probabilities_dict()
fig, ax = plt.subplots(figsize=(8, 3.6))
styles = {"UCC-D": (COL["VQE"], "-"), "Compact": (COL["Compact"], "--"), "Hardware-efficient": (COL["HEA"], "-.")}
for name, r in runs.items():
err = np.maximum(r["history"] - E_FCI, 1e-12) # floor for the log scale
ax.semilogy(np.arange(1, len(err)+1), err * 1e3, color=styles[name][0], ls=styles[name][1], label=name)
ax.axhline(CHEM_ACC*1e3, color=COL["muted"], ls="--", lw=1.2)
ax.text(ax.get_xlim()[1], CHEM_ACC*1e3*1.6, "chemical accuracy (1.6 mHa)", color="#52514e", fontsize=9, ha="right")
ax.set_xlabel("circuit evaluations"); ax.set_ylabel("E − E_FCI (mHa, log)")
ax.set_title("VQE convergence", loc="left"); ax.legend(loc="lower center", bbox_to_anchor=(0.45, 0.05)); plt.tight_layout(); plt.show()
Ansatz E_VQE (Ha) error (mHa) evaluations to 1.6 mHa time (s) ms/eval UCC-D -1.13730604 -1.11e-12 44 5 0.34 7.78 Compact -1.13730604 -6.66e-13 47 8 0.15 3.10 Hardware-efficient -1.13730604 8.07e-08 533 352 1.13 2.13 Optimal UCC angle θ* = -0.1118 rad Amplitudes: HF +0.99376, doubly excited -0.11154 Ground state: |ψ0⟩ = +0.99376·|0101⟩ -0.11154·|1010⟩
Interpretation¶
- VQE is exact when three conditions hold: the ansatz can represent the ground state (R4), the optimiser converges, and energies are measured without error (here, an ideal simulator). All three hold in this run, so all three circuits reproduce FCI — UCC-D and Compact in about 50 evaluations, Hardware-efficient in 533.
- Parameter count determines run time. The 12-parameter circuit needed 11 times more evaluations to full convergence — and about 50–80 times more to reach chemical accuracy. The convergence plot shows why: long plateaus where the optimiser moves through flat regions, typical of circuits that do not encode the physics. On quantum hardware each evaluation costs thousands to millions of shots (R7), so 533 evaluations against about 50 is the difference that becomes significant.
- The evaluation count also depends on the optimiser. L-BFGS-B costs d+1 evaluations per iteration, because it estimates the gradient by finite differences. Other methods have a different balance between cost and performance. Gradient-free methods are cheapest per step — COBYLA needs one evaluation per iteration — but their cost appears in the number of iterations, which grows quickly with parameter count. Parameter-shift gives an exact gradient at a cost of two evaluations per parameter. SPSA estimates the gradient from only two evaluations per iteration, regardless of parameter count, at the price of a noisier gradient and potentially lower final accuracy. Quantum natural gradient uses the quantum Fisher information to reduce the number of iterations, at the cost of extra evaluations to measure the metric tensor.
- COBYLA's spikes are normal. A derivative-free method probes points around its current best, so some of them will temporarily give worse results, which is why the curve shows spikes.
Conclusion. With perfect measurements, VQE recovers the exact energy with any of the three circuits. Problem-specific circuits converge about 10 times faster than generic ones.
R6 · VQE with the qiskit-algorithms VQE class¶
R6 repeats the calculation of R5, but uses the packaged VQE class instead of the explicit VQE loop. The class belongs to the qiskit-algorithms package. It takes the estimator, the ansatz and the optimiser and runs the loop internally.
To make the comparison like for like, the code uses the same estimator (StatevectorEstimator), the same starting points, and the same optimisers as in R5: COBYLA for UCC-D and Compact, L-BFGS-B for Hardware-efficient.
The code will:
- record the energy at every circuit evaluation through the class's
callbackhook; - print energies, errors against FCI, evaluation counts and times in the layout of R5;
- plot the convergence of the
VQEclass (solid) over the explicit VQE loop.
# ── R6 · The same three VQE runs with the qiskit-algorithms VQE class ──────────
from qiskit_algorithms import VQE
from qiskit_algorithms.optimizers import COBYLA, L_BFGS_B
# Same starting points and optimiser settings as R5, so the comparison is like for like
rng_R6 = np.random.default_rng(seed=42)
x0_R6 = {"UCC-D": [0.0], "Compact": [0.5],
"Hardware-efficient": rng_R6.uniform(-0.1, 0.1, hea.num_parameters)}
runs_class = {}
for name, circ in ANSATZE.items():
history = [] # energy at every circuit evaluation
def record(eval_count, params, value, metadata, history=history):
history.append(float(value)) # VQE calls this after every energy evaluation
opt = L_BFGS_B() if name == "Hardware-efficient" else COBYLA(maxiter=1000, rhobeg=0.2, tol=1e-10)
vqe = VQE(estimator=estimator, ansatz=circ, optimizer=opt, initial_point=np.array(x0_R6[name]), callback=record)
t0 = time.perf_counter()
res = vqe.compute_minimum_eigenvalue(H)
runs_class[name] = {"E": float(res.eigenvalue), "x": res.optimal_point, "nfev": len(history),
"history": np.array(history), "seconds": time.perf_counter() - t0}
# Cost table in the layout of R5, with the R5 evaluation counts alongside
print(f"{'Ansatz':<20}{'E_VQE (Ha)':>14}{'error (mHa)':>13}{'evaluations':>13}{'to 1.6 mHa':>12}{'time (s)':>10}{'ms/eval':>9}")
for name, r in runs.items():
print(f"{name:<20}{r['E']:>14.8f}{(r['E']-E_FCI)*1e3:>13.2e}{r['nfev']:>13}"
f"{evals_to(r, CHEM_ACC):>12}{r['seconds']:>10.2f}{r['seconds']/r['nfev']*1e3:>9.2f}")
print("\n|E_class − E_R5| (Ha):", {n: f"{abs(runs_class[n]['E'] - runs[n]['E']):.1e}" for n in runs})
print("|θ_class − θ_R5| (rad):", {n: f"{np.abs(runs_class[n]['x'] - runs[n]['x']).max():.1e}" for n in ("UCC-D", "Compact")})
# Convergence plot: VQE class (solid) over the R5 loop (faint)
fig, ax = plt.subplots(figsize=(8, 3.6))
for name, r in runs_class.items():
col, ls = styles[name]
for rr, alpha, lab in ((runs[name], 0.35, f"{name} (explicit VQE loop)"), (r, 1.0, f"{name} (VQE class)")):
err = np.maximum(rr["history"] - E_FCI, 1e-12) # floor for the log scale
ax.semilogy(np.arange(1, len(err)+1), err * 1e3, color=col, ls=ls, alpha=alpha, label=lab)
ax.axhline(CHEM_ACC*1e3, color=COL["muted"], ls="--", lw=1.2)
ax.set_xlabel("circuit evaluations"); ax.set_ylabel("E − E_FCI (mHa, log)")
ax.set_title("VQE class vs explicit loop", loc="left"); ax.legend(fontsize=8, ncol=2); plt.tight_layout(); plt.show()
/Users/lzrvc/Documents/Quantum Computing/IBM Quantum/Quantum Hands-on Lab Workgroup/red-04-chemistry/code/.venv/lib/python3.12/site-packages/qiskit_algorithms/optimizers/scipy_optimizer.py:162: OptimizeWarning: Unknown solver options: iprint raw_result = minimize(
Ansatz E_VQE (Ha) error (mHa) evaluations to 1.6 mHa time (s) ms/eval
UCC-D -1.13730604 -1.11e-12 44 5 0.34 7.78
Compact -1.13730604 -6.66e-13 47 8 0.15 3.10
Hardware-efficient -1.13730604 8.07e-08 533 352 1.13 2.13
|E_class − E_R5| (Ha): {'UCC-D': '0.0e+00', 'Compact': '0.0e+00', 'Hardware-efficient': '0.0e+00'}
|θ_class − θ_R5| (rad): {'UCC-D': '0.0e+00', 'Compact': '0.0e+00'}
Interpretation¶
- The two implementations give the same result, and the energies, optimal angles and evaluation counts are identical (52, 52 and 533 evaluations). On the plot the faint R5 curves lie under the solid
VQE-class curves and cannot be told apart. - The total times of two implementations differ by at most 4 %, in both directions. The wrapper overhead is therefore negligible for the cost of the circuit evaluations. This is expected, because the class implements the same algorithm as R5. It builds the same cost function (one
StatevectorEstimatorcall per evaluation) and hands it to the same SciPy optimisers (COBYLA,L-BFGS-B). The simulator is deterministic and the starting points are the same, so the optimiser follows the same trajectory. - Using the
VQEclass saves writing the loop and providesoptimal_point,cost_function_evalsand acallbackhook. The explicit version gains nothing in accuracy or speed; what it gains is visibility into the tolerances, gradients and bookkeeping.
Conclusion. The packaged
VQEclass reproduces the explicit loop of R5 exactly. The choice between them is one of convenience and transparency, not of results.
R7 · Adapt-VQE¶
Standard VQE uses a fixed ansatz where the circuit structure is chosen before anything is known about how the optimiser will behave. That choice has some consequences, one of which appeared in R5:
- if the ansatz is too large, it has redundant parameters, a flat landscape that doesn't converge quickly, and many gates;
- if the ansatz is too small, it cannot reach the ground state.
ADAPT-VQE is the method that removes this choice by growing the ansatz iteratively, adding one operator at a time, and adding only operators that actually lower the energy.
The core idea¶
Instead of "here is the ansatz, optimise it", ADAPT-VQE asks at each step which operator, added to the current circuit, would lower the energy the most?
It answers by measuring a gradient for every candidate operator, selects the largest, adds that operator to the circuit, re-optimises all parameters, and repeats.
The algorithm¶
1. Define an operator pool. A set of candidate operators, typically fermionic excitations (singles and doubles) or qubit Pauli strings:
$$ \mathcal{P} = \{G_1, G_2, \ldots, G_m\} $$
2. Start from a reference state, usually HF: $|\psi^{(0)}\rangle = |0101\rangle$.
3. Measure the gradient for every pool operator in the current state. For operator $G_i$, the gradient is
$$ g_i = \left.\frac{\partial E}{\partial \theta_i}\right|_{\theta_i = 0} = \langle \psi^{(k)} | i[G_i, \hat H] | \psi^{(k)} \rangle . $$
This is a commutator, which tells how strongly the operator $G_i$ is coupled to the Hamiltonian in the current state — i.e. whether turning $G_i$ on would move the state to a lower energy. This commutator can be measured on the quantum computer without running the optimiser: one measurement per operator.
4. Select the operator with the largest gradient, $G^\star = \arg\max_i |g_i|$.
5. Add it to the ansatz and re-optimise all parameters:
$$ |\psi^{(k+1)}\rangle = e^{\theta_{k+1} G^\star} |\psi^{(k)}\rangle . $$
6. Repeat until the gradient norm falls below a threshold, $\|g\| = \sqrt{\sum_i g_i^2} < \epsilon$. At that point no operator in the pool can lower the energy further.
The operator pool¶
The operator pool is the set of candidate excitations the algorithm may choose from. For H₂ there are only three spin-conserving excitations out of the HF reference — the two single excitations and the double excitation — so the pool contains all of them:
| Operator | What it does |
|---|---|
| S α0→α1 | moves the α electron from $\sigma_g$ to $\sigma_u^*$ |
| S β0→β1 | moves the β electron from $\sigma_g$ to $\sigma_u^*$ |
| D αβ 00→11 | moves both electrons from $\sigma_g$ to $\sigma_u^*$ |
For a larger molecule the pool would contain many more operators — for example over 15'000 for water molecule in a standard pool.
What the code does¶
- Builds the three operators as $G = i(T - T^\dagger)$, where $T$ is the fermionic excitation, so that $e^{-i\theta G}$ is a unitary excitation.
- Defines the gradient observable for each $i[G, \hat H]$, which is Hermitian and can be measured directly.
- Validates the gradient formula by comparing the expectation value of $i[G_i, \hat H]$ with a central finite difference at the HF state. Finite difference is used as the simplest way to get a derivative: evaluate the function nearby and take the slope.
- Runs the ADAPT loop, measuring all three gradients each iteration and adding the largest until the norm falls below $10^{-4}$.
- Compares the result with UCC-D and Compact from R5.
# ── R7 · ADAPT-VQE: grow the ansatz one operator at a time ────────────────────
from qiskit.circuit import ParameterVector
# ── Operator pool: all spin-conserving single and double excitations out of HF ──
# G = i(T − T†) is Hermitian, so exp(−iθG) = exp(θ(T − T†)) is a unitary excitation (same form as the UCC-D generator in R4)
def excitation_generator(T):
return (1j * (T - T.adjoint())).simplify()
POOL = {
"S α0→α1": excitation_generator(ad[spin_orbital(1, 0)].dot(a[spin_orbital(0, 0)])),
"S β0→β1": excitation_generator(ad[spin_orbital(1, 1)].dot(a[spin_orbital(0, 1)])),
"D αβ 00→11": G, # the R4 double-excitation generator
}
def adapt_circuit(selected):
"""HF reference followed by exp(−iθ_k G_k) for each selected pool operator, in selection order."""
params = ParameterVector("θ", len(selected))
qc = hf_circuit()
for p, name in zip(params, selected):
qc.append(PauliEvolutionGate(POOL[name], time=p), range(N_QUBITS))
return qc
# Gradient operator: dE/dθ at θ = 0 for U = exp(−iθG) is ⟨ψ| i[G, H] |ψ⟩ (a Hermitian observable, one measurement per operator)
GRAD_OPS = {name: (1j * (Gk.dot(H) - H.dot(Gk))).simplify() for name, Gk in POOL.items()}
# Check: the commutator expectation must equal a central finite-difference derivative of the energy
chk = adapt_circuit(["D αβ 00→11"])
d = 1e-5
E_pm = [estimator.run([(chk, H, [s * d])]).result()[0].data.evs for s in (+1, -1)]
g_exact = estimator.run([(hf_circuit(), GRAD_OPS["D αβ 00→11"])]).result()[0].data.evs
print(f"Gradient check at HF: commutator {float(g_exact): .8f} vs finite difference {(E_pm[0]-E_pm[1])/(2*d): .8f}\n")
# ── ADAPT-VQE loop ────────────────────────────────────────────────────────────
GRAD_TOL, MAX_ITER = 1e-4, 6 # stop when ‖g‖ < ε (cap on iterations as a safeguard). GRAD_TOL is convergence threshold
def run_adapt(hamiltonian, pool_ops, grad_tol=GRAD_TOL, max_iter=MAX_ITER):
selected = []
x = np.array([])
history = [float(estimator.run([(hf_circuit(), hamiltonian)]).result()[0].data.evs)] # energy of the reference
log, n_grad = [], 0
t0 = time.perf_counter()
for it in range(1, max_iter + 1):
# (3) gradient of every pool operator at the current state — one measurement each
circ = adapt_circuit(selected)
grads = {}
for name, op in GRAD_OPS.items():
grads[name] = float(np.real(estimator.run([(circ, op, x)]).result()[0].data.evs))
n_grad += len(grads)
norm = np.sqrt(sum(v**2 for v in grads.values()))
log.append({"iter": it, "grads": grads, "norm": norm, "energy": history[-1], "added": None})
if norm < grad_tol: # (6) converged: no operator can lower the energy
break
best = max(grads, key=lambda n: abs(grads[n])) # (4) largest |gradient|
selected.append(best); log[-1]["added"] = best
# (5) add it and re-optimise ALL parameters, starting from the previous optimum (new angle = 0)
circ = adapt_circuit(selected)
r = run_vqe(circ, hamiltonian, np.append(x, 0.0), "COBYLA", {"rhobeg": 0.2, "tol": 1e-10})
x = r["x"]; history.extend(r["history"])
log[-1]["energy_after"] = r["E"]
final = adapt_circuit(selected)
return {"E": float(np.min(history)), "x": x, "nfev": len(history), "n_grad": n_grad, "history": np.array(history),
"seconds": time.perf_counter() - t0, "selected": selected, "log": log, "circuit": final}
adapt = run_adapt(H, POOL)
# ── Gradient table per iteration ─────────────────────────────────────────────
print(f"{'iter':<6}" + "".join(f"{n:>14}" for n in POOL) + f"{'‖g‖':>12}{'added':>14}")
for row in adapt["log"]:
print(f"{row['iter']:<6}" + "".join(f"{row['grads'][n]:>14.6f}" for n in POOL)
+ f"{row['norm']:>12.2e}{(row['added'] or '— (converged)'):>14}")
# ── Cost table in the layout of R5: ADAPT-VQE against the fixed ansätze ──────
print(f"\n{'Ansatz':<20}{'E_VQE (Ha)':>14}{'error (mHa)':>13}{'evaluations':>13}{'to 1.6 mHa':>12}{'time (s)':>10}{'ms/eval':>9}")
for name, r in (("UCC-D (R5)", runs["UCC-D"]), ("Compact (R5)", runs["Compact"]), ("ADAPT-VQE", adapt)):
print(f"{name:<20}{r['E']:>14.8f}{(r['E']-E_FCI)*1e3:>13.2e}{r['nfev']:>13}"
f"{evals_to(r, CHEM_ACC):>12}{r['seconds']:>10.2f}{r['seconds']/r['nfev']*1e3:>9.2f}")
tq = transpile(adapt["circuit"], basis_gates=BASIS_GATES, optimization_level=3, seed_transpiler=7)
print(f"\nADAPT-VQE: {len(adapt['selected'])} operator(s) {adapt['selected']}, {adapt['circuit'].num_parameters} parameter(s), "
f"{tq.count_ops().get('cx', 0)} CNOTs after transpilation")
print(f"Extra cost of the search: {adapt['n_grad']} gradient measurements in addition to {adapt['nfev']} energy evaluations")
print(f"|E_ADAPT − E_UCC-D (R5)| = {abs(adapt['E'] - runs['UCC-D']['E']):.1e} Ha")
# ── Convergence plot: ADAPT-VQE against the R5 fixed ansätze ──────────────────
fig, ax = plt.subplots(figsize=(8, 3.6))
for name in ("UCC-D", "Compact"):
err = np.maximum(runs[name]["history"] - E_FCI, 1e-12)
ax.semilogy(np.arange(1, len(err)+1), err * 1e3, color=styles[name][0], ls=styles[name][1], alpha=0.35, label=f"{name} (R5)")
err = np.maximum(adapt["history"] - E_FCI, 1e-12)
ax.semilogy(np.arange(1, len(err)+1), err * 1e3, color="#d4a017", label="ADAPT-VQE")
ax.axhline(CHEM_ACC*1e3, color=COL["muted"], ls="--", lw=1.2)
ax.text(ax.get_xlim()[1], CHEM_ACC*1e3*1.6, "chemical accuracy (1.6 mHa)", color="#52514e", fontsize=9, ha="right")
ax.set_xlabel("circuit evaluations (energy only; gradient measurements not shown)"); ax.set_ylabel("E − E_FCI (mHa, log)")
ax.set_title("ADAPT-VQE vs fixed ansätze", loc="left"); ax.legend(loc="upper right"); plt.tight_layout(); plt.show()
Gradient check at HF: commutator 0.36186240 vs finite difference 0.36186240 iter S α0→α1 S β0→β1 D αβ 00→11 ‖g‖ added 1 0.000000 0.000000 0.361862 3.62e-01 D αβ 00→11 2 0.000000 0.000000 -0.000000 2.83e-09 — (converged) Ansatz E_VQE (Ha) error (mHa) evaluations to 1.6 mHa time (s) ms/eval UCC-D (R5) -1.13730604 -1.11e-12 44 5 0.34 7.78 Compact (R5) -1.13730604 -6.66e-13 47 8 0.15 3.10 ADAPT-VQE -1.13730604 -4.44e-13 43 6 0.24 5.68 ADAPT-VQE: 1 operator(s) ['D αβ 00→11'], 1 parameter(s), 44 CNOTs after transpilation Extra cost of the search: 6 gradient measurements in addition to 43 energy evaluations |E_ADAPT − E_UCC-D (R5)| = 6.7e-16 Ha
Interpretation¶
- The gradient formula is validated before it is used. The commutator $\langle i[G_i, \hat H]\rangle$ and the finite-difference derivative agree to eight decimal places at the HF state, so the gradients measured in the loop can be trusted. Only double-excitation operator is used for the gradient check, since it is the only operator with a nonzero gradient.
- Adapt-VQE reaches the same state as UCC-D and Compact. The energy matches UCC-D to $10^{-15}$ Ha.
- But it inherits UCC-D's implementation, not the compact circuit's. The selected double-excitation operator is implemented as a
PauliEvolutionGatewith eight Pauli strings, where each Pauli string requires six CNOTs plus one rotation, and the transpilation reduces the total to 44 CNOTs. - The search costs extra measurements. Six gradient measurements (3 operators × 2 iterations) were needed in addition to the 44 energy evaluations. That is small here because the pool has only three operators; for a larger molecule the pool grows and so does the gradient cost.
Outlook for larger molecules. The advantage of Adapt-VQE appears for larger molecules and larger pools. For H₂ the pool has three operators, but for a larger molecule the pool grows rapidly: a standard QEB pool (qubit-excitation-based, not fermionic) for water contains over 15'000 candidate operators. There ADAPT-VQE adds only the operators that lower the energy, producing a far smaller ansatz and CNOT count than a fixed UCCSD circuit, with the ability in reported cases to escape the zero-gradient traps that can stall a fixed UCCSD ansatz entirely. The price is gradient measurements that scale with the pool size; for H₂ that is six measurements, for water it is hundreds per iteration, which is why pool reduction is an active area of research.
Conclusion. ADAPT-VQE finds the right operator automatically, reaching the same energy as UCC-D and the same one-parameter structure as the compact circuit — but it implements that operator with the general machinery, so it pays 44 CNOTs rather than 3. The advantage in this case is that it removed the operator selection step, so we didn't have to know in advance that only the double excitation matters.
Sample-based quantum diagonalization (SQD)¶
Introduction to SQD¶
The previous runs used variational methods: VQE with a fixed ansatz, then ADAPT-VQE with an ansatz developed iteratively. But both these approaches share a limitation that becomes significant with larger molecules.
VQE requires a parameterised circuit and an optimiser loop. On real hardware, the noise in each energy evaluation accumulates through the optimisation, and for larger systems the landscape flattens — gradients vanish exponentially, a problem known as barren plateaus. The circuit must also be deep enough to be expressive, which on noisy devices means more errors per evaluation.
ADAPT-VQE reduces the circuit depth by growing the ansatz one operator at a time, and it avoids barren plateaus because each new operator starts with a nonzero gradient. But at every iteration it must measure the gradient for every operator in the pool. For a large molecule the pool contains thousands of candidates, so the search cost becomes substantial.
The Sample-based Quantum Diagonalization (SQD) method uses the quantum computer only to sample configurations, and the energy is obtained by diagonalising the Hamiltonian classically in the sampled subspace. This removes the optimiser loop, avoids barren plateaus, and is more tolerant of hardware noise, because corrupted samples are corrected rather than propagated through a variational search.
The workflow:
First, we analyse the molecule classically. Run Hartree–Fock and then Coupled Cluster Singles and Doubles (CCSD) method on the specific molecule to obtain the $t_1$ and $t_2$ amplitudes. This is a classical preprocessing step that allows us to initialize the quantum circuit.
Build the sampling circuit. Construct a Local Unitary Cluster Jastrow (LUCJ) ansatz from those amplitudes via double factorization technique. The double factorization takes CCSD $t_2$ amplitudes that describe which electron pairs are excited, and factors them into two types of tensors: orbital rotations ($U$ term) and density–density interactions ($J$ - or Jastrow term). Interaction pairs restrict which density–density interactions are included, which makes the density–density tensor local.
The number of terms is a user-chosen parameter $L$: the full factorization of the CCSD amplitudes would need many layers for a general system, but in practice we truncate this to the smallest number needed to reach chemical accuracy, trading some accuracy for a shallower circuit. The number of layers is also determined by how restricted the qubit connectivity is (for all-to-all or square qubit connectivity one would set $L\geq2$, and the heavy-hex would require $L\geq4$).
The LUCJ circuit therefore consists of the HF reference state, prepared once, followed by $L$ layers that are added because one layer may not capture all the correlation.
The LUCJ ansatz is therefore molecule-specific: it encodes what the classical calculation found about this molecule, which is why its samples are concentrated near the ground state rather than spread over the whole Hilbert space.
Sample. Run the circuit only once and measure it for a fixed number of shots, collecting bitstrings. Each bitstring is a Slater determinant (antisymmetrized electron configuration). The subspace is built from the distinct configurations among them.
Recover. Noise corrupts some bitstrings, giving the wrong electron number or spin. Using the average orbital occupancies from the previous diagonalisation, the routine probabilistically flips bits until each bitstring has the correct electron number and spin. This step is entirely classical.
Project and diagonalise. The recovered configurations define a subspace. The Hamiltonian is projected into this subspace and diagonalised classically, so the lowest eigenvalue will be an upper bound ($\geq E_0$) on the ground-state energy.
Repeat. The occupancies of the diagonalised ground state guide the next recovery: configurations in which an orbital is almost always occupied (or almost always empty) are treated as more reliable, and the probabilistic bit-flips are weighted toward those average occupancies. The loop stops when the energy and the recovered subspace stop changing.
This method is robust to noise because corrupted samples are corrected rather than discarded, but its cost is dominated by the number of shots and by the size of the classical diagonalisation, which is the limiting factor for larger molecules.
For H₂, only two configurations appear in the samples, and the recovered subspace is small enough that SQD converges in two iterations — the diagonalisation reduces to the 2×2 problem of R3.
The code:
- reuses the HF orbitals and the integrals from R1–R2, which are already available;
- runs CCSD to obtain the $t_1$ and $t_2$ amplitudes, then applies double factorization to build the LUCJ parameters;
- sets the number of layers to 1 — one orbital rotation and one Jastrow term — because there is only one double excitation;
- checks, as a diagnostic, that the CCSD energy is close to FCI before sampling;
- samples bitstrings from the circuit built from the LUCJ parameters and and identifies the distinct configurations among them;
- recovers configurations with the correct electron number and spin;
- projects the Hamiltonian onto the recovered subspace and diagonalises it;
- compares the energy with $E_\text{FCI}$.
# ── R8 · Sample-based quantum diagonalization (SQD) ───────────────────────────
import math
from functools import partial
import pyscf.cc
import ffsim
from qiskit.primitives import BitArray, StatevectorSampler
from qiskit.circuit import QuantumRegister
from qiskit_addon_sqd.fermion import SCIResult, diagonalize_fermionic_hamiltonian, solve_sci_batch
# ── (1) Classical pre-processing: CCSD amplitudes from the HF reference of R1 ──
# Qubit layout of ffsim: [q0 q1 | q2 q3] = [α0 α1 | β0 β1], the same block ordering as R3
norb, nelec = n_orb, (1, 1) # 2 spatial orbitals, one α and one β electron
ccsd = pyscf.cc.CCSD(ref["mf"]).run() # builds the solver and solves the coupled-cluster equations to populate e_tot, t_1, t_2
t1, t2 = ccsd.t1, ccsd.t2 # t1: (occ, virt) t2: (occ, occ, virt, virt)
print("Checking that the CCSD energy is close to FCI before sampling")
print(f"CCSD energy: {ccsd.e_tot: .10f} Ha (FCI {E_FCI: .10f}, error {(ccsd.e_tot-E_FCI)*1e3:.2e} mHa)")
print(f"\nt1 amplitude: {t1[0,0]: .6f} t2 amplitude: {t2[0,0,0,0]: .6f}")
# ── (2) LUCJ circuit from the CCSD amplitudes (double factorisation of t2) ────
N_REPS = 1 # set to one layer
# Interaction pairs restrict only the density–density (diagonal Coulomb) part, exp(i/2 Σ J_pq n_p n_q): J_pq may be nonzero only for listed pairs.
# They do not restrict the orbital rotations, which come unrestricted from the double factorisation of t2.
# Fewer pairs -> fewer two-qubit gates, so the lists are chosen to match the hardware connectivity (the "local" in LUCJ).
pairs_aa = [(p, p + 1) for p in range(norb - 1)] # same-spin (α–α and β–β) interactions between neighbouring orbitals: a line
pairs_ab = [(p, p) for p in range(norb)] # opposite-spin (α–β) interactions between the same spatial orbital only
ucj_op = ffsim.UCJOpSpinBalanced.from_t_amplitudes(
t2=t2, t1=t1, n_reps=N_REPS, interaction_pairs=(pairs_aa, pairs_ab), optimize=True) # this build the LUCJ mathematical operator
qubits = QuantumRegister(2 * norb, name="q")
lucj = QuantumCircuit(qubits)
lucj.append(ffsim.qiskit.PrepareHartreeFockJW(norb, nelec), qubits) # this builds the HF reference state |0101> in the Jordan-Wigner encoding and appends it to the circuit
lucj.append(ffsim.qiskit.UCJOpSpinBalancedJW(ucj_op), qubits) # this builds the gate from the LUCJ operator in the Jordan-Wigner encoding and appends it to the circuit
lucj_isa = transpile(lucj, basis_gates=BASIS_GATES, optimization_level=3, seed_transpiler=42)
lucj_isa.measure_all()
print(f"\nLUCJ circuit after transpilation: {lucj_isa.count_ops().get('cx', 0)} CNOTs, depth {lucj_isa.depth()}")
# ── (3) Sample the circuit ────────────────────────────────────────────────────
SHOTS = 10_000
counts = StatevectorSampler(seed=42).run([lucj_isa], shots=SHOTS).result()[0].data.meas.get_counts()
def is_valid(bitstring):
"""Valid = one α and one β electron. Bit-string is q3 q2 q1 q0: β block on the left, α block on the right."""
return bitstring[norb:].count("1") == nelec[0] and bitstring[:norb].count("1") == nelec[1]
# -- Computing how many of the sampled bitstrings are physically valid — extracting the distinct configurations as valid samples.
random_valid = math.comb(norb, nelec[0]) * math.comb(norb, nelec[1]) / 2 ** (2 * norb)
frac = sum(v for b, v in counts.items() if is_valid(b)) / SHOTS
print(f"Distinct bitstrings (= configurations) after generating {SHOTS} Samples: {len(counts)} - {dict(counts)}")
print(f"Valid fraction {frac:.3f} (uniform random bit-strings: {random_valid:.3f})")
# ── (4–6) Configuration recovery, projection and diagonalisation ──────────────
history = [] # will be filled by the callback
def callback(results: list[SCIResult]): # called in each iteration of the Main SQD loop
history.append(min(r.energy for r in results) + ref["E_nuc"]) # energy of every recovery iteration
hf_occ = (np.array([1] * nelec[0] + [0] * (norb - nelec[0])), np.array([1] * nelec[1] + [0] * (norb - nelec[1]))) # uses HF for the initial occupancy
t0 = time.perf_counter() # records the start time so the SQD run can be timed.
# ── Main SQD loop: recovery, projection and diagonalisation
result = diagonalize_fermionic_hamiltonian(
h1, g, BitArray.from_counts(counts, num_bits=N_QUBITS), # SQD expects the samples as a BitArray
samples_per_batch=SHOTS, norb=norb, nelec=nelec, num_batches=1,
energy_tol=1e-8, occupancies_tol=1e-8, max_iterations=5, initial_occupancies=hf_occ,
sci_solver=partial(solve_sci_batch, spin_sq=0.0), symmetrize_spin=True, callback=callback, seed=42)
sqd = {"E": result.energy + ref["E_nuc"], "history": np.array(history), "nfev": len(history),
"dim": int(np.prod(result.sci_state.amplitudes.shape)), "seconds": time.perf_counter() - t0}
print(f"\n{'Method':<10}{'E_SQD (Ha)':>14}{'error (mHa)':>13}{'iterations':>12}{'subspace dim':>14}{'time (s)':>10}")
print(f"{'SQD':<10}{sqd['E']:>14.8f}{(sqd['E']-E_FCI)*1e3:>13.2e}{sqd['nfev']:>12}{sqd['dim']:>14}{sqd['seconds']:>10.2f}")
print(f"\nVariational bound E_SQD ≥ E_FCI holds: {sqd['E'] >= E_FCI - 1e-9}")
occ = np.sum(result.orbital_occupancies, axis=0)
print(f"Orbital occupancies (α+β) of the SQD ground state: σg {occ[0]:.4f}, σu* {occ[1]:.4f}")
# ── Plot: distribution of sampled configurations and the SQD energy error ─────
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3.6))
labels = [format(k, f"0{N_QUBITS}b") for k in range(2 ** N_QUBITS)]
ax1.bar(range(len(labels)), [counts.get(b, 0) / SHOTS for b in labels], color=COL["VQE"])
ax1.set_xticks(range(len(labels))); ax1.set_xticklabels(labels, rotation=90, fontsize=8)
ax1.set_xlabel("sampled bit-string q3 q2 q1 q0"); ax1.set_ylabel("probability")
ax1.set_title("LUCJ samples", loc="left")
err = np.maximum(sqd["history"] - E_FCI, 1e-12) # floor for the log scale
ax2.semilogy(np.arange(1, len(err)+1), err * 1e3, "o-", color=COL["VQE"], label="SQD")
ax2.axhline(CHEM_ACC*1e3, color=COL["muted"], ls="--", lw=1.2)
ax2.set_xlabel("configuration-recovery iteration"); ax2.set_ylabel("E − E_FCI (mHa, log)")
ax2.set_title("SQD convergence", loc="left"); ax2.legend(fontsize=8)
plt.tight_layout(); plt.show()
Checking that the CCSD energy is close to FCI before sampling
CCSD energy: -1.1373061934 Ha (FCI -1.1373060358, error -1.58e-04 mHa)
t1 amplitude: 0.000000 t2 amplitude: -0.112237
LUCJ circuit after transpilation: 14 CNOTs, depth 26
Distinct bitstrings (= configurations) after generating 10000 Samples: 2 - {'0101': 9976, '1010': 24}
Valid fraction 1.000 (uniform random bit-strings: 0.250)
Method E_SQD (Ha) error (mHa) iterations subspace dim time (s)
SQD -1.13730604 0.00e+00 2 4 0.03
Variational bound E_SQD ≥ E_FCI holds: True
Orbital occupancies (α+β) of the SQD ground state: σg 1.9751, σu* 0.0249
Notes about the code¶
- The code uses PySCF's coupled-cluster solver
pyscf.cc.CCSD. Running it returns the t1 and t2 amplitudes. BitArrayis Qiskit's NumPy-backed container for an array of bitstrings, providing methods that operate on it.- The code uses
qiskit_addon_sqd, which implements the full SQD workflow. Itssolve_sci_batchsolver diagonalises the Hamiltonian projected onto the sampled subspace and returns the result asSCIResultobjects. It handles systems with ~25 spatial orbitals and ~10 electrons, subspace dimensions of ~$10^7$, using ~10–30 cores. Beyond that, the same package offers an alternative solver, SBD, which exploits parallel computing and GPU-based infrastructure. N_REPSis set to 1, because H₂ has one double excitation, so the LUCJ operator has one orbital rotation and one density–density term.ffsimis the library that builds the LUCJ operator, and the circuit uses three of its functions:from_t_amplitudesperforms the double factorization, taking thet2amplitudes and producing aUCJOpSpinBalancedoperator — a sequence of orbital rotations and density–density interactions;PrepareHartreeFockJWprepares the HF reference state; andUCJOpSpinBalancedJWapplies the LUCJ operator as a gate. The circuit is therefore the HF reference followed by the LUCJ layers, as described in step 2.- We override the default number of shots with 10'000, as we need more shots to reliably sample the rare configurations. SQD studies use 50'000 - 100'000 shots per run.
- We use
optimization_level = 3in the transpilation step, as this collapses consecutive two-qubit operations into optimal blocks. Using level 1 would leave the circuit deeper and noisier than necessary. diagonalize_fermionic_hamiltoniantakes molecular integralsh1andgfrom R2 and builds the fermionic Hamiltonian from them, and then projects it onto the recovered subspace.
Interpretation¶
- The classical preprocessing already contains the answer. CCSD, which for two electrons includes the complete excitation space, gives $E_\text{CCSD}$ equal to $E_\text{FCI}$ to $2 \times 10^{-4}$ mHa. The $t_1$ amplitude is zero: single excitations are forbidden by inversion symmetry, which is why ADAPT-VQE in R7 found their gradients to be exactly zero. The LUCJ circuit built from the amplitudes $t_1$ and $t_2$ therefore starts close to the ground state, and its samples concentrate on the configurations linked by the double excitation.
- The samples are reduced to only the two important configurations. The circuit returns just two distinct bitstrings, $|0101\rangle$ and $|1010\rangle$, exactly the two configurations identified in R3. All samples are valid (correct electron number and spin), compared with 25 % for uniformly random bitstrings.
- The recovered subspace has dimension 4, even though the samples contain only two configurations;
symmetrize_spin=Trueadds their spin partners. The energy error against FCI is zero to numerical precision. - This is a best-case demonstration. For a small molecule like H₂ the recovered subspace is complete, so SQD necessarily reproduces FCI. For a molecule with many orbitals the sampled subspace covers only a small fraction of the full space, so the energy becomes an upper bound on the exact ground energy $E_0$, and the achievable accuracy depends on the number of samples and on the recovery iterations. That is the regime in which SQD is useful, and there the cost shifts from the quantum device to the classical diagonalisation of the subspace.
Conclusion. SQD recovers the FCI energy of H₂ from sampled configurations alone, with no parameter optimisation. For H₂ the diagonalisation is trivial. Its value is relevant for large molecules, where the full Hamiltonian cannot be diagonalised but the Hamiltonian of the sampled subspace can.
Quantum-Classical Auxiliary-Field Quantum Monte Carlo (QC-AFQMC)¶
Introduction to QC-AFQMC¶
The previous method (SQD) used the quantum device to produce samples, diagonalize the subspace, and read the energy from the lowest eigenvalue. The limitation of this method is that SQD is fundamentally a subspace method, so its accuracy is bounded by whether the sampled configurations span enough of the true ground state. For H₂ this is not a problem, but for larger molecules it quickly becomes the bottleneck.
QC-AFQMC uses the quantum computer in a different way. Despite the name, "Quantum Monte Carlo" here is a classical stochastic method. We simulate the quantum imaginary-time Schrödinger equation (or ITSE; see the Introduction, section 4), $\partial_\tau |\Psi\rangle = -(\hat{H}-E_\text{ref})|\Psi\rangle$, which exponentially suppresses excited states to leave the ground state. However, the Hamiltonian contains two-body electron repulsion, and simulating these two-body interactions stochastically is extremely difficult. To solve this, we use a Cholesky transformation to replace the difficult two-body interactions with a one-body interaction coupled to a "fluctuating field" (the auxiliary field).
The "Monte Carlo" part is the algorithm that uses random numbers to sample this auxiliary field. These samples are then used to update the orbital coefficients of the Slater determinants (specific electron configurations that respect the fermionic principle of antisymmetry). This step-by-step perturbation of the coefficients is what causes the Slater determinants to 'walk'—which is why we refer to each Slater determinant in the simulation as a "walker." At each imaginary-time step, walkers that get into high-energy regions (where they disagree with the trial state) get pruned out, while the low-energy walkers are cloned. The underlying math is just the ITSE filtering out the excited states. Thus, the quantum computer only provides the trial wavefunction that guides these walkers, ensuring this classical random walk does not get lost.
The error structure between SQD and QC-AFQMC differs in a conceptually important way: SQD produces an upper bound to the ground-state energy: for any subspace the diagonalized energy cannot fall below the true $E_0$. QC-AFQMC is non-variational. It produces an estimate with a systematic bias set by the quality of the trial wavefunction, and because of the phaseless approximation, this bias can push the energy in either direction—meaning the final estimate can actually fall below the true $E_{FCI}$. In this sense, the quantum computer's role is not to provide a strict lower bound, but to reduce the classical method's systematic error.
The practical consequence is that in SQD, the classical diagonalization cost grows rapidly with subspace dimension, and the sampling burden falls entirely on the quantum device. In QC-AFQMC, the accuracy is determined by the quality of the trial wavefunction, so the quantum computer needs to supply a trial with the right qualitative structure. The projection step can then correct an imperfect trial through classical walker propagation.
This also distinguishes QC-AFQMC from the variational methods. VQE and ADAPT-VQE, for example, optimize circuit parameters to minimize energy directly. QC-AFQMC does not optimize the quantum state at all. It uses a quantum-prepared state—typically from a shallow circuit—as a constraint, and the computational work of correlation recovery happens classically through walker propagation.
The code that follows is organised into four stages:
- classical pre-processing step that factorizes the Hamiltonian and creates auxiliary fields,
- preparation of the quantum trial state as a sum of Slater determinants,
- Trotterized imaginary-time propagation of walkers as the classical solution of the ITSE, and
- statistical extraction of the plateau energy.
R9. Stage 1: Classical Pre-processing — Hamiltonian Factorization¶
Before involving any quantum sampling or Monte Carlo walkers, we must rewrite the Hamiltonian. The standard molecular Hamiltonian contains a difficult two-body interaction term with 4-index electron repulsion integrals $(pq|rs)$, which is too large to propagate efficiently in a stochastic simulation:
$$ H_\text{standard} = E_\text{nuc} + \sum_{pq} h_{pq} a^\dagger_p a_q + \frac{1}{2} \sum_{pqrs} (pq|rs) a^\dagger_p a^\dagger_q a_r a_s $$
To make this tractable for Monte Carlo, we factorize the 4-index tensor into a sum of 3-index Cholesky vectors, $(pq|rs) = \sum_\gamma L^\gamma_{pq} L^\gamma_{rs}$. This allows us to eliminate the 4-index integrals entirely and rewrite the Hamiltonian as a sum of squares of one-body operators:
$$H = E_\text{nuc} + \sum_{\sigma}\sum_{pq}K_{pq}a^\dagger_{p\sigma}a_{q\sigma} + \frac{1}{2}\sum_\gamma \hat{L}_\gamma^2$$
where $\hat{L}_\gamma = \sum_{\sigma}\sum_{pq}L^\gamma_{pq}a^\dagger_{p\sigma}a_{q\sigma}$.
The number of auxiliary fields $\gamma$ is typically much smaller than the number of 4-index integrals. For our minimal-basis H₂ molecule, the factorization yields just 3 fields.
Normal-ordering correction: Wick's theorem tells us that when we factorize two-body interactions, a piece of this two-body interaction "leaks" into the one-body space. We absorb this remainder into the one-body Hamiltonian $h_1$ to form an effective one body matrix: $K = h_1 - \frac{1}{2}\sum_\gamma L_\gamma L_\gamma$. This ensures the simulation remains mathematically exact and the walkers are propagated with the correct one-body energy.
# ── R9.1 Hamiltonian in AFQMC form: H = E_nuc + Σ_σ Σ_pq K_pq a†_pσ a_qσ + ½ Σ_γ L̂_γ² ──────────────
# with (pq|rs) = Σ_γ L^γ_pq L^γ_rs and L̂_γ = Σ_σ Σ_pq L^γ_pq a†_pσ a_qσ
def factorize_eri(g, tol=1e-10):
"""Eigenvalue (Cholesky-type) factorisation of the two-electron integrals: g_(pq),(rs) = Σ_γ L^γ_pq L^γ_rs."""
n = g.shape[0]
lam, V = np.linalg.eigh(g.reshape(n * n, n * n))
keep = lam > tol
L = (V[:, keep] * np.sqrt(lam[keep])).T.reshape(-1, n, n)
return 0.5 * (L + L.transpose(0, 2, 1))
afqmc_L = factorize_eri(g)
assert np.allclose(np.einsum("gpq,grs->pqrs", afqmc_L, afqmc_L), g, atol=1e-8)
# Normal-ordering correction: K = h − ½ Σ_γ L_γ L_γ
afqmc_K = h1 - 0.5 * np.einsum("gpr,grq->pq", afqmc_L, afqmc_L)
n_gamma = afqmc_L.shape[0]
print(f"Hamiltonian factorised into {n_gamma} auxiliary fields (Cholesky vectors) for {n_orb} spatial orbitals")
Hamiltonian factorised into 3 auxiliary fields (Cholesky vectors) for 2 spatial orbitals
R9. Stage 2: Quantum Trial State Preparation¶
In the Introduction of this notebook (Section 5), we defined a Slater determinant as a specific occupation pattern of the spin orbitals (e.g., the bitstring $|0101\rangle$). AFQMC walkers are exactly these Slater determinants, but the classical algorithm requires them to be in a matrix form.
Therefore, the trial wavefunction $|\Psi_T\rangle$ must be expressed in the same way: $$|\Psi_T\rangle = \sum_i c_i |D_i^\alpha D_i^\beta\rangle$$ where $|D_i\rangle$ represents one of these configurations, and $c_i$ is its coefficient.
For our two comparisons:
- The classical baseline (HF trial state) is made of one single determinant, the Hartree–Fock reference $|0101\rangle$. This represents the mean-field starting point.
- The quantum trial (LUCJ trial state): The state prepared by the LUCJ circuit from R8. For H₂, this is a superposition of two determinants (the HF state and the double excitation).
Comparing the two trial states will show how the quality of the quantum trial reduces the systematic error of the classical projection.
In the Jordan-Wigner representation, every bitstring with the correct number of electrons corresponds to a Slater determinant. To decompose the quantum state, the function determinant_trial() reads a Jordan–Wigner statevector, extracts the bitstrings with the correct electron number, and builds the orbital coefficient matrices $T^\alpha$ and $T^\beta$ for each determinant. The printout confirms that the LUCJ trial has a significantly lower variational energy than the HF trial, making it a better guide for the projection.
# ── R9.2 Quantum trial wavefunctions → expansions in Slater determinants ───────────────────────────
def determinant_trial(psi, norb, nelec, tol=1e-8):
"""Convert a Jordan–Wigner statevector into |Ψ_T> = Σ_i c_i |D_i^α D_i^β> (orbital occupations of the sampled bitstrings)."""
coef, Ta, Tb = [], [], []
for k, amp in enumerate(psi):
if abs(amp) < tol:
continue
bits = [(k >> j) & 1 for j in range(2 * norb)]
occ_a = [p for p in range(norb) if bits[p]]
occ_b = [p for p in range(norb) if bits[norb + p]]
if (len(occ_a), len(occ_b)) != tuple(nelec): # discard states with the wrong particle number
continue
coef.append(amp)
Ta.append(np.eye(norb)[:, occ_a]) # orbital coefficients of the α determinant
Tb.append(np.eye(norb)[:, occ_b])
coef = np.array(coef)
return {"c": coef / np.linalg.norm(coef), "Ta": np.array(Ta), "Tb": np.array(Tb)}
# Quantum trial: the state prepared by the LUCJ circuit of R8 (simulated exactly; on hardware the overlaps come from shadow tomography)
psi_lucj = Statevector(lucj_isa.remove_final_measurements(inplace=False)).data
psi_hf = np.zeros(2 ** N_QUBITS, dtype=complex)
psi_hf[int(HF_BITSTRING, 2)] = 1.0 # classical baseline: single-determinant trial |0101>
TRIALS = {"HF trial (classical)": determinant_trial(psi_hf, n_orb, nelec),
"LUCJ trial (quantum)": determinant_trial(psi_lucj, n_orb, nelec)}
for name, psi in (("HF trial (classical)", psi_hf), ("LUCJ trial (quantum)", psi_lucj)):
print(f" {name:<22}: {len(TRIALS[name]['c'])} determinant(s), variational energy <Ψ_T|H|Ψ_T> = "
f"{np.vdot(psi, Hmat @ psi).real: .8f} Ha (error {(np.vdot(psi, Hmat @ psi).real - E_FCI)*1e3: .3e} mHa)")
HF trial (classical) : 1 determinant(s), variational energy <Ψ_T|H|Ψ_T> = -1.11699900 Ha (error 2.031e+01 mHa) LUCJ trial (quantum) : 2 determinant(s), variational energy <Ψ_T|H|Ψ_T> = -1.13041836 Ha (error 6.888e+00 mHa)
R9. Stage 3: The AFQMC Kernel (Imaginary-Time Projection)¶
This is the core of the method. We propagate a population of Slater determinants (walkers) through imaginary time $\tau$. The propagation operator is split using the Trotter-Suzuki decomposition:
$$e^{-\Delta\tau(H-E_\text{ref})} \approx e^{-\Delta\tau K/2}\,e^{i\sqrt{\Delta\tau}\sum_\gamma(x_\gamma-\bar x_\gamma)\hat L_\gamma}\,e^{-\Delta\tau K/2}$$
where $x_\gamma \sim \mathcal{N}(0,1)$ are Gaussian auxiliary fields and $\bar x_\gamma$ is the "force bias" that shifts the Gaussian toward regions of lower energy.
Because the exact wavefunction is complex, this stochastic projection suffers from a severe sign problem. We fix this using the phaseless approximation: we compare the phase of the walker to the phase of the quantum trial wavefunction. If the phase rotates more than 90° away from the trial, we kill the walker.
The engine consists of three parts:
mixed_quantities(): Uses Wick's theorem to calculate the local energy and force bias for every walker.run_afqmc(): The main loop. It applies the kinetic and potential propagators, enforces the phaseless constraint (max(0, cos(arg I))), and manages the walker population (cloning successful walkers and eliminating failed ones).- The execution: We run the loop twice—once with the HF trial and once with the LUCJ trial—to see how the trial quality affects the final energy.
A subtle numerical detail: The exact Hartree-Fock determinant is orthogonal to the double-excitation in the LUCJ trial. If we started walkers exactly at HF, the overlap would be zero and the Green's functions would be singular. To prevent this, we initialize the walkers with a slight artificial rotation (0.3 radians) so that every walker has a non-zero overlap with every trial determinant.
# ── R9.3a Walker–trial quantities: overlap, local energy and force-bias source ──────────────────────
def trial_overlap(phi_a, phi_b, trial):
"""<Ψ_T|φ> = Σ_i c_i^* det(T_i^α† φ^α) det(T_i^β† φ^β) for a batch of walkers φ = (φ^α, φ^β)."""
ov = 0
for c, Ta, Tb in zip(trial["c"], trial["Ta"], trial["Tb"]):
ov = ov + np.conj(c) * np.linalg.det(Ta.T @ phi_a) * np.linalg.det(Tb.T @ phi_b)
return ov
def mixed_quantities(phi_a, phi_b, trial, h, L):
"""Return <Ψ_T|φ>, the local energy E_L = <Ψ_T|H_el|φ>/<Ψ_T|φ> and l_γ = <Ψ_T|L̂_γ|φ>/<Ψ_T|φ>.
Green's function G[p,q] = <c†_q c_p> = [φ (T†φ)^-1 T†]_pq; Wick's theorem gives the energy:
E_L = Σ h_pq G_qp + ½ Σ_γ [ (Σ_σ tr L_γ G_σ)² − Σ_σ tr(L_γ G_σ L_γ G_σ) ]."""
nw, ov, num_e, num_l = phi_a.shape[0], 0, 0, 0
for c, Ta, Tb in zip(trial["c"], trial["Ta"], trial["Tb"]):
Ma, Mb = Ta.T @ phi_a, Tb.T @ phi_b
Ga = phi_a @ np.linalg.inv(Ma) @ Ta.T
Gb = phi_b @ np.linalg.inv(Mb) @ Tb.T
G = Ga + Gb
l = np.einsum("gpq,wqp->wg", L, G)
e = np.einsum("pq,wqp->w", h, G) + 0.5 * np.sum(l ** 2, axis=1)
for Gs in (Ga, Gb):
LG = np.einsum("gpq,wqr->wgpr", L, Gs)
e -= 0.5 * np.einsum("wgpr,wgrp->w", LG, LG)
wgt = np.conj(c) * np.linalg.det(Ma) * np.linalg.det(Mb)
ov, num_e, num_l = ov + wgt, num_e + wgt * e, num_l + wgt[:, None] * l
return ov, num_e / ov, num_l / ov[:, None]
# ── R9.3b Phaseless AFQMC imaginary-time projection guided by the trial ─────────────────────────────
def run_afqmc(trial, dt=0.01, n_walkers=400, n_steps=3000, seed=7, taylor_order=8, popctrl=5):
"""Propagate walkers with exp(−Δτ(H − E_ref)) ≈ e^{−Δτ K/2} e^{i√Δτ Σ_γ (x_γ − x̄_γ) L_γ} e^{−Δτ K/2}.
x_γ ~ N(0,1); force bias x̄_γ = −i√Δτ <L_γ> (importance sampling); weight update
w ← w · |I| · max(0, cos arg I) · e^{Δτ E_ref}, I = <Ψ_T|φ'>/<Ψ_T|φ> · e^{x·x̄ − x̄²/2} (phaseless constraint)."""
rng = np.random.default_rng(seed)
na, nb = nelec
eK, UK = np.linalg.eigh(afqmc_K)
expK = (UK * np.exp(-0.5 * dt * eK)) @ UK.T # real one-body propagator e^{−Δτ K/2}
# Initial walker: the HF determinant with orbitals rotated by 0.3 rad, so that its overlap with every trial determinant is nonzero
# (the exact HF determinant is orthogonal to the σu*² determinant of the LUCJ trial, which would make the Green's function singular).
rot = np.array([[np.cos(0.3), -np.sin(0.3)], [np.sin(0.3), np.cos(0.3)]]) if n_orb == 2 else np.eye(n_orb)
phi0_a, phi0_b = rot[:, :na].astype(complex), rot[:, :nb].astype(complex)
phi_a, phi_b = np.tile(phi0_a, (n_walkers, 1, 1)), np.tile(phi0_b, (n_walkers, 1, 1))
w = np.ones(n_walkers)
ov, e_loc, _ = mixed_quantities(phi_a, phi_b, trial, h1, afqmc_L)
E_ref = float(np.sum(w * e_loc.real) / np.sum(w)) # starting guess for the energy offset
E_series = np.zeros(n_steps)
clip = np.sqrt(2.0 / dt) # standard bound on local-energy outliers
def apply_exp(A, phi): # e^A φ by Taylor series (‖A‖ ~ √Δτ is small)
out, term = phi.copy(), phi
for k in range(1, taylor_order + 1):
term = (A @ term) / k
out = out + term
return out
for step in range(n_steps):
ov, e_loc, l = mixed_quantities(phi_a, phi_b, trial, h1, afqmc_L)
e_re = np.clip(e_loc.real, E_ref - clip, E_ref + clip)
E_series[step] = np.sum(w * e_re) / np.sum(w) # mixed estimator at imaginary time τ = step·Δτ
xbar = -1j * np.sqrt(dt) * l # force bias
xbar *= np.minimum(1.0, 1.0 / np.maximum(np.abs(xbar), 1e-12)) # |x̄| ≤ 1 for stability
x = rng.standard_normal((n_walkers, n_gamma))
A = 1j * np.sqrt(dt) * np.einsum("wg,gpq->wpq", x - xbar, afqmc_L)
phi_a, phi_b = expK @ apply_exp(A, expK @ phi_a), expK @ apply_exp(A, expK @ phi_b)
I = trial_overlap(phi_a, phi_b, trial) / ov * np.exp(np.sum(x * xbar - 0.5 * xbar ** 2, axis=1))
w = w * np.abs(I) * np.maximum(0.0, np.cos(np.angle(I))) * np.exp(dt * E_ref)
dead = ~np.isfinite(w) | (w <= 0)
w[dead], phi_a[dead], phi_b[dead] = 0.0, phi0_a, phi0_b # walkers killed by the phaseless constraint
if (step + 1) % popctrl == 0: # population control (comb) + re-orthonormalisation
idx = np.searchsorted(np.cumsum(w) / np.sum(w), (rng.random() + np.arange(n_walkers)) / n_walkers)
phi_a, phi_b = np.linalg.qr(phi_a[np.minimum(idx, n_walkers - 1)])[0], np.linalg.qr(phi_b[np.minimum(idx, n_walkers - 1)])[0]
w = np.ones(n_walkers)
if (step + 1) % 20 == 0: # slowly track the growth estimate
E_ref = 0.5 * E_ref + 0.5 * float(np.mean(E_series[step - 19:step + 1]))
return E_series + ref["E_nuc"]
R9. Stage 4: Statistical Analysis, Execution, and Results¶
The imaginary-time projection produces a noisy energy time series $E(\tau)$. We cannot simply read the final value, because the walkers are constantly fluctuating. Instead, we must extract the plateau.
- Equilibration: We discard the early part of the simulation ($\tau < 10\ \text{Ha}^{-1}$) where the walkers are still relaxing from their initial state.
- Block Averaging: The data points in imaginary time are highly correlated. To compute a reliable statistical error bar, we group the remaining data into large blocks and compute the standard error across the block means.
- Execution: We run the entire simulation twice—once for the classical HF trial and once for the quantum LUCJ trial—to directly compare how the trial wavefunction affects the final energy.
Finally, the plots show the two main features of QC-AFQMC:
- Left: The projection over imaginary time. Both trials start at their respective variational energies and decay toward the FCI energy.
- Right: The final plateau energies. Because AFQMC is non-variational (due to the phaseless approximation), the errors can land below the true FCI line.
# ── (5) Plateau extraction, execution, and plotting ──────────────────────────────────────────────
def plateau_energy(E_series, dt, tau_eq, block_steps):
"""Long-τ plateau: discard the equilibration τ < τ_eq, then average block means; error = standard error of the blocks."""
data = E_series[int(round(tau_eq / dt)):]
nblk = len(data) // block_steps
blocks = data[:nblk * block_steps].reshape(nblk, block_steps).mean(axis=1)
return blocks.mean(), blocks.std(ddof=1) / np.sqrt(nblk)
# DT, N_STEPS, N_WALKERS, TAU_EQ, BLOCK = 0.01, 3000, 400, 10.0, 200
DT, N_STEPS, N_WALKERS, TAU_EQ, BLOCK = 0.005, 4000, 4000, 10.0, 500
afqmc = {}
for name, trial in TRIALS.items():
t0 = time.perf_counter()
series = run_afqmc(trial, dt=DT, n_walkers=N_WALKERS, n_steps=N_STEPS)
E_mean, E_err = plateau_energy(series, DT, TAU_EQ, BLOCK)
afqmc[name] = {"series": series, "E": E_mean, "err": E_err, "seconds": time.perf_counter() - t0}
print(f"\nΔτ = {DT}, {N_WALKERS} walkers, τ_max = {N_STEPS*DT:.0f} Ha⁻¹, plateau averaged for τ > {TAU_EQ:.0f} Ha⁻¹")
print(f"{'Trial':<24}{'E_AFQMC (Ha)':>16}{'± stat (mHa)':>14}{'error vs FCI (mHa)':>20}{'time (s)':>10}")
for name, r in afqmc.items():
print(f"{name:<24}{r['E']:>16.8f}{r['err']*1e3:>14.3f}{(r['E']-E_FCI)*1e3:>20.3f}{r['seconds']:>10.2f}")
print(f"\nChemical accuracy: {CHEM_ACC*1e3:.1f} mHa. Unlike SQD, AFQMC is not variational: the error can have either sign.")
# ── Plot: imaginary-time projection and final accuracy ────────────────────────────────────────────
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3.6))
tau = np.arange(N_STEPS) * DT
for (name, r), col in zip(afqmc.items(), (COL["HF"], COL["VQE"])):
smooth = np.convolve(r["series"] - E_FCI, np.ones(50) / 50, mode="valid")
ax1.plot(tau[49:], smooth * 1e3, color=col, label=name)
ax1.axhspan(-CHEM_ACC * 1e3, CHEM_ACC * 1e3, color=COL["grid"], alpha=0.6, label="chemical accuracy")
ax1.axhline(0, color=COL["FCI"], ls="--", lw=1.2, label="FCI")
ax1.set_xlabel("imaginary time τ (Ha⁻¹)"); ax1.set_ylabel("E − E_FCI (mHa)")
ax1.set_title("Imaginary-time projection", loc="left"); ax1.legend(fontsize=8)
ax2.bar(range(len(afqmc)), [(r["E"] - E_FCI) * 1e3 for r in afqmc.values()],
yerr=[r["err"] * 1e3 for r in afqmc.values()], color=(COL["HF"], COL["VQE"]), capsize=4)
ax2.axhline(CHEM_ACC * 1e3, color=COL["muted"], ls="--", lw=1.2); ax2.axhline(-CHEM_ACC * 1e3, color=COL["muted"], ls="--", lw=1.2)
ax2.set_xticks(range(len(afqmc))); ax2.set_xticklabels(list(afqmc), fontsize=8)
ax2.set_ylabel("E_AFQMC − E_FCI (mHa)"); ax2.set_title("Plateau energy error", loc="left")
plt.tight_layout(); plt.show()
Δτ = 0.005, 4000 walkers, τ_max = 20 Ha⁻¹, plateau averaged for τ > 10 Ha⁻¹ Trial E_AFQMC (Ha) ± stat (mHa) error vs FCI (mHa) time (s) HF trial (classical) -1.13696020 0.149 0.346 80.23 LUCJ trial (quantum) -1.13729905 0.068 0.007 105.75 Chemical accuracy: 1.6 mHa. Unlike SQD, AFQMC is not variational: the error can have either sign.
Interpretation¶
The results demonstrate that the quality of the quantum trial state directly controls the systematic error of the classical projection that is introduced into the final energy.
- The classical trial (HF): The HF trial state is a single determinant. It provides a rough guide for the walkers, resulting in a final energy that is off by 0.346 mHa. While this is within chemical accuracy, the error is purely systematic—a bias introduced because the method struggles to correct for the missing correlation in the trial state.
- The quantum trial (LUCJ): The LUCJ trial state, which includes electron correlation, reduces the error by a factor of 50, down to 0.007 mHa. Looking at the left plot, the LUCJ walkers converge closer to the exact FCI line and stay there with less fluctuation. Looking at the right plot, the final energy is nearly indistinguishable from zero error, and the statistical error bar (±0.068 mHa) is much smaller than the systematic error of the HF trial.
- Non-variational behavior: Notice that the final AFQMC energies can have either sign (the HF trial error is positive, while the LUCJ trial error is slightly positive but much closer to zero). This is the hallmark of the phaseless approximation: to solve the fermionic sign problem, the algorithm eliminates walkers that drift out of phase with the trial state. Because part of the wavefunction is discarded, the method is no longer variational. Thus, unlike SQD or VQE, which are guaranteed to be upper bounds, AFQMC can overshoot the exact energy and land below $E_{FCI}$.
A note on computational cost: The LUCJ trial took about 25% longer to simulate (105 seconds vs 80 seconds). This is because the LUCJ trial is a superposition of two determinants, meaning the code has to calculate twice as many matrix determinants and Green's functions at every step.
Conclusion: Advantages, Disadvantages, and Scaling¶
QC-AFQMC is fundamentally different from the other methods in this lab. While VQE and SQD attempt to solve the time-independent Schrödinger equation to find eigenvalues, QC-AFQMC simulates the imaginary-time Schrödinger equation. This difference dictates its strengths and weaknesses.
The Advantages¶
- No variational optimization loop: VQE requires a classical optimizer that can get stuck in local minima or suffer from barren plateaus. QC-AFQMC does not optimize the quantum circuit; it just uses it as a guide. This drastically reduces the quantum runtime.
- No deep circuits: SQD requires sampling, and QPE requires extremely deep, fault-tolerant circuits. QC-AFQMC can work with very shallow, near-term quantum circuits (like the LUCJ ansatz) because the classical projection does the heavy lifting.
- Systematic error control: The accuracy of the method is entirely tunable via the trial wavefunction. As the quantum computer gets better at preparing correlated states, the classical AFQMC error shrinks accordingly.
The Disadvantages¶
- Mathematical complexity: This is the most mathematically involved method in the notebook. It requires understanding Wick's theorem, Green's functions, Hubbard-Stratonovich transformations, and Trotterization. It is much harder to implement and debug than VQE or SQD.
- Computational bottleneck: The classical post-processing is demanding. The code must continuously evaluate the overlap between the trial state and thousands of walkers. As the molecule gets larger, this matrix determinant calculation becomes the bottleneck.
- The Phaseless Bias: The phaseless approximation introduces a systematic error that is not variational. You cannot use the result as a strict upper bound.
Scaling to Larger Problems¶
If we scaled this from H₂ to a larger molecule (like water or a transition metal complex), the trade-offs shift:
- The quantum side stays cheap: The quantum circuit only needs to prepare a trial state. This scales polynomially with the number of qubits and does not require deep circuits.
- The classical side becomes expensive: The classical cost scales as $O(N^4)$ to $O(N^5)$ with the number of orbitals, depending on how the Hamiltonian is factorized. Furthermore, as the system grows, the variance of the Monte Carlo walkers increases, meaning we would need exponentially more walkers to achieve the same statistical accuracy. This is the ultimate bottleneck of the method.
What one should pay attention to: When applying QC-AFQMC, the most critical choices are the trial wavefunction and the imaginary time step . The trial state dictates the size of the systematic error, while the time step dictates the Trotterization error. We also have to carefully monitor the walker population—too few walkers, and the statistical noise will dominate over the physical result; too many, and the classical matrix operations will exceed the available memory and compute limits.
Quantum Phase Estimation (QPE)¶
Introduction to QPE¶
Quantum Phase Estimation (QPE) takes a completely different approach from the previous methods. VQE optimizes a circuit, SQD samples bitstrings, and QC-AFQMC uses imaginary-time projection. QPE, by contrast, uses the time-dependent Schrödinger equation (TDSE) to extract the energy.
In the Introduction (Section 4), we saw that applying the unitary time-evolution operator $e^{-i\hat{H}t/\hbar}$ to an eigenstate $|\psi_n\rangle$ leaves the state unchanged, but attaches a phase factor: $$ e^{-i\hat{H}t/\hbar}|\psi_n\rangle = e^{-iE_n t/\hbar}|\psi_n\rangle $$ The energy $E_n$ is encoded in this phase, so if we can measure the accumulated phase, we can read off the energy in this way.
How QPE works¶
QPE uses an ancilla register (the counting qubits) to measure this phase.
- The ancilla qubits are placed into a uniform superposition using Hadamard gates.
- They control the application of the unitary operator $U = e^{-i\hat{H}t}$ onto the target qubit register that holds the molecular state.
- An inverse Quantum Fourier Transform (QFT) is applied to the ancilla register.
- Measuring the ancilla qubits yields a bitstring that encodes the phase $E_n t / 2\pi$.
For our H₂ problem, R3 established that the ground state lies in a two-dimensional subspace spanned by $|0101\rangle$ and $|1010\rangle$. QPE will start with the Hartree-Fock state $|0101\rangle$, which is a superposition of the ground state and an excited state. The algorithm will project this state into one of the energy eigenstates and measure its phase.
The challenge: Deep circuits¶
Unlike VQE or QC-AFQMC, QPE requires deep circuits.
- The TDSE dictates that the state evolves under the unitary operator $e^{-i\hat{H}t}$. However, because the 15 Pauli terms in the H₂ Hamiltonian do not commute, this operator cannot be applied in a single step. We must Trotterize the evolution: we divide the total evolution time $t$ into $N$ small slices $\Delta t$, and then repeat the sequence of all 15 Pauli terms $N$ times. The circuit depth therefore scales with the number of Trotter steps.
- On near-term hardware, the accumulated gate noise would destroy the phase before it could be measured. QPE is therefore designed for fault-tolerant, error-corrected quantum computers, which are yet to be developed.
- To extract the phase with high precision, the ancilla register must be large (often 6–10 qubits just for the phase).
What the code does¶
Because we are running on a classical simulator, we can execute QPE without noise (and then add noise later to show how it breaks). The code will:
- Build a Trotterized time-evolution circuit that approximates the unitary operator $e^{-i\hat{H}t}$ for the 15-term H₂ Hamiltonian (R3).
- Implement the QPE circuit (ancilla preparation, controlled evolution, inverse QFT).
- Run the simulation and extract the most probable phase, which corresponds to the ground-state energy.
- Compare the simulated result to the exact $E_\text{FCI}$.
(Note: To run QPE on the 4-qubit H₂ Hamiltonian, we will use a small number of ancilla qubits. In a real fault-tolerant application, the register would be much larger to achieve the desired precision.)
R10. Stage 1: Preparation — Mapping Energy to Phase¶
The phase $e^{-iE_n t}$ is periodic: energies that differ by $2\pi/t$ produce the same phase, making it impossible to distinguish them. To resolve this, we will first shift the Hamiltonian by a reference energy $E_\text{top}$ and choose a time $t = 2\pi/W$ such that the accumulated phase is strictly between 0 and 1, removing any ambiguity. This defines a "window" $W$ that must contain the true ground state.
We set the top of the window to $E_\text{top} = E_\text{HF} + 0.05$ Ha. By the variational principle (from R1), the true ground state must lie below the Hartree-Fock energy. We add a small offset of 0.05 Ha to ensure that all relevant energies fall safely inside the window, while preventing any ambiguity at the boundary where the phase would be exactly zero.
Furthermore, because the 15 Pauli terms of the H₂ Hamiltonian do not commute, we cannot apply $e^{-i\hat{H}t}$ in a single gate. We must use a Trotterized time-evolution circuit (here, a second-order Suzuki-Trotter decomposition). R10.1 builds this circuit, checks that it faithfully approximates the unitary time-evolution operator, and verifies that its ground-state eigenphase corresponds to the FCI energy before we build the full QPE circuit.
# ── R10.1 Preparation: energy-to-phase map and Trotterised time evolution ─────────────────────────
from scipy.linalg import expm
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.circuit.library import QFTGate, UnitaryGate
from qiskit.quantum_info import Operator
from qiskit.primitives import StatevectorSampler
from qiskit.synthesis import SuzukiTrotter
# ── (1) Map energy to phase: U = exp(−i (H − E_top) t) with t = 2π/W ──────────────────────────────
# Eigenvalue E of H gives U|ψ> = exp(2πi φ)|ψ> with φ = (E_top − E)/W. φ must stay in [0, 1), so the window
# [E_top − W, E_top] must contain the ground energy. The variational principle gives E_0 ≤ E_HF, so the
# upper edge is set just above the Hartree–Fock energy of R1; the window width W sets the resolution W/2^m.
E_TOP, WINDOW = E_HF + 0.05, 1.0 # Ha
T_EVO = 2 * np.pi / WINDOW # evolution time of the first controlled unitary (Ha⁻¹)
H_shift = (H - E_TOP * SparsePauliOp.from_sparse_list([("", [], 1.0)], num_qubits=N_QUBITS)).simplify()
QPE_BASIS = ["cx", "rz", "sx", "x"]
# ── (2) Trotterised time evolution of the 15-term Hamiltonian (second-order Suzuki–Trotter) ──────────
N_TROTTER = 100 # Trotter steps used to approximate U = exp(−iH't)
def trotter_unitary(t, steps):
"""Matrix of the Trotter circuit for exp(−i H' t): (S₂(t/steps))^steps, S₂ = symmetric product of the Pauli exponentials."""
step = QuantumCircuit(N_QUBITS)
step.append(PauliEvolutionGate(H_shift, time=t / steps, synthesis=SuzukiTrotter(order=2, reps=1)), range(N_QUBITS))
return np.linalg.matrix_power(Operator(step.decompose(reps=2)).data, steps), step
U_trot, step_circ = trotter_unitary(T_EVO, N_TROTTER)
U_exact = expm(-1j * H_shift.to_matrix() * T_EVO)
# ── Check: the Trotter error shifts the ground-state eigenphase; compare with the exact ground energy of H ──
def phase_to_energy(phi):
return E_TOP - WINDOW * phi
evals_H, evecs_H = np.linalg.eigh(Hmat)
psi0 = evecs_H[:, 0] # exact ground state of H (from R3)
w_t, v_t = np.linalg.eig(U_trot)
k0 = int(np.argmax(np.abs(v_t.conj().T @ psi0))) # Trotter eigenvector with the largest overlap with the ground state
E_trot0 = phase_to_energy((np.angle(w_t[k0]) / (2 * np.pi)) % 1.0)
hf_vec = np.zeros(2 ** N_QUBITS); hf_vec[int(HF_BITSTRING, 2)] = 1.0
print(f"Window [{E_TOP - WINDOW: .4f}, {E_TOP: .4f}] Ha, t = 2π/W = {T_EVO:.3f} Ha⁻¹, {N_TROTTER} second-order Trotter steps")
print(f"Ground energy of H : {evals_H[0]: .8f} Ha (E_FCI {E_FCI: .8f})")
print(f"Ground eigenphase of Trotter U : {E_trot0: .8f} Ha (Trotter bias {(E_trot0 - E_FCI)*1e3: .4f} mHa)")
print(f"||U_trot − U_exact||₂ : {np.linalg.norm(U_trot - U_exact, 2):.2e}")
print(f"HF overlap with the ground state : |<0101|ψ₀>|² = {abs(psi0[int(HF_BITSTRING, 2)])**2:.4f} -> QPE succeeds with this probability")
Window [-2.0670, -1.0670] Ha, t = 2π/W = 6.283 Ha⁻¹, 100 second-order Trotter steps Ground energy of H : -1.13730604 Ha (E_FCI -1.13730604) Ground eigenphase of Trotter U : -1.13728932 Ha (Trotter bias 0.0167 mHa) ||U_trot − U_exact||₂ : 1.39e-04 HF overlap with the ground state : |<0101|ψ₀>|² = 0.9876 -> QPE succeeds with this probability
Interpretation¶
- The energy window: The code prints the window as
[-2.0670, -1.0670] Ha. This confirms that the top of the window ($-1.0670$) is slightly above the Hartree-Fock energy ($E_\text{HF} \approx -1.117$ Ha), and the width of $1.0$ Ha contains the true ground state ($-1.137$ Ha). - The exact vs. Trotter ground energy: The exact ground-state energy that we obtained with
np.linalg.eigh(Hmat)is $-1.13730604$ Ha, matching the FCI reference from R1. The Trotterized phase, when mapped back to an energy, yields $-1.13728932$ Ha. The difference (0.0167 mHa) is the Trotter bias. This is well below chemical accuracy (1.6 mHa), proving that 100 Trotter steps are sufficient to simulate the time evolution accurately. - The Trotter error: The matrix distance between the Trotterized unitary and the exact unitary is
1.39e-04. This is a small but non-zero error, confirming that Trotterization is an approximation. However, this matrix error translates to an energy error that is practically negligible. - The HF overlap: The probability that the initial Hartree-Fock state ($|0101\rangle$) will overlap with the true ground state is 0.9876 (98.76%). This means that when we prepare the system in the Hartree-Fock state, there is a 98.76% chance that the QPE circuit will successfully project it into the ground state and measure the correct ground-state phase.
R10. Stage 2: The QPE Circuit¶
R10.2 builds the actual Quantum Phase Estimation circuit. The circuit uses two registers:
- The system register: The 4 qubits holding the H₂ molecular state. We initialize them in the Hartree-Fock state $|0101\rangle$.
- The counting register: $m$ ancilla qubits. These are the counting qubits that will extract the phase.
The circuit is built in three stages:
Ancilla Preparation (Hadamards) The counting qubits are placed into a uniform superposition using Hadamard gates. This allows them to act as a "clock" that records the phase accumulated by the system.
Controlled Time Evolution ($U^{2^k}$) Each ancilla qubit $k$ controls the application of the time-evolution operator raised to the power $2^k$:
- Ancilla 0 controls $U^1$
- Ancilla 1 controls $U^2$
- Ancilla 2 controls $U^4$
- ...and so on.
This exponential sequence is the main part of QPE: the $k$-th ancilla performs a phase kickback proportional to $2^k E t$. On a real quantum computer, $U^{2^k}$ is implemented by repeating the Trotter circuit $2^k$ times, which is why the circuit depth grows exponentially with the number of counting qubits.
- Inverse Quantum Fourier Transform (QFT) The phase information is currently stored in the relative phases of the ancilla qubits. The inverse QFT converts these phases into a measurable bitstring. When we measure the counting register, the binary string we obtain directly encodes the phase $\phi$.
What the code draws¶
Because drawing a 10-ancilla circuit is too large for a notebook, the code draws a 3-ancilla demonstration circuit. The structure is identical to the 10-ancilla version, just shorter. The code then draws three figures:
- The circuit with the counting-qubit circuit, inverse QFT block, and measurements.
- The same circuit with the inverse QFT expanded into elementary Hadamards and controlled-phase rotations, showing how the inverse QFT block is actually built.
- One Trotter step expanded into 70 CNOTs and single-qubit rotations, to show the size of the building block that is repeated inside every controlled-$U^{2^k}$.
# ── R10.2 The QPE circuit: ancilla Hadamards, controlled-U^(2^k), inverse QFT, measurement ───────
def qpe_circuit(m, U, measure=True):
"""m counting qubits (little endian: ancilla k controls U^(2^k)) + 4 system qubits prepared in |0101> (HF).
Output integer j = Σ_k b_k 2^k -> φ = j / 2^m."""
qr_anc, qr_sys = QuantumRegister(m, "anc"), QuantumRegister(N_QUBITS, "sys")
cr_phase = ClassicalRegister(m, "phase")
qc = QuantumCircuit(qr_anc, qr_sys, cr_phase)
qc.x([qr_sys[0], qr_sys[2]]) # HF reference |0101>
qc.h(qr_anc) # uniform superposition on the counting register
qc.barrier()
for k in range(m):
Uk = np.linalg.matrix_power(U, 2 ** k) # U^(2^k) (on hardware: 2^k repetitions of the Trotter circuit)
qc.append(UnitaryGate(Uk, label=f"U^{2**k}").control(1), [qr_anc[k], *qr_sys])
qc.barrier()
qc.append(QFTGate(m).inverse(), qr_anc) # inverse QFT turns the phase kicks into a bit-string
if measure:
qc.measure(qr_anc, cr_phase)
return qc
# ── Visualisation: a 3-counting-qubit version of the circuit (the 10-qubit one has the same structure) ──
qc_demo = qpe_circuit(3, U_trot)
print("Gate counts of the 3-counting-qubit circuit:", dict(qc_demo.count_ops()))
display(qc_demo.draw(output="mpl", fold=-1, style="iqp", scale=0.9))
plt.show()
# ── The same circuit with the inverse QFT expanded into elementary gates ────────────────────────────
qc_qft = qc_demo.decompose(gates_to_decompose=["qft_dg", "QFT", "qft"])
print("Gate counts after expanding the inverse QFT:", dict(qc_qft.count_ops()))
display(qc_qft.draw(output="mpl", fold=-1, style="iqp", scale=0.9))
plt.show()
# ── One Trotter step: the building block repeated inside every controlled-U^(2^k), expanded into gates ──
step_gates = step_circ.decompose(reps=2)
print(f"\nOne second-order Trotter step of exp(−i H' t/{N_TROTTER}): {dict(step_gates.count_ops())}")
display(step_gates.draw(output="mpl", fold=60, style="iqp", scale=0.6))
plt.show()
Gate counts of the 3-counting-qubit circuit: {'h': 3, 'c-unitary': 3, 'measure': 3, 'x': 2, 'barrier': 2, 'qft_dg': 1}
Gate counts after expanding the inverse QFT: {'h': 6, 'c-unitary': 3, 'cp': 3, 'measure': 3, 'x': 2, 'barrier': 2, 'swap': 1}
One second-order Trotter step of exp(−i H' t/100): {'cx': 70, 'sdg': 32, 'h': 32, 's': 32, 'u': 32, 'p': 16, 'rz': 11}
Interpretation¶
- The inverse QFT cost: The second printout expands the
qft_dginto 3 additional Hadamards and 3 controlled-phase gates (cp), plus 1swapgate to reverse the qubit order. This shows that the QFT is not a single primitive operation, but a small circuit of its own. - The Trotter building block: The third printout expands a single second-order Trotter step. It requires 70 CNOTs, along with 32 Hadamards, 32 phase gates, and various single-qubit rotations.
- The influence of the Trotter steps: The number of Trotter steps (
N_TROTTER = 100) dictates the size of this block. Because we use 100 steps, one full application of the time-evolution operator $U$ requires $100 \times 70 = 7'000$ CNOTs.
This means that to apply $U^{2^k}$ for the largest ancilla ($k=9$) in the 10-qubit version, the circuit must repeat this 7'000-CNOT block $2^9 = 512$ times. Summed over all ancilla qubits, the full QPE circuit requires millions of CNOTs. This is why the full 10-qubit circuit is far beyond the reach of current quantum computers without fault tolerance.
R10. Stage 3: Execution and Analysis¶
R10.3 runs the full QPE circuit on a classical simulator and analyses the results. The goal is to see whether the measured phase actually encodes the ground-state energy, and to understand the accuracy limits of the algorithm.
The code does four things:
Execute the circuit with 10 counting qubits.
We run QPE twice: once using the exact unitary $U_\text{exact}$, and once using the Trotterized unitary $U_\text{trot}$. As the relative error of a probability estimate scales as $1/\sqrt{N}$, where $N$ is the number of shots, with $N = 20'000$ the relative error drops to about 0.7%. Thus, we use for each run 20'000 shots. The measurement outcomes on the counting register form a distribution of bitstrings. The most probable bitstring (the "peak") encodes the phase $\phi$, which we map back to an energy.
(Note: On a real quantum computer, applying $U_\text{exact}$ in a single step is impossible as this unitary would have to be Trotterized. But here on the classical simulator, we can apply the exact matrix directly as a theoretical baseline to isolate the Trotter error.
Compare against the exact energy.
The measured QPE energy is compared to $E_\text{FCI}$. Because the phase is discretized onto a grid of $2^m$ bins (where $m=10$), the best possible resolution is $\Delta E = W/2^m$. For our window $W = 1.0$ Ha, this is about 0.98 mHa. Any error larger than this is due to the Trotter approximation or sampling noise, but any error smaller than this is impossible to resolve.
Estimate the total CNOT cost.
The code calculates the total number of CNOTs required for the full QPE circuit. It multiplies the CNOTs per Trotter step by the total number of $U$ applications ($2^m - 1 = 1023$). This gives a lower bound on the gate count for a fault-tolerant implementation.
Plot the accuracy scaling.
The right-hand plot shows how the QPE error decreases as we increase the number of counting qubits $m$. The dashed line shows the theoretical resolution $W/2^{m+1}$. This plot confirms the exponential scaling of QPE: each additional counting qubit halves the resolution error. It also illustrates why QPE is so demanding: to reach chemical accuracy (1.6 mHa), we need enough counting qubits to resolve the energy to that level.
# ── R10.3 Execution on the simulator, comparison with E_FCI and plots ────────────────────────────
M_ANC, SHOTS = 10, 20_000
res = {}
for label, U in (("exact U", U_exact), ("Trotter U", U_trot)):
qc = qpe_circuit(M_ANC, U)
counts = StatevectorSampler(seed=42).run([qc], shots=SHOTS).result()[0].data.phase.get_counts()
j_best = int(max(counts, key=counts.get), 2)
res[label] = {"counts": counts, "j": j_best, "E": phase_to_energy(j_best / 2 ** M_ANC), "p": counts[format(j_best, f"0{M_ANC}b")] / SHOTS}
delta = WINDOW / 2 ** M_ANC
print(f"\nQPE with {M_ANC} counting qubits + {N_QUBITS} system qubits, {SHOTS} shots, energy resolution W/2^m = {delta*1e3:.2f} mHa")
print(f"{'Evolution':<12}{'peak j':>8}{'P(peak)':>9}{'E_QPE (Ha)':>14}{'error vs FCI (mHa)':>20}")
for label, r in res.items():
print(f"{label:<12}{r['j']:>8}{r['p']:>9.3f}{r['E']:>14.8f}{(r['E'] - E_FCI)*1e3:>20.3f}")
print(f"\nChemical accuracy: {CHEM_ACC*1e3:.1f} mHa. The error is limited by the grid spacing, not by sampling: the best bin lies within {delta/2*1e3:.2f} mHa of E_FCI.")
# ── Cost of the circuit: gates needed on a fault-tolerant machine (uncontrolled Trotter circuit, lower bound) ──
step_t = transpile(step_circ.decompose(reps=2), basis_gates=QPE_BASIS, optimization_level=1)
cx_step = step_t.count_ops().get("cx", 0)
n_steps_total = N_TROTTER * (2 ** M_ANC - 1) # Σ_k 2^k = 2^m − 1 applications of U
print(f"\nOne Trotter step: {cx_step} CNOTs, depth {step_t.depth()}. Total for U^(2^m − 1): {n_steps_total} steps ≈ {cx_step * n_steps_total:,} CNOTs "
f"(before adding the control)")
# ── Precision versus number of counting qubits (exact probabilities, no shot noise) ───────────────────
ms = list(range(3, M_ANC + 1))
err_m = []
for m in ms:
probs = Statevector(qpe_circuit(m, U_trot, measure=False)).probabilities(list(range(m)))
err_m.append(abs(phase_to_energy(int(np.argmax(probs)) / 2 ** m) - E_FCI))
# ── Plot: phase distribution and error versus ancilla count ───────────────────────────────────────────
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3.6))
cnt = res["Trotter U"]["counts"]
js = np.array([int(b, 2) for b in cnt]); pr = np.array([v / SHOTS for v in cnt.values()])
ax1.bar(phase_to_energy(js / 2 ** M_ANC), pr, width=delta, color=COL["VQE"], label="QPE samples (Trotter U)")
ax1.axvline(E_FCI, color=COL["FCI"], ls="--", lw=1.2, label="E_FCI")
ax1.set_xlabel("energy read from the counting register (Ha)"); ax1.set_ylabel("probability")
ax1.set_title("QPE phase distribution", loc="left"); ax1.legend(fontsize=8)
ax2.semilogy(ms, np.array(err_m) * 1e3, "o-", color=COL["VQE"], label="|E_QPE − E_FCI|")
ax2.semilogy(ms, WINDOW / 2 ** np.array(ms) * 1e3 / 2, "--", color=COL["muted"], label="resolution W/2^(m+1)")
ax2.axhline(CHEM_ACC * 1e3, color=COL["muted"], ls=":", lw=1.2)
ax2.set_xlabel("number of counting qubits m"); ax2.set_ylabel("error (mHa, log)")
ax2.set_title("Precision versus ancilla count", loc="left"); ax2.legend(fontsize=8)
plt.tight_layout(); plt.show()
QPE with 10 counting qubits + 4 system qubits, 20000 shots, energy resolution W/2^m = 0.98 mHa Evolution peak j P(peak) E_QPE (Ha) error vs FCI (mHa) exact U 72 0.986 -1.13731150 -0.005 Trotter U 72 0.985 -1.13731150 -0.005 Chemical accuracy: 1.6 mHa. The error is limited by the grid spacing, not by sampling: the best bin lies within 0.49 mHa of E_FCI. One Trotter step: 70 CNOTs, depth 116. Total for U^(2^m − 1): 102300 steps ≈ 7,161,000 CNOTs (before adding the control)
Interpretation¶
- The most probable measurement outcome: For both the exact and Trotterized unitaries, the most probable measurement outcome (the peak) is the bitstring corresponding to $j = 72$. The probability of measuring this peak is 98.5%. This means that if we run the circuit once, we have a 98.5% chance of reading the correct energy bin. The remaining 1.5% is spread across the neighboring bins due to the finite resolution of the counting register.
- The energy error: The measured energy is $-1.13731150$ Ha, which is 0.005 mHa below the exact FCI energy. This tiny difference is purely a result of the grid resolution. With 10 counting qubits and a window of $W = 1.0$ Ha, the energy grid has a spacing of $W/2^{10} \approx 0.98$ mHa. The true energy falls between two grid points, and the QPE circuit rounds it to the nearest one (or the one with the highest probability). If we had more ancilla qubits, this spacing would be reduced, but the fact that the error is well within chemical accuracy (1.6 mHa) proves that 10 counting (ancilla) qubits are sufficient for this molecule.
- The Trotter error is invisible: The results for
exact UandTrotter Uare identical (both peak at $j=72$). This is because the Trotter error (0.0167 mHa from R10.1) is much smaller than the grid resolution (0.98 mHa). The Trotterization is so accurate that it doesn't shift the peak to a different bin. On a real quantum computer, the Trotter approximation would be indistinguishable from the exact evolution at this precision. - The astronomical gate cost: The printout reveals the true cost of this algorithm: 7'161'000 CNOTs. This is the number of CNOT gates required to run the full QPE circuit on a fault-tolerant quantum computer ($2^m - 1 = 1023$ applications of $U$, each containing 100 Trotter steps of 70 CNOTs). For a 4-qubit molecule, 7 million CNOTs is already massive. For a real molecule with hundreds of spin orbitals, the QPE circuit would require trillions of CNOT gates. Even on a future fault-tolerant quantum computer, due to error-correction codes and magic state distillation, this would require impractically long runtimes. If we reduce the problem to an active space of a few dozen orbitals, the CNOT count drops to the billions. This is a realistic target for early fault-tolerant hardware, but it still requires a fully error-corrected quantum computer to execute.
Conclusion. In principle, QPE is the most direct and precise method for extracting the ground-state energy. With just 10 counting qubits, it achieves chemical accuracy with 98.5% confidence. However, the 7 million CNOT gates required for this small molecule highlight the immense hardware challenge: QPE is an algorithm for the fault-tolerant era, and even for these fault-tolerant devices it would require rigorous optimization of the problem formulation and reduction of the orbital space so to keep the circuits tractable.
Conclusion: Interpreting the Lab as a Whole¶
This lab explored four fundamentally different quantum-computing strategies for finding the ground-state energy of a molecule. Using H₂ as a common test case, we evaluated how each method trades off between quantum resources, classical post-processing, algorithmic complexity, and hardware requirements.
The Four Strategies Compared¶
The methods in this lab fall into four distinct algorithmic strategies:
- Variational (VQE, Adapt-VQE): Uses a parameterized quantum circuit and a classical optimizer. It is designed for near-term, noisy hardware but is limited by the expressiveness of the ansatz, measurement noise, and the risk of barren plateaus.
- Sampling (SQD): Uses the quantum computer as a sampler to build a subspace of relevant configurations, then diagonalizes the Hamiltonian classically. It avoids the optimization loop of VQE and is robust to noise, but its accuracy is limited by whether the samples span enough of the true ground state.
- Projection (QC-AFQMC): Uses a quantum-prepared trial state to guide a imaginary-time projection. It requires no optimization loop and uses very shallow circuits, but is mathematicaly complex and the classical Monte Carlo post-processing is demanding in computational resources.
- Phase-Estimation (QPE): Measures the accumulated phase of real-time evolution. It is the most direct and precise method, but it requires exponentially deep circuits that are impossible to run without fault-tolerant quantum error correction.
The H₂ Benchmark¶
On the H₂ molecule, all four methods successfully recovered the ground-state energy to within chemical accuracy (1.6 mHa). However, they achieved this in vastly different ways:
- VQE found the energy by optimizing a few angles, but the hardware-efficient ansatz required hundreds of circuit evaluations.
- SQD found the energy by sampling just two bitstrings and diagonalizing a 2×2 matrix.
- QC-AFQMC found the energy by filtering 4'000 walkers through imaginary time, using the quantum state as a guide.
- QPE found the energy by running a circuit with over 7 million CNOTs, extracting the phase directly.
Key Takeaways¶
The most important takeaway from this lab is that there is no single "best" quantum algorithm. The choice of method depends entirely on the hardware available and the size of the problem.
- For today's noisy, near-term hardware, VQE and SQD are the most viable options. They use shallow circuits and tolerate noise, even if they require complex classical post-processing. QC-AFQMC is also a promising hybrid approach. It pushes the heavy computational work to the classical computer, requiring only a shallow quantum circuit to prepare the trial state.
- For full fault-tolerant hardware, QPE is the ultimate goal. Its precision is rigorously controlled by the number of ancilla qubits, and it requires no classical optimization. However, as we saw with H₂, the gate counts scale so rapidly that even fault-tolerant machines will require careful chemical problem reduction (like active-space truncation) to be practical.
Beyond This Lab¶
The four strategies studied here represent the main pillars of the field, but several other approaches are actively being researched:
- Krylov Subspace Methods: Techniques that aim to combine the rigor of QPE with the shallow circuits of VQE by classically diagonalizing a subspace of time-evolved states.
- Excited-State Methods: Techniques like Variational Quantum Deflation (VQD) designed to find not just the ground state, but the excited states needed for spectroscopy.
- Advanced Subspace Methods: Techniques like Quantum-Selected CI (QSCI) and Sample-based Krylov Quantum Diagonalization (SKQD) that further optimize the interplay between quantum sampling and classical diagonalization. SKQD, in particular, combines SQD's sampling with Krylov subspaces generated by time-evolution, offering rigorous convergence guarantees with shallower circuits (especially with randomized compilation variants like SqDRIFT).
The Enduring Role of Classical Computing¶
Finally, this lab demonstrates that quantum algorithms do not replace classical chemistry; they complement it.
- R1–R3 showed that classical computations (Hartree-Fock, integral evaluation, Jordan-Wigner mapping) are essential prerequisites for any quantum algorithm.
- SQD and QC-AFQMC rely heavily on classical linear algebra and Monte Carlo methods to extract the final energy.
- QPE requires classical preprocessing to select active spaces and reduce the circuit depth to a feasible level.
The future of quantum chemistry doesn't lie in purely quantum solutions, but in hybrid quantum-classical pipelines where each processor does what it does best.
Glossary¶
| Term | Meaning in this lab |
|---|---|
| Hartree (Ha) | Atomic unit of energy. 1 Ha = 27.211 eV = 627.5 kcal/mol; The milli-hartree (mHa) is commonly used for chemical accuracy. |
| Chemical accuracy | 1 kcal/mol ≈ 1.6 mHa. The accuracy needed for computed energies to predict chemistry reliably. |
| Basis set (STO-3G) | The set of functions used to mathematically approximate molecular orbitals via linear combination. STO-3G is the smallest possible basis set, good for quick estimates: each hydrogen atom is represented by one contracted function based on 3 Gaussians (3G) mimicking a spherical (1s) orbital. |
| Molecular orbital | A one-electron wavefunction spread over the molecule. H₂ has two orbitals in STO-3G: bonding $\sigma_g$ and antibonding $\sigma_u^*$. |
| Spatial orbital | A one-electron wavefunction that depends only on the position of the electron, not its spin. In STO-3G, H₂ has two spatial orbitals ($\sigma_g$ and $\sigma_u^*$). Each spatial orbital can hold up to two electrons (one $\alpha$, one $\beta$), combining with spin to form spin orbitals. |
| Spin orbital | A molecular orbital combined with an electron spin ($\alpha$ = up, $\beta$ = down). Each spin orbital is encoded by one qubit. For H₂, 4 spin orbitals → 4 qubits. |
| Core orbital | A core orbital is close to the atom's nucleus, but it doesn't participate in bonding. In molecular simulations they are often frozen (not simulated) to reduce the number of qubits. |
| Configuration (Slater determinant) | A specific assignment of electrons to spin orbitals that respects the fermionic principle of antisymmetry. It is represented as a bitstring in the computational basis (e.g., $\|1100\rangle$), or as an orbital coefficient matrix in classical algorithms like QC-AFQMC. |
| Fock matrix | The one-electron effective Hamiltonian used in Hartree-Fock. It contains the kinetic energy, nuclear attraction, and the average electron-electron repulsion (the mean field). Diagonalizing it yields the molecular orbitals. |
| Hartree–Fock (HF) | The best description using a single configuration. Each electron moves in the average field of the others. It captures ~99% of the energy but misses correlation. |
| Correlation energy | The energy HF misses because electrons actually avoid each other instantaneously. $E_\text{corr} = E_\text{exact} - E_\text{HF}$. |
| CCSD (Coupled Cluster Singles and Doubles) | A highly accurate classical quantum chemistry method that improves on Hartree-Fock by explicitly including electron correlation (single and double excitations). In this lab, its amplitudes are used to build the quantum circuits for SQD and QC-AFQMC. |
| Full Configuration Interaction (FCI) | The exact solution of the electronic Schrödinger equation within the given basis set. It considers all possible electron configurations and finds the optimal mixture. Its cost grows exponentially with molecule size. |
| Active space | A subset of orbitals (usually the frontier valence orbitals) explicitly simulated on the quantum computer, while deep core orbitals are frozen and treated classically. |
| Hamiltonian | The operator whose eigenvalues are the allowed energies of the system; the lowest eigenvalue is the ground-state energy. |
| Molecular integrals | The numerical values ($h_{pq}$ and $(pq\|rs)$) computed by classical software (PySCF) that describe the kinetic energy, nuclear attraction, and electron-electron repulsion in a chosen basis set. They are the inputs to the Hamiltonian. |
| Second quantization | A mathematical formalism that rewrites the many-body Hamiltonian using creation ($a^\dagger$) and annihilation ($a$) operators. Instead of tracking individual electron coordinates, it tracks how electrons are created in or removed from spin orbitals. |
| Jordan–Wigner mapping | A transformation that maps fermionic creation and annihilation operators to Pauli operators (X, Y, Z) acting on qubits. It ensures that the anti-symmetry of fermions (the Pauli exclusion principle) is preserved in the qubit representation. |
| Pauli string | A product of Pauli operators (I, X, Y, Z) acting on the qubits, such as XXYY. The qubit Hamiltonian is a weighted sum of Pauli strings. |
| Trotterization | A technique to approximate the time-evolution operator $e^{-i\hat{H}t}$ by breaking the total time into small slices and applying the non-commuting Hamiltonian terms sequentially. As the number of slices increases, the error decreases. |
| Time-Independent Schrödinger Equation (TISE) | The eigenvalue equation $\hat{H}\|\psi_n\rangle = E_n\|\psi_n\rangle$. Its lowest eigenvalue is the ground-state energy. Solving the TISE is the central goal of VQE, SQD, and FCI. |
| Time-Dependent Schrödinger Equation (TDSE) | The equation describing how a state evolves in real time: $i\hbar \partial_t\|\psi\rangle = \hat{H}\|\psi\rangle$. Its solution is the unitary operator $e^{-i\hat{H}t/\hbar}$, which is the foundation of QPE. |
| Imaginary-Time Schrödinger Equation (ITSE) | The TDSE with real time replaced by imaginary time ($\tau = it$): $-\partial_\tau\|\psi\rangle = \hat{H}\|\psi\rangle$. It acts as a filter that exponentially suppresses excited states to leave the ground state, forming the foundation of QC-AFQMC. |
Terms specific to VQE (Variational Quantum Eigensolver)¶
| Term | Meaning in this lab |
|---|---|
| Ansatz | A parameterised circuit that prepares trial states $\|\psi(\theta)\rangle$. The parameters $\theta$ are tuned by the classical optimizer. |
| Expectation value | $\langle\psi\|H\|\psi\rangle$: the average energy measured in state $\psi$. VQE minimizes this quantity to find the ground state. |
| Gradient | The derivative of the energy with respect to a circuit parameter, $\partial E / \partial \theta$. It tells the classical optimizer which direction to adjust the parameters to lower the energy. In ADAPT-VQE, the operator with the largest gradient is selected at each step. |
| ADAPT-VQE | An adaptive variant of VQE that builds the ansatz one operator at a time. At each iteration, it selects the operator with the largest gradient from a pool, avoiding barren plateaus but requiring many circuit evaluations. |
| Operator pool | A pre-defined set of candidate operators (usually fermionic excitations) from which ADAPT-VQE selects the next operator to add to the ansatz. A larger pool gives more flexibility but requires more measurements at each iteration. |
Terms specific to SQD (Sample-based Quantum Diagonalization)¶
| Term | Meaning in this lab |
|---|---|
| Subspace | The small set of distinct configurations (bitstrings) sampled by the quantum computer. The Hamiltonian is projected onto this subspace and diagonalized classically. |
| Selected CI | A classical method that approximates FCI by diagonalizing the Hamiltonian only in a selected subspace of important configurations (instead of all of them). SQD is essentially a quantum-assisted version of Selected CI, where the quantum computer provides the important configurations. |
| Jastrow term | A mathematical factor that explicitly correlates electrons by making the wavefunction depend on the distances between them (or their orbital occupations). In the LUCJ ansatz, it is used to capture density-density interactions. |
| LUCJ (Local Unitary Cluster Jastrow) | A specific, shallow quantum circuit used to prepare a correlated trial state. It is built from classical CCSD amplitudes and is used in both SQD and QC-AFQMC. |
Terms specific to QC-AFQMC (Quantum-Classical Auxiliary-Field Quantum Monte Carlo)¶
| Term | Meaning in this lab |
|---|---|
| Quantum Monte Carlo (QMC) | A class of classical stochastic algorithms that use random sampling (walkers) to solve quantum many-body problems. In QC-AFQMC, it is used to simulate the imaginary-time evolution of the wavefunction. |
| Walker | A single Slater determinant that is propagated through imaginary time. The true wavefunction is approximated by the weighted average of a swarm of walkers. |
| Trial wavefunction ($\Psi_T$) | The initial state used to guide the walkers. In this lab, we compare a classical Hartree-Fock trial against a quantum LUCJ trial. |
| Auxiliary field | A fluctuating one-body field introduced by the Hubbard-Stratonovich transformation to replace the difficult two-body electron repulsion. It is sampled using random numbers. |
| Cholesky factorization | The mathematical decomposition of the 4-index electron repulsion integrals into a sum of 3-index vectors, $(pq\|rs) = \sum_\gamma L^\gamma_{pq} L^\gamma_{rs}$. This is what creates the auxiliary fields. |
| Hubbard-Stratonovich transformation | A mathematical identity that rewrites the two-body interaction (the squared Cholesky vectors) as an integral over a continuous auxiliary field. |
| Wick's theorem | A theorem used to evaluate the expectation value of many-body operators. In this lab, it is used to calculate the local energy and Green's functions from the Slater determinants. |
| Green's function ($G$) | A matrix representing the electron density and coherences of a walker relative to the trial state. It is used to calculate the local energy. |
| Local energy ($E_L$) | The energy of a single walker at a given imaginary-time step, calculated using the trial state and the Green's function. |
| Force bias ($\bar{x}$) | A shift applied to the random auxiliary field that pushes the walkers toward regions of lower energy (importance sampling). |
| Phaseless approximation | A numerical constraint that kills walkers whose phase drifts more than 90° away from the trial state. It solves the fermionic sign problem, but introduces a systematic, non-variational bias. |
| Population control (resampling) | The process of cloning walkers with large weights and killing walkers with small weights, keeping the total population constant. |
Terms specific to QPE (Quantum Phase Estimation)¶
| Term | Meaning in this lab |
|---|---|
| QFT (Quantum Fourier Transform) | The quantum analogue of the discrete Fourier transform. In QPE, the inverse QFT converts the accumulated phase on the ancilla qubits into a measurable bitstring. |
| Ancilla / Counting qubits | Extra qubits used to store the phase in QPE. The precision of QPE scales with the number of ancilla qubits ($1/2^m$). |
| Evolution time ($t$) | The duration for which the time-evolution operator $e^{-i\hat{H}t}$ is applied. In QPE, it is chosen so that the accumulated phase is strictly between 0 and 1. |
| Trotterization | The approximation of the time-evolution operator $e^{-i\hat{H}t}$ by breaking the time into small slices and applying the non-commuting Hamiltonian terms sequentially. In QPE, this is required to build the controlled-$U$ gate from native gates. |
| Energy window ($W$) | The range of energies QPE can resolve without ambiguity. It is defined by the evolution time: $W = 2\pi/t$. |
| Grid resolution | The spacing between the discrete energy values that QPE can output. It is determined by the window and the number of ancilla qubits: $W/2^m$. |