Traveling salesman problem¶
A salesman starts from home, visits every city once and comes back. The goal is the shortest tour. Drilling holes in a circuit board, picking items in a warehouse and planning a delivery round all lead to this problem, and it is the classic test of every method for ordering problems.
This example solves two instances of TSPLIB (Reinelt, 1991), the standard library of TSP benchmarks:
| Instance | Cities | Optimal length |
|---|---|---|
| eil51 | 51 | 426 (Christofides and Eilon) |
| st70 | 70 | 675 (Smith and Thompson) |
As TSPLIB prescribes for these instances (EUC_2D), each distance is the Euclidean distance rounded to the nearest integer, so the optima are whole numbers. The coordinates are copied from TSPLIB.
The right tool for a large TSP is a specialized solver. Concorde proves optimal tours for instances with thousands of cities, and LKH (Helsgaun's Lin-Kernighan heuristic) finds optimal or near optimal tours for much larger ones. Both find the optimal tours of these two small instances easily. This page uses the TSP as a benchmark: it shows how to model an ordering problem with ypea, which general methods work, and how close they get. The same setup carries over to ordering problems with rules that the specialized solvers do not handle.
The model¶
A solution is a tour: one Permutation variable with one item per city, the cities in the order of the visit. The objective adds up the distances between consecutive cities, plus the way back from the last city to the first. Every permutation is a valid tour, so there are no constraints. ypea.problems.tsp builds this problem from the coordinates and a distance matrix, with a vectorized objective.
Two things matter most for a good search:
- Moves made for tours. Every algorithm can search the [0, 1] codes of a permutation (random keys), but a crossover of two codes does not keep parts of the parents' tours. GA and SA with
space="native"use crossovers and moves made for permutations instead. The local searches (hill climbing, ILS) always use the moves of the type: swap, insertion and inversion. An inversion reverses a part of the tour, which is the 2-opt move of the sketch above. - Knowledge of distances. The ant colony methods build each tour city by city and prefer close cities, with the heuristic
1 / distance.
import numpy as np
import ypea
from ypea.problems import tsplib_distances
# eil51: x y of each city, ten cities per line
EIL51 = """
37 52, 49 49, 52 64, 20 26, 40 30, 21 47, 17 63, 31 62, 52 33, 51 21
42 41, 31 32, 5 25, 12 42, 36 16, 52 41, 27 23, 17 33, 13 13, 57 58
62 42, 42 57, 16 57, 8 52, 7 38, 27 68, 30 48, 43 67, 58 48, 58 27
37 69, 38 46, 46 10, 61 33, 62 63, 63 69, 32 22, 45 35, 59 15, 5 6
10 17, 21 10, 5 64, 30 15, 39 10, 32 39, 25 32, 25 55, 48 28, 56 37
30 40
"""
coords = np.array(EIL51.replace(",", " ").split(), dtype=float).reshape(-1, 2)
distances = tsplib_distances(coords, "EUC_2D") # Euclidean, rounded to the nearest integer
n = len(coords)
problem = ypea.problems.tsp(coords, distances, name="eil51", optimum=426)
# the ants prefer a close next city: 1 / distance
closeness = 1 / (distances + np.eye(n)) # the diagonal is never used
alg = ypea.MMAS(heuristic={"tour": closeness}, max_nfe=20_000)
result = alg.solve(problem, seed=1)
print(result.summary())
MMAS on eil51
best objective value: 432
error: 6
feasible: True (violation 0)
evaluations: 20000, iterations: 393, time: 0.727 s, stopped by: max_nfe
Differs from Python: MATLAB draws its own random numbers, so the results differ from Python's. The heuristic is a struct keyed by the variable name.
% eil51: x y of each city
eil51 = [
37 52
49 49
52 64
20 26
40 30
21 47
17 63
31 62
52 33
51 21
42 41
31 32
5 25
12 42
36 16
52 41
27 23
17 33
13 13
57 58
62 42
42 57
16 57
8 52
7 38
27 68
30 48
43 67
58 48
58 27
37 69
38 46
46 10
61 33
62 63
63 69
32 22
45 35
59 15
5 6
10 17
21 10
5 64
30 15
39 10
32 39
25 32
25 55
48 28
56 37
30 40
];
coords = eil51;
distances = ypea.problems.tsplib_distances(coords, "EUC_2D"); % Euclidean, rounded to the nearest integer
n = size(coords, 1);
problem = ypea.problems.tsp(coords, distances=distances, name="eil51", optimum=426);
% the ants prefer a close next city: 1 / distance
closeness = 1 ./ (distances + eye(n)); % the diagonal is never used
alg = ypea.MMAS(heuristic=struct("tour", closeness), max_nfe=20000);
result = alg.solve(problem, seed=1);
disp(result.summary())
MMAS on eil51
best objective value: 430
error: 4
feasible: true (violation 0)
evaluations: 20000, iterations: 393, time: 2.77 s, stopped by: max_nfe
MAX-MIN Ant System finds a tour of length 432 in under a second, 1.4 percent above the optimum of 426. The full script, examples/applications/tsp.py, holds both instances and draws the tours below.
Results¶
Six setups, each with 10 seeded runs of 100 000 evaluations:
- GA, codes: GA on the [0, 1] codes of the tour (random keys), the default
space="encoded". - GA, native: GA with
space="native", so the permutation crossovers (OX, PMX and CX) and moves. - Memetic GA: the native GA with a population of 20, where 10 percent of the new tours get a 2-opt local search of up to 1000 evaluations (
local_search=, see Memetic runs). - HC, 2-opt: hill climbing with inversion moves only, which restarts from a random tour at each local optimum.
- ILS: iterated local search with its defaults.
- MMAS: MAX-MIN Ant System with the heuristic
1 / distance.
The gap is the distance above the optimum.
| Instance | Algorithm | Best | Mean | Worst | Runs at optimum | Gap of best | Mean gap |
|---|---|---|---|---|---|---|---|
| eil51 | GA, codes | 765 | 839.9 | 893 | 0 of 10 | 79.6% | 97.2% |
| eil51 | GA, native | 432 | 444.3 | 458 | 0 of 10 | 1.4% | 4.3% |
| eil51 | Memetic GA | 437 | 449.0 | 459 | 0 of 10 | 2.6% | 5.4% |
| eil51 | HC, 2-opt | 436 | 442.0 | 449 | 0 of 10 | 2.3% | 3.8% |
| eil51 | ILS | 427 | 436.7 | 445 | 0 of 10 | 0.2% | 2.5% |
| eil51 | MMAS | 426 | 429.0 | 432 | 1 of 10 | 0.0% | 0.7% |
| st70 | GA, codes | 1655 | 1910.8 | 2068 | 0 of 10 | 145.2% | 183.1% |
| st70 | GA, native | 702 | 720.0 | 745 | 0 of 10 | 4.0% | 6.7% |
| st70 | Memetic GA | 687 | 716.4 | 743 | 0 of 10 | 1.8% | 6.1% |
| st70 | HC, 2-opt | 701 | 720.6 | 741 | 0 of 10 | 3.9% | 6.8% |
| st70 | ILS | 682 | 718.8 | 742 | 0 of 10 | 1.0% | 6.5% |
| st70 | MMAS | 681 | 700.7 | 786 | 0 of 10 | 0.9% | 3.8% |
What the table shows:
- Codes do not work for tours. GA on the codes ends about 80 to 180 percent above the optimum. The same GA with native operators gets within a few percent.
- A local search does most of the work. Hill climbing with 2-opt moves alone is as good as the native GA. ILS, which perturbs each local optimum and searches again, finds the best single tours among the methods without a heuristic (0.2 and 1.0 percent above the optimum), but its runs vary a lot.
- The memetic GA gains little at this budget. Each local search costs up to 1000 evaluations, so the memetic GA makes few generations in this budget. It finds a better best tour than the plain GA on st70, but its mean is about the same, and it does a little worse on eil51.
- Knowledge of distances wins. MMAS is the best on both instances. It finds the optimal tour of eil51 once and stays within 1.4 percent in every run there. On st70, its mean is 3.8 percent above the optimum, with one poor run at 786. Ant Colony System (
ypea.ACS) found tours of similar quality on eil51 in a trial, but each run took several times longer than MMAS, so it is not in the table.
No method reaches the optimum reliably in 100 000 evaluations. The last percent is where the specialized TSP methods are much stronger: Lin-Kernighan moves in LKH, and exact branch and cut in Concorde.
Try it on your own cities¶
Replace the coordinates with your own, or pass any distance matrix to ypea.problems.tsp(distances=...): road distances, travel times, or costs that differ by direction (an asymmetric TSP). The tour is closed. For an open route that does not return to the start, add a dummy city at a tiny distance from every city (0 would make the ant heuristic 1 / distance infinite), and cut the tour there.
Practical advice:
- Use a method that knows tours. In the table, MMAS with the heuristic
1 / distanceis the best, then ILS, then GA withspace="native". Never search the [0, 1] codes of a tour. - Give the ants a heuristic. Without one, they learn from the pheromone alone and are much slower.
- The TSPLIB readers
read_tsplibandread_tsplib_tourload the library's files, andTSPLIB_OPTIMAholds the optimal lengths of a few small instances. - For hundreds of cities and more, or when only the shortest tour matters, use Concorde or LKH. Use ypea when the problem has rules of its own that do not fit those solvers, such as time windows (VRPTW), several objectives, or a cost that depends on the whole order.