The goal is a short closed route that visits every city once and returns to its start.
Click the map to add a city, or press NEW MAP for random ones. Press DRAW YOUR ROUTE to trace a route by hand and compare it with the agents.
Choose an agent and press RUN AGENT to watch its route shorten, or RACE ALL THREE to run all three side by side.
The route planner solves the traveling salesman problem (TSP): find a short closed tour through a set of cities, a route that visits each city once and returns to its start. The length of a tour is the sum of straight-line distances between consecutive cities. Three heuristic agents search over tours. A heuristic is a method that finds good answers quickly but cannot promise the best one. For up to 12 cities, an exact method (Held-Karp) gives the true shortest tour to compare against.
Trying every tour is hopeless at this size. A closed tour can start at any city and run in either direction, so n cities give \frac{(n-1)!}{2} distinct tours. For 20 cities that is about 6 \times 10^{16}, over 60 quadrillion.
The distance between two cities is the straight-line (Euclidean) distance. The code computes every pair once into a distance matrix1, so each later length is a table lookup.
A tour t lists the cities in order, and t_k is the city at position k, counting from 0. The length of the closed tour is
Here n is the number of cities. For k = 0 the term uses t_{-1}, the last position, so the edge that closes the tour back to its start is included.
A 2-opt move chooses two positions i < j and reverses the stretch of the tour from i to j. It removes two edges, (a,b) and (c,d), and adds (a,c) and (b,d), where a = t_{i-1}, b = t_i, c = t_j and d = t_{j+1}, wrapping to position 0 after the last. Every edge inside the stretch keeps its length when walked backwards, so only these four distances change.
Here \Delta is the change in tour length, so a negative \Delta means the move shortens the tour. Four lookups give \Delta, instead of measuring the whole tour again.
Two edges that cross can always be uncrossed: when two edges of a tour cross, a 2-opt move that reverses the stretch between them makes the tour shorter.4 A tour that no 2-opt move can shorten is a local optimum. It is best among the tours one 2-opt move away, but not necessarily the shortest tour overall.
function TWO-OPT-DELTA(tour, i, j, dist):
n ← length of tour
a ← tour[i − 1]
b ← tour[i]
c ← tour[j]
d ← tour[(j + 1) mod n]
return dist[a][c] + dist[b][d] − dist[a][b] − dist[c][d]
This is the baseline. A greedy method makes the locally best choice at each step. The nearest-neighbour tour starts at city 0 and always moves to the closest city not yet visited, then closes the loop.5 It is quick, but it tends to leave a few long edges at the end, when the cities that remain are far apart.
The tour is then improved by 2-opt descent. Each pass tries every pair of positions and applies each 2-opt move that shortens the tour. Passes repeat until one makes no improvement, or until 50 passes have run.6 On the committed 12-city run this agent finished 1.53% above the exact optimum.7
function NEAREST-NEIGHBOR-2OPT(cities):
tour ← NEAREST-NEIGHBOR(cities, start = city 0)
repeat:
improved ← false
for each pair of positions i < j: # a move is applied as soon as it helps
if TWO-OPT-DELTA(tour, i, j) < 0:
REVERSE(tour, i, j)
improved ← true
if not improved: stop # local optimum reached
return tour
constants: MAX-PASSES = 50, MAX-FRAMES = 150, TOLERANCE = 1e−12
function NEAREST-NEIGHBOR-2OPT(cities):
dist ← DISTANCE-MATRIX(cities)
tour ← NEAREST-NEIGHBOR(dist, start = 0)
length ← TOUR-LENGTH(tour, dist)
frames ← [{step: 0, best_length: round(length, 5), tour: COPY(tour)}]
improvements ← TWO-OPT-DESCENT(tour, dist, MAX-PASSES, ON-IMPROVE)
count ← number of frames
stride ← max(1, count // MAX-FRAMES) # thin the frames for long runs
keep the frames at positions 0, stride, 2 · stride, …
if (count − 1) mod stride ≠ 0: keep the last frame too
return tour, TOUR-LENGTH(tour, dist), improvements, frames
function ON-IMPROVE(count, tour, length): # called after each improvement
append {step: count, best_length: round(length, 5), tour: COPY(tour)} to frames
function NEAREST-NEIGHBOR(dist, start):
tour ← [start]
unvisited ← all cities except start
while unvisited is not empty:
here ← last city in tour
nearest ← the city in unvisited with the smallest dist[here][city]
append nearest to tour
remove nearest from unvisited
return tour
function TWO-OPT-DESCENT(tour, dist, max-passes, on-improve):
n ← length of tour
length ← TOUR-LENGTH(tour, dist)
improvements ← 0
repeat max-passes times:
improved ← false
for i in 1 … n − 2:
for j in i + 1 … n − 1:
delta ← TWO-OPT-DELTA(tour, i, j, dist)
if delta < −TOLERANCE: # ignore rounding noise
REVERSE(tour, i, j) # tour[i … j] reversed in place
length ← length + delta
improvements ← improvements + 1
improved ← true
on-improve(improvements, tour, length)
if not improved: stop # local optimum reached
return improvements
Frames. Each improvement adds a frame, which lets the page animate the descent. The list is thinned afterwards so that long runs stay small. The first frame and the last frame are always kept.
Tolerance. A move counts as an improvement only if it shortens the tour by more than 10−12, so rounding error cannot be mistaken for progress.
Simulated annealing is a local search that sometimes accepts a worse tour, so that it can leave a local optimum. The name comes from annealing in metallurgy, where a metal is heated and then cooled slowly so that it settles into a strong structure.
The search starts from a random tour, a random ordering of the cities.9 Each iteration picks two positions i < j from 1 to n-1, so the city at position 0 never moves, and proposes the 2-opt move between them. The move is judged by the Metropolis acceptance rule. It always accepts a shorter tour, and it accepts a longer one with a probability that shrinks as the tour gets worse.10
Here T is the current temperature and u is a fresh random number between 0 and 1. Accepting a longer tour is what lets the search climb out of a local optimum. A small increase is accepted more often than a large one, and every increase is accepted less often as T falls. A move with \Delta < 0 is accepted without drawing u.
The temperature starts at T_0 and is multiplied by a cooling rate r after every iteration, so after k iterations T_k = T_0 r^k. Early on the search wanders freely, and later it becomes greedy.12
Here N is the number of iterations. With this default rate the temperature has fallen to 0.1% of T_0 after the last iteration. The page's COOLING slider replaces the default with a rate between 0.99901 and 0.99999, through a mapping onto that range.14
The start temperature T_0 is set from the map, so it adapts to the scale of the distances. The code samples 200 random moves from the starting tour, averages the uphill ones (moves with \Delta > 0), and chooses T_0 so that a move as costly as that average is accepted with probability \alpha = 0.8.15
Here \bar{\Delta} is that average uphill move, and \ln is the natural logarithm. Solving e^{-\bar{\Delta}/T_0} = \alpha for T_0 gives this formula. If none of the sampled moves is uphill, \bar{\Delta} is set to 1.
The default run is 60,000 iterations, and the page slider offers 5,000 to 150,000. The best tour seen is kept, because the current tour may have wandered away from it.17 At the end, a 2-opt descent polishes the best tour, applying any improving move that the random proposals missed.18
The page animates each run from snapshots. The recorder stores about 150 evenly spaced snapshots, one every iterations // 150 steps, so a small budget stores a few more.19
function SIMULATED-ANNEALING(cities, iterations):
tour ← a random ordering of the cities
best ← COPY(tour)
T ← INITIAL-TEMPERATURE(tour) # sized from sampled uphill moves
r ← 0.001 ^ (1 / iterations) # cools to 0.1% of T over the run
for step in 0 … iterations − 1:
i, j ← two random positions, 1 ≤ i < j ≤ n − 1
delta ← TWO-OPT-DELTA(tour, i, j)
if delta < 0 or random() < exp(−delta / T): # the Metropolis rule
REVERSE(tour, i, j)
if the length of tour is the best so far:
best ← COPY(tour)
T ← T · r
TWO-OPT-DESCENT(best) # polish the best tour
return best
constants: ITERATIONS = 60000, SAMPLES = 200, ACCEPT = 0.8, TOLERANCE = 1e−12
function SIMULATED-ANNEALING(cities, iterations, cooling, start-temp, seed):
if iterations < 1: raise error "simulated_annealing needs at least one iteration"
if cooling is set and not 0 < cooling ≤ 1: raise error "cooling must be above 0 and at most 1"
dist ← DISTANCE-MATRIX(cities)
n ← number of cities
tour ← a random ordering of the cities # shuffled, so the animation shows the untangling
length ← TOUR-LENGTH(tour, dist)
best, best-length ← COPY(tour), length
T ← start-temp if set, otherwise INITIAL-TEMPERATURE(tour, dist)
r ← cooling if set, otherwise 0.001 ^ (1 / iterations) # reach 0.1% of the start temperature
frames ← RECORDER(iterations) # keeps about 150 evenly spaced frames
uphill-accepted ← 0
for step in 0 … iterations − 1:
if n > 3:
i, j ← two distinct random positions from 1 … n − 1, sorted
else:
i, j ← 1, n − 1
delta ← TWO-OPT-DELTA(tour, i, j, dist)
# The Metropolis rule: always go downhill, sometimes go uphill.
if delta < 0 or random() < exp(−delta / T):
REVERSE(tour, i, j) # tour[i … j] reversed in place
length ← length + delta
if delta > 0: uphill-accepted ← uphill-accepted + 1
if length < best-length − TOLERANCE: # ignore rounding noise
best, best-length ← COPY(tour), length
RECORD(frames, step, best, best-length, length, T, uphill-accepted)
T ← T · r
# Finishing pass: polish the best tour with a 2-opt descent.
if TWO-OPT-DESCENT(best, dist) made any improvement:
best-length ← TOUR-LENGTH(best, dist)
append to frames a copy of the last frame, with step ← iterations, best ← COPY(best)
return best, TOUR-LENGTH(best, dist)
function INITIAL-TEMPERATURE(tour, dist, samples = 200, accept = 0.8):
n ← number of cities
uphill ← empty list
repeat samples times:
i, j ← two distinct random positions from 1 … n − 1, sorted
delta ← TWO-OPT-DELTA(tour, i, j, dist) # the tour itself is not changed
if delta > 0: append delta to uphill
avg ← mean of uphill, or 1 if uphill is empty
return −avg / log(accept) # log is the natural logarithm
Validation. Settings outside the allowed range are rejected before the run starts. A cooling rate of 0 would drive the temperature to 0 and divide by it in the acceptance test, and a rate above 1 would heat the search instead of cooling it.21
Finishing pass. The descent stops at the first pass without an improvement, or after 50 passes.6 The extra frame it may add carries the step number of the last iteration.
A genetic algorithm keeps a population of candidate solutions and improves it over a series of generations. The method is inspired by natural selection: good candidates are more likely to become parents, and each child combines parts of two parents. Here a candidate is a tour, and its fitness is its length, so a shorter tour is fitter.
The population starts as random tours.22 Each generation first copies the elite, the 4 shortest tours, unchanged into the next generation, so the best tour found is never lost. This rule is called elitism. Children then fill the rest of the population.23
Selection. A tournament picks 3 random tours and keeps the shortest. Two tournaments choose the two parents of each child.24
Here C is the set of contenders, drawn at random from the population, and L(t) is the length of tour t. A larger tournament favours the best tours more strongly, and a smaller one keeps more variety.
Crossover. Order crossover (OX1) builds a child that is always a valid tour, with each city exactly once. It copies a random slice of parent A into the same positions of the child. It then fills the other positions with the cities missing from the slice, in the order they appear in parent B, starting after the slice and wrapping around.25
Example. The docstring example labels the cities 1 to 7. With parent A = 1 2 3 4 5 6 7 and parent B = 5 7 1 6 2 4 3, the slice 3 4 5 is copied from A. The missing cities, in B's order from after the slice, are 7, 1, 6, 2, so the child is 6 2 3 4 5 7 1.26
Mutation. With probability equal to the mutation rate, 0.3 by default, a child has a random stretch reversed.27 It is the same reversal that 2-opt uses, except that the stretch may start at the first city.28
The defaults are a population of 120, 300 generations, a mutation rate of 0.3, 4 elite tours and tournaments of 3.29
function GENETIC-ALGORITHM(cities, generations):
population ← random tours of the cities
repeat generations times:
next ← the 4 shortest tours of population, copied unchanged # elitism
while next is not full:
parent-a ← TOURNAMENT(population)
parent-b ← TOURNAMENT(population)
child ← ORDER-CROSSOVER(parent-a, parent-b)
sometimes INVERSION-MUTATION(child)
add child to next
population ← next
return the shortest tour seen in any generation
constants: POPULATION = 120, GENERATIONS = 300, MUTATION-RATE = 0.3, ELITE = 4, TOURNAMENT-SIZE = 3
function GENETIC-ALGORITHM(cities, population-size, generations, mutation-rate, elite):
if population-size < 1 or generations < 1: raise error "genetic_algorithm needs at least one tour and one generation"
dist ← DISTANCE-MATRIX(cities)
population ← population-size random tours, each a shuffled ordering of the cities
best ← COPY(population[0]); best-length ← infinity
for gen in 0 … generations − 1:
lengths ← TOUR-LENGTH(t, dist) for each tour t in population
ranked ← indices of population sorted by lengths, shortest first
if lengths[ranked[0]] < best-length:
best, best-length ← COPY(population[ranked[0]]), lengths[ranked[0]]
RECORD(frames, gen, best, best-length, mean of lengths) # about 150 frames in all
next ← COPY(population[k]) for each k in ranked[0] … ranked[elite − 1] # elitism
while size of next < population-size:
child ← ORDER-CROSSOVER(TOURNAMENT(population, lengths), TOURNAMENT(population, lengths))
if random() < mutation-rate:
INVERSION-MUTATION(child)
append child to next
population ← next
return best, best-length # children bred in the last generation are never scored
function TOURNAMENT(population, lengths, size = 3):
contenders ← size distinct random indices into population
return population[the contender with the smallest length]
function ORDER-CROSSOVER(parent-a, parent-b):
n ← length of parent-a
i, j ← two distinct random positions from 0 … n − 1, sorted
child ← n copies of −1 # −1 marks a position not filled yet
child[i … j] ← parent-a[i … j]
kept ← the cities in parent-a[i … j]
fill ← [parent-b[(j + 1 + k) mod n] for k in 0 … n − 1 if that city is not in kept]
for k, city in enumerate(fill):
child[(j + 1 + k) mod n] ← city
return child
function INVERSION-MUTATION(tour):
n ← length of tour
i, j ← two distinct random positions from 0 … n − 1, sorted
REVERSE(tour, i, j)
Last generation. Each population is scored before it is bred, so the children bred in the final pass are never scored. They cannot be returned, and the answer is always a tour that was scored.
Frames. The recorder keeps about 150 frames. Each one shows the best tour so far and the mean length of the population.31
Dynamic programming solves a problem by storing the answers to smaller subproblems and reusing them. Held-Karp applies this to the traveling salesman problem. For each set S of cities, city 0 excluded, and each city j in S, the table stores the length of the shortest path that starts at city 0, visits every city of S exactly once, and ends at j. Each set is stored as a bitmask, an integer whose bit k-1 is set when city k is in the set.32
Here S \setminus \{j\} is the set S without city j. The base case covers the path from city 0 straight to a single city. The code stores each entry as a pair: the length, and the city k that gave the minimum, so the tour can be rebuilt afterwards. Ties in length go to the smaller k, because the minimum is taken over pairs.
Here L^{*} is the length of the shortest closed tour. The best tour returns from the last city j to city 0. The tour itself is then rebuilt by following the stored predecessors back from j.35
The table has (n-1)\,2^{n-2} entries, and each is computed from up to n-1 others. The time is therefore O(n^2 2^n) and the memory O(n 2^n).36 That beats trying all (n-1)! orders, but the method is practical only for about a dozen cities. The code refuses more than 12 cities,37 and the server computes the exact optimum only for maps of 12 cities or fewer.38
function HELD-KARP(cities):
cost[({j}, j)] ← dist(0, j) for each city j # the path straight from city 0
for each set s of cities, from small to large, and each j in s:
cost[(s, j)] ← min over k in s − {j} of cost[(s − {j}, k)] + dist(k, j)
return the tour that closes the best path: min over j of cost[(all-cities, j)] + dist(j, 0)
constants: HELD-KARP-LIMIT = 12
function HELD-KARP(cities):
n ← number of cities
if n > HELD-KARP-LIMIT: raise error "held_karp is limited to 12 cities"
dist ← DISTANCE-MATRIX(cities)
if n ≤ 2:
return the tour 0, 1, … , n − 1 and its length
# Bit k − 1 of a mask stands for city k. City 0 is the fixed start and has no bit.
cost ← empty table
for each city j from 1 to n − 1:
cost[(mask of {j}, j)] ← (dist[0][j], 0) # the path 0 → j; predecessor 0 marks the start
for size in 2 … n − 1:
for each mask from 1 to 2^(n−1) − 1 with exactly size bits set:
for each city j in mask:
rest ← mask without j
cost[(mask, j)] ← min over k in rest of (cost[(rest, k)][0] + dist[k][j], k)
full ← the mask with all n − 1 bits set
length, last ← min over j from 1 to n − 1 of (cost[(full, j)][0] + dist[j][0], j)
# walk the stored predecessors back from the last city to rebuild the tour
tour ← empty list; mask ← full; j ← last
while j ≠ 0:
append j to tour
mask, j ← mask without j, cost[(mask, j)][1] # both right-hand values use the old mask and j
append 0 to tour; reverse tour
return tour, length
Tests. The test suite checks Held-Karp against brute force over every order of the cities, for 3, 5 and 8 cities.40
One committed run. The committed comparison uses a random 12-city map with seed 1, produced by python -m routes --compare --cities 12. Lengths are in map units, where the full width of the map is 1. Timings vary between runs, so they are not repeated here.41
| Agent | Route length | Above optimal |
|---|---|---|
| Greedy + 2-opt | 3.682 | 1.53% |
| Simulated annealing | 3.627 | 0.00% |
| Genetic algorithm | 3.627 | 0.00% |
| Held-Karp (exact) | 3.627 | 0.00% |
Tests. The heuristics are also checked on a 10-city map, where each must come within 5% of the exact optimum.42
How these were chosen. The defaults (60,000 iterations, population 120, 300 generations, mutation rate 0.3, 4 elite tours, tournament size 3) are fixed in the code, and no tuning run is committed.43 The start temperature is not a constant: it is computed from the average uphill move on the current map, so it adapts to the scale of the distances. The 0.1% end temperature and the 80% acceptance target are design choices in the code.15