Skip to main content

Chapter 1: The best tour in one SQL query

Chapter 1: The best tour in one SQL query

TipAt a glance
  • You will build: the shortest straight-line loop through fifteen cafes, found and proven in the database
  • You need: PostgreSQL with PostGIS and pgRouting (section 1), and the Python environment of this repository
  • Time to run: under a minute once the software is installed
  • Level: some SQL (joins, GROUP BY); new to routing

You want to visit fifteen cafes in Bandung and end where you started. In which order should you visit them? This is the Traveling Salesman Problem, TSP for short: given a list of stops and the distance between every pair, find the shortest loop that visits each stop once.

Many tools answer it with a good loop. This chapter finds the best one, with SQL alone, and the method itself guarantees that no other order is shorter. Distances here are straight lines; Chapter 2 moves the same stops onto real roads. Python only sends the queries and draws the maps: every query also runs in psql, pgAdmin or the QGIS DB Manager, once you replace %(n)s with the number of stops.

Three drawings of the same six cafes. A tangled red loop has the longest bar below it, an orange loop a shorter one, and a tidy green loop the shortest.
The same six cafes in three different orders. The bar below each loop shows its length.
NoteLearning objectives

By the end of this chapter you will be able to:

  • build a table of distances between points with a self-join in PostGIS;
  • list every possible loop with a recursive query, and say why that stops working after a few more stops;
  • explain the idea that makes an exact answer possible for fifteen stops (the Held-Karp method);
  • write that method as one recursive query, and check it against the list of every loop;
  • turn a visiting order into a line on a map.

1. Setup

The database. You need PostgreSQL with two extensions: PostGIS for geometry and pgRouting for Chapter 2. On Windows, install PostgreSQL 18 and then the PostGIS bundle, which contains both (ledger L1). Chapter 2 of our PostGIS tutorial shows this step by step, including the password file that lets a notebook connect without a password in its code. On macOS and Linux, use your package manager; conda-forge has PostGIS for both, but not for Windows (ledger L2).

The Python environment. In the repository folder, run conda env create -f environment.yml, then conda activate tsp and jupyter lab.

The settings. config.yml says where your database server is. The cell below reads it, creates a database called tsp if there is none yet, switches on the two extensions, and defines query(), which runs a query and shows the result as a table.

import os
os.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL")   # before numpy is imported (ledger L3)

import time
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import psycopg
import shapely
import yaml
from matplotlib.patheffects import withStroke
from psycopg import sql

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
DB = yaml.safe_load((ROOT / "config.yml").read_text(encoding="utf-8"))["database"]

with psycopg.connect(**{**DB, "dbname": "postgres"}, autocommit=True) as conn:
    if not conn.execute("SELECT 1 FROM pg_database WHERE datname = %s", [DB["dbname"]]).fetchone():
        conn.execute(sql.SQL("CREATE DATABASE {} TEMPLATE template0 ENCODING 'UTF8'").format(sql.Identifier(DB["dbname"])))


def connect():
    """A new session in the tutorial database. Used with `with`, it saves its changes when the block ends."""
    return psycopg.connect(**DB)


def query(text, **params):
    """Run one query and return its rows as a table."""
    with connect() as conn:
        cur = conn.execute(text, params or None)
        return pd.DataFrame(cur.fetchall(), columns=[c.name for c in cur.description])


with connect() as conn:
    conn.execute("CREATE EXTENSION IF NOT EXISTS postgis")
    conn.execute("CREATE EXTENSION IF NOT EXISTS pgrouting")

query("""
    SELECT current_setting('server_version') AS postgresql,
           postgis_lib_version() AS postgis,
           pgr_version() AS pgrouting""")
postgresql postgis pgrouting
0 18.7 3.7.0 4.0.3

2. Fifteen cafes

The stops are in sample-data/cafes.csv: fifteen coffee stops in Kota Bandung, taken from OpenStreetMap and chosen by hand (ledger L4). They are an example, not a ranking, and opening hours play no part in this problem.

The cell loads them into a table called stop. Stop 0 is where the tour starts and ends. The positions arrive as longitude and latitude in degrees. ST_Transform turns them into UTM zone 48 South (EPSG:32748), a flat map of this part of the world whose coordinates are in metres, so distances come out in metres too.

A second file, sample-data/kecamatan.csv, brings the borders of the kecamatan (districts) in and around the city, from Badan Informasi Geospasial, Indonesia’s mapping agency (ledger L22). The tour does not need them. They tell us where we are: ST_Contains finds the kecamatan of each cafe, and the maps show the borders in grey.

cafes = pd.read_csv(ROOT / "sample-data" / "cafes.csv")

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS stop;
        CREATE TABLE stop (
            id   integer PRIMARY KEY,
            name text NOT NULL,
            geom geometry(Point, 32748) NOT NULL
        )""")
    conn.cursor().executemany("""
        INSERT INTO stop
        VALUES (%s, %s, ST_Transform(ST_Point(%s, %s, 4326), 32748))""",
        cafes[["id", "name", "lon", "lat"]].values.tolist())

    conn.execute("""
        DROP TABLE IF EXISTS kecamatan;
        CREATE TABLE kecamatan (
            code    text PRIMARY KEY,
            name    text NOT NULL,
            regency text NOT NULL,             -- the kabupaten or kota
            geom    geometry(MultiPolygon, 32748) NOT NULL
        )""")
    conn.cursor().executemany("""
        INSERT INTO kecamatan
        VALUES (%s, %s, %s, ST_Transform(ST_GeomFromText(%s, 4326), 32748))""",
        pd.read_csv(ROOT / "sample-data" / "kecamatan.csv").values.tolist())

stops = query("""
    SELECT id, stop.name, kecamatan.name AS kecamatan,
           ST_X(stop.geom)::integer AS x_m, ST_Y(stop.geom)::integer AS y_m
    FROM stop
    JOIN kecamatan ON ST_Contains(kecamatan.geom, stop.geom)
    ORDER BY id""")
stops
id name kecamatan x_m y_m
0 0 Kopi Toko Djawa Sumur Bandung 788343 9234581
1 1 Calf Sukajadi 785275 9237694
2 2 Kisah Manis Cidadap 788175 9239809
3 3 Kopi Aroma Sumur Bandung 788008 9234585
4 4 Kopi Celah Kota Lengkong 790140 9232057
5 5 Kopi Goy Bandung Wetan 790326 9235594
6 6 Kopi Mandja Arcamanik 794819 9234700
7 7 Kopi Saring Sinar Pagi Bandung Wetan 789636 9235737
8 8 Lasco Koffie Haus Lengkong 789352 9232919
9 9 Makmur Jaya Bandung Wetan 788397 9236479
10 10 Smiljan Gedebage 798112 9230557
11 11 Tanulo Coffee Bojongloa Kidul 787989 9230721
12 12 Tedja Coffee Antapani Antapani 794095 9234047
13 13 Wheel's Coffee Roasters Coblong 789139 9238549
14 14 Yumaju Babakan Ciparay 785486 9234400
INK, GREEN, GREY = "#003A40", "#3E9A4B", "#7C8B8D"
# Where a name goes if not to the right of its dot: shift in points, and alignment
LABEL = {1: (-11, 0, "right"), 3: (4, -14, "right"), 4: (3, -14, "left"), 7: (3, 13, "left"),
         9: (-11, 0, "right"), 12: (10, -14, "right"), 14: (-11, 0, "right")}
# Metres to move a kecamatan name that would lie under a cafe
MOVE = {"Coblong": (-100, -900), "Gedebage": (-200, -800), "Sumur Bandung": (900, 100), "Lengkong": (150, 700),
        "Kiaracondong": (0, 900), "Sukajadi": (200, -700), "Bandung Wetan": (-500, 250), "Batununggal": (0, -1000),
        "Bandung Kulon": (1500, -50), "Sukasari": (350, -400), "Ujungberung": (50, -600), "Cicendo": (-500, 0), "Cibeunying Kaler": (350, -350)}
HALO = [withStroke(linewidth=2.5, foreground="white")]

borders = query("""
    SELECT name, regency, ST_AsBinary(geom) AS shape,
           ST_X(ST_PointOnSurface(geom)) AS x, ST_Y(ST_PointOnSurface(geom)) AS y
    FROM kecamatan""")
borders["shape"] = shapely.from_wkb(borders["shape"].map(bytes))
city = shapely.union_all(borders["shape"][borders.regency == "Kota Bandung"])


def base_map(title):
    """The stops as numbered dots, the start in green, over the kecamatan borders, with a 2 km scale bar."""
    fig, ax = plt.subplots(figsize=(9, 6.9))
    ax.set_facecolor("#F1F3F3")                               # outside the city
    for part in shapely.get_parts(city):
        ax.fill(*part.exterior.xy, color="white", zorder=0)
    for shape in shapely.get_parts(borders["shape"]):
        ax.plot(*shape.exterior.xy, color="#CCD4D5", lw=0.8, zorder=1)
    for part in shapely.get_parts(city):
        ax.plot(*part.exterior.xy, color=GREY, lw=1.8, zorder=1)
    for k in borders.itertuples():
        if k.regency == "Kota Bandung":
            dx, dy = MOVE.get(k.name, (0, 0))
            ax.text(k.x + dx, k.y + dy, k.name, color="#93A2A4", fontsize=6.5, ha="center", va="center", zorder=1)
    for s in stops[::-1].itertuples():                        # stop 0 last, so nothing covers it
        ax.plot(s.x_m, s.y_m, "o", ms=13, color=GREEN if s.id == 0 else INK, mec="white", mew=1, zorder=3)
        ax.text(s.x_m, s.y_m, s.id, color="white", ha="center", va="center_baseline", fontsize=7.5, weight="bold", zorder=3)
        dx, dy, ha = LABEL.get(s.id, (11, 0, "left"))
        ax.annotate(s.name + (" (start)" if s.id == 0 else ""), (s.x_m, s.y_m), xytext=(dx, dy), zorder=4,
                    textcoords="offset points", va="center", ha=ha, fontsize=8.5, color=INK, path_effects=HALO)
    west, south, east, north = city.bounds
    ax.set_xlim(west - 900, east + 600)
    ax.set_ylim(south - 900, north + 300)
    for x, y, name in [(0.05, 0.66, "KOTA CIMAHI"), (0.80, 0.86, "KABUPATEN BANDUNG"), (0.12, 0.93, "KABUPATEN BANDUNG BARAT"),
                       (0.45, 0.05, "KABUPATEN BANDUNG")]:
        ax.text(x, y, name, transform=ax.transAxes, color=GREY, fontsize=7.5, ha="center", va="center", zorder=1)
    x0, y0 = ax.get_xlim()[0] + 300, ax.get_ylim()[0] + 300
    ax.plot([x0, x0 + 2000], [y0, y0], color=INK, lw=2, zorder=4)
    ax.text(x0 + 1000, y0 + 110, "2 km", ha="center", fontsize=8.5, color=INK, zorder=4, path_effects=HALO)
    ax.set_title(title, loc="left", fontsize=11.5, color=INK)
    ax.set_aspect("equal")
    ax.set(xticks=[], yticks=[])
    ax.spines[:].set_visible(False)
    fig.subplots_adjust(left=0.01, right=0.99, bottom=0.04, top=0.95)
    fig.text(0.99, 0.012, "Cafes © OpenStreetMap contributors. Borders: Badan Informasi Geospasial", ha="right", fontsize=7.5, color=GREY)
    return ax


base_map("Fifteen coffee stops in Kota Bandung")
plt.show()

Map of the fifteen numbered cafes over the kecamatan of Kota Bandung. Most lie in the centre and north of the city; stop 10 is far to the east, in Gedebage.

Look before moving on. Trace a loop by eye that starts and ends at stop 0 and visits every number once. Write the order down: section 6 scores it against the best one.

3. A distance matrix

Every method in this tutorial starts from the same thing: the cost of going from each stop to each other stop. Joining the table to itself gives all the pairs, and ST_Distance measures them. In the table leg, a row says that going from stop i to stop j costs metres.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS leg;
        CREATE TABLE leg AS
        SELECT a.id AS i, b.id AS j, ST_Distance(a.geom, b.geom) AS metres
        FROM stop a
        JOIN stop b ON a.id <> b.id;
        ALTER TABLE leg ADD PRIMARY KEY (i, j);
        ANALYZE leg""")

query("""
    WITH measured AS (
        SELECT leg.metres AS flat,
               ST_Distance(ST_Transform(a.geom, 4326)::geography,
                           ST_Transform(b.geom, 4326)::geography) AS curved
        FROM leg
        JOIN stop a ON a.id = leg.i
        JOIN stop b ON b.id = leg.j
    )
    SELECT count(*) AS legs,
           min(flat)::integer AS shortest_m,
           max(flat)::integer AS longest_m,
           round(100 * max(abs(flat / curved - 1))::numeric, 3)
               AS largest_map_error_percent
    FROM measured""")
legs shortest_m longest_m largest_map_error_percent
0 210 335 14688 0.069

Fifteen stops with fourteen others each make 210 legs, and each pair appears twice, once per direction. In straight lines both directions cost the same. On roads they do not, which is why the table keeps both from the start.

The last column checks the flat map. It compares every leg with the distance on the curved Earth, which PostGIS computes from the geography type, and shows the largest difference.

4. Nine cafes: try every loop

Start small, with stops 0 to 8. The plainest method is to write down every possible order, add up each loop and take the shortest.

A recursive query can do that. It has two halves joined by UNION ALL. The first half is the starting point: a route that contains only stop 0. The second half takes the routes found in the previous round and extends each one by every stop it has not visited yet. PostgreSQL repeats the second half until it adds no more rows (ledger L5).

EVERY_ROUTE = """
WITH RECURSIVE route (path, metres) AS (
    -- start: a route that contains only stop 0
    SELECT ARRAY[0], 0::float8
    UNION ALL
    -- extend each route from its last stop to a stop it has not visited
    SELECT route.path || leg.j, route.metres + leg.metres
    FROM route
    JOIN leg ON leg.i = route.path[cardinality(route.path)]
    WHERE leg.j < %(n)s AND leg.j <> ALL (route.path)
),
tour AS (
    -- close each full route back to stop 0
    SELECT route.path, route.metres + leg.metres AS metres
    FROM route
    JOIN leg ON leg.i = route.path[%(n)s] AND leg.j = 0
    WHERE cardinality(route.path) = %(n)s
)
"""

t = time.perf_counter()
tours9 = query(EVERY_ROUTE + "SELECT * FROM tour ORDER BY metres, path", n=9)
seconds9 = time.perf_counter() - t
print(f"{len(tours9):,} tours in {seconds9:.1f} s")
tours9.head(4)
40,320 tours in 0.6 s
path metres
0 [0, 8, 4, 6, 5, 7, 2, 1, 3] 26163.405111
1 [0, 3, 1, 2, 7, 5, 6, 4, 8] 26163.405111
2 [0, 1, 2, 7, 5, 6, 4, 8, 3] 26590.061606
3 [0, 3, 8, 4, 6, 5, 7, 2, 1] 26590.061606

Look before moving on. The tours come in pairs of equal length: the same loop, driven in one direction and in the other. So the number of different loops is half the number of tours.

How much does the order matter? The figure shows the length of every tour.

km = tours9.metres / 1000
fig, ax = plt.subplots(figsize=(8, 3.4))
ax.hist(km, bins=60, color=GREEN, edgecolor="white", linewidth=0.8)
top = ax.get_ylim()[1]
for value, label in [(km.min(), "best"), (km.median(), "typical (median)"), (km.max(), "worst")]:
    ax.axvline(value, color=INK, lw=1.2)
    ax.text(value, top * 1.02, f"{label}\n{value:.1f} km", ha="center", va="bottom", fontsize=9, color=INK)
ax.set_xlabel("length of the tour (km, straight lines)")
ax.set_ylabel("number of tours")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
print(f"a typical tour is {km.median() / km.min():.1f} times as long as the best one")

Histogram of the length of every tour through nine stops. Most tours are far longer than the best one, which sits alone at the left edge.

a typical tour is 1.5 times as long as the best one

Why this stops working

From stop 0 there are 8 choices for the first visit, 7 for the second, and so on: 8 x 7 x … x 1 orders, written 8! (8 factorial). Each further stop multiplies that number. PostgreSQL can count the different loops for us. The last column is a rough projection: the time of the cell above, scaled up by the number of loops.

query("""
    SELECT n AS stops,
           (factorial(n - 1) / 2)::bigint AS different_loops,
           round(factorial(n - 1) / factorial(8)
                 * %(s)s::numeric / 3600, 1) AS projected_hours
    FROM unnest(ARRAY[9, 10, 12, 15, 20]) AS n""", s=seconds9).map("{:,}".format)
stops different_loops projected_hours
0 9 20,160 0.0
1 10 181,440 0.0
2 12 19,958,400 0.2
3 15 43,589,145,600 363.7
4 20 60,822,550,204,416,000 507,500,472.6

Nine stops are easy. Fifteen are not practical, and the projection leaves out the space that billions of routes would need. A faster computer does not help much either: going from fifteen stops to sixteen takes fifteen times the work.

5. Fifteen cafes: keep only what matters

The list of every route is wasteful, and a small example shows why. Take the routes that start at stop 0, visit stops 1 and 2, and are now at stop 3. There are two of them.

query(EVERY_ROUTE + """
    SELECT path, round(metres) AS metres
    FROM route
    WHERE cardinality(path) = 4 AND path[4] = 3
    ORDER BY metres""", n=4)
path metres
0 [0, 2, 1, 3] 12961.0
1 [0, 1, 2, 3] 13188.0
Stops 0, 2, 1 and 3 joined by a green route, and the same stops in the order 0, 1, 2, 3 joined by a dotted red route. Both end at stop 3, where a dashed grey line leads on to stops marked with question marks.
Two ways to reach stop 3. Whatever comes after it is the same for both, so only the shorter one is worth keeping.

Both routes have visited the same stops and stand at the same place, so from here on they have the same choices at the same cost. Whatever the rest of the tour looks like, the shorter start gives the shorter tour. The longer one can be thrown away at once, together with every tour that begins with it.

So there is no need to remember every route. For each set of visited stops and each last stop, one route is enough: the shortest. This is the Held-Karp method, published in 1962 by Held and Karp, and by Bellman in the same year (ledger L6).

Writing a set of stops as a number

The query has to recognise that 0-1-2-3 and 0-2-1-3 visited the same stops. It gives each stop one binary digit: stop 0 is worth 1, stop 1 is worth 2, stop 2 is worth 4, stop 3 is worth 8. A set of stops is the sum, so {0, 1, 2, 3} is 1 + 2 + 4 + 8 = 15, whatever the order. In SQL, 1 << j is the digit of stop j, visited | (1 << j) adds the stop to the set, and visited & (1 << j) = 0 is true when the stop is not in it yet.

Two rows of four boxes for stops 0 to 3. In the first row all boxes are on and 1 + 2 + 4 + 8 is 15. In the second row the box of stop 2 is off and 1 + 2 + 0 + 8 is 11.
Each stop is a switch with its own value. The sum says which switches are on.

The query

It has the same two halves as before. The new part is DISTINCT ON, which keeps the first row of each group of equal values, in the order given by ORDER BY (ledger L5). The group is the set of visited stops and the last stop; the first row is the shortest route. GROUP BY with min() would be the usual way to say this, but PostgreSQL refuses aggregate functions in the recursive half of a query (ledger L7).

HELD_KARP = """
WITH RECURSIVE best (visited, last, metres, path) AS (
    -- start: only stop 0 visited, standing at stop 0
    SELECT 1, 0, 0::float8, ARRAY[0]
    UNION ALL
    SELECT * FROM (
        -- extend each route; keep one per set of stops and last stop
        SELECT DISTINCT ON (best.visited | (1 << leg.j), leg.j)
               best.visited | (1 << leg.j),
               leg.j,
               best.metres + leg.metres,
               best.path || leg.j
        FROM best
        JOIN leg ON leg.i = best.last
        WHERE leg.j < %(n)s AND best.visited & (1 << leg.j) = 0
        -- the shortest of each group comes first
        ORDER BY best.visited | (1 << leg.j), leg.j,
                 best.metres + leg.metres
    ) AS shortest
)
"""

BEST_TOUR = HELD_KARP + """
-- every stop visited: go back to stop 0 and take the shortest
SELECT best.path, best.metres + leg.metres AS metres
FROM best
JOIN leg ON leg.i = best.last AND leg.j = 0
WHERE best.visited = (1 << %(n)s) - 1
ORDER BY metres
LIMIT 1
"""

t = time.perf_counter()
best15 = query(BEST_TOUR, n=15).iloc[0]
seconds15 = time.perf_counter() - t
print(f"{best15.metres / 1000:.2f} km in {seconds15:.1f} s")
print(" - ".join(str(i) for i in [*best15.path, 0]))
41.20 km in 1.4 s
0 - 8 - 11 - 4 - 10 - 6 - 12 - 5 - 7 - 9 - 13 - 2 - 1 - 14 - 3 - 0

That is the shortest possible loop through all fifteen stops. Your run may print it in the opposite direction, which has the same length here.

Is it really the best?

The argument above says so, but a query can contain a mistake. Section 4 listed every tour through nine stops, so the two methods can be compared: for four to nine stops, the new query must find the same shortest length as the full list.

check = pd.DataFrame([{
    "stops": n,
    "every_tour_m": query(EVERY_ROUTE + "SELECT min(metres) AS m FROM tour", n=n).m[0],
    "held_karp_m": query(BEST_TOUR, n=n).metres[0]} for n in range(4, 10)])
check["same"] = (check.every_tour_m - check.held_karp_m).abs() < 1e-6
check.round(2)
stops every_tour_m held_karp_m same
0 4 13295.62 13295.62 True
1 5 19161.10 19161.10 True
2 6 19438.04 19438.04 True
3 7 25850.63 25850.63 True
4 8 26149.44 26149.44 True
5 9 26163.41 26163.41 True

How much work did it save?

The next query counts the routes that Held-Karp kept after each round. Beside them is the number of routes the full list would hold at that point.

work = query(HELD_KARP + """
    SELECT cardinality(path) AS stops_visited,
           (factorial(14) / factorial(15 - cardinality(path)))::bigint
               AS routes_in_full_list,
           count(*) AS routes_kept
    FROM best
    GROUP BY 1, 2
    ORDER BY 1""", n=15)
print(f"kept in total: {work.routes_kept.sum():,}")
work.map("{:,}".format)
kept in total: 114,689
stops_visited routes_in_full_list routes_kept
0 1 1 1
1 2 14 14
2 3 182 182
3 4 2,184 1,092
4 5 24,024 4,004
5 6 240,240 10,010
6 7 2,162,160 18,018
7 8 17,297,280 24,024
8 9 121,080,960 24,024
9 10 726,485,760 18,018
10 11 3,632,428,800 10,010
11 12 14,529,715,200 4,004
12 13 43,589,145,600 1,092
13 14 87,178,291,200 182
14 15 87,178,291,200 14

Look before moving on. The full list grows in every round. The kept routes grow until the middle and then shrink again, because near the end there are few sets of stops left to tell apart.

The method is still not free. Each extra stop a little more than doubles the number of routes to keep. That is why this tutorial uses fifteen cafes and not thirty. In our test, the query took 1.4 seconds for 15 stops, 3 seconds for 16, 8 seconds for 17 and 19 seconds for 18 (ledger L23). Fifteen is enough to make a real puzzle, and the exact answer still comes while you wait. Chapter 4 tries two hundred other sets of fifteen, and Chapter 5 has a tour with twenty stops.

6. Draw the loop

The answer is a list of numbers. To map it, unnest ... WITH ORDINALITY turns the list into rows that remember their position, a join fetches each point, and ST_MakeLine connects them in that order. The table tour stores the result under a name, because the next chapters add their own tours to it.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS tour;
        CREATE TABLE tour (
            name   text PRIMARY KEY,
            path   integer[] NOT NULL,
            metres float8 NOT NULL,                  -- straight-line length
            geom   geometry(LineString, 32748) NOT NULL
        )""")

SAVE_TOUR = """
INSERT INTO tour
SELECT %(name)s, %(path)s::integer[], ST_Length(line), line
FROM (
    SELECT ST_MakeLine(stop.geom ORDER BY visit.position) AS line
    -- || 0 returns to the start
    FROM unnest(%(path)s::integer[] || 0)
         WITH ORDINALITY AS visit (id, position)
    JOIN stop USING (id)
) AS drawn
ON CONFLICT (name) DO UPDATE
SET path = excluded.path, metres = excluded.metres, geom = excluded.geom
"""


def save_tour(name, path):
    path = [int(i) for i in path]
    if sorted(path) != list(range(len(stops))) or path[0] != 0:
        raise ValueError("a tour starts at stop 0 and visits every stop once")
    with connect() as conn:
        conn.execute(SAVE_TOUR, {"name": name, "path": path})


save_tour("best straight-line loop", best15.path)
query("SELECT name, round(metres) AS metres, ST_NPoints(geom) AS points, ST_IsClosed(geom) AS closed FROM tour")
name metres points closed
0 best straight-line loop 41205.0 16 True
line = query("SELECT (p).path[1] AS n, ST_X((p).geom) AS x, ST_Y((p).geom) AS y "
             "FROM (SELECT ST_DumpPoints(geom) AS p FROM tour WHERE name = 'best straight-line loop') AS d ORDER BY n")
ax = base_map(f"The shortest straight-line loop: {best15.metres / 1000:.1f} km")
ax.plot(line.x, line.y, color=GREEN, lw=2.2, zorder=2)
plt.show()

Map of the shortest straight-line loop: one closed line through all fifteen cafes that never crosses itself, with a long arm to stop 10 in the east.

Score your own loop

Replace the numbers in MY_ORDER with the order you wrote down in section 2 and run the cell. Until you do, it scores the order of the file, which is alphabetical.

MY_ORDER = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

save_tour("my order", MY_ORDER)
query("""
    SELECT name, round((metres / 1000)::numeric, 1) AS km,
           round(((metres / min(metres) OVER () - 1) * 100)::numeric, 1)
               AS percent_over_best
    FROM tour
    ORDER BY metres""")
name km percent_over_best
0 best straight-line loop 41.2 0.0
1 my order 80.0 94.1

Checkpoint

The cell below stops with an error if the results are not what this chapter expects. It tests the length of the best loop and not its direction, so it passes either way round.

assert len(stops) == 15 and query("SELECT count(*) AS n FROM leg").n[0] == 210
assert len(tours9) == 40320                                     # 8!
assert check.same.all()
assert work.routes_kept.sum() == 14 * 2**13 + 1                 # every set and last stop, plus the start
saved = query("SELECT metres FROM tour WHERE name = 'best straight-line loop'").metres[0]
assert abs(saved - best15.metres) < 1e-6                        # ST_Length agrees with the sum of the legs
assert abs(saved - 41204.8) < 1                                # the author's result, in metres
print("checkpoint passed")
checkpoint passed

Troubleshooting

Symptom Cause Fix
connection refused The server is not running, or it uses another port Start PostgreSQL; put its port in config.yml
fe_sendauth: no password supplied There is no password file, or its line does not match config.yml Follow section 3 of the setup chapter of our PostGIS tutorial
extension "pgrouting" is not available pgRouting is not installed on the server Windows: install the PostGIS bundle; elsewhere: install the pgRouting package for your PostgreSQL version
Section 4 runs for minutes n is larger than 10 in the query that lists every route Interrupt the kernel and go back to 9
The notebook stops without a message The numpy problem of ledger L3 Restart the kernel and run the first cell before anything else

What comes next

Nobody drives in straight lines. Chapter 2 puts the same cafes on Bandung’s streets, where some roads run one way only, and runs the same query on the new distances.