QAOA for Traveling Salesman Problem (TSP)
What You'll Learn:
- How QAOA handles constrained optimization (not just simple partitions)
- How the city-timestep encoding maps TSP routes to qubit states
- Why constraint penalties are crucial and how to tune them
- How validity rate and tour quality trade off in QAOA solutions
Level: Intermediate | Time: 30 minutes | Qubits: 4 | Framework: Qiskit
Prerequisites
- QAOA for MaxCut — QAOA fundamentals (cost/mixer, gamma/beta optimization)
- Bell State — entanglement basics
- Grover's Search — quantum search over bitstrings
The Idea
Imagine you're a delivery driver with a list of addresses. You need to visit every address exactly once and return home, minimizing total driving distance. That's the Traveling Salesman Problem (TSP) — one of the most famous NP-hard problems in computer science.
Unlike MaxCut (where any bitstring is a valid partition), TSP has constraints: you must visit each city exactly once, and each timestep must have exactly one city. This makes TSP harder for QAOA — the algorithm must learn to avoid invalid routes while minimizing distance.
The key insight: we encode both the objective (minimize distance) and the constraints (valid routes) into the same cost Hamiltonian. Penalty terms push the optimization away from invalid solutions, while distance terms guide it toward short tours. In qubit operators this cost becomes two-qubit RZZ gates plus single-qubit RZ gates, and the circuit applies both.
How It Works
The Problem
Given n cities and pairwise distances, find the shortest round-trip route visiting each city once:
CODEDefault: 2 cities, distance 5 City 0 <--- 5 ---> City 1 Valid tours: [0, 1] or [1, 0] Optimal tour length: 10 (5 + 5, round trip)
The Encoding: City x Timestep
Each qubit represents "city c is visited at timestep t". For n cities, we need n^2 qubits:
CODE2 cities, 4 qubits: Time 0 Time 1 City 0: q0 q2 City 1: q1 q3 Valid state "0110": q1=1 (city 1 at t=0), q2=1 (city 0 at t=1) -> Tour: [1, 0] (visit city 1 first, then city 0) Valid state "1001": q0=1 (city 0 at t=0), q3=1 (city 1 at t=1) -> Tour: [0, 1] (visit city 0 first, then city 1)
Constraints
Two types of constraints ensure valid tours:
-
Row constraint (each city visited exactly once): For each city c, exactly one of the qubits (c, t=0), (c, t=1), ..., (c, t=n-1) should be 1.
-
Column constraint (one city per timestep): For each timestep t, exactly one of the qubits (c=0, t), (c=1, t), ..., (c=n-1, t) should be 1.
Violations are penalized with weight penalty (default: 10.0, which exceeds the maximum distance).
The QAOA Circuit
CODE┌───┐ ┌────────────┐ ┌───────────┐ ┌───────────┐ ┌─────────┐ ┌────────┐ q_0: ┤ H ├─┤ dist q0-q3 ├─┤ row q0-q2 ├─┤ col q0-q1 ├─┤ RZ(-5γ) ├─┤ RX(2β) ├── measure ├───┤ ├────────────┤ ├───────────┤ ├───────────┤ ├─────────┤ ├────────┤ q_1: ┤ H ├─┤ dist q1-q2 ├─┤ row q1-q3 ├─┤ col q0-q1 ├─┤ RZ(-5γ) ├─┤ RX(2β) ├── measure ├───┤ ├────────────┤ ├───────────┤ ├───────────┤ ├─────────┤ ├────────┤ q_2: ┤ H ├─┤ dist q1-q2 ├─┤ row q0-q2 ├─┤ col q2-q3 ├─┤ RZ(-5γ) ├─┤ RX(2β) ├── measure ├───┤ ├────────────┤ ├───────────┤ ├───────────┤ ├─────────┤ ├────────┤ q_3: ┤ H ├─┤ dist q0-q3 ├─┤ row q1-q3 ├─┤ col q2-q3 ├─┤ RZ(-5γ) ├─┤ RX(2β) ├── measure └───┘ └────────────┘ └───────────┘ └───────────┘ └─────────┘ └────────┘ ├───────────── Cost: RZZ pairs, then RZ ─────────────┤ ├─Mixer──┤ dist = RZZ(5γ) on a distance pair; row, col = RZZ(10γ) on a penalty pair
Step 1: Uniform Superposition
All n^2 qubits start in |+> — equal probability over all 2^(n^2) states (mostly invalid!).
Step 2: Cost Operator
The cost operator exp(-igammaC) applies the cost C from The Math below. The code builds C's QUBO coefficients (build_tsp_qubo), rewrites them with x = (1 - Z)/2 (qubo_to_ising), and applies one gate per term:
- Two-qubit terms:
RZZ(2*gamma*J)on every interacting pair. Distance pairs, qubit (c1, t) with qubit (c2, t+1), carry the distances. Row pairs (the same city at two timesteps) and column pairs (two cities at one timestep) carry the penalty. - Single-qubit terms:
RZ(2*gamma*h)on every qubit. They come from the same substitution, and they are what lets the cost tell a valid tour from any other bitstring with the same number of 1s.
For the default instance (distance 5, penalty 10) that is RZZ(5*gamma) on the distance pairs q0-q3 and q1-q2, RZZ(10*gamma) on the row pairs q0-q2, q1-q3 and the column pairs q0-q1, q2-q3, and RZ(-5*gamma) on every qubit. The energies these gates give equal the cost C up to a constant: 10 for the two valid tours, 20 for the other bitstrings with two 1s and for every bitstring with a single 1, 30 for three 1s, 40 for 0000 and 60 for 1111. verify_qaoa() checks this for all 16 bitstrings.
Step 3: Mixer Operator
RX(2*beta) on each qubit. Same transverse field mixer as MaxCut — explores neighboring states.
Step 4: Measure and Optimize
Measure all qubits, decode bitstrings to tours, evaluate tour length + constraint violations. Classically optimize gamma and beta to minimize expected cost.
PYTHONfrom circuit import run_circuit, optimize_qaoa # Default parameters result = run_circuit() print(f"Validity rate: {result['validity_rate']:.1%}") print(f"Best tour: {result['best_tour']}, length: {result['best_length']}") # Optimize parameters opt = optimize_qaoa(p=1, max_iterations=50, seed=42) print(f"Optimized validity: {opt['validity_rate']:.1%}")
The Math
Cost Hamiltonian
The TSP cost Hamiltonian has three parts:
C = C_distance + C_row + C_column
Written with binary variables x_q = (1 - Z_q)/2, where x = 1 means "city c is visited at timestep t":
Distance cost — minimize total tour length:
C_distance = sum_{t} sum_{c1 != c2} d_{c1,c2} * x_{(c1,t)} * x_{(c2,t+1)}
Row constraint — each city visited exactly once:
C_row = penalty * sum_c (sum_t x_{(c,t)} - 1)^2
Column constraint — one city per timestep:
C_column = penalty * sum_t (sum_c x_{(c,t)} - 1)^2
Substituting x = (1 - Z)/2 gives both two-qubit ZZ terms (RZZ gates) and single-qubit Z terms (RZ gates). A QUBO term a·x_q becomes -(a/2)·Z_q, and a term b·x_q·x_q' becomes (b/4)·(Z_q Z_q' - Z_q - Z_q'), plus constants that only add a global phase. The circuit applies both kinds of gate (Step 2). The single-qubit terms matter. An RZZ gate gives "both qubits 0" the same phase as "both qubits 1", so RZZ gates alone give every bitstring the same energy as its complement (0000 the same as 1111, a single 1 the same as three 1s), although the cost C does not. If every qubit pair also carries the same RZZ weight, the energy depends only on how many qubits are 1, and the valid tours (0110, 1001) cannot be told apart from the other bitstrings with two 1s (0011, 0101, 1010, 1100). With the RZ gates, the circuit's energies match C: valid tours cost 10 and those invalid ones 20.
Mixer Hamiltonian
B = sum_{q} X_q
The standard transverse field mixer. More advanced TSP formulations use XY-mixers that preserve the feasible subspace, but the simple RX mixer works for educational purposes.
QAOA State
After p layers:
|gamma, beta> = exp(-i*beta_p * B) exp(-i*gamma_p * C) ... exp(-i*beta_1 * B) exp(-i*gamma_1 * C) |+>^(n^2)
The expected cost ⟨gamma,beta|C|gamma,beta⟩ is minimized over the 2p parameters (unlike MaxCut which maximizes).
Penalty Tuning
A sufficient condition for the penalty weight (Lucas 2014, Section 7.2) is:
penalty > max distance between two cities
If penalty is too low, the optimizer finds short but invalid routes. If too high, the optimizer focuses on constraint satisfaction and ignores distance optimization. Default: 10.0, twice the only distance here (2 cities, distance 5; the round trip is also 10).
Expected Output
| Metric | Value |
|---|---|
| Optimal tour length (2 cities) | 10 |
| Valid tours possible | 2 ([0,1] and [1,0]) |
| QAOA p=1 (default γ = 0.57, β = 0.31) | validity ~32% (31.9% exact; 29% to 37% over 15 runs of 1,024 shots), expected cost 17.7 |
QAOA p=1 (optimize_qaoa, seed 42) | validity 14% to 19%, expected cost 22.5 to 24 in 34 runs (COBYLA stops near γ = 0.61, β = 0.67) |
| Random baseline (valid tours) | 2/16 = 12.5%, expected cost 25 |
Note: These are noiseless simulator results. For 2 cities both valid tours have length 10, so any valid sample is optimal. At the default angles the two valid tours are the two most likely outcomes (16.0% each), ahead of the four invalid bitstrings with two 1s (9.3% each) and the four with a single 1 (6.7% each). The defaults sit near the minimum of the expected cost on a p=1 grid (17.67 at γ = 0.571, β = 0.313). A p=1 circuit can make valid tours more likely, up to 50% at γ = π/10, β = π/4, but only by also putting 25% each on 0000 and 1111, which raises the expected cost to 30, worse than random guessing. optimize_qaoa from seed 42 stops at a poorer point than the defaults; from other seeds it reached the minimum in some of our runs and stalled near random guessing in others, so its result depends on the starting angles.
Running the Circuit
PYTHONfrom circuit import ( run_circuit, optimize_qaoa, verify_qaoa, compute_exact_solution, decode_bitstring ) import numpy as np # Exact solution exact = compute_exact_solution() print(f"Optimal: length={exact['optimal_length']}, tours={exact['optimal_tours']}") # QAOA with defaults result = run_circuit(shots=2048) print(f"Validity: {result['validity_rate']:.1%}") print(f"Best tour: {result['best_tour']}, length: {result['best_length']}") # Optimize opt = optimize_qaoa(p=1, shots=2048, seed=42) print(f"Optimized validity: {opt['validity_rate']:.1%}") # Custom 3-city problem (9 qubits!) distances_3 = np.array([ [0, 5, 10], [5, 0, 3], [10, 3, 0] ]) result = run_circuit(distances=distances_3, gamma=[0.2], beta=[0.6]) # Verification v = verify_qaoa() for check in v["checks"]: print(f"[{'PASS' if check['passed'] else 'FAIL'}] {check['name']}")
Scaling Challenge
TSP is much harder to scale than MaxCut due to the n^2 qubit overhead:
| Cities | Qubits (n^2) | RZZ gates per layer | Classical tours | Feasibility |
|---|---|---|---|---|
| 2 | 4 | 6 | 1 | Simulator |
| 3 | 9 | 36 | 1 | Simulator |
| 4 | 16 | 96 | 3 | Near-term hardware |
| 5 | 25 | 200 | 12 | Challenging |
| 10 | 100 | 1,800 | 181,440 | Future hardware |
Each layer also has n^2 RZ gates, one per qubit (RZZ counts assume every pair of cities has a nonzero distance). The "Classical tours" column counts distinct round trips, (n-1)!/2 for n ≥ 3. The valid solution space is tiny: only n! out of 2^(n^2) possible bitstrings are valid (each rotation and direction of a tour is a different bitstring). For 5 cities, that's 120 valid states out of ~33 million.
Try It Yourself
-
Increase penalty: Try
penalty=20vspenalty=5. How does the validity rate change? What happens to tour quality? -
3-city instance: Use
distances=np.array([[0,5,10],[5,0,3],[10,3,0]]). The optimal tour is [0,1,2] with length 18. How many qubits does this need? -
Increase p: Run with p=2 (
optimize_qaoa(p=2)). Does the validity rate improve? How many more iterations are needed? -
Compare with MaxCut: Run both MaxCut and TSP with 4 qubits. Why does TSP have much lower success rates?
-
Analyze invalid states: Look at the
countsdict — what fraction of bitstrings have exactly 2 ones? Why is this relevant?
What's Next
- Portfolio Optimization — QAOA for financial portfolio selection (another constrained problem)
- VQE H2 Ground State — Another variational algorithm, for quantum chemistry
MaxCut vs TSP: Key Differences
| Aspect | MaxCut | TSP |
|---|---|---|
| Encoding | 1 qubit per vertex | n^2 qubits (city x timestep) |
| Valid states | All 2^n (any partition) | Only n! out of 2^(n^2) |
| Constraints | None | Row + column constraints |
| Objective | Maximize cut edges | Minimize tour length |
| Success metric | Approximation ratio | Validity rate + tour quality |
| Difficulty | Moderate for QAOA | Hard (feasible space is tiny) |
Applications
| Domain | Use case |
|---|---|
| Logistics | Delivery route optimization, last-mile routing |
| Manufacturing | Tool path planning, CNC drill sequencing |
| PCB design | Minimize drilling distance between holes |
| Genome sequencing | DNA fragment assembly (shortest superstring) |
References
- Farhi, E., Goldstone, J., Gutmann, S. (2014). "A Quantum Approximate Optimization Algorithm." arXiv: 1411.4028
- Lucas, A. (2014). "Ising formulations of many NP problems." Frontiers in Physics 2:5. DOI: 10.3389/fphy.2014.00005
- Hadfield, S. et al. (2019). "From the Quantum Approximate Optimization Algorithm to a Quantum Alternating Operator Ansatz." Algorithms 12(2):34. DOI: 10.3390/a12020034