Learning Tutorial
QAOA MaxCut: Tune a Four-Qubit Circuit
Build a small QAOA circuit, search two angles and compare a sampled graph cut with its exact prediction.
4 qubits · 81 ideal parameter evaluations · 4,096 final samples
Can one QAOA layer improve the average cut of a four-node square over uniformly random partitions?
Define the teaching problem
Use vertices 0, 1, 2 and 3 with edges (0,1), (1,2), (2,3) and (3,0). Each bit assigns a vertex to one of two groups. Count an edge when its endpoint bits differ.
The classical optimum is 4, achieved by 0101 and 1010. The random baseline has mean cut 2. We maximize C = Σedges (I − ZuZv)/2; the mean score and the probability of finding an optimal partition are different quantities.
Follow the workflow
- Apply H to all four qubits to prepare an equal superposition.
- Apply the cost unitary exp(−iγC). Each edge uses CX, Rz(−γ), CX, ignoring a global phase. Then apply Rx(2β) to every qubit. Rotation angles use the standard half-angle convention.
- Evaluate exact ideal probabilities on a 9 × 9 grid: γ from 0 to π/2 and β from 0 to π/4. Choose the grid point with the largest mean cut. This small search is classical computation over simulated circuits.
- Draw 4,096 independent simulator samples at the chosen angles, score each bitstring and compare the sample mean with the ideal mean. The grid uses ideal probabilities; it does not submit 81 sampled quantum jobs.
Compare with the expected result
Scroll the table horizontally to see every column.
| Quantity | Ideal reference |
|---|---|
| Selected angles | γ = π/4, β = π/8 |
| Mean cut | 3 of 4 edges |
| Probability of an optimal cut | 17/32 = 53.125% |
| Mean / classical optimum | 3/4 = 0.75 |
For this graph and convention, the ideal mean is 2 + sin(4β) sin(2γ). At the selected angles it equals 3, even though individual samples can score 0, 2 or 4. A mean of 3 does not mean every sampled partition cuts three edges.
Finite-shot means fluctuate around 3. With 4,096 independent ideal samples, a fixed-circuit 99% Hoeffding bound for a score in [0,4] is about ±0.102. This is a sampling consistency check, not a hardware accuracy or advantage claim.
Run the complete tutorial locally
Download the complete Python tutorial, then open a terminal in the folder containing qaoa-maxcut.py.
Use Python 3.10 or later and NumPy 2.x. From that folder, create a virtual environment, install NumPy and run the script. The code uses explicit small statevectors and local pseudorandom sampling. It requires no Marqov account, credentials or external service.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install 'numpy>=2,<3'
python qaoa-maxcut.pyInspect the complete Python source
"""Learning: ideal p=1 QAOA on a four-cycle, not a research replication.
Run: python qaoa-maxcut.py (NumPy required). No network or hosted jobs.
Basis |q0 q1 q2 q3>, q0 leftmost. Cost U_C=exp(-i gamma C),
C=sum_edges (I-ZuZv)/2. Background: arXiv:1411.4028.
"""
import json
import math
import numpy as np
EDGES = ((0, 1), (1, 2), (2, 3), (3, 0))
BITS = [format(i, "04b") for i in range(16)]
CUTS = np.array([sum(b[u] != b[v] for u, v in EDGES) for b in BITS])
def state(gamma, beta):
# H on each zero qubit, diagonal cost, then Rx(2 beta) per wire.
psi = np.exp(-1j * gamma * CUTS) / 4
rx = np.array([[math.cos(beta), -1j * math.sin(beta)],
[-1j * math.sin(beta), math.cos(beta)]])
mixer = rx
for _ in range(3):
mixer = np.kron(mixer, rx)
return mixer @ psi
def mean_cut(gamma, beta):
return float(np.abs(state(gamma, beta)) ** 2 @ CUTS)
def qasm(gamma=math.pi / 4, beta=math.pi / 8):
lines = ['OPENQASM 2.0;', 'include "qelib1.inc";',
'qreg q[4];', 'creg c[4];']
lines += [f'h q[{i}];' for i in range(4)]
for u, v in EDGES:
# CNOT-Rz(-gamma)-CNOT implements U_C up to global phase.
lines += [f'cx q[{u}],q[{v}];', f'rz({-gamma:.17g}) q[{v}];',
f'cx q[{u}],q[{v}];']
lines += [f'rx({2 * beta:.17g}) q[{i}];' for i in range(4)]
return '\n'.join(lines + ['measure q -> c;', ''])
def run():
# Tiny deterministic landscape, not a scalable optimizer.
candidates = [(mean_cut(g, b), g, b)
for g in np.linspace(0, math.pi / 2, 9)
for b in np.linspace(0, math.pi / 4, 9)]
value, gamma, beta = max(candidates)
probs = np.abs(state(gamma, beta)) ** 2
counts = np.random.default_rng(7).multinomial(4096, probs / probs.sum())
analytical = 2 + math.sin(4 * beta) * math.sin(2 * gamma)
return {"gamma": gamma, "beta": beta, "search_statevector_evaluations": len(candidates),
"final_statevector_evaluations": 1, "sampling_batches": 1, "shots": 4096,
"backend": "local_numpy_statevector", "seed": 7,
"analytical_mean_cut": analytical, "ideal_minus_analytical": value - analytical,
"selected_circuit_openqasm": qasm(gamma, beta),
"ideal_mean_cut": value, "classical_max_cut": int(CUTS.max()),
"ideal_optimal_cut_probability": float(probs[CUTS == 4].sum()),
"sample_mean_cut": float(counts @ CUTS / counts.sum()),
"counts_q0_first": dict(zip(BITS, map(int, counts)))}
if __name__ == "__main__":
print(json.dumps(run(), indent=2))
Try a fixed circuit in Marqov
The OpenQASM circuit fixes γ = π/4 and β = π/8. It samples one circuit; parameter search and graph scoring remain in the Python workflow.
Save existing editor work, open Marqov and sign in if required. Set the editor format to OpenQASM and paste a circuit below. Choose an available browser simulator and run explicitly. The link opens the editor; it does not load code or start execution. These tutorial circuits are not in the Examples dropdown.
These Python scripts label bitstrings with q0 on the left. Before comparing editor or native framework output, check the displayed wire and classical-bit order and convert it to the same convention.
qaoa-maxcut.qasm
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
h q[0];
h q[1];
h q[2];
h q[3];
cx q[0],q[1];
rz(-0.78539816339744828) q[1];
cx q[0],q[1];
cx q[1],q[2];
rz(-0.78539816339744828) q[2];
cx q[1],q[2];
cx q[2],q[3];
rz(-0.78539816339744828) q[3];
cx q[2],q[3];
cx q[3],q[0];
rz(-0.78539816339744828) q[0];
cx q[3],q[0];
rx(0.78539816339744828) q[0];
rx(0.78539816339744828) q[1];
rx(0.78539816339744828) q[2];
rx(0.78539816339744828) q[3];
measure q -> c;
Download qaoa-maxcut.qasmChange one thing
- Set γ = 0: the mean returns to the random baseline 2.
- Change β while holding γ = π/4 and compare the printed mean with the analytical formula.
Scope and verification
- This is a single-layer, four-vertex teaching problem. It establishes no practical speedup or general approximation guarantee.
- The square is degree two; the cubic-graph guarantee discussed in the QAOA paper does not apply.
- The local simulator has no device noise. The grid search and final histogram are new tutorial outputs, not retained research results.
Checks compare the Python state and OpenQASM gates with independent mathematical references, including complex phases where needed. Sampling checks use the circuit’s own predicted distribution. Local mathematical checks do not establish hosted or hardware qualification.
Learning tutorial or research replication?
The research reference studies triangle, square and Petersen graphs, with retained results and scientific comparisons. This tutorial shares the square model and cost convention, but has its own grid, samples and validation.
Read the QAOA research replication →
References and provenance
New Marqov learning implementation informed by the reviewed QAOA replication’s graph definition and cost convention. No private research code package or historical count data is included.
Learning scope reviewed with the Replications project, October 17, 2026. The local Python scripts and fixed circuit snapshots are separate from the source-pinned twelve-example editor catalog.