Skip to main content
KetQat

Appearance

Lesson 61 h 15 min

QAOA for MaxCut

Formulating MaxCut, the QAOA ansatz, parameter landscapes and comparison with classical heuristics.

After this lesson you can

  • Write MaxCut as a diagonal Ising cost Hamiltonian and compile its QAOA layers into gates
  • Use the symmetries of the QAOA landscape to restrict the parameter search
  • Evaluate the p = 1 QAOA expectation in closed form for any graph and verify it against simulation
  • Explore the p = 1 and p = 2 landscapes with grid search and local optimisation, and report instance approximation ratios correctly
  • Compare QAOA with brute force, random assignment and 1-flip local search, and state the Goemans–Williamson guarantee and the known hardness results precisely
  • Distinguish an approximation ratio measured on one instance from a worst-case guarantee

Read first: The variational quantum eigensolver, VQE in practice, Classical versus quantum complexity

MaxCut and what "approximation ratio" means

Given a graph G=(V,E)G = (V, E) with nn vertices, a cut assigns each vertex to one of two sides, and its value is the number of edges whose endpoints lie on different sides. MaxCut asks for the largest cut value, Cmax⁡C_{\max}. Deciding whether a cut of a given size exists is NP-complete, so no polynomial-time exact algorithm is expected, and practical work focuses on approximation.

Two different numbers are both called an approximation ratio, and mixing them up is the most common error in QAOA claims.

  • Instance ratio. For one graph and one algorithm, the (expected) value found divided by Cmax⁡C_{\max}. Measuring it requires knowing Cmax⁡C_{\max}, which for small graphs means brute force.
  • Worst-case guarantee. A number α\alpha such that the algorithm achieves at least α Cmax⁡\alpha\,C_{\max} (in expectation) on every graph. This is a theorem about an algorithm.

A ratio of 0.94 on a six-vertex graph says nothing about a guarantee.

MaxCut as an Ising Hamiltonian

Encode an assignment as a bit string z∈{0,1}nz \in \{0,1\}^n. An edge (u,v)(u, v) is cut when zu≠zvz_u \ne z_v. With Zu∣z⟩=(−1)zu∣z⟩Z_u\ket z = (-1)^{z_u}\ket z, the operator (1−ZuZv)/2(1 - Z_uZ_v)/2 has eigenvalue 1 on cut edges and 0 otherwise, so

C=∑(u,v)∈E1−ZuZv2,C∣z⟩=cut(z)∣z⟩.C = \sum_{(u,v)\in E} \frac{1 - Z_uZ_v}{2}, \qquad C\ket z = \mathrm{cut}(z)\ket z .

CC is diagonal: every computational basis state is an eigenstate, and its eigenvalue is the cut value. MaxCut is the problem of finding the largest eigenvalue of CC, or equivalently the ground state of the Ising Hamiltonian ∑(u,v)ZuZv\sum_{(u,v)} Z_uZ_v, an antiferromagnet on GG.

In this lesson's exercise, vertex vv is bit vv of the integer zz counted from the least significant end, so vertex 0 is the rightmost character of a bit string. That is the opposite of the course's usual qubit order, chosen so that assignments can be compared with the KetQat SDK's qaoa-maxcut product directly; for a cut value only consistency matters.

The QAOA ansatz

The Quantum Approximate Optimization Algorithm of Farhi, Goldstone and Gutmann prepares

∣γ,β⟩=e−iβpBe−iγpC⋯e−iβ1Be−iγ1C∣+⟩⊗n,B=∑vXv,\ket{\boldsymbol\gamma,\boldsymbol\beta} = e^{-i\beta_pB}e^{-i\gamma_pC}\cdots e^{-i\beta_1B}e^{-i\gamma_1C}\ket{+}^{\otimes n}, \qquad B = \sum_v X_v ,

with 2p2p angles, and chooses them to maximise Fp(γ,β)=⟨γ,β∣C∣γ,β⟩F_p(\boldsymbol\gamma,\boldsymbol\beta) = \bra{\boldsymbol\gamma,\boldsymbol\beta}C\ket{\boldsymbol\gamma,\boldsymbol\beta} (Farhi, Goldstone and Gutmann 2014). Measuring the final state gives assignments whose average cut is FpF_p. The paper shows that the best value of FpF_p cannot decrease with pp and approaches Cmax⁡C_{\max} as p→∞p\to\infty, through a connection with adiabatic evolution; how fast it does so is instance-dependent.

Compiling a layer. The cost layer factorises over edges, since all terms commute: e−iγ(1−ZuZv)/2=e−iγ/2 eiγZuZv/2e^{-i\gamma(1 - Z_uZ_v)/2} = e^{-i\gamma/2}\,e^{i\gamma Z_uZ_v/2}. Because CXu→v (I⊗RZ(ϕ)) CXu→v=e−iϕZuZv/2\mathrm{CX}_{u\to v}\,(I\otimes R_Z(\phi))\,\mathrm{CX}_{u\to v} = e^{-i\phi Z_uZ_v/2}, each edge needs two CNOTs and one RZ(−γ)R_Z(-\gamma). The mixer is e−iβXv=RX(2β)e^{-i\beta X_v} = R_X(2\beta) on every vertex. One layer on a triangle:

Quantum circuit on 3 wires (a, b, c). step 1: H on a; H on b; H on c. step 2: CNOT, control a, target b. step 3: RZ(-γ) on b. step 4: CNOT, control a, target b. step 5: CNOT, control b, target c. step 6: RZ(-γ) on c. step 7: CNOT, control b, target c. step 8: CNOT, control a, target c. step 9: RZ(-γ) on c. step 10: CNOT, control a, target c. step 11: RX(2β) on a; RX(2β) on b; RX(2β) on c.abcHHHRZ(-γ)RZ(-γ)RZ(-γ)RX(2β)RX(2β)RX(2β)
One QAOA layer (p = 1) for MaxCut on a triangle with vertices a, b, c: Hadamards prepare |+⟩, each edge contributes CX–RZ(−γ)–CX, and RX(2β) on every qubit is the mixer.

So one layer costs 2∣E∣2\abs E CNOTs plus ∣E∣+n\abs E + n rotations before routing on real hardware.

Symmetries of the landscape

The search space is smaller than it looks. Because cut values are integers, e−i(γ+2π)C=e−iγCe^{-i(\gamma+2\pi)C} = e^{-i\gamma C}, so each γ\gamma has period 2π2\pi. Because e−i(β+π/2)B=(−i)nX⊗ne−iβBe^{-i(\beta+\pi/2)B} = (-i)^nX^{\otimes n}e^{-i\beta B} and X⊗nX^{\otimes n} (flipping every vertex) commutes with CC and fixes ∣+⟩⊗n\ket{+}^{\otimes n}, each β\beta has period π/2\pi/2 for MaxCut. And because CC and BB are real, (γ,β)→(−γ,−β)(\boldsymbol\gamma,\boldsymbol\beta)\to(-\boldsymbol\gamma,-\boldsymbol\beta) conjugates the state and leaves FpF_p unchanged. The exercise checks all three on the prism graph below: at (γ,β)=(1.1,0.3)(\gamma,\beta) = (1.1, 0.3), (1.1,0.3+π/2)(1.1, 0.3+\pi/2), (−1.1,−0.3)(-1.1,-0.3) and (1.1+2π,0.3)(1.1+2\pi, 0.3) the expectation is 5.1127655.112765 every time. The SDK's grid uses β∈[0,π)\beta\in[0,\pi) and γ∈[0,2π)\gamma\in[0,2\pi), which covers every distinct point twice over in β\beta; that costs time, not correctness.

The p = 1 expectation in closed form

At depth one, ⟨C⟩\expval{C} is a sum of edge terms, and each edge term depends only on the edge's neighbourhood, because gates far from the edge cancel in U†(ZuZv)UU^\dagger(Z_uZ_v)U. Wang, Hadfield, Jiang and Rieffel derived the closed form for an arbitrary graph (Wang et al. 2018). With d=deg⁡(u)−1d = \deg(u) - 1, e=deg⁡(v)−1e = \deg(v) - 1 and ff the number of triangles containing the edge, in the conventions above,

⟨Cuv⟩=12+14sin⁡(4β)sin⁡γ (cos⁡dγ+cos⁡eγ)−14sin⁡2(2β) cos⁡ d+e−2fγ (1−cos⁡f2γ).\expval{C_{uv}} = \frac12 + \frac14\sin(4\beta)\sin\gamma\,\big(\cos^d\gamma + \cos^e\gamma\big) - \frac14\sin^2(2\beta)\,\cos^{\,d+e-2f}\gamma\,\big(1 - \cos^f 2\gamma\big).

Conventions matter here: papers differ in the sign of γ\gamma, in whether the mixer is e−iβBe^{-i\beta B} or e−2iβBe^{-2i\beta B}, and in whether CC counts cut or uncut edges. Before trusting any closed form, compare it with a simulation at random angles; the exercise does this on graphs with and without triangles, and the agreement is at the level of 10−1510^{-15}.

Triangle-free DD-regular graphs. With f=0f = 0 and d=e=D−1d = e = D - 1 the formula reduces to 12+12sin⁡(4β)sin⁡γcos⁡D−1γ\tfrac12 + \tfrac12\sin(4\beta)\sin\gamma\cos^{D-1}\gamma, the case treated by Farhi, Goldstone and Gutmann. It is maximised at β=π/8\beta = \pi/8 and tan⁡γ=1/D−1\tan\gamma = 1/\sqrt{D-1}.

  • For D=2D = 2 (rings), the maximum of sin⁡γcos⁡γ\sin\gamma\cos\gamma is 1/21/2, so each edge is cut with probability 3/43/4. For an even ring every edge can be cut, so the instance ratio is exactly 3/43/4. For the six-vertex ring, F1=4.5F_1 = 4.5 against Cmax⁡=6C_{\max} = 6.
  • For D=3D = 3, the maximum of sin⁡γcos⁡2γ\sin\gamma\cos^2\gamma is 2/(33)2/(3\sqrt3), so each edge is cut with probability 12+1/(33)≈0.69245\tfrac12 + 1/(3\sqrt3) \approx 0.69245. For a bipartite 3-regular graph such as the three-dimensional cube (Cmax⁡=∣E∣=12C_{\max} = \abs E = 12) the ratio is therefore 0.692450.69245. Farhi, Goldstone and Gutmann proved that on every 3-regular graph QAOA at p=1p = 1 achieves at least 0.69240.6924 times the optimal cut: that is a worst-case guarantee, and the cube shows it is essentially tight.

A worked example: the prism graph

The triangular prism has six vertices, two triangles {0,1,2}\{0,1,2\} and {3,4,5}\{3,4,5\}, and three rungs (0,3)(0,3), (1,4)(1,4), (2,5)(2,5): nine edges, 3-regular, but not triangle-free. Each triangle can have at most two of its three edges cut, so Cmax⁡≤2+2+3=7C_{\max} \le 2 + 2 + 3 = 7, and brute force confirms Cmax⁡=7C_{\max} = 7. All the numbers below were computed with the exercise's reference solution.

method expected or found cut ratio to Cmax⁡=7C_{\max} = 7
uniformly random assignment 4.5 0.643
QAOA p=1p=1, 24×2424\times24 grid 5.90625 0.844
QAOA p=1p=1, local optimisation of the closed form 5.93922 0.848
QAOA p=2p=2, 10410^4-point grid 6.35999 0.909
QAOA p=2p=2, BFGS from 40 seeded random starts 6.60295 0.943
1-flip local search, one random start 7 1

At the continuous p=1p = 1 optimum, (γ,β)≈(0.5703,0.3482)(\gamma,\beta) \approx (0.5703, 0.3482), measuring the QAOA state returns an optimal cut with probability 0.40080.4008, so a handful of shots finds the optimum on this instance. The coarse landscape at p=1p = 1, from the closed form (rows γ\gamma, columns β\beta):

γ\gamma \ β\beta 0 π/16\pi/16 π/8\pi/8 3π/163\pi/16 π/4\pi/4
0 4.500 4.500 4.500 4.500 4.500
π/8\pi/8 4.500 5.484 5.782 5.219 4.125
π/4\pi/4 4.500 5.515 5.716 4.985 3.750
3π/83\pi/8 4.500 4.876 4.921 4.610 4.125
π/2\pi/2 4.500 4.500 4.500 4.500 4.500

The row γ=0\gamma = 0 is flat at ∣E∣/2\abs E/2 because ∣+⟩⊗n\ket{+}^{\otimes n} is an eigenstate of the mixer, and the column β=0\beta = 0 is flat because without mixing the cost layer only adds phases to basis states. The γ=π/2\gamma = \pi/2 row is also flat here because cos⁡γ=0\cos\gamma = 0 removes every term of the closed form for the prism's edges; that is not true for every graph (on a lone triangle it fails). These flat directions are why random initialisation can stall, and why grid search, although exponential in pp, is the honest choice at p≤2p \le 2: at its resolution it is exhaustive, so the reported value is a lower bound on what QAOA can reach, not where an optimiser happened to stop. The two p=2p = 2 rows of the table show the price of resolution: the 10×1010\times10 grid per layer misses about 0.24 of expected cut that local optimisation finds.

Classical baselines, stated precisely

A fair comparison needs the right classical numbers.

  • Random assignment cuts each edge with probability 1/21/2: expected value ∣E∣/2≥Cmax⁡/2\abs E/2 \ge C_{\max}/2.
  • 1-flip local search moves single vertices while that increases the cut. At a local optimum every vertex has at least half of its edges cut (otherwise flipping it would help), and summing over vertices gives a cut of at least ∣E∣/2≥Cmax⁡/2\abs E/2 \ge C_{\max}/2. That is a deterministic guarantee of 1/21/2, and on small graphs local search with a few restarts is usually optimal, as on the prism.
  • Goemans–Williamson. Semidefinite programming followed by random-hyperplane rounding achieves an expected cut of at least αGWCmax⁡\alpha_{GW}C_{\max} with αGW≈0.87856\alpha_{GW} \approx 0.87856 on every graph (Goemans and Williamson 1995). This is a worst-case guarantee.
  • Hardness. Approximating MaxCut better than 16/17≈0.94116/17 \approx 0.941 is NP-hard (Håstad 2001). If the Unique Games Conjecture holds, beating αGW\alpha_{GW} by any constant is NP-hard (Khot, Kindler, Mossel and O'Donnell 2007).

Against these, the proven worst-case guarantee for QAOA at p=1p = 1 on 3-regular graphs is 0.69240.6924, below Goemans–Williamson. There are also proven limitations at low depth: Bravyi, Kliesch, Koenig and Tang showed that on families of regular bipartite graphs, QAOA whose depth grows more slowly than logarithmically in the number of vertices has approximation ratios bounded away from 1, on graphs whose optimal cut a classical algorithm finds trivially (Bravyi et al. 2020). Whether QAOA at larger depth beats the best classical algorithms on instances of practical interest is an open, empirical question. A correct statement of the prism result is: "on this six-vertex instance, p=2p = 2 QAOA with optimised angles has an expected cut of 6.606.60, ratio 0.9430.943; local search finds the optimum with one restart." It is not evidence of a quantum advantage.

Using the SDK product

The SDK runs the same grid search with its own simulator and reports the closed form beside the simulation where it applies (KetQat SDK):

from ketqat_runner import catalog

edges = ["0-1", "1-2", "2-0", "3-4", "4-5", "5-3", "0-3", "1-4", "2-5"]
record = catalog.run("[email protected]", seed=7, graph="custom", n_vertices=6, edges=edges,
                     layers=1, grid=24, shots=1000)
r = record.result
print(r["max_cut"], round(r["best_expectation"], 6), round(r["approximation_ratio"], 6),
      r["analytic_p1_applies"])

This prints 7 5.90625 0.84375 False: the same grid optimum as the table. The SDK evaluates its closed form only for triangle-free regular graphs, where the Farhi–Goldstone–Gutmann formula holds, so for the prism it reports that the formula does not apply; your exercise implements the general formula.

Exercise: a QAOA study

In qaoa-maxcut-study you implement cut values, the QAOA state and expectation, the general p=1p = 1 closed form, grid search, brute force and 1-flip local search. The checks compare the closed form with simulation on five graphs (including K4K_4, the prism and a seeded random graph with triangles), recover the ring's 3/43/4 and the cube's 0.692450.69245 from the formula, check that local search returns a genuine local optimum with at least ∣E∣/2\abs E/2, and compare your grid optimum and brute-force optimum with the SDK product on three instances, one at p=2p = 2.

Common mistakes

  • Calling an instance ratio a guarantee. A ratio measured on one small graph is an observation.
  • Comparing with random guessing only. The baselines that matter are local search, Goemans–Williamson and specialised heuristics.
  • Trusting a closed form without checking its conventions. Sign of γ\gamma, factor 2 in the mixer, and cut versus uncut edges all change the formula.
  • Searching β\beta over [0,2π)[0, 2\pi). For MaxCut the period is π/2\pi/2; extra range only wastes evaluations.
  • Reporting the best sampled cut as QAOA's performance without the number of shots. With enough samples even random assignments find the optimum of a small graph.

Summary

MaxCut becomes the diagonal Hamiltonian C=∑(u,v)(1−ZuZv)/2C = \sum_{(u,v)}(1 - Z_uZ_v)/2, and QAOA alternates e−iγCe^{-i\gamma C} (two CNOTs and an RZR_Z per edge) with the mixer e−iβ∑Xe^{-i\beta\sum X}. The landscape has period 2π2\pi in γ\gamma, π/2\pi/2 in β\beta and a reflection symmetry. At p=1p = 1 the expectation has a closed form for any graph, which gives exactly 3/43/4 on even rings and 0.692450.69245 on bipartite 3-regular graphs, consistent with the proven 0.69240.6924 guarantee on 3-regular graphs. On the prism graph, optimised p=2p = 2 QAOA reaches an instance ratio of 0.9430.943, while 1-flip local search solves the instance outright. Goemans–Williamson guarantees 0.878560.87856 on every graph, and beating it is NP-hard under the Unique Games Conjecture, so any QAOA advantage claim must be made against that bar, on instances large enough to matter. The next lesson applies the same scrutiny to quantum machine learning.

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.

QAOA for MaxCut against closed forms and classical baselines

advanced · about 1 h 30 min · needs numpy, pytest, ketqat[algorithms]

Implement QAOA for MaxCut as a statevector simulation, check it against the general p=1p = 1 closed form, search its landscape, and compare it honestly with brute force and 1-flip local search.

Conventions (chosen to match the SDK's qaoa-maxcut product, and opposite to the course's usual qubit order): an assignment is an integer zz, vertex vv is on side (z >> v) & 1, so vertex 0 is the least significant bit. C(z)C(z) counts cut edges; the cost layer is e−iγCe^{-i\gamma C} and the mixer e−iβ∑vXve^{-i\beta\sum_v X_v}.

Functions to implement in starter.py

Function Contract
cut_values(n, edges) array of C(z)C(z) for z=0..2n−1z = 0..2^n-1
qaoa_state(n, edges, gammas, betas) ∏le−iβlBe−iγlC∣+⟩⊗n\prod_l e^{-i\beta_l B}e^{-i\gamma_l C}\ket{+}^{\otimes n}
qaoa_expectation(n, edges, gammas, betas) ⟨C⟩\expval{C} in that state
p1_edge_expectation(gamma, beta, degree_u, degree_v, triangles) the Wang–Hadfield–Jiang–Rieffel closed form for one edge (see the lesson)
p1_expectation_analytic(n, edges, gamma, beta) sum of the edge terms
grid_search(n, edges, layers, grid) exhaustive grid βi=πi/grid\beta_i = \pi i/\text{grid}, γi=2πi/grid\gamma_i = 2\pi i/\text{grid} per layer, β\beta the outer loop; return (best, gammas, betas) for the first strict maximum
brute_force_maxcut(n, edges) (max cut, sorted optimal assignments)
local_search_maxcut(n, edges, restarts, seed) 1-flip hill climbing (sweep v=0..n−1v = 0..n-1, flip when it increases the cut, until a sweep makes no flip) from seeded random starts; return (best cut, its assignment)

What the checks verify

  • Cut values and optima on a triangle, the 6-ring, K4K_4, the prism and the 3-cube.
  • The state is normalised and gives ∣E∣/2\abs E/2 at zero angles.
  • The closed form equals the simulation at 15 random angle pairs on five graphs, with and without triangles (independent methods).
  • From the closed form: the even ring reaches ratio 3/43/4 and a triangle-free 3-regular edge reaches 1/2+1/(33)1/2 + 1/(3\sqrt3).
  • Grid search on the 6-ring finds ⟨C⟩=4.5\expval{C} = 4.5.
  • Local search returns a true local optimum (no single flip improves it) with at least ∣E∣/2\abs E/2 cut edges, and with 20 restarts solves the small instances.
  • Your grid optimum and brute-force optimum equal the SDK product's best_expectation and max_cut for the 6-ring at p=1p = 1 and p=2p = 2 and for the prism (skipped if the SDK is not installed).

Run the checks

python -m pytest test_exercise.py

Going further

Start BFGS from the best p=1p = 1 grid point, then from 40 seeded random points at p=2p = 2, and reproduce the prism table in the lesson. How many shots from the optimised p=2p = 2 state do you need before the best sampled cut equals 7 with probability 0.99? Compare with random assignments.

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

starter.py

Python
"""Starter: QAOA for MaxCut, analytic p=1 expectation, and classical baselines.

Conventions (chosen to match the KetQat SDK's qaoa-maxcut product):
- An assignment is an integer z; vertex v is on side (z >> v) & 1, so vertex 0 is the
  LEAST significant bit (the rightmost character of a bit string). This is the opposite
  of the course's qubit-0-most-significant convention; it is used here so that
  assignments can be compared with the SDK directly.
- C(z) is the number of cut edges. The cost layer is exp(-i gamma C), the mixer
  exp(-i beta sum_v X_v). Angles: gamma in [0, 2 pi), beta in [0, pi).
"""

import math

import numpy as np


def cut_values(n, edges):
    """Array of C(z) for z = 0 .. 2^n - 1."""
    raise NotImplementedError


def qaoa_state(n, edges, gammas, betas):
    """QAOA state for depth p = len(gammas): alternate exp(-i gamma C) and exp(-i beta sum X)."""
    raise NotImplementedError


def qaoa_expectation(n, edges, gammas, betas):
    """<C> in the QAOA state."""
    raise NotImplementedError


def p1_edge_expectation(gamma, beta, degree_u, degree_v, triangles):
    """Closed-form p=1 probability that edge (u, v) is cut (Wang, Hadfield, Jiang, Rieffel 2018):

    1/2 + 1/4 sin(4b) sin(g) (cos^d g + cos^e g) - 1/4 sin^2(2b) cos^(d+e-2f) g (1 - cos^f 2g),
    with d = degree_u - 1, e = degree_v - 1 and f the number of triangles containing the edge.
    """
    raise NotImplementedError


def p1_expectation_analytic(n, edges, gamma, beta):
    """Sum of p1_edge_expectation over the edges of the graph."""
    raise NotImplementedError


def grid_search(n, edges, layers, grid):
    """Exhaustive grid: beta_i = pi i / grid, gamma_i = 2 pi i / grid for every layer.

    Returns (best expectation, best gammas, best betas); the first strict maximum in the
    order (beta_1, gamma_1, beta_2, gamma_2, ...) with beta the outer loop of each layer.
    """
    raise NotImplementedError


def brute_force_maxcut(n, edges):
    """(maximum cut, sorted list of optimal assignments z) by enumeration."""
    raise NotImplementedError


def local_search_maxcut(n, edges, restarts, seed):
    """Best cut found by 1-flip local search from `restarts` seeded random assignments.

    From each start, repeatedly sweep v = 0..n-1 and flip v whenever that increases the cut,
    until a full sweep makes no flip. Returns (best cut, its assignment z).
    """
    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 itertools
import math

import numpy as np
import pytest

RING6 = [(i, (i + 1) % 6) for i in range(6)]
PRISM = [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)]
K4 = [(i, j) for i in range(4) for j in range(i + 1, 4)]
CUBE = [(a, b) for a in range(8) for b in range(a + 1, 8) if bin(a ^ b).count("1") == 1]


def random_graph(n, p, seed):
    rng = np.random.default_rng(seed)
    return [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p]


def test_cut_values_on_small_graphs():
    assert target.brute_force_maxcut(3, [(0, 1), (1, 2), (0, 2)])[0] == 2
    assert target.brute_force_maxcut(6, RING6) == (6, [0b010101, 0b101010])
    assert target.brute_force_maxcut(4, K4)[0] == 4
    assert target.brute_force_maxcut(6, PRISM)[0] == 7
    assert target.brute_force_maxcut(8, CUBE)[0] == 12
    # Vertex 0 is the least significant bit: z = 1 puts only vertex 0 on side 1.
    assert target.cut_values(3, [(0, 1)])[1] == 1 and target.cut_values(3, [(1, 2)])[1] == 0


def test_qaoa_state_is_normalised_and_trivial_at_zero_angles():
    psi = target.qaoa_state(5, random_graph(5, 0.5, 1), [0.7, 1.9], [0.3, 2.2])
    assert np.isclose(np.linalg.norm(psi), 1)
    edges = random_graph(5, 0.5, 1)
    assert np.isclose(target.qaoa_expectation(5, edges, [0.0], [0.0]), len(edges) / 2)


@pytest.mark.parametrize("n,edges", [(4, K4), (6, PRISM), (6, RING6), (7, random_graph(7, 0.6, 3)), (8, CUBE)])
def test_closed_form_matches_simulation(n, edges):
    rng = np.random.default_rng(n)
    for _ in range(15):
        g, b = rng.uniform(0, 2 * math.pi), rng.uniform(0, math.pi)
        assert np.isclose(target.p1_expectation_analytic(n, edges, g, b), target.qaoa_expectation(n, edges, [g], [b]), atol=1e-10)


def test_ring_and_cube_reach_the_known_p1_ratios():
    # Even ring (2-regular, triangle-free): best p=1 ratio is exactly 3/4.
    # Triangle-free 3-regular and bipartite (the cube): 1/2 + 1/(3 sqrt 3) = 0.6924...
    g = np.linspace(0, 2 * math.pi, 721)
    b = np.linspace(0, math.pi, 361)
    ring = max(target.p1_expectation_analytic(6, RING6, gg, bb) for gg in g[::4] for bb in b[::4])
    assert ring / 6 == pytest.approx(0.75, abs=1e-3)
    cube = max(target.p1_edge_expectation(gg, math.pi / 8, 3, 3, 0) for gg in g)
    assert cube == pytest.approx(0.5 + 1 / (3 * math.sqrt(3)), abs=1e-5)


def test_grid_optimum_on_the_ring():
    best, gammas, betas = target.grid_search(6, RING6, 1, 24)
    assert best == pytest.approx(4.5, abs=1e-9)
    assert target.qaoa_expectation(6, RING6, gammas, betas) == pytest.approx(best)


def test_local_search_returns_a_local_optimum_with_at_least_half_the_edges():
    for seed in range(5):
        edges = random_graph(9, 0.5, seed)
        value, z = target.local_search_maxcut(9, edges, restarts=1, seed=seed)
        assert value >= len(edges) / 2
        assert value <= target.brute_force_maxcut(9, edges)[0]
        c = target.cut_values(9, edges)
        assert c[z] == value
        assert all(c[z ^ (1 << v)] <= value for v in range(9)), "a single flip must not improve a local optimum"


def test_local_search_with_restarts_solves_small_instances():
    for n, edges in [(6, PRISM), (8, CUBE), (6, RING6)]:
        assert target.local_search_maxcut(n, edges, restarts=20, seed=0)[0] == target.brute_force_maxcut(n, edges)[0]


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


@pytest.mark.parametrize("graph,n,edges,layers,grid", [
    ("ring", 6, RING6, 1, 24),
    ("custom", 6, PRISM, 1, 24),
    ("ring", 6, RING6, 2, 8),
])
def test_agrees_with_the_ketqat_sdk(ketqat_home, graph, n, edges, layers, grid):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    kwargs = {"edges": [f"{u}-{v}" for u, v in edges]} if graph == "custom" else {}
    record = catalog.run("[email protected]", seed=7, graph=graph, n_vertices=n, layers=layers, grid=grid, shots=100, **kwargs)
    assert record.status == "succeeded"
    best, _, _ = target.grid_search(n, edges, layers, grid)
    assert best == pytest.approx(record.result["best_expectation"], abs=1e-9)
    assert target.brute_force_maxcut(n, edges)[0] == record.result["max_cut"]

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. Run grid_search(6, PRISM, 1, 24) from your qaoa-maxcut-study solution, where PRISM is the triangular prism (edges 0-1, 1-2, 2-0, 3-4, 4-5, 5-3, 0-3, 1-4, 2-5). What is the best expected cut? (Deterministic.)

    1 pt

    Computed by running exercise “qaoa-maxcut-study” on your computer.

  2. At the grid optimum from the previous question, what is the probability that measuring the QAOA state returns an optimal cut (value 7)? Use qaoa_state and cut_values from your solution.

    1 pt

    Computed by running exercise “qaoa-maxcut-study” on your computer.

  3. A paper reports that QAOA at p=3p = 3 reached an approximation ratio of 0.95 on a 12-vertex graph. Which conclusion is justified?

    1 pt
  4. For a triangle-free 3-regular graph, what is the maximum over (γ,β)(\gamma, \beta) of the probability that a given edge is cut by p=1p = 1 QAOA? Use 12+12sin⁡(4β)sin⁡γcos⁡2γ\tfrac12 + \tfrac12\sin(4\beta)\sin\gamma\cos^{2}\gamma.

    1 pt
  5. Over which range of a single β\beta do you need to search for MaxCut QAOA, given that γ\gamma is searched over [0,2π)[0, 2\pi)?

    1 pt
  6. Which statements about classical MaxCut algorithms are correct? Select all that apply.

    1 pt

    Select all that apply.

  7. Up to a global phase, which gate sequence implements e−iγ(1−ZuZv)/2e^{-i\gamma(1 - Z_uZ_v)/2} for one edge?

    1 pt

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

References

  1. Edward Farhi, Jeffrey Goldstone, Sam Gutmann (2014). A quantum approximate optimization algorithm. arXiv:1411.4028
  2. Zhihui Wang et al. (2018). Quantum approximate optimization algorithm for MaxCut: A fermionic view. Physical Review A 97, 022304. doi:10.1103/PhysRevA.97.022304
  3. Michel X. Goemans, David P. Williamson (1995). Improved approximation algorithms for maximum cut and satisfiability problems using semidefinite programming. Journal of the ACM 42(6), 1115-1145. doi:10.1145/227683.227684
  4. Johan Håstad (2001). Some optimal inapproximability results. Journal of the ACM 48(4), 798-859. doi:10.1145/502090.502098
  5. Subhash Khot et al. (2007). Optimal inapproximability results for MAX-CUT and other 2-variable CSPs?. SIAM Journal on Computing 37(1), 319-357. doi:10.1137/S0097539705447372
  6. Sergey Bravyi et al. (2020). Obstacles to variational quantum optimization from symmetry protection. Physical Review Letters 125, 260505. doi:10.1103/PhysRevLett.125.260505
  7. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.