Skip to main content

Chapter 2: Real roads with pgRouting

Chapter 2: Real roads with pgRouting

TipAt a glance
  • You will build: a street network with one-way rules, the road cost between every pair of cafes, and the best loop on real roads
  • You need: Chapter 1 completed, in the same database
  • Time to run: under a minute
  • Level: some SQL (joins, GROUP BY, window functions); new to routing

Chapter 1 found the shortest loop through fifteen cafes in straight lines. A car follows streets, and some of them may be driven in one direction only. Does the order from Chapter 1 survive that?

This chapter turns OpenStreetMap streets into a network, measures the road between every pair of cafes, and runs the exact query of Chapter 1 on the new costs. It then asks pgRouting’s own solver, pgr_TSP, for a tour and measures how far its answer is from the best one.

NoteLearning objectives

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

  • turn streets into a network with SQL: cut them at the junctions, keep the one-way rules, and give each a travel time;
  • explain why a network needs to be strongly connected before you route on it;
  • compute a cost matrix on roads with pgr_dijkstraCostMatrix, and show that the way there and the way back can differ;
  • reuse one exact query for distance and for time;
  • run pgr_TSP, say what its guarantee covers, and get a much better answer by asking it many times.

1. Setup

The cell connects to the database of Chapter 1 and defines the same query() helper. It stops if the tables of Chapter 1 are not there.

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

import gzip
import time
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import psycopg
import shapely
import yaml
from matplotlib.collections import LineCollection

# 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"]


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])


straight = query("SELECT path, metres FROM tour WHERE name = 'best straight-line loop'").iloc[0]
stops = query("SELECT id, name, ST_X(geom) AS x_m, ST_Y(geom) AS y_m FROM stop ORDER BY id")
print(f"{len(stops)} stops; best straight-line loop: {straight.metres / 1000:.1f} km")
15 stops; best straight-line loop: 41.2 km

2. From streets to a network

Load the streets

sample-data/streets.csv.gz holds the streets of Kota Bandung and a margin around it, taken from OpenStreetMap (ledger L8). Streets that are closed to cars are left out. That matters here: many of Bandung’s small alleys, called gang, are mapped as streets but marked motorcar=no, and a route that uses them is of no use to a driver.

In OpenStreetMap a one-way street normally runs in the direction in which its line was drawn. Three streets in the file carry the value -1, which means the opposite direction (ledger L9). The query turns those lines around, so that from here on every one-way street runs from its first point to its last.

with connect() as conn:
    conn.execute("""
        CREATE TEMP TABLE raw_street (
            osm_id bigint, highway text, oneway text, junction text, wkt text
        )""")
    with conn.cursor().copy("COPY raw_street FROM STDIN (FORMAT csv, HEADER)") as copy:
        copy.write(gzip.open(ROOT / "sample-data" / "streets.csv.gz").read())
    conn.execute("""
        DROP TABLE IF EXISTS street;
        CREATE TABLE street AS
        SELECT osm_id,
               -- a slip road (motorway_link) counts as its parent class
               replace(highway, '_link', '') AS highway,
               -- no oneway tag: look at junction; no junction tag: false
               coalesce(oneway IN ('yes', '-1'),
                        junction IN ('roundabout', 'circular'),
                        false) AS one_way,
               CASE WHEN oneway = '-1' THEN ST_Reverse(line) ELSE line
               END AS geom
        FROM raw_street,
             ST_Transform(ST_GeomFromText(wkt, 4326), 32748) AS line;
        ALTER TABLE street ADD PRIMARY KEY (osm_id);
        ANALYZE street""")

query("""
    SELECT highway, count(*) AS streets,
           count(*) FILTER (WHERE one_way) AS one_way,
           round(sum(ST_Length(geom)) / 1000) AS km
    FROM street
    GROUP BY highway
    ORDER BY km DESC""")
highway streets one_way km
0 residential 31838 1290 3031.0
1 living_street 7060 48 552.0
2 tertiary 1752 613 401.0
3 unclassified 848 128 285.0
4 primary 1605 1249 232.0
5 secondary 981 510 196.0
6 motorway 409 396 156.0
7 trunk 733 598 109.0

Cut the streets at the junctions

These are lines on a map, not yet a network. One line can pass ten side streets, and nothing says that you may turn into them. A network has nodes, where you can choose, and roads between them.

OpenStreetMap makes the cut easy. Where two streets meet, they share a point with exactly the same position. Where one only passes over the other on a bridge, they do not. So a node is a position that is used more than once, or where a street ends. No distance tolerance and no search for crossing lines is needed.

Left: grey streets with their drawn points. One crosses another at a shared point, and one passes over on a bridge. Right: the same streets cut into coloured roads between dark nodes, with no node under the bridge.
Left, the streets as they are drawn. Right, the network: a node where streets share a point, and none where one passes over another.

The first query takes every street apart into its points and keeps the positions that are nodes.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS vertex, crossing;

        -- every point of every street, n = its place along the street
        CREATE TABLE vertex AS
        SELECT osm_id, (p).path[1] AS n, (p).geom AS geom
        FROM (SELECT osm_id, ST_DumpPoints(geom) AS p FROM street) AS d;

        CREATE TABLE crossing AS
        SELECT row_number() OVER (
                   ORDER BY ST_X(geom), ST_Y(geom)
               )::integer AS id,
               geom
        FROM (
            SELECT vertex.geom
            FROM vertex
            JOIN street USING (osm_id)
            GROUP BY vertex.geom
            -- streets meet here, or one ends here
            HAVING count(*) > 1
                OR bool_or(n IN (1, ST_NPoints(street.geom)))
        ) AS used;
        ANALYZE vertex;
        ANALYZE crossing""")

query("""
    SELECT (SELECT count(*) FROM vertex) AS points,
           (SELECT count(*) FROM crossing) AS nodes""")
points nodes
0 290766 66645

The second query walks along each street from node to node. lead() looks one row ahead, so each node finds the next one on its street, and the points between the two become one road. A small table adds a speed for each class of street.

The speeds are assumptions. They are round numbers chosen for this tutorial, not measurements, and they leave out traffic, traffic lights and waiting at junctions. They make a wide road faster than an alley, which is enough to compare tours with each other. Change them if you know better.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS speed, piece;

        CREATE TABLE speed (highway text PRIMARY KEY, kmh integer);
        INSERT INTO speed VALUES
            ('motorway', 60), ('trunk', 35), ('primary', 30),
            ('secondary', 25), ('tertiary', 22), ('unclassified', 18),
            ('residential', 15), ('living_street', 10);

        CREATE TABLE piece AS
        WITH cut AS (
            -- from each node (a) to the next node (b) on the same street
            SELECT osm_id, n AS a, lead(n) OVER along AS b,
                   crossing.id AS source,
                   lead(crossing.id) OVER along AS target
            FROM vertex
            JOIN crossing USING (geom)
            WINDOW along AS (PARTITION BY osm_id ORDER BY n)
        ),
        line AS (
            SELECT osm_id, a, source, target,
                   ST_MakeLine(vertex.geom ORDER BY n) AS geom
            FROM cut
            JOIN vertex USING (osm_id)
            WHERE n BETWEEN a AND b
              -- a loop back to the same node leads nowhere
              AND source <> target
            GROUP BY osm_id, a, source, target
        )
        SELECT row_number() OVER (ORDER BY osm_id, a)::integer AS id,
               source, target, highway, one_way,
               ST_Length(line.geom) AS metres,
               ST_Length(line.geom) / (kmh / 3.6) AS seconds,
               line.geom
        FROM line
        JOIN street USING (osm_id)
        JOIN speed USING (highway);
        ANALYZE piece""")

query("""
    SELECT count(*) AS roads, round(sum(metres) / 1000) AS km,
           round(avg(metres)) AS mean_m
    FROM piece""")
roads km mean_m
0 78606 4959.0 63.0

Keep the part where you can always get back

Some pieces are traps. A street may lead into a gated area that is cut off from the rest, or a one-way street may run off the edge of the download with no way back. If a cafe were attached to such a piece, some trips would have no route.

A network is strongly connected when you can drive from every node to every other node, respecting the one-way streets. pgr_strongComponents sorts the nodes into groups with that property. Like every pgRouting function, it takes a query as text. That query returns the roads with the cost of driving along the line (cost) and against it (reverse_cost), and a negative cost means that this direction does not exist (ledger L10).

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS component;
        CREATE TABLE component AS
        SELECT node, component
        FROM pgr_strongComponents('
            SELECT id, source, target, metres AS cost,
                   CASE WHEN one_way THEN -1 ELSE metres END AS reverse_cost
            FROM piece')""")

groups = query("""
    SELECT component, count(*) AS nodes,
           round(100 * count(*) / sum(count(*)) OVER (), 2) AS percent
    FROM component
    GROUP BY component
    ORDER BY nodes DESC""")
print(f"{len(groups):,} groups; the five largest:")
groups.head()
692 groups; the five largest:
component nodes percent
0 1 65182 97.80
1 60 28 0.04
2 21533 24 0.04
3 66143 19 0.03
4 10491 14 0.02

One group holds nearly everything, and the others are scraps. The next cell keeps the large group as the final tables node and road.

It also defines two views, drive_metres and drive_seconds. Each has the columns pgRouting expects, so every query that follows can say which cost it wants in a few words.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS node, road CASCADE;

        CREATE TABLE node AS
        SELECT crossing.id, crossing.geom
        FROM crossing
        JOIN component ON component.node = crossing.id
        WHERE component = (SELECT component FROM component
                           GROUP BY component ORDER BY count(*) DESC LIMIT 1);
        ALTER TABLE node ADD PRIMARY KEY (id);
        CREATE INDEX ON node USING gist (geom);

        CREATE TABLE road AS
        SELECT piece.*
        FROM piece
        JOIN node AS s ON s.id = source
        JOIN node AS t ON t.id = target;
        ALTER TABLE road ADD PRIMARY KEY (id);
        CREATE INDEX ON road USING gist (geom);
        ANALYZE node;
        ANALYZE road;

        CREATE VIEW drive_metres AS
        SELECT id, source, target, metres AS cost,
               CASE WHEN one_way THEN -1 ELSE metres END AS reverse_cost
        FROM road;

        CREATE VIEW drive_seconds AS
        SELECT id, source, target, seconds AS cost,
               CASE WHEN one_way THEN -1 ELSE seconds END AS reverse_cost
        FROM road""")

network = query("""
    SELECT (SELECT count(*) FROM node) AS nodes,
           count(*) AS roads,
           round(sum(metres) / 1000) AS km,
           round((100 * sum(metres) FILTER (WHERE one_way)
                  / sum(metres))::numeric, 1) AS percent_one_way
    FROM road""")
network
nodes roads km percent_one_way
0 65182 77550 4858.0 11.9
INK, GREEN, GREY, AMBER = "#003A40", "#3E9A4B", "#7C8B8D", "#C4622D"


def lines(text, **params):
    """The lines of a query that returns ST_AsBinary(geom) AS wkb, ready for matplotlib."""
    return [shapely.get_coordinates(g) for g in shapely.from_wkb(query(text, **params).wkb.map(bytes))]


STREETS = lines("SELECT ST_AsBinary(geom) AS wkb FROM road")


def street_map(ax, title, ids=None, also=(), margin=700):
    """Streets in light grey, the chosen stops as numbered dots (the start in green), and a 2 km scale bar.

    The map frames the stops and the lines in `also`."""
    chosen = stops if ids is None else stops[stops.id.isin(ids)]
    frame = np.vstack([chosen[["x_m", "y_m"]], *also])
    ax.add_collection(LineCollection(STREETS, colors="#C3CCCE", linewidths=0.45, zorder=1, rasterized=True))
    for s in chosen[::-1].itertuples():
        ax.plot(s.x_m, s.y_m, "o", ms=13, color=GREEN if s.id == 0 else INK, mec="white", mew=1, zorder=5)
        ax.text(s.x_m, s.y_m, s.id, color="white", ha="center", va="center_baseline", fontsize=7.5, weight="bold", zorder=5)
    ax.set_xlim(frame[:, 0].min() - margin, frame[:, 0].max() + margin)
    ax.set_ylim(frame[:, 1].min() - margin, frame[:, 1].max() + margin)
    x0, y0 = ax.get_xlim()[0] + 250, ax.get_ylim()[0] + 250
    ax.plot([x0, x0 + 2000], [y0, y0], color=INK, lw=2, zorder=6)
    ax.text(x0 + 1000, y0 + 90, "2 km", ha="center", fontsize=8.5, color=INK, zorder=6,
            bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.8, "pad": 0.5})
    ax.set_title(title, loc="left", fontsize=11, color=INK)
    ax.set_aspect("equal")
    ax.axis("off")


def finish(fig):
    fig.subplots_adjust(left=0.01, right=0.99, bottom=0.04, top=0.95, wspace=0.04)
    fig.text(0.99, 0.01, "Data © OpenStreetMap contributors", ha="right", fontsize=7.5, color=GREY)


fig, ax = plt.subplots(figsize=(9, 7))
street_map(ax, "The street network, with one-way streets in green")
ax.add_collection(LineCollection(lines("SELECT ST_AsBinary(geom) AS wkb FROM road WHERE one_way"),
                                 colors=GREEN, linewidths=1.1, zorder=2))
finish(fig)
plt.show()

Street map of Bandung in light grey with the one-way streets in green. One-way streets are dense in the centre around stops 0 and 3, and the main roads across the city show as long green lines.

Look before moving on. Two things are green. The streets of the centre, around stops 0 and 3, are one-way streets in the everyday sense. The long lines across the city are divided main roads, which OpenStreetMap draws as two one-way streets side by side (ledger L9). You cannot turn around on those just anywhere, so they cause detours too.

3. Put the cafes on the network

A route runs from node to node, so each cafe needs one. The query takes the nearest. The operator <-> in ORDER BY lets the spatial index find it without measuring the distance to every node.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS stop_node;
        CREATE TABLE stop_node AS
        SELECT stop.id AS stop, nearest.id AS node, nearest.moved_m
        FROM stop
        CROSS JOIN LATERAL (
            SELECT node.id, node.geom <-> stop.geom AS moved_m
            FROM node
            ORDER BY node.geom <-> stop.geom
            LIMIT 1
        ) AS nearest;
        ALTER TABLE stop_node ADD PRIMARY KEY (stop)""")

moved = query("""
    SELECT stop, name, round(moved_m::numeric) AS moved_m
    FROM stop_node
    JOIN stop ON stop.id = stop
    ORDER BY moved_m DESC""")
nodes_used = query("SELECT count(DISTINCT node) AS n FROM stop_node").n[0]
print(f"{nodes_used} different nodes; the stops that moved furthest:")
moved.head(4)
15 different nodes; the stops that moved furthest:
stop name moved_m
0 10 Smiljan 62
1 11 Tanulo Coffee 48
2 13 Wheel's Coffee Roasters 38
3 5 Kopi Goy 37

Every cafe has its own node, a short walk away at most. The trips below therefore run between junctions near the cafes and not between their doors, which is a small error on tours of this length.

4. What does each trip cost?

pgr_dijkstraCostMatrix finds the cheapest route between every pair in a list of nodes and returns only its cost. The name comes from Edsger Dijkstra, whose algorithm it uses (ledger L10). We run it twice, once for the shortest route and once for the fastest, and store both costs in road_leg. The table has the same form as leg in Chapter 1: a row says what it costs to go from stop i to stop j.

t = time.perf_counter()
with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS road_leg;
        CREATE TABLE road_leg AS
        SELECT a.stop AS i, b.stop AS j,
               shortest.agg_cost AS metres,
               fastest.agg_cost AS seconds
        FROM pgr_dijkstraCostMatrix(
                 'SELECT * FROM drive_metres',
                 (SELECT array_agg(node) FROM stop_node)) AS shortest
        JOIN pgr_dijkstraCostMatrix(
                 'SELECT * FROM drive_seconds',
                 (SELECT array_agg(node) FROM stop_node)) AS fastest
             USING (start_vid, end_vid)
        JOIN stop_node AS a ON a.node = start_vid
        JOIN stop_node AS b ON b.node = end_vid;
        ALTER TABLE road_leg ADD PRIMARY KEY (i, j);
        ANALYZE road_leg""")
print(f"two cost matrices in {time.perf_counter() - t:.1f} s")

query("""
    SELECT count(*) AS legs,
           round(min(road_leg.metres / leg.metres)::numeric, 2) AS smallest,
           round((percentile_cont(0.5) WITHIN GROUP
                  (ORDER BY road_leg.metres / leg.metres))::numeric, 2)
               AS median,
           round(max(road_leg.metres / leg.metres)::numeric, 2) AS largest
    FROM road_leg
    JOIN leg USING (i, j)""")
two cost matrices in 0.9 s
legs smallest median largest
0 210 1.09 1.32 4.95

The last three columns divide the road distance by the straight line. The median says how much longer a typical trip is on the road. The largest value belongs to two stops that are close together but hard to reach from each other.

There is not the same as back

In Chapter 1 both directions of a leg cost the same. The next query joins road_leg to itself with i and j swapped and lists the pairs where the two directions differ most.

uneven = query("""
    SELECT go.i, go.j,
           round((go.metres / 1000)::numeric, 1) AS km_i_to_j,
           round((back.metres / 1000)::numeric, 1) AS km_j_to_i,
           round((leg.metres / 1000)::numeric, 1) AS km_straight
    FROM road_leg AS go
    JOIN road_leg AS back ON back.i = go.j AND back.j = go.i
    JOIN leg ON leg.i = go.i AND leg.j = go.j
    WHERE go.metres > back.metres
    ORDER BY go.metres - back.metres DESC""")
uneven.head()
i j km_i_to_j km_j_to_i km_straight
0 1 14 8.6 5.5 3.3
1 1 11 11.0 8.7 7.5
2 1 0 7.4 5.4 4.4
3 1 6 13.2 11.3 10.0
4 1 8 9.6 7.9 6.3

The matrix has the costs but not the routes. pgr_dijkstraVia returns the roads of a route through a list of nodes, in order (ledger L10). The function below asks it for a route and joins the roads of each leg into one line. A road that is driven against its drawn direction has to be turned around first. The figure shows the first pair of the table, both ways.

ROUTE = """
SELECT path_id AS leg,
       ST_AsBinary(ST_MakeLine(
           CASE WHEN road.source = via.node THEN road.geom
                ELSE ST_Reverse(road.geom) END
           ORDER BY path_seq)) AS wkb
FROM pgr_dijkstraVia(
         'SELECT * FROM drive_metres',
         (SELECT array_agg(node ORDER BY position)
          FROM unnest(%(path)s::integer[])
               WITH ORDINALITY AS visit (stop, position)
          JOIN stop_node USING (stop))) AS via
JOIN road ON road.id = via.edge
GROUP BY path_id
ORDER BY path_id
"""


def route(path):
    """The shortest route through the stops in this order, one line per leg."""
    return lines(ROUTE, path=[int(i) for i in path])


def draw_route(ax, legs, color=GREEN):
    """The legs of a route, with an arrow halfway along each."""
    for xy in legs:
        ax.plot(*xy.T, color=color, lw=2.4, zorder=3)
        whole = shapely.LineString(xy)
        a, b = (whole.interpolate(f, normalized=True) for f in (0.49, 0.51))
        ax.annotate("", (b.x, b.y), (a.x, a.y), zorder=4,
                    arrowprops={"arrowstyle": "-|>", "color": color, "mutation_scale": 22, "lw": 0})


first = uneven.iloc[0]
pair = [int(first.i), int(first.j)]
there, back = route(pair), route(pair[::-1])
fig, axes = plt.subplots(1, 2, figsize=(9, 5.6))
for ax, title, legs, color in [
        (axes[0], f"Stop {pair[0]} to stop {pair[1]}: {first.km_i_to_j} km", there, AMBER),
        (axes[1], f"Stop {pair[1]} to stop {pair[0]}: {first.km_j_to_i} km", back, GREEN)]:
    street_map(ax, title, ids=pair, also=[*there, *back], margin=500)
    draw_route(ax, legs, color)
finish(fig)
plt.show()

Two street maps of the same two cafes, side by side. The route from the first to the second takes a much longer way round than the route back.

Look before moving on. A loop uses fourteen or fifteen such trips, and every one of them has a direction. So on roads a loop has two costs, one for each way round. A method that ignores direction can find a good loop and then drive it the wrong way.

5. The exact tour on roads

Nothing in the method of Chapter 1 needs both directions to cost the same. It extends routes one leg at a time, always from the last stop to the next, and looks up that leg in that direction. So the query can stay as it is. Only the first lines are new: they define leg from the road costs, which hides the table leg of Chapter 1 inside this query. The column is called cost now, because it can hold metres or seconds.

def best_tour(cost):
    """The exact best loop from stop 0 by 'metres' or 'seconds': the query of Chapter 1 on road costs."""
    return query(f"""
        WITH RECURSIVE leg AS (
            SELECT i, j, {cost} AS cost FROM road_leg
        ),
        best (visited, last, cost, path) AS (
            SELECT 1, 0, 0::float8, ARRAY[0]
            UNION ALL
            SELECT * FROM (
                SELECT DISTINCT ON (best.visited | (1 << leg.j), leg.j)
                       best.visited | (1 << leg.j),
                       leg.j,
                       best.cost + leg.cost,
                       best.path || leg.j
                FROM best
                JOIN leg ON leg.i = best.last
                WHERE best.visited & (1 << leg.j) = 0
                ORDER BY best.visited | (1 << leg.j), leg.j,
                         best.cost + leg.cost
            ) AS cheapest
        )
        SELECT best.path, best.cost + leg.cost AS cost
        FROM best
        JOIN leg ON leg.i = best.last AND leg.j = 0
        WHERE best.visited = (1 << %(n)s) - 1
        ORDER BY cost
        LIMIT 1""", n=len(stops)).iloc[0]


t = time.perf_counter()
shortest, fastest = best_tour("metres"), best_tour("seconds")
print(f"both tours in {time.perf_counter() - t:.1f} s")
print(f"shortest: {shortest.cost / 1000:6.2f} km   ", *shortest.path, 0)
print(f"fastest:  {fastest.cost / 60:6.1f} min  ", *fastest.path, 0)
print("the loop of Chapter 1:", *straight.path, 0)
print("the same, backwards:  ", 0, *straight.path[::-1])
both tours in 2.6 s
shortest:  61.26 km    0 3 14 1 2 13 9 7 5 12 6 10 4 8 11 0
fastest:   142.9 min   0 3 14 1 2 13 9 7 5 6 12 10 11 4 8 0
the loop of Chapter 1: 0 8 11 4 10 6 12 5 7 9 13 2 1 14 3 0
the same, backwards:   0 3 14 1 2 13 9 7 5 12 6 10 4 11 8 0

Those are the best possible loops on this network. The minutes are driving only, at the assumed speeds and without traffic.

To compare tours, the table road_tour stores each visiting order under a name. One query then scores them all, in both directions. For the direction backwards it does not need to turn the order around: it swaps i and j when it looks up each leg.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS road_tour;
        CREATE TABLE road_tour (
            name text PRIMARY KEY,
            path integer[] NOT NULL
        )""")


def save_road_tour(name, path):
    """Store a loop, turned so that it begins at stop 0."""
    path = [int(i) for i in path]
    if sorted(path) != list(range(len(stops))):
        raise ValueError("a tour visits every stop once")
    k = path.index(0)
    with connect() as conn:
        conn.execute("""
            INSERT INTO road_tour VALUES (%s, %s)
            ON CONFLICT (name) DO UPDATE SET path = excluded.path""", [name, path[k:] + path[:k]])


SCORES = """
WITH step AS (
    SELECT name, id AS i,
           lead(id) OVER (PARTITION BY name ORDER BY position) AS j
    FROM road_tour,
         unnest(path || 0) WITH ORDINALITY AS visit (id, position)
)
SELECT name,
       sum(go.metres) / 1000 AS km,
       sum(back.metres) / 1000 AS km_backwards,
       sum(go.seconds) / 60 AS minutes,
       sum(back.seconds) / 60 AS minutes_backwards
FROM step
JOIN road_leg AS go ON go.i = step.i AND go.j = step.j
JOIN road_leg AS back ON back.i = step.j AND back.j = step.i
GROUP BY name
ORDER BY least(sum(go.metres), sum(back.metres))
"""

save_road_tour("exact, shortest", shortest.path)
save_road_tour("exact, fastest", fastest.path)
save_road_tour("loop of Chapter 1", straight.path)
query(SCORES).round(2)
name km km_backwards minutes minutes_backwards
0 exact, shortest 61.26 66.34 149.87 153.39
1 loop of Chapter 1 66.22 61.51 153.62 149.95
2 exact, fastest 61.94 67.02 142.92 149.47

Read the row of the straight-line loop first. In one direction it is almost the best road loop: only stops 8 and 11 have changed places. In the other direction it is clearly longer. Chapter 1 had no way to tell the two apart, because in straight lines they are equal. The exact loops have a bad direction too.

The shortest loop and the fastest loop are also different tours. Each wins in its own column and loses a little in the other.

6. The tour from pgr_TSP

pgRouting has its own solver. pgr_TSP does not search for the best loop. It builds a good one quickly, which is what you need when there are too many stops for an exact query.

What it promises. The documentation says that its tour is at worst twice as long as the best one, if the costs are the same in both directions, every pair has a cost, and no detour is cheaper than the direct trip (ledger L11). Our one-way costs break the first condition. The documentation therefore recommends a cost matrix made with directed => false, which ignores the one-way rules. The promise then holds for that simplified city, and not for the real one. So we let pgr_TSP solve the simplified problem and score its answer on the real costs.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS two_way_leg;
        CREATE TABLE two_way_leg AS
        SELECT a.stop AS i, b.stop AS j,
               round(agg_cost) AS metres  -- whole metres: see below
        FROM pgr_dijkstraCostMatrix(
                 'SELECT * FROM drive_metres',
                 (SELECT array_agg(node) FROM stop_node),
                 directed => false)
        JOIN stop_node AS a ON a.node = start_vid
        JOIN stop_node AS b ON b.node = end_vid""")

# In pgr_TSP the number 0 means "any stop", so our stops are 1 to 15 here
answer = query("""
    SELECT node - 1 AS stop, agg_cost AS metres_so_far
    FROM pgr_TSP(
        'SELECT i + 1 AS start_vid, j + 1 AS end_vid, metres AS agg_cost
         FROM two_way_leg',
        start_id => 1)
    ORDER BY seq""")

print(*answer.stop)
print(f"{answer.metres_so_far.iloc[-1] / 1000:.2f} km, if every street could be driven both ways")
save_road_tour("pgr_TSP, one answer", answer.stop[:-1])
query(SCORES).round(2)
0 8 4 10 6 12 5 7 11 14 1 2 13 9 3 0
60.38 km, if every street could be driven both ways
name km km_backwards minutes minutes_backwards
0 exact, shortest 61.26 66.34 149.87 153.39
1 loop of Chapter 1 66.22 61.51 153.62 149.95
2 exact, fastest 61.94 67.02 142.92 149.47
3 pgr_TSP, one answer 66.86 67.50 159.28 159.35

The length that pgr_TSP reports is for the city without one-way rules. It is not a distance you can drive, and here it is even shorter than the best possible road loop. The table has the real cost of the same loop.

Why whole metres? Some cafes lie exactly on the shortest way between two others, so some sums of costs are equal. The computer rounds such sums a little differently, far behind the decimal point. In our test that was enough to change the answer of pgr_TSP by several kilometres (ledger L12). Rounding to metres removes differences that mean nothing.

One answer is a lottery ticket

The documentation warns that the result changes with the order of the input (ledger L11). We can see how much. The method connects the stops into a tree, starting from the first one, and then walks around the tree (ledger L13). Which branch it walks first has nothing to do with Bandung. It depends on how the stops happen to be numbered.

Left: six stops joined by a tree. Middle and right: two loops that follow the tree in different orders. The bar below the second loop is shorter.
One tree and two ways to walk around it. Each loop visits the stops in the order of its walk, and their lengths differ.

So number the same stops in a different way and ask again, two hundred times. The table shuffle holds two hundred numberings. It sorts the stops by md5(), which scrambles text in a fixed way, so your run uses the same numberings as this page. One query then asks for all the tours and scores them on the real costs, in both directions.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS shuffle;
        CREATE TABLE shuffle AS
        SELECT attempt, stop,
               row_number() OVER (
                   PARTITION BY attempt
                   ORDER BY md5(attempt || '-' || stop)
               )::integer AS number
        FROM generate_series(1, 200) AS attempt, stop_node;
        ALTER TABLE shuffle ADD PRIMARY KEY (attempt, stop)""")

t = time.perf_counter()
tries = query("""
    WITH answer AS (
        SELECT attempt, seq, shuffle.stop AS i,
               lead(shuffle.stop) OVER (PARTITION BY attempt ORDER BY seq) AS j
        FROM generate_series(1, 200) AS attempt
        CROSS JOIN LATERAL pgr_TSP(
            format('SELECT a.number AS start_vid, b.number AS end_vid,
                           metres AS agg_cost
                    FROM two_way_leg
                    JOIN shuffle AS a ON a.attempt = %1$s AND a.stop = i
                    JOIN shuffle AS b ON b.attempt = %1$s AND b.stop = j',
                   attempt),
            start_id => 1) AS tour
        JOIN shuffle USING (attempt)
        WHERE shuffle.number = tour.node
    )
    SELECT attempt,
           sum(go.metres) / 1000 AS km,
           sum(back.metres) / 1000 AS km_backwards,
           array_agg(answer.i ORDER BY seq) AS path
    FROM answer
    JOIN road_leg AS go ON go.i = answer.i AND go.j = answer.j
    JOIN road_leg AS back ON back.i = answer.j AND back.j = answer.i
    GROUP BY attempt
    ORDER BY least(sum(go.metres), sum(back.metres)), attempt""")
print(f"{len(tries)} tours in {time.perf_counter() - t:.1f} s")

winner = tries.iloc[0]
save_road_tour("pgr_TSP, best of 200",
               winner.path if winner.km <= winner.km_backwards else winner.path[::-1])
200 tours in 0.2 s
better = tries[["km", "km_backwards"]].min(axis=1)
best_km = shortest.cost / 1000

fig, ax = plt.subplots(figsize=(8, 3.4))
ax.hist(better, bins=30, color=GREEN, edgecolor="white", linewidth=0.8)
top = ax.get_ylim()[1]
for value, label in [(best_km, "exact best"), (better.median(), "median of 200"), (better.max(), "worst of 200")]:
    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 loop on real roads, better direction (km)")
ax.set_ylabel("number of answers")
ax.yaxis.get_major_locator().set_params(integer=True)
ax.spines[["top", "right"]].set_visible(False)
plt.show()
print(f"over the exact best: lowest {100 * (better.min() / best_km - 1):.1f}%, "
      f"median {100 * (better.median() / best_km - 1):.1f}%, highest {100 * (better.max() / best_km - 1):.1f}%")
print(f"answers that are the exact best loop: {(better < best_km + 0.001).sum()} of {len(better)}")

Histogram of the length of two hundred pgr_TSP loops in their better direction. They spread over several kilometres, and only a few come close to the exact best loop, marked by a line at the left edge.

over the exact best: lowest 0.0%, median 7.7%, highest 14.4%
answers that are the exact best loop: 2 of 200

Look before moving on. All these answers come from one method, one city and one set of cafes. Only the numbering changed. A single answer can land anywhere in this range, and nothing in it tells you where. But asking is cheap, and among two hundred answers is the exact best loop itself.

Was that luck? We repeated the experiment with fifty different sets of two hundred numberings. The exact loop was among the answers in 43 of them, and in the other seven the best answer was at most 0.41% longer (ledger L12). Without the exact query we could not have said that, because an approximate answer does not show how good it is.

This is worth remembering for larger problems, where the exact query no longer finishes: ask an approximate method many times, score every answer on the real costs, and keep the best.

7. The same loop, backwards

All the tours are in the table now. over_best_pct says by how many percent each one, in its better direction, is longer than the exact shortest loop. wrong_way_pct says how much longer the same loop gets when you drive it the other way round.

scores = query(SCORES)
both = scores[["km", "km_backwards"]]
low, high = both.min(axis=1), both.max(axis=1)
scores["over_best_pct"] = 100 * (low / best_km - 1)
scores["wrong_way_pct"] = 100 * (high / low - 1)
scores.drop(columns=["minutes", "minutes_backwards"]).round(2)
name km km_backwards over_best_pct wrong_way_pct
0 exact, shortest 61.26 66.34 0.00 8.28
1 pgr_TSP, best of 200 61.26 66.34 0.00 8.28
2 loop of Chapter 1 66.22 61.51 0.41 7.65
3 exact, fastest 61.94 67.02 1.10 8.20
4 pgr_TSP, one answer 66.86 67.50 9.14 0.95

Look before moving on. The last column shows what the straight lines of Chapter 1 could not. For most of these tours, turning around adds several percent, far more than the gap between the straight-line loop and the exact one. Checking both directions takes one extra join, so there is no reason to skip it.

The table also has a surprise. On these streets the straight-line loop, driven the right way round, beats the single answer of pgr_TSP, although it knows nothing about roads. It was the exact answer to a simplified problem, and pgr_TSP gave an approximate answer to a better one.

One set of fifteen cafes says nothing about which method is better in general. Chapter 4 looks at that question.

Finally, the best loop on the map, with arrows for the direction.

fig, ax = plt.subplots(figsize=(9, 7))
loop = route([*shortest.path, 0])
street_map(ax, f"The shortest loop by road: {shortest.cost / 1000:.1f} km", also=loop, margin=500)
draw_route(ax, loop)
finish(fig)
plt.show()

Map of the shortest loop by road through all fifteen cafes, drawn along the streets with an arrow on each leg. It circles the centre and has a long arm to stop 10 in the east.

Try it yourself

  • Section 6 uses metres. Build two_way_leg from drive_seconds as well, and ask for the fastest of fifteen tours. How close does it get to the exact fastest loop?
  • Change a speed in section 2, for example 20 km/h on a residential street, and run the notebook again. Which of the two exact tours can change, and which cannot?
  • Open the tables road and road_leg in QGIS through a PostGIS connection, and follow one of the detours street by street.

Checkpoint

The cell stops with an error if the results are not what this chapter expects. If you changed a speed or the streets, the last lines will not match.

assert len(stops) == 15 and query("SELECT count(*) AS n FROM road_leg").n[0] == 210
assert query("SELECT count(DISTINCT node) AS n FROM stop_node").n[0] == 15
# no road distance is below the straight line between the two nodes
assert query("""
    SELECT bool_and(metres >= ST_Distance(a.geom, b.geom) - 0.001) AS ok
    FROM road_leg
    JOIN stop_node AS s ON s.stop = i JOIN node AS a ON a.id = s.node
    JOIN stop_node AS e ON e.stop = j JOIN node AS b ON b.id = e.node""").ok[0]
# the scores agree with the exact query, and nothing beats it
exact = scores.set_index("name")
assert abs(exact.km["exact, shortest"] - best_km) < 1e-6
assert abs(exact.minutes["exact, fastest"] - fastest.cost / 60) < 1e-6
assert scores.over_best_pct.min() > -1e-6
assert scores[["minutes", "minutes_backwards"]].min().min() > fastest.cost / 60 - 1e-6
# the author's results
assert (network.nodes[0], network.roads[0]) == (65182, 77550)
assert abs(shortest.cost - 61264.3) < 1 and abs(fastest.cost - 8575.0) < 1
print("checkpoint passed")
checkpoint passed

Troubleshooting

Symptom Cause Fix
relation "tour" does not exist Chapter 1 has not been run in this database Run Chapter 1 first, with the same config.yml
function pgr_strongcomponents(unknown) does not exist pgRouting is not switched on in this database Run the first cell of Chapter 1, which creates the extension
road_leg has fewer than 210 rows Two cafes share a node, or a stop is on a piece that is cut off Run section 2 again to the end, then section 3
pgr_TSP starts at a stop you did not ask for The start was given as 0, which means “any stop” Number the stops from 1
The numbers differ from this page You made a new street file, and OpenStreetMap has changed since Expected. Use the file in the repository to repeat this page

What comes next

The tables node, road, stop_node, road_leg and road_tour stay in the database. Chapter 3 takes the same streets into GRASS and solves the same tour with v.net.salesman, which can use one-way costs directly.