Skip to main content

Chapter 4: How good is your tour?

Chapter 4: How good is your tour?

TipAt a glance
  • You will build: a scoreboard of seven ways to plan a tour, each tried on two hundred random sets of cafes
  • You need: Chapters 1 and 2 completed, in the same database. Chapter 3 is useful but not required
  • Time to run: about two minutes
  • Level: some Python (NumPy, pandas) and SQL

A solver always returns a tour, and on a map most tours look sensible. Chapters 2 and 3 scored several of them against the exact best one, but only for one set of fifteen cafes. Perhaps those cafes were kind to one method and unkind to another.

So this chapter repeats the comparison on two hundred random sets of fifteen cafes. Each method gets the same sets and the same costs, and each tour is measured against the exact best one for its set. At the end there is a check that needs no best tour at all: PostGIS looks at the drawing and tells you that some tours cannot be the best.

Left: a cloud of dots, some of them dark. Arrows lead to three small sets with a loop each. From each set an arrow leads to three bars of different length, measured from one dashed line.
The experiment: draw random cafes, plan a tour with each method, and measure how far it goes beyond the best one (the dashed line).
NoteLearning objectives

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

  • score tours fairly: the same stops, the same costs, the better of the two directions;
  • report a typical result and a bad one, not a single example;
  • tell a real difference between two methods from the luck of the draw;
  • use ST_IsSimple to spot a straight-line tour that cannot be the best, and say why it does not work for road tours;
  • say which shortcuts cost little and which cost a lot.

1. Setup

The cell connects to the database of the earlier chapters and checks that the network of Chapter 2 is there.

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 numpy as np
import pandas as pd
import psycopg
import shapely
import yaml

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


query("SELECT (SELECT count(*) FROM node) AS nodes, (SELECT count(*) FROM road) AS roads, "
      "(SELECT count(*) FROM stop_node) AS stops")
nodes roads stops
0 65182 77550 15

2. Two hundred sets of cafes

The pool

The random sets should look like real errands, so they are drawn from real places. sample-data/cafe-pool.csv holds the position of every cafe with a name that OpenStreetMap knew in the area of our streets (ledger L18). Each cafe goes to its nearest network node, as in Chapter 2. Where several cafes share a node, such as those in one shopping mall, the pool keeps one of them, because a trip from a node to itself is no trip.

places = pd.read_csv(ROOT / "sample-data" / "cafe-pool.csv")

with connect() as conn:
    conn.execute("""
        CREATE TEMP TABLE cafe (id integer, geom geometry(Point, 32748))""")
    conn.cursor().executemany("""
        INSERT INTO cafe
        VALUES (%s, ST_Transform(ST_Point(%s, %s, 4326), 32748))""",
        places[["id", "lon", "lat"]].values.tolist())
    conn.execute("""
        DROP TABLE IF EXISTS pool;
        CREATE TABLE pool AS
        SELECT DISTINCT ON (nearest.id)        -- one cafe per node
               cafe.id, nearest.id AS node, nearest.geom, moved_m
        FROM cafe
        CROSS JOIN LATERAL (
            SELECT node.id, node.geom, node.geom <-> cafe.geom AS moved_m
            FROM node
            ORDER BY node.geom <-> cafe.geom
            LIMIT 1
        ) AS nearest
        ORDER BY nearest.id, moved_m, cafe.id;
        ALTER TABLE pool ADD PRIMARY KEY (node);
        ANALYZE pool""")

pool = query("""
    SELECT count(*) AS cafes_in_pool,
           round((percentile_cont(0.5) WITHIN GROUP
                  (ORDER BY moved_m))::numeric) AS median_moved_m,
           round(max(moved_m)::numeric) AS largest_moved_m
    FROM pool""")
print(f"{len(places)} cafes in the file")
pool
524 cafes in the file
cafes_in_pool median_moved_m largest_moved_m
0 397 35 337

The draws

A draw is one random set of fifteen. The query sorts the pool by md5(), which scrambles text in a fixed way, and takes the first fifteen. It looks random, but your run draws the same cafes as this page.

Draw 0 is special: it holds the fifteen cafes of the earlier chapters. They go through exactly the same steps as the random sets, so we can check the new code against results we already know, and see at the end whether those cafes were typical.

DRAWS = 200

with connect() as conn:
    conn.execute(f"""
        DROP TABLE IF EXISTS draw_stop;
        CREATE TABLE draw_stop AS
        SELECT 0 AS draw, stop AS place, node
        FROM stop_node
        UNION ALL
        SELECT draw, place, node
        FROM (
            SELECT draw, node,
                   row_number() OVER (
                       PARTITION BY draw
                       ORDER BY md5(draw || '-' || id)
                   )::integer - 1 AS place
            FROM generate_series(1, {DRAWS}) AS draw, pool
        ) AS shuffled
        WHERE place < 15;
        ALTER TABLE draw_stop ADD PRIMARY KEY (draw, place);
        ANALYZE draw_stop""")

query("""
    SELECT count(DISTINCT draw) AS draws, count(*) AS stops,
           count(DISTINCT node) AS different_cafes
    FROM draw_stop""")
draws stops different_cafes
0 201 3015 397

The costs

Each method is tried with three goals: the shortest loop by distance on the road, the fastest loop by time, and the shortest loop in a straight line, as in Chapter 1.

The table trip holds the cost between every pair of cafes in the pool. cost respects the one-way streets. cost_both is for the simplified city in which every street may be driven both ways, rounded to whole metres or seconds, because that is what Chapter 2 gave to pgr_TSP. In straight lines the two are the same.

Then draw_leg picks the trips of each draw. It is the table road_leg of Chapter 2 with two more columns in front, draw and goal.

Slow cell: under a minute. It finds the cheapest route between all pairs of cafes four times over.

t = time.perf_counter()
with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS trip, draw_leg;
        CREATE TABLE trip (
            goal text, start integer, finish integer,
            cost float8, cost_both float8
        )""")
    for goal, view in [("distance", "drive_metres"), ("time", "drive_seconds")]:
        conn.execute(f"""
            INSERT INTO trip
            SELECT '{goal}', start_vid, end_vid,
                   real.agg_cost, round(simplified.agg_cost)
            FROM pgr_dijkstraCostMatrix(
                     'SELECT * FROM {view}',
                     (SELECT array_agg(node) FROM pool)) AS real
            JOIN pgr_dijkstraCostMatrix(
                     'SELECT * FROM {view}',
                     (SELECT array_agg(node) FROM pool),
                     directed => false) AS simplified
                 USING (start_vid, end_vid)""")
    conn.execute("""
        INSERT INTO trip
        SELECT 'straight line', a.node, b.node, metres, metres
        FROM pool AS a
        JOIN pool AS b ON a.node <> b.node,
             ST_Distance(a.geom, b.geom) AS metres;
        ANALYZE trip;

        CREATE TABLE draw_leg AS
        SELECT draw, goal, a.place AS i, b.place AS j, cost, cost_both
        FROM draw_stop AS a
        JOIN draw_stop AS b USING (draw)
        JOIN trip ON start = a.node AND finish = b.node;
        ALTER TABLE draw_leg ADD PRIMARY KEY (draw, goal, i, j);
        ANALYZE draw_leg""")
print(f"done in {time.perf_counter() - t:.0f} s")

legs = query("SELECT * FROM draw_leg")
legs.groupby("goal").cost.agg(["count", "median", "max"]).round(0)
done in 36 s
count median max
goal
distance 42210 6218.0 31140.0
straight line 42210 4587.0 24923.0
time 42210 839.0 3369.0

Each draw has 15 x 14 = 210 trips per goal, and there are 201 draws. The distances are in metres and the times in seconds.

3. Seven ways to plan a tour

The exact best tour, in NumPy

The query of Chapter 1 takes a second or so for fifteen stops. Now we need a thousand exact tours, so this function does the same in NumPy. The idea has not changed: for every set of visited stops and every last stop, keep only the cheapest route. The set is again a number with one binary digit per stop. NumPy is faster here because it fills a table of numbers in memory, while the SQL query has to sort rows.

def best_tour(cost):
    """The exact best loop from stop 0 (Held-Karp, Chapter 1). cost[i, j] is the cost from stop i to stop j."""
    n = len(cost) - 1                                  # the stops other than stop 0 are the digits 0 to n - 1
    visited = np.arange(1 << n)                        # every set of visited stops
    size = sum(visited >> k & 1 for k in range(n))     # how many stops are in it
    best = np.full((1 << n, n), np.inf)                # cheapest route for each set and last stop
    before = np.zeros((1 << n, n), dtype=int)          # the stop that this route visited before the last one
    best[1 << np.arange(n), np.arange(n)] = cost[0, 1:]
    for s in range(2, n + 1):
        for last in range(n):
            now = visited[(size == s) & (visited >> last & 1 == 1)]
            routes = best[now - (1 << last)] + cost[1:, last + 1]
            before[now, last] = routes.argmin(axis=1)
            best[now, last] = routes.min(axis=1)
    # every stop visited: go back to stop 0, then read the route from its end to its start
    now, last, path = (1 << n) - 1, int((best[-1] + cost[1:, 0]).argmin()), []
    while now:
        path.insert(0, last + 1)
        now, last = now - (1 << last), int(before[now, last])
    return [0, *path]


# one array per goal: cost[goal][draw, i, j]
cost, cost_both = {}, {}
for goal, rows in legs.groupby("goal"):
    for arrays, column in [(cost, "cost"), (cost_both, "cost_both")]:
        arrays[goal] = np.zeros((DRAWS + 1, 15, 15))
        arrays[goal][rows.draw, rows.i, rows.j] = rows[column]

t = time.perf_counter()
new = {goal: best_tour(cost[goal][0]) for goal in ["distance", "time"]}
print(f"two exact tours in {time.perf_counter() - t:.2f} s")

from_sql = query("SELECT name, path FROM road_tour WHERE name LIKE 'exact%'").set_index("name").path
for goal, name in [("distance", "exact, shortest"), ("time", "exact, fastest")]:
    print(f"{goal:9}", *new[goal], "  same as the SQL query:", new[goal] == from_sql[name])
two exact tours in 0.07 s
distance  0 3 14 1 2 13 9 7 5 12 6 10 4 8 11   same as the SQL query: True
time      0 3 14 1 2 13 9 7 5 6 12 10 11 4 8   same as the SQL query: True

Both give the tours that the SQL query found in Chapter 2. We also ran that query on the first twenty random draws, by distance and by time, and all forty costs were the same (ledger L19).

The two that grow a loop

The next function is farthest insertion from Chapter 3, the method of GRASS. There it gave the same tours as v.net.salesman. To be sure, we ran GRASS itself on ten random draws, by distance and by time. The twenty tours cost the same as those of this function. Eighteen are the same stop for stop, and in two of them a pair of neighbouring stops is swapped, at no cost (ledger L20). So the scoreboard can use the function in place of GRASS.

The other method is what many people do without a computer: from each cafe, drive to the nearest one that is left.

def farthest_insertion(cost):
    """Grow a loop like v.net.salesman in GRASS (Chapter 3)."""
    stops = range(len(cost))
    loop = [int(s) for s in np.unravel_index(cost.argmax(), cost.shape)]     # the two stops farthest apart
    while len(loop) < len(stops):
        new = max((s for s in stops if s not in loop),                       # the stop farthest from the loop
                  key=lambda s: cost[s, loop].min() + cost[loop, s].min())
        detour = [cost[a, new] + cost[new, b] - cost[a, b]                   # where does it add the least?
                  for a, b in zip(loop, loop[1:] + loop[:1])]
        loop.insert(detour.index(min(detour)) + 1, new)
    return loop


def nearest_next(cost):
    """From stop 0, always go to the nearest stop that is left."""
    path, left = [0], set(range(1, len(cost)))
    while left:
        path.append(min(left, key=lambda s: cost[path[-1], s]))
        left.remove(path[-1])
    return path


print("nearest next:      ", *nearest_next(cost["distance"][0]))
print("farthest insertion:", *farthest_insertion(cost["distance"][0]))
nearest next:       0 3 9 7 5 8 4 11 14 1 13 2 12 6 10
farthest insertion: 1 2 13 9 7 5 12 6 10 4 8 11 0 3 14

Solve them all

Every answer goes into one table, draw_tour. The exact tour is used in three ways:

  • exact best: with the real costs of the goal. This is the ruler for all others.
  • one-way ignored: exact for the simplified city where every street goes both ways.
  • straight lines: exact in a straight line, as in Chapter 1, and then driven on the road.
t = time.perf_counter()
tours = []
for draw in range(DRAWS + 1):
    straight = best_tour(cost["straight line"][draw])
    for goal in cost:
        c = cost[goal][draw]
        tours += [(draw, goal, "nearest next", 1, nearest_next(c)),
                  (draw, goal, "farthest insertion", 1, farthest_insertion(c))]
        if goal == "straight line":
            tours.append((draw, goal, "exact best", 1, straight))
        else:
            tours += [(draw, goal, "exact best", 1, best_tour(c)),
                      (draw, goal, "one-way ignored", 1, best_tour(cost_both[goal][draw])),
                      (draw, goal, "straight lines", 1, straight)]

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS draw_tour;
        CREATE TABLE draw_tour (
            draw integer, goal text, method text, attempt integer,
            path integer[] NOT NULL,
            PRIMARY KEY (draw, goal, method, attempt)
        )""")
    conn.cursor().executemany("INSERT INTO draw_tour VALUES (%s, %s, %s, %s, %s)", tours)
print(f"{len(tours):,} tours in {time.perf_counter() - t:.0f} s")
2,613 tours in 31 s

pgr_TSP runs in the database. Chapter 2 showed that its answer depends on the numbering of the stops, so it gets twenty attempts per draw. Attempt 1 keeps the stops in the order in which they were drawn. The other nineteen shuffle them. As in Chapter 2, it works on cost_both and its answers are scored on the real costs.

t = time.perf_counter()
with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS numbering;
        CREATE TABLE numbering AS
        SELECT attempt, place,
               CASE WHEN attempt = 1 THEN place + 1
                    ELSE row_number() OVER (
                             PARTITION BY attempt
                             ORDER BY md5(attempt || '-' || place))
               END::integer AS number
        FROM generate_series(1, 20) AS attempt,
             generate_series(0, 14) AS place;
        ALTER TABLE numbering ADD PRIMARY KEY (attempt, place);
        ANALYZE numbering;

        INSERT INTO draw_tour
        SELECT draw, goal, 'pgr_TSP', attempt,
               array_agg(place ORDER BY seq)
        FROM (SELECT DISTINCT draw, goal FROM draw_leg) AS task
        CROSS JOIN generate_series(1, 20) AS attempt
        CROSS JOIN LATERAL pgr_TSP(
            format('SELECT a.number AS start_vid, b.number AS end_vid,
                           cost_both AS agg_cost
                    FROM draw_leg
                    JOIN numbering AS a ON a.place = i
                    JOIN numbering AS b ON b.place = j
                    WHERE draw = %s AND goal = %L
                      AND a.attempt = %s AND b.attempt = a.attempt',
                   draw, goal, attempt),
            start_id => 1) AS answer
        JOIN numbering USING (attempt)
        WHERE numbering.number = answer.node
          AND seq <= 15                         -- row 16 is the return
        GROUP BY draw, goal, attempt""")
print(f"done in {time.perf_counter() - t:.0f} s")

query("SELECT method, count(*) AS tours FROM draw_tour GROUP BY method ORDER BY method")
done in 11 s
method tours
0 exact best 603
1 farthest insertion 603
2 nearest next 603
3 one-way ignored 402
4 pgr_TSP 12060
5 straight lines 402

4. One ruler for every tour

One query scores every tour. It is the query of Chapter 2 with the draw and the goal added: it looks up the cost of each leg in the real costs, once as the tour was written and once backwards.

Each tour counts in its better direction. Trying both takes no effort, so it would be unfair to punish a method for a choice that you can correct for free. What the wrong direction costs gets its own row: the exact best loop, driven the other way round.

scores = query("""
    WITH step AS (
        SELECT draw, goal, method, attempt, place AS i,
               lead(place) OVER (PARTITION BY draw, goal, method, attempt
                                 ORDER BY position) AS j
        FROM draw_tour,
             unnest(path || path[1]) WITH ORDINALITY AS v (place, position)
    )
    SELECT draw, goal, method, attempt,
           sum(go.cost) AS forwards, sum(back.cost) AS backwards
    FROM step
    JOIN draw_leg AS go USING (draw, goal, i, j)
    JOIN draw_leg AS back USING (draw, goal)
    WHERE back.i = step.j AND back.j = step.i
    GROUP BY draw, goal, method, attempt
    ORDER BY draw, goal, method, attempt""")
scores["cost"] = scores[["forwards", "backwards"]].min(axis=1)

# one column per method, one row per goal and draw
table = scores[scores.attempt == 1].pivot(index=["goal", "draw"], columns="method", values="cost")
exact = scores[scores.method == "exact best"].set_index(["goal", "draw"])
pgr = scores[scores.method == "pgr_TSP"].groupby(["goal", "draw"])
table = table.rename(columns={"pgr_TSP": "pgr_TSP, one answer"})
table["pgr_TSP, best of 20"] = pgr.cost.min()
table["best loop, wrong way"] = exact[["forwards", "backwards"]].max(axis=1)

# percent over the exact best tour of the same draw
over = table.div(table["exact best"], axis=0).sub(1).mul(100).drop(columns="exact best")
over.loc["distance"].head(4).T.round(1)
draw 0 1 2 3
method
farthest insertion 0.0 0.8 0.7 2.2
nearest next 18.5 23.2 6.6 12.9
one-way ignored 0.5 2.7 4.2 1.5
pgr_TSP, one answer 9.1 4.4 11.4 0.7
straight lines 0.4 9.6 3.8 2.0
pgr_TSP, best of 20 0.4 2.4 1.6 0.7
best loop, wrong way 8.3 27.4 26.4 10.5

Each number says by how many percent a tour is longer than the best possible one for that draw. Column 0 holds our fifteen cafes, and its numbers are those of Chapters 2 and 3. The other columns are random sets, and they already disagree about which method is better.

5. The scoreboard

A single number per method hides too much, so the table gives three. median is the typical result: half of the sets are better and half are worse. one_in_ten is a bad day: one set in ten is worse than this. worst is the worst of the two hundred. found_best is the share of sets in which the method found the exact best loop. The last column is for our fifteen cafes, which are not part of the others.

def scoreboard(goal):
    """Percent over the exact best tour, for the two hundred random draws."""
    x = over.loc[goal].drop(index=0)
    return pd.DataFrame({
        "median": x.median().round(1),
        "one_in_ten": x.quantile(0.9).round(1),
        "worst": x.max().round(1),
        "found_best": (x < 1e-6).mean().map("{:.0%}".format),
        "our_fifteen": over.loc[(goal, 0)].round(1),
    }).sort_values("median")


best_km = table.loc["distance", "exact best"].drop(index=0) / 1000
print(f"the best loops are {best_km.min():.0f} to {best_km.max():.0f} km long, median {best_km.median():.1f} km")
scoreboard("distance")
the best loops are 31 to 87 km long, median 61.6 km
median one_in_ten worst found_best our_fifteen
method
pgr_TSP, best of 20 0.2 2.1 18.5 38% 0.4
one-way ignored 0.4 3.1 19.0 32% 0.5
farthest insertion 0.8 3.8 10.0 32% 0.0
straight lines 2.0 6.1 22.6 11% 0.4
pgr_TSP, one answer 4.2 9.5 20.1 7% 9.1
best loop, wrong way 6.2 14.7 37.3 0% 8.3
nearest next 17.4 27.0 50.0 0% 18.5
best_min = table.loc["time", "exact best"].drop(index=0) / 60
print(f"the best loops take {best_min.min():.0f} to {best_min.max():.0f} minutes, median {best_min.median():.0f}")
scoreboard("time")
the best loops take 77 to 198 minutes, median 133
median one_in_ten worst found_best our_fifteen
method
pgr_TSP, best of 20 0.4 2.3 10.3 31% 3.0
one-way ignored 0.7 3.9 14.5 24% 0.0
farthest insertion 1.4 5.6 10.0 24% 2.6
straight lines 3.6 9.1 19.9 6% 4.9
pgr_TSP, one answer 4.5 10.0 18.3 3% 10.6
best loop, wrong way 8.0 16.6 32.2 0% 4.6
nearest next 15.8 25.1 35.9 0% 8.9
INK, GREEN, GREY, AMBER = "#003A40", "#3E9A4B", "#7C8B8D", "#C4622D"
order = over.loc["distance"].drop(index=0).median().sort_values(ascending=False).index
jitter = np.random.default_rng(1).uniform(-0.28, 0.28, DRAWS)

fig, axes = plt.subplots(1, 2, figsize=(9, 4.6), sharey=True, sharex=True)
for ax, goal in zip(axes, ["distance", "time"]):
    for row, method in enumerate(order):
        x = over.loc[goal][method]
        ax.scatter(x.drop(index=0), row + jitter, s=9, color=GREEN, alpha=0.45, lw=0, zorder=2)
        ax.plot([x.drop(index=0).median()] * 2, [row - 0.38, row + 0.38], color=INK, lw=2.5, zorder=3)
        ax.plot(x[0], row, "D", ms=6.5, color=AMBER, mec="white", mew=1, zorder=4)
    ax.set_title(f"by {goal}", loc="left", fontsize=11, color=INK)
    ax.set_xlabel("percent over the exact best loop")
    ax.grid(axis="x", color="#E3E8E9", lw=0.8)
    ax.set_axisbelow(True)
    ax.spines[["top", "right", "left"]].set_visible(False)
    ax.tick_params(axis="y", length=0)
axes[0].set_yticks(range(len(order)), order)
axes[1].plot([], [], "o", ms=4, color=GREEN, label="one random set")
axes[1].plot([], [], color=INK, lw=2.5, label="median")
axes[1].plot([], [], "D", ms=6, color=AMBER, label="our fifteen cafes")
axes[1].legend(loc="upper right", bbox_to_anchor=(1, 0.8), frameon=False, fontsize=9)
fig.tight_layout()
plt.show()

Two dot plots, by distance and by time. Each of seven methods has a row with one dot per random set. The best of 20 answers of pgr_TSP lies closest to zero. Nearest next is far to the right of all others.

Look before moving on. Start with the row at the bottom. Driving to the nearest cafe next feels sensible, and it is by far the worst plan. It picks up the easy stops first and pays for it at the end, when the stops that are left lie far apart.

Then look for the row of the best loop driven the wrong way. Its typical loss is larger than that of a single answer from pgr_TSP, and by distance it is about three times that of the straight lines. Apart from nearest next, checking the direction matters more than the choice of method, and it costs nothing.

Last, the diamonds. Our fifteen cafes were not a typical set. Farthest insertion found the best loop for them, which happens on about one set in three. The single answer of pgr_TSP was more than twice as far off as usual. If we had stopped after Chapter 3, we would have praised one program and blamed the other for what was mostly the luck of the draw.

Is the difference luck?

Two hundred sets are a sample. Another two hundred would give slightly different medians. A simple way to see how much is to split the sets in two halves and compute every median twice.

x = over.loc["distance"].drop(index=0)
halves = pd.DataFrame({"draws 1 to 100": x.loc[1:100].median(), "draws 101 to 200": x.loc[101:200].median()})
halves.loc[scoreboard("distance").index].round(1)
draws 1 to 100 draws 101 to 200
method
pgr_TSP, best of 20 0.3 0.1
one-way ignored 0.7 0.2
farthest insertion 0.9 0.7
straight lines 2.0 2.2
pgr_TSP, one answer 4.3 4.0
best loop, wrong way 6.5 6.0
nearest next 17.1 17.5

Most medians move by a few tenths of a percentage point. The three methods at the top are less than that apart in places, so two hundred sets are just enough to rank them. The large gaps further down are safe. We also ran five further groups of two hundred sets, by distance and by time. The order of the seven methods by their median was the same every time (ledger L21).

When two methods are close, compare them set by set, because both had the same cafes to visit.

def duel(a, b, goal="distance"):
    """On how many of the random sets is method a better than method b?"""
    d = (over.loc[goal][a] - over.loc[goal][b]).drop(index=0)
    print(f"{a} against {b}, by {goal}: better on {(d < -1e-6).sum()}, equal on {(d.abs() <= 1e-6).sum()}, "
          f"worse on {(d > 1e-6).sum()}")


duel("straight lines", "pgr_TSP, one answer")
duel("straight lines", "pgr_TSP, one answer", "time")
duel("farthest insertion", "one-way ignored")
duel("farthest insertion", "pgr_TSP, best of 20")
straight lines against pgr_TSP, one answer, by distance: better on 128, equal on 8, worse on 64
straight lines against pgr_TSP, one answer, by time: better on 97, equal on 3, worse on 100
farthest insertion against one-way ignored, by distance: better on 66, equal on 36, worse on 98
farthest insertion against pgr_TSP, best of 20, by distance: better on 54, equal on 33, worse on 113

The first two lines compare the simplest idea with a real routing function. By distance, the straight-line loop of Chapter 1 wins about twice as often as it loses against a single answer of pgr_TSP. By time they are even, because a straight line knows nothing about fast and slow roads. A method can be better on the median and still lose on many single sets, so the result of one example says little.

Does it depend on fifteen stops? We repeated the comparison by distance with 8, 10, 12, 17 and 19 stops (ledger L23). With fewer stops, every method looks better: with 8 stops, farthest insertion and twenty answers of pgr_TSP usually find the best loop. The order of the methods stayed the same, apart from one case: with 10 stops, a single answer of pgr_TSP was slightly ahead of the straight lines.

6. A check without the answer

All of this needed the exact best tour. With fifty stops you do not have it. Is there anything you can still check?

For tours in straight lines there is. The best loop never crosses itself. Suppose two of its legs cross, A to B and C to D. Replace them with A to C and B to D, and drive the part in between the other way round. It is still one loop through all the stops. And it is shorter: the two crossing legs are the diagonals of a four-sided figure, and together they are always longer than two of its opposite sides. So the loop was not the best.

Left: the legs A to B and C to D cross, and dashed lines join B to C and D to A. Right: the legs A to C and B to D have replaced them, and nothing crosses.
Two legs that cross can always be replaced by two shorter ones. The dashed parts of the loop stay as they are.

PostGIS has a function that looks for this. ST_IsSimple is true when a line does not pass through the same point twice, apart from its two ends (ledger L24). The query draws each loop as one closed line and asks.

drawn = query("""
    SELECT draw, goal, method, attempt,
           NOT ST_IsSimple(ST_MakeLine(node.geom ORDER BY position))
               AS crosses
    FROM draw_tour
    CROSS JOIN LATERAL unnest(path || path[1])
               WITH ORDINALITY AS v (place, position)
    JOIN draw_stop USING (draw, place)
    JOIN node ON node.id = draw_stop.node
    GROUP BY draw, goal, method, attempt""")

# add the score of each tour: percent over the exact best of its draw and goal
drawn = drawn.merge(scores[["draw", "goal", "method", "attempt", "cost"]])
drawn["over_best"] = 100 * (drawn.cost / drawn.set_index(["goal", "draw"]).index.map(table["exact best"]) - 1)

checked = drawn[(drawn.goal == "straight line") & (drawn.draw > 0) & (drawn.attempt == 1)]
print(f"straight-line loops that cross themselves, of {DRAWS}:")
print(checked.groupby("method").crosses.sum().to_string(header=False))
straight-line loops that cross themselves, of 200:
exact best              0
farthest insertion      5
nearest next          180
pgr_TSP                47

No exact loop crosses itself, as the argument says. Nearly all the loops of the nearest-next rule do. The next table takes the six hundred loops of the other three methods and asks what the check is worth.

others = checked[checked.method != "exact best"]
verdict = others.groupby("crosses").over_best.agg(
    loops="size", exact_best=lambda x: (x < 1e-6).sum(),
    median="median", largest="max").round(1)
verdict.rename(index={False: "does not cross", True: "crosses"})
loops exact_best median largest
crosses
does not cross 368 104 1.1 20.1
crosses 232 0 14.6 39.7
where = query("""
    SELECT method, array_agg(ST_X(geom) ORDER BY position) AS x, array_agg(ST_Y(geom) ORDER BY position) AS y
    FROM draw_tour
    CROSS JOIN LATERAL unnest(path || path[1]) WITH ORDINALITY AS v (place, position)
    JOIN draw_stop USING (draw, place)
    JOIN node ON node.id = draw_stop.node
    WHERE draw = 0 AND goal = 'straight line' AND method IN ('nearest next', 'exact best')
    GROUP BY method""").set_index("method")

fig, axes = plt.subplots(1, 2, figsize=(9, 3.9))
for ax, method, color in [(axes[0], "nearest next", AMBER), (axes[1], "exact best", GREEN)]:
    x, y = where.x[method], where.y[method]
    ax.plot(x, y, color=color, lw=2, zorder=2)
    ax.plot(x, y, "o", ms=8, color=INK, mec="white", mew=1, zorder=3)
    ax.plot(x[0], y[0], "o", ms=10, color=GREEN, mec="white", mew=1, zorder=4)
    edges = [shapely.LineString([a, b]) for a, b in zip(zip(x, y), zip(x[1:], y[1:]))]
    for i, e in enumerate(edges):
        for f in edges[i + 1:]:
            if e.crosses(f):                                   # legs that only share a stop do not count
                p = e.intersection(f)
                ax.plot(p.x, p.y, "o", ms=15, mfc="none", mec=INK, mew=1.6, zorder=5)
    km = shapely.LineString(list(zip(x, y))).length / 1000
    ax.set_title(f"{method}: {km:.1f} km in a straight line", loc="left", fontsize=10.5, color=INK)
    ax.set_aspect("equal")
    ax.axis("off")
fig.tight_layout()
plt.show()

Two maps of the fifteen cafes joined by straight lines. The nearest-next loop on the left crosses itself at the points marked with circles. The best loop on the right has no crossing.

Look before moving on. A loop that crosses itself is never the best one, and it is usually a poor one. The check works in one direction only, though. Most of the loops that pass are not the best either, and the worst of them is a long way off. Treat it like a spelling check: it finds certain mistakes, and a clean result does not make the text good.

On roads it does not work

The argument needs straight lines. Roads bend, share bridges and run one way, so two legs that cross on paper may be the right choice. Here are the exact best loops by road, drawn with straight lines between the stops:

by_road = drawn[(drawn.method == "exact best") & (drawn.goal != "straight line") & (drawn.draw > 0)]
crossing = by_road.groupby("goal").crosses.mean()
print("best loops by road that cross themselves when drawn straight:")
print(crossing.map("{:.0%}".format).to_string(header=False))
best loops by road that cross themselves when drawn straight:
distance    30%
time        46%

So do not straighten out a road tour because it looks untidy on the map. It may look untidy and be the best there is.

7. What to take from it

Percentages are hard to feel. The table turns them into kilometres and minutes on a typical set.

extra = pd.DataFrame({
    goal: (table.loc[goal].sub(table.loc[goal, "exact best"], axis=0) / unit).drop(index=0).median()
    for goal, unit in [("distance", 1000), ("time", 60)]}).drop(index="exact best")
extra.columns = ["extra_km", "extra_minutes"]
extra.sort_values("extra_km").round(1)
extra_km extra_minutes
method
pgr_TSP, best of 20 0.1 0.5
one-way ignored 0.2 0.9
farthest insertion 0.5 1.7
straight lines 1.3 4.6
pgr_TSP, one answer 2.4 5.8
best loop, wrong way 3.8 10.8
nearest next 10.5 20.8

For tours of about this size on these streets:

  1. Do not just drive to the nearest stop. Any of the other methods is better, and by a lot.
  2. Score both directions. The wrong one costs more than the difference between any two of the first five methods in the table.
  3. Ask an approximate solver many times and keep the best answer on the real costs. Twenty answers of pgr_TSP were closer to the best loop than any other method here.
  4. If you can ask only once, farthest insertion with one-way costs (v.net.salesman) was a safe choice. It had the smallest worst case of all seven, by distance and by time.
  5. Straight lines are a fair first guess by distance, and a weaker one by time.

These are results for fifteen cafes in one city, with the speeds that Chapter 2 assumed. Another city, or fifty stops, can give another order. The method of this chapter carries over: draw many sets, use the same ruler, and look at the bad days too.

Try it yourself

  • Change '-' in the md5() of section 2 to another text, such as '-mine-', and run the notebook again. You get two hundred new sets. Which numbers in the scoreboard change, and which stay?
  • Give pgr_TSP fifty attempts in place of twenty. How much does the best answer still improve?
  • Write a function that takes a straight-line loop, finds two legs that cross, uncrosses them, and repeats until ST_IsSimple is happy. How far from the best loop does it end?

Checkpoint

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

assert len(legs) == 3 * (DRAWS + 1) * 210 and legs.cost.gt(0).all()
assert all(new[goal] == from_sql[name] for goal, name in [("distance", "exact, shortest"), ("time", "exact, fastest")])
assert len(scores) == 201 * (3 * 20 + 3 * 3 + 2 * 2)                     # every tour was scored
assert over.min().min() > -1e-6                                          # nothing beats the exact loops
assert checked[checked.method == "exact best"].crosses.sum() == 0        # the best loop never crosses itself
assert verdict.exact_best[True] == 0                                     # and a loop that does is never the best
# the author's results
assert abs(table.loc[("distance", 0), "exact best"] - 61264.3) < 1 and abs(table.loc[("time", 0), "exact best"] - 8575.0) < 1
assert abs(over.loc["distance"].drop(index=0)["nearest next"].median() - 17.4) < 0.1
assert abs(over.loc["distance"].drop(index=0)["pgr_TSP, best of 20"].median() - 0.2) < 0.1
print("checkpoint passed")
checkpoint passed

Troubleshooting

Symptom Cause Fix
relation "stop_node" does not exist Chapter 2 has not been run in this database Run Chapters 1 and 2 first
draw_leg has too few rows A cafe of the pool has no route to another one Run section 2 of Chapter 2 again to the end; it keeps only the connected part of the network
The cost matrices take many minutes The server has little memory, or other work to do Let it finish once. The table trip stays in the database
The medians differ a little from this page You use another version of pgRouting, or other streets Expected. Compare the order of the methods, not the decimals

What comes next

The cafes were for fun. Chapter 5 plans a working day: a technician, twenty puskesmas, and the question whether it all fits before evening.