Skip to main content
KetQat

Appearance

Lesson 41 h

The variational quantum eigensolver

The variational principle, ansatz circuits, Pauli expectation values and a first VQE loop.

After this lesson you can

  • State and prove the variational principle, including when equality holds
  • Decompose a Hermitian matrix into Pauli strings with c_P = Tr(PH)/2^n and build a Hamiltonian from such a list
  • Estimate a Pauli expectation value from simulated measurements after the correct basis change, and give its standard error
  • Distinguish hardware-efficient and problem-inspired ansätze and explain why a product ansatz cannot reach an entangled ground state
  • Implement a VQE loop for the transverse-field Ising chain and verify it against exact diagonalisation and the KetQat SDK vqe-ground-state product
  • Separate what VQE guarantees (an upper bound) from what it does not (convergence, accuracy, advantage)

Read first: Quantum gates and unitary transformations, Measurement and probability, Multiple qubits and entanglement, Quantum circuits and simulation

Why a variational method

Phase estimation, from the previous module, can read off an energy to many bits, but it needs long coherent circuits with controlled time evolution. The variational quantum eigensolver (VQE) asks much less of the quantum computer. It prepares a family of states ∣ψ(θ)⟩\ket{\psi(\boldsymbol\theta)} with a short parameterised circuit, measures the energy, and lets a classical optimiser adjust θ\boldsymbol\theta to lower it. The idea was demonstrated on a photonic processor by Peruzzo and coauthors (Peruzzo et al. 2014) and analysed systematically by McClean and coauthors (McClean et al. 2016).

The price is that VQE is a heuristic. This lesson makes precise which part is a theorem (the energy is an upper bound) and which parts are not (whether the optimiser finds a good state, how many measurements it needs, and whether any of this beats classical methods).

The variational principle

Theorem. Let HH be Hermitian with smallest eigenvalue E0E_0. For every normalised state ∣ψ⟩\ket\psi,

⟨H⟩ψ=⟨ψ∣H∣ψ⟩≥E0,\expval{H}_\psi = \bra\psi H\ket\psi \ge E_0,

with equality if and only if ∣ψ⟩\ket\psi lies in the eigenspace of E0E_0.

Proof. HH has an orthonormal eigenbasis {∣ek⟩}\{\ket{e_k}\} with eigenvalues E0≤E1≤…E_0 \le E_1 \le \dots. Expand ∣ψ⟩=∑kck∣ek⟩\ket\psi = \sum_k c_k\ket{e_k} with ∑k∣ck∣2=1\sum_k\abs{c_k}^2 = 1. Then

⟨ψ∣H∣ψ⟩=∑k∣ck∣2Ek=E0+∑k∣ck∣2(Ek−E0)≥E0,\bra\psi H\ket\psi = \sum_k \abs{c_k}^2 E_k = E_0 + \sum_k \abs{c_k}^2 (E_k - E_0) \ge E_0,

since every term in the last sum is non-negative. Equality forces ck=0c_k = 0 whenever Ek>E0E_k > E_0. □\square

Two consequences matter in practice. Every energy a correct VQE reports is an upper bound on E0E_0; an energy below the exact ground energy proves a bug (or, on hardware, a biased estimator). And a low energy does not imply a good state: if the gap E1−E0E_1 - E_0 is small, a state with energy close to E0E_0 can still have a large weight on excited states.

Hamiltonians as sums of Pauli strings

A quantum computer measures in the computational basis, so we need HH in a form whose pieces are easy to measure. The 4n4^n Pauli strings P∈{I,X,Y,Z}⊗nP \in \{I,X,Y,Z\}^{\otimes n} form an orthogonal basis of 2n×2n2^n\times 2^n matrices under the trace inner product: Tr⁡(PQ)=2n\tr(P Q) = 2^n if P=QP = Q and 00 otherwise. Hence every Hermitian HH can be written as

H=∑PcP P,cP=Tr⁡(PH)2n∈R.H = \sum_P c_P\,P, \qquad c_P = \frac{\tr(P H)}{2^n} \in \R .

The coefficients are real because HH and PP are Hermitian. In this course a string such as ZXIZXI means Z⊗X⊗IZ\otimes X\otimes I with the first letter on qubit 0, the most significant bit.

Worked example. The two-qubit SWAP gate is Hermitian. Its traces against the sixteen Pauli strings are Tr⁡(SWAP)=2\tr(\mathrm{SWAP}) = 2 and Tr⁡(XX SWAP)=Tr⁡(YY SWAP)=Tr⁡(ZZ SWAP)=2\tr(XX\,\mathrm{SWAP}) = \tr(YY\,\mathrm{SWAP}) = \tr(ZZ\,\mathrm{SWAP}) = 2, and zero for the rest, so

SWAP=12 (II+XX+YY+ZZ).\mathrm{SWAP} = \tfrac12\,(II + XX + YY + ZZ).

General nn-qubit matrices need up to 4n4^n terms, but physical Hamiltonians are local and have polynomially many. Our running example is the open transverse-field Ising chain

HTFIM=−J∑i=0n−2ZiZi+1−h∑i=0n−1Xi,H_{\text{TFIM}} = -J\sum_{i=0}^{n-2} Z_iZ_{i+1} - h\sum_{i=0}^{n-1} X_i,

with 2n−12n-1 terms. For n=3n=3 and J=h=1J = h = 1 the terms are ZZIZZI, IZZIZZ, XIIXII, IXIIXI and IIXIIX, each with coefficient −1-1.

A ground energy by hand

For n=2n = 2, H=−ZZ−h(XI+IX)H = -ZZ - h(XI + IX) commutes with swapping the qubits. On the symmetric states ∣e1⟩=(∣00⟩+∣11⟩)/2\ket{e_1} = (\ket{00}+\ket{11})/\sqrt2 and ∣e2⟩=(∣01⟩+∣10⟩)/2\ket{e_2} = (\ket{01}+\ket{10})/\sqrt2 we find ZZ∣e1⟩=∣e1⟩ZZ\ket{e_1} = \ket{e_1}, ZZ∣e2⟩=−∣e2⟩ZZ\ket{e_2} = -\ket{e_2} and (XI+IX)∣e1⟩=2∣e2⟩(XI+IX)\ket{e_1} = 2\ket{e_2}, so HH acts as the 2×22\times2 matrix (−1−2h−2h1)\begin{pmatrix}-1 & -2h\\ -2h & 1\end{pmatrix} with eigenvalues ±1+4h2\pm\sqrt{1+4h^2}. The two antisymmetric states are eigenvectors with energies −1-1 and +1+1. The ground energy is therefore E0=−1+4h2E_0 = -\sqrt{1+4h^2}, which is −5≈−2.2361-\sqrt5 \approx -2.2361 at h=1h = 1. The exercise uses this closed form to test your Hamiltonian builder.

Measuring an expectation value

To estimate ⟨P⟩\expval{P} for one Pauli string, rotate each qubit so that the relevant Pauli becomes ZZ, measure in the computational basis, and multiply the ±1\pm1 eigenvalues of the measured qubits.

  • For ZZ: no rotation.
  • For XX: apply HH, since HXH=ZHXH = Z.
  • For YY: apply S†S^\dagger and then HH, since (HS†) Y (HS†)†=Z(HS^\dagger)\,Y\,(HS^\dagger)^\dagger = Z.
  • For II: ignore the qubit.

A single shot returns the eigenvalue (−1)b(-1)^{b}, where bb is the parity of the measured bits on the non-identity positions. It is a ±1\pm1 random variable with mean ⟨P⟩\expval P and variance 1−⟨P⟩21 - \expval P^2, so SS shots give an estimate with standard error (1−⟨P⟩2)/S\sqrt{(1-\expval P^2)/S}. The energy is the weighted sum E=∑PcP⟨P⟩E = \sum_P c_P\expval P; the identity term needs no measurement.

Worked example. At the VQE optimum for the three-site chain (J=h=1J = h = 1) the exact expectation values are ⟨ZZI⟩=⟨IZZ⟩=0.48344\expval{ZZI} = \expval{IZZ} = 0.48344, ⟨XII⟩=⟨IIX⟩=0.87112\expval{XII} = \expval{IIX} = 0.87112 and ⟨IXI⟩=0.78485\expval{IXI} = 0.78485. The energy is −(0.48344+0.48344)−(0.87112+0.78485+0.87112)=−3.49396-(0.48344 + 0.48344) - (0.87112 + 0.78485 + 0.87112) = -3.49396. Estimating ⟨XII⟩\expval{XII} from 1,000 shots has standard error (1−0.871122)/1000≈0.0155\sqrt{(1 - 0.87112^2)/1000} \approx 0.0155; the exercise's sampler with seed 1 returns 0.860, within one standard error. Reaching an energy error of 10−310^{-3} needs far more shots; the lesson on VQE in practice turns this into a measurement budget.

Choosing an ansatz

The ansatz is the parameterised circuit. It fixes which states the optimiser can reach, so it fixes the best possible energy before any optimisation happens.

Hardware-efficient ansätze alternate layers of single-qubit rotations with entangling gates that are native to the device, as in the experiments of Kandala and coauthors (Kandala et al. 2017). They are shallow and easy to run, but they ignore the structure of HH. The one used in this course's exercise applies RY(θ)R_Y(\theta) to every qubit, then a ladder of CNOTs, repeated, with a final rotation layer:

Quantum circuit on 3 wires (q0, q1, q2). step 1: RY(θ0) on q0; RY(θ1) on q1; RY(θ2) on q2. step 2: CNOT, control q0, target q1. step 3: CNOT, control q1, target q2. step 4: RY(θ3) on q0; RY(θ4) on q1; RY(θ5) on q2.q0q1q2RY(θ0)RY(θ1)RY(θ2)RY(θ3)RY(θ4)RY(θ5)
One layer of the hardware-efficient ansatz on three qubits: RY rotations, a CNOT ladder, then a final RY layer. Repeating the first two columns adds layers.

Because RYR_Y and CNOT are real matrices, this ansatz only produces states with real amplitudes. That is enough for the transverse-field Ising model, whose ground state can be chosen real, but it would be a hidden limitation for a Hamiltonian whose ground state needs complex phases.

Problem-inspired ansätze build the structure of the problem into the circuit: in chemistry, unitary coupled-cluster circuits generated by excitations from a reference state; for spin models, the Hamiltonian variational ansatz that alternates exponentials of the terms of HH. They respect symmetries and often need fewer parameters, at the cost of deeper circuits.

Expressiveness is not free. Too few entangling gates and the ground state is out of reach; the numbers below show this. Too many generic layers and the optimisation landscape becomes hard to navigate, which the lesson on VQE in practice discusses under barren plateaus.

The VQE loop

  1. Choose θ\boldsymbol\theta (seeded random starts, or a physically motivated guess).
  2. Prepare ∣ψ(θ)⟩\ket{\psi(\boldsymbol\theta)} and estimate E(θ)=∑PcP⟨P⟩E(\boldsymbol\theta) = \sum_P c_P\expval{P}.
  3. Let a classical optimiser propose a new θ\boldsymbol\theta; repeat until the energy stops improving.
  4. Report the lowest energy, its uncertainty, and the parameters.

In this lesson energies come from the exact state vector, so the optimiser sees a smooth, noise-free function and BFGS works well. For the three-site chain with J=h=1J = h = 1, exact diagonalisation gives E0=−3.493959E_0 = -3.493959. With the exercise's ansatz and four seeded restarts:

ansatz layers (CNOT ladders) parameters lowest energy found
0 (product state) 3 −3.162278-3.162278
1 6 −3.484435-3.484435
2 9 −3.493959-3.493959

The product ansatz stops at −10≈−3.162278-\sqrt{10} \approx -3.162278 no matter how well it is optimised: the ground state is entangled and no product state can represent it. One ladder is close but not exact; two reach E0E_0 to optimiser precision. These are numerical observations for this instance, not general laws about layer counts.

The KetQat SDK has an independent implementation with a different ansatz layout and a gradient-free optimiser (KetQat SDK). It also reports whether its ansatz can represent the ground state at all:

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=7, hamiltonian="transverse-ising",
                     qubits=3, layers=2)
r = record.result
print(round(r["energy"], 6), round(r["exact_ground_energy"], 6), r["ansatz_can_represent_ground_state"])

This prints -3.493959 -3.493959 True. With entangling=False it reports -3.162278 and False, the same product-state ceiling as above, found by a different optimiser on a different code path.

What VQE does not promise

  • No convergence guarantee. The energy landscape is non-convex; the optimiser can stall above E0E_0 even when the ansatz could reach it. Use several seeded restarts and report them all.
  • No accuracy guarantee. On hardware the energy is a statistical estimate, and noise biases it. An energy needs an error bar.
  • No proven advantage. Small instances like these are solved instantly by exact diagonalisation, and for larger ones VQE competes with very strong classical methods. Whether VQE outperforms them for any practically relevant problem is open.
  • No chemistry from approximate coefficients. The SDK's two-qubit H2 Hamiltonian is a testbed whose coefficients are, by the SDK's own provenance note, not a validated molecular Hamiltonian. Use it to test algorithms, not to report molecular energies.

Exercise: a first VQE loop

In vqe-first-loop you build Pauli matrices and Hamiltonians, decompose matrices into Pauli strings, write the ansatz, the energy, a shot-based Pauli estimator, and a BFGS-based VQE with seeded restarts. The checks test your decomposition on SWAP and on a random Hermitian matrix, the two-site closed form −1+4h2-\sqrt{1+4h^2}, the variational principle at 50 random parameter vectors, convergence to E0E_0 for the three-site chain, the sampled estimator against exact values within five standard errors, and agreement with the SDK product on the Ising model and on a custom Hamiltonian.

Common mistakes

  • Reversing the Pauli string order. If your Hamiltonian treats the first letter as the least significant qubit but your ansatz does not, every energy at fixed parameters is wrong, even though the exact ground energy (a property of the spectrum) is unchanged. Test energies of basis states, not just E0E_0.
  • Dropping the identity term. It shifts every energy by a constant; the optimum parameters do not change, so the bug hides until you compare with a reference energy.
  • Measuring YY with only a Hadamard. HYH=−YHYH = -Y, not ZZ; you need S†S^\dagger first.
  • Reporting an energy below E0E_0. With exact expectation values this is impossible; it means the Hamiltonian, the state or the expectation value is wrong.
  • Treating one optimiser run as the answer. Restart from several seeds and compare.

Summary

The variational principle guarantees that every energy expectation is an upper bound on the ground energy, with equality only in the ground eigenspace. To use it on a quantum computer, write HH as a sum of Pauli strings with cP=Tr⁡(PH)/2nc_P = \tr(PH)/2^n, estimate each ⟨P⟩\expval{P} by rotating into its eigenbasis and averaging ±1\pm1 outcomes, and let a classical optimiser lower the energy of a parameterised ansatz. The ansatz decides what is reachable: a product ansatz cannot capture an entangled ground state, while two entangling layers suffice for the three-site Ising chain. Everything beyond the upper bound, including convergence, measurement cost and any advantage over classical methods, has to be checked rather than assumed. The lesson on VQE in practice continues with measurement budgets, gradients and debugging; a later lesson asks what quantum speed-ups are actually known.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

A first VQE loop for the transverse-field Ising chain

intermediate · about 1 h · needs numpy, scipy, pytest, ketqat[algorithms]

Write every piece of a small variational quantum eigensolver yourself: Pauli strings, Hamiltonians, a Pauli decomposition, a hardware-efficient ansatz, a shot-based expectation estimator and the optimisation loop. Then check it against exact diagonalisation and the KetQat SDK.

Conventions: the first letter of a Pauli string acts on qubit 0, the most significant bit, so "ZXI" is kron(Z, X, I). A Hamiltonian is a list of (coefficient, label) pairs. RY(θ)=e−iθY/2R_Y(\theta) = e^{-i\theta Y/2}.

Functions to implement in starter.py

Function Contract
pauli_string_matrix(label) Kronecker product of the letters, in order
hamiltonian_matrix(terms) ∑iciPi\sum_i c_i P_i as a dense matrix
pauli_decompose(H) {label: c_P} with cP=Tr⁡(PH)/2nc_P = \tr(PH)/2^n, omitting ∣cP∣<10−12\abs{c_P} < 10^{-12}
tfim_terms(n, J=1.0, h=1.0) the open chain −J∑ZiZi+1−h∑Xi-J\sum Z_iZ_{i+1} - h\sum X_i
exact_ground_energy(terms) smallest eigenvalue by dense diagonalisation
ansatz_state(theta, n, layers) layers blocks of [RYR_Y on every qubit, CX(0→1), CX(1→2), …], then a final RYR_Y layer; n(layers+1)n(\text{layers}+1) parameters, qubit by qubit
energy(theta, terms, n, layers) ⟨ψ(θ)∣H∣ψ(θ)⟩\bra{\psi(\theta)}H\ket{\psi(\theta)}
estimate_pauli_expectation(state, label, shots, rng) rotate (H for X, S†S^\dagger then H for Y), sample with rng, average the ±1\pm1 parity
run_vqe(terms, n, layers, restarts=5, seed=0) BFGS (scipy.optimize.minimize) from seeded uniform starts in [0,2π)[0, 2\pi); return (best energy, best parameters)

The private helpers _ry, _apply_one and _apply_cx are provided.

What the checks verify

  • Pauli string ordering against explicit Kronecker products.
  • Your decomposition of SWAP is 12(II+XX+YY+ZZ)\tfrac12(II + XX + YY + ZZ), and decomposing then rebuilding a seeded random Hermitian matrix returns it.
  • The two-site chain has E0=−1+4h2E_0 = -\sqrt{1 + 4h^2} (closed form derived in the lesson).
  • tfim_terms builds the same matrix as an explicit sum of Kronecker products.
  • The ansatz is normalised, real, and gives ∣000⟩\ket{000} at zero angles.
  • The variational principle holds at 50 seeded random parameter vectors.
  • run_vqe reaches E0E_0 of the three-site chain (J=h=1J = h = 1) to 10−610^{-6} with two layers.
  • Your sampled estimator lies within five standard errors of the exact value for four strings.
  • Your exact ground energy matches the SDK product [email protected] on its own transverse-Ising model, and your VQE matches the SDK's energy and exact energy on a custom two-qubit Hamiltonian (skipped if the SDK is not installed).

Run the checks

python -m pytest test_exercise.py

Going further

Run run_vqe with layers=0, 1, 2 and compare with the table in the lesson. Then change the field to h=0.2h = 0.2 and to h=3h = 3: how many layers do you need now, and why might the answer depend on hh?

Terminal
python -m pip install numpy scipy pytest "ketqat[algorithms]"

starter.py

Python
"""Starter: a first variational quantum eigensolver with NumPy and SciPy.

Conventions: a Pauli string such as "ZXI" acts with its first letter on qubit 0,
and qubit 0 is the most significant bit of the basis index, so "ZXI" is the matrix
kron(Z, X, I). A Hamiltonian is a list of (coefficient, Pauli string) pairs.
"""

import itertools
import math

import numpy as np
from scipy.optimize import minimize

PAULI = {
    "I": np.eye(2, dtype=complex),
    "X": np.array([[0, 1], [1, 0]], dtype=complex),
    "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
    "Z": np.array([[1, 0], [0, -1]], dtype=complex),
}


def pauli_string_matrix(label):
    """Dense matrix of a Pauli string, first letter on qubit 0 (most significant)."""
    raise NotImplementedError


def hamiltonian_matrix(terms):
    """Sum of coefficient * Pauli string over (coefficient, label) pairs."""
    raise NotImplementedError


def pauli_decompose(H):
    """Pauli coefficients c_P = Tr(P H) / 2^n of a Hermitian matrix, as {label: real coefficient}.

    Terms with |c_P| < 1e-12 are omitted.
    """
    raise NotImplementedError


def tfim_terms(n, J=1.0, h=1.0):
    """Open-chain transverse-field Ising model H = -J sum Z_i Z_{i+1} - h sum X_i."""
    raise NotImplementedError


def exact_ground_energy(terms):
    """Lowest eigenvalue of the Hamiltonian by dense diagonalisation."""
    raise NotImplementedError


def _ry(theta):
    c, s = math.cos(theta / 2), math.sin(theta / 2)
    return np.array([[c, -s], [s, c]], dtype=complex)


def _apply_one(state, n, q, gate):
    psi = np.moveaxis(state.reshape([2] * n), q, 0)
    psi = np.tensordot(gate, psi, axes=(1, 0))
    return np.moveaxis(psi, 0, q).reshape(-1)


def _apply_cx(state, n, control, target):
    psi = state.reshape([2] * n).copy()
    index = [slice(None)] * n
    index[control] = 1
    sub = psi[tuple(index)]
    t_axis = target if target < control else target - 1
    psi[tuple(index)] = np.flip(sub, axis=t_axis)
    return psi.reshape(-1)


def ansatz_state(theta, n, layers):
    """Hardware-efficient ansatz on |0...0>.

    `layers` blocks of [RY(theta) on every qubit, then CX(0->1), CX(1->2), ..., CX(n-2->n-1)],
    followed by a final RY layer. Parameters are consumed qubit by qubit, block by block:
    n * (layers + 1) of them in total.
    """
    raise NotImplementedError


def energy(theta, terms, n, layers):
    """<psi(theta)| H |psi(theta)> computed from the state vector."""
    raise NotImplementedError


def estimate_pauli_expectation(state, label, shots, rng):
    """Estimate <P> from `shots` simulated measurements.

    Rotate each qubit into the eigenbasis of its letter (H for X; S^dagger then H for Y),
    sample computational-basis outcomes from the rotated state with `rng`, and average
    the product of the +-1 eigenvalues over the qubits where the letter is not I.
    """
    raise NotImplementedError


def run_vqe(terms, n, layers, restarts=5, seed=0):
    """Minimise the energy with BFGS from `restarts` seeded random starts in [0, 2 pi).

    Returns (best_energy, best_parameters).
    """
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest

X = np.array([[0, 1], [1, 0]])
Z = np.diag([1, -1])
I2 = np.eye(2)


def test_pauli_string_order():
    # First letter acts on qubit 0, the most significant bit.
    assert np.allclose(target.pauli_string_matrix("ZI"), np.diag([1, 1, -1, -1]))
    assert np.allclose(target.pauli_string_matrix("IZ"), np.diag([1, -1, 1, -1]))
    assert np.allclose(target.pauli_string_matrix("XZ"), np.kron(X, Z))


def test_decomposition_of_swap_is_known_in_closed_form():
    swap = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])
    coeffs = target.pauli_decompose(swap)
    assert set(coeffs) == {"II", "XX", "YY", "ZZ"}
    assert all(np.isclose(v, 0.5) for v in coeffs.values())


def test_decomposition_round_trips_a_random_hermitian_matrix():
    rng = np.random.default_rng(3)
    a = rng.normal(size=(8, 8)) + 1j * rng.normal(size=(8, 8))
    H = a + a.conj().T
    coeffs = target.pauli_decompose(H)
    rebuilt = target.hamiltonian_matrix([(c, p) for p, c in coeffs.items()])
    assert np.allclose(rebuilt, H)


def test_two_site_ising_ground_energy_is_analytic():
    # H = -Z Z - h (X I + I X): in the sector spanned by |00>+|11> and |01>+|10> the
    # lowest eigenvalue is -sqrt(1 + 4 h^2).
    for h in (0.3, 1.0, 2.0):
        e0 = target.exact_ground_energy(target.tfim_terms(2, 1.0, h))
        assert np.isclose(e0, -math.sqrt(1 + 4 * h**2))


def test_tfim_terms_build_the_model_from_its_definition():
    H = target.hamiltonian_matrix(target.tfim_terms(3, 0.7, 1.3))
    ZZ1 = np.kron(np.kron(Z, Z), I2)
    ZZ2 = np.kron(I2, np.kron(Z, Z))
    Xs = np.kron(np.kron(X, I2), I2) + np.kron(np.kron(I2, X), I2) + np.kron(np.kron(I2, I2), X)
    assert np.allclose(H, -0.7 * (ZZ1 + ZZ2) - 1.3 * Xs)


def test_ansatz_is_normalised_and_real():
    rng = np.random.default_rng(0)
    psi = target.ansatz_state(rng.uniform(0, 6.3, size=9), 3, 2)
    assert np.isclose(np.linalg.norm(psi), 1)
    assert np.allclose(psi.imag, 0)


def test_ansatz_with_zero_angles_is_the_all_zero_state():
    psi = target.ansatz_state(np.zeros(6), 3, 1)
    assert np.isclose(abs(psi[0]), 1)


def test_variational_principle_holds_at_random_parameters():
    terms = target.tfim_terms(3, 1.0, 1.0)
    e0 = target.exact_ground_energy(terms)
    rng = np.random.default_rng(1)
    for _ in range(50):
        theta = rng.uniform(0, 2 * math.pi, size=9)
        assert target.energy(theta, terms, 3, 2) >= e0 - 1e-12


def test_vqe_reaches_the_exact_ground_energy():
    terms = target.tfim_terms(3, 1.0, 1.0)
    e0 = target.exact_ground_energy(terms)
    e, theta = target.run_vqe(terms, 3, layers=2, restarts=4, seed=0)
    assert e >= e0 - 1e-12
    assert e - e0 < 1e-6


def test_sampled_expectation_agrees_with_the_exact_value():
    rng = np.random.default_rng(2024)
    theta = np.random.default_rng(9).uniform(0, 2 * math.pi, size=9)
    psi = target.ansatz_state(theta, 3, 2)
    shots = 20000
    for label in ("ZZI", "XII", "IXX", "YZY"):
        P = target.pauli_string_matrix(label)
        exact = float(np.vdot(psi, P @ psi).real)
        est = target.estimate_pauli_expectation(psi, label, shots, rng)
        sigma = math.sqrt(max(1 - exact**2, 1e-12) / shots)
        assert abs(est - exact) < 5 * sigma + 1e-12, (label, est, exact)


@pytest.fixture
def ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


def test_ground_energy_agrees_with_the_sdk_ising_model(ketqat_home):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    record = catalog.run("[email protected]", seed=7, hamiltonian="transverse-ising", qubits=3,
                         ising_coupling=1.0, ising_field=1.0, layers=2, restarts=4)
    assert record.status == "succeeded"
    assert np.isclose(target.exact_ground_energy(target.tfim_terms(3, 1.0, 1.0)), record.result["exact_ground_energy"], atol=1e-9)


def test_vqe_agrees_with_the_sdk_on_a_custom_hamiltonian(ketqat_home):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    terms = [(0.5, "ZZ"), (-0.8, "XI"), (-0.3, "IX"), (0.2, "XX")]
    record = catalog.run("[email protected]", seed=7, hamiltonian="custom", qubits=2,
                         terms=[{"coefficient": c, "pauli": p} for c, p in terms], layers=2, restarts=6)
    assert record.status == "succeeded"
    ours, _ = target.run_vqe(terms, 2, layers=2, restarts=4, seed=1)
    assert np.isclose(ours, record.result["exact_ground_energy"], atol=1e-6)
    assert np.isclose(ours, record.result["energy"], atol=1e-6)

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Your VQE on a 4-qubit Hamiltonian reports an energy of −5.21-5.21, computed from the exact state vector. Exact diagonalisation gives E0=−5.18E_0 = -5.18. What do you conclude?

    1 pt
  2. Decompose H=(311−1)H = \begin{pmatrix} 3 & 1 \\ 1 & -1 \end{pmatrix} into Pauli matrices, H=cII+cXX+cYY+cZZH = c_I I + c_X X + c_Y Y + c_Z Z. What is cZc_Z?

    1 pt
  3. Which single-qubit rotation must you apply before a computational-basis measurement to estimate ⟨Y⟩\expval{Y}?

    1 pt
  4. Run exact_ground_energy(tfim_terms(3, 1.0, 1.0)) from your vqe-first-loop solution. What is the ground energy of the open three-site transverse-field Ising chain with J=h=1J = h = 1? (Deterministic.)

    1 pt

    Computed by running exercise “vqe-first-loop” on your computer.

  5. Run run_vqe(tfim_terms(3), 3, layers=1, restarts=4, seed=0) and enter the energy. (The seed fixes the starting points; BFGS is deterministic from there.)

    1 pt

    Computed by running exercise “vqe-first-loop” on your computer.

  6. A product ansatz (no entangling gates) reaches −3.162278-3.162278 on the same chain, however long it is optimised. Which statements are correct?

    1 pt

    Select all that apply.

  7. Which claim about VQE is a theorem?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Alberto Peruzzo et al. (2014). A variational eigenvalue solver on a photonic quantum processor. Nature Communications 5, 4213. doi:10.1038/ncomms5213
  2. Jarrod R. McClean et al. (2016). The theory of variational hybrid quantum-classical algorithms. New Journal of Physics 18, 023023. doi:10.1088/1367-2630/18/2/023023
  3. Abhinav Kandala et al. (2017). Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets. Nature 549, 242-246. doi:10.1038/nature23879
  4. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  5. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.