Skip to main content

Chapter 5: Twenty puskesmas in one day?

Chapter 5: Twenty puskesmas in one day?

TipAt a glance
  • You will build: an exact round of twenty puskesmas, a timetable for it, and an answer to how many fit in a day
  • You need: Chapters 1 and 2 completed, in the same database. Chapters 3 and 4 are useful but not required
  • Time to run: about two minutes
  • Level: some Python (NumPy, pandas) and SQL

The cafes were for fun. This chapter plans a working day. A technician has to check the equipment of twenty puskesmas (community health centres) in Bandung and be back by the end of office hours. Is that one day of work or two?

Two things are new. The round is longer than the query of Chapter 1 can comfortably handle, so we hand it to HiGHS, an open-source solver. And the best round is no longer the whole answer, because a day also holds visits, a break and traffic.

A van drives along a road with five health centres. Below, the day is drawn as a bar of driving, visits and a break. It starts at half past seven and runs past the line at four o'clock.
A day is made of driving (dark), visits (green) and a break. The question is whether it ends before the dashed line.
NoteLearning objectives

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

  • prepare health facility points from open data, and say what is missing from them;
  • say why the exact SQL query stops being practical at about twenty stops;
  • solve a larger tour exactly with HiGHS, through SciPy, and check the solver against a result you trust;
  • turn a tour into a timetable;
  • tell which answers come from the data and which come from your assumptions.

1. Setup

The cell connects to the database of the earlier chapters and checks that their tables are 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
from matplotlib.collections import LineCollection
from matplotlib.patheffects import withStroke
from scipy.optimize import Bounds, LinearConstraint, milp

# 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 kecamatan) AS kecamatan")
nodes roads kecamatan
0 65182 77550 55

2. Find the puskesmas

healthsites.io collects health facilities from OpenStreetMap and publishes them by country. sample-data/puskesmas.csv holds every site in our area whose name contains “puskesmas” (ledger L25). It was selected by name because the tag is not reliable. Look at how the same kind of place is classified:

sites = pd.read_csv(ROOT / "sample-data" / "puskesmas.csv", keep_default_na=False)
print(f"{len(sites)} sites, last edited between {sites.edited.min()} and {sites.edited.max()}")
print(sites.amenity.replace("", "(no tag)").value_counts().to_string(header=False))
48 sites, last edited between 2011-08-06 and 2026-09-21
clinic      29
hospital    15
(no tag)     3
disused      1

Open data needs a look before it goes into a plan. The next cell loads the sites and lists the rows that raise a question: no name of their own, not in use, or a name that appears more than once. The kecamatan come from Chapter 1.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS health_site;
        CREATE TABLE health_site (
            osm_id text PRIMARY KEY,
            name text, amenity text, edited date,
            geom geometry(Point, 32748)
        )""")
    conn.cursor().executemany("""
        INSERT INTO health_site VALUES (%s, %s, %s, %s,
            ST_Transform(ST_Point(%s, %s, 4326), 32748))""",
        list(sites.itertuples(index=False, name=None)))

query("""
    SELECT site.name, amenity, edited,
           kecamatan.name AS kecamatan, regency
    FROM health_site AS site
    JOIN kecamatan ON ST_Contains(kecamatan.geom, site.geom)
    WHERE site.name = 'Puskesmas'
       OR amenity = 'disused'
       OR site.name IN (SELECT name FROM health_site
                        GROUP BY name HAVING count(*) > 1)
    ORDER BY site.name, edited""")
name amenity edited kecamatan regency
0 Puskesmas hospital 2014-09-05 Bandung Wetan Kota Bandung
1 Puskesmas clinic 2023-09-10 Antapani Kota Bandung
2 Puskesmas Dago hospital 2018-07-30 Coblong Kota Bandung
3 Puskesmas Dago 2021-01-25 Coblong Kota Bandung
4 Puskesmas Padasuka clinic 2022-06-10 Cibeunying Kidul Kota Bandung
5 Puskesmas Padasuka clinic 2022-06-14 Cimahi Tengah Kota Cimahi
6 Puskesmas Pasirkaliki 2020-05-14 Cimahi Utara Kota Cimahi
7 Puskesmas Pasirkaliki clinic 2025-08-05 Cicendo Kota Bandung
8 Puskesmas Sarijadi disused 2022-02-16 Sukasari Kota Bandung

Two sites are called just “Puskesmas”, so nobody would know where to send the technician. Sarijadi is marked as no longer in use. Dago, Padasuka and Pasirkaliki appear twice. The two entries for Dago are the same place, mapped twice. The other two names belong to one puskesmas in the city and another one in Kota Cimahi.

So the rules are: inside Kota Bandung, with a name of its own, in use, and for a repeated name the entry that was edited last. The same query attaches each puskesmas to its nearest network node, as in Chapter 2. It also takes UPT and UPTD off the names, an abbreviation for a technical unit of the local government.

with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS puskesmas;
        CREATE TABLE puskesmas AS
        SELECT DISTINCT ON (site.name)         -- the latest entry per name
               site.osm_id, site.name AS full_name,
               regexp_replace(site.name,
                              '^(UPTD? )?Puskesmas ', '') AS name,
               kecamatan.name AS kecamatan,
               nearest.id AS node, moved_m, site.geom
        FROM health_site AS site
        JOIN kecamatan ON ST_Contains(kecamatan.geom, site.geom)
        CROSS JOIN LATERAL (
            SELECT node.id, node.geom <-> site.geom AS moved_m
            FROM node
            ORDER BY node.geom <-> site.geom
            LIMIT 1
        ) AS nearest
        WHERE regency = 'Kota Bandung'
          AND site.name <> 'Puskesmas'
          AND amenity <> 'disused'
        ORDER BY site.name, edited DESC;
        ALTER TABLE puskesmas ADD PRIMARY KEY (node);
        ANALYZE puskesmas""")

query("""
    SELECT count(*) AS puskesmas,
           count(DISTINCT kecamatan) AS in_kecamatan,
           (SELECT count(*) FROM kecamatan
            WHERE regency = 'Kota Bandung') AS of_kecamatan,
           round(max(moved_m)::numeric) AS largest_moved_m
    FROM puskesmas""")
puskesmas in_kecamatan of_kecamatan largest_moved_m
0 32 23 30 146

This is not the official list. The health office of the city counted 80 puskesmas in 2021, with at least one in every kecamatan (ledger L26). Our file has fewer than half of them by name. That is enough to practise on, and not enough to plan real maintenance. If you know one that is missing, add it to OpenStreetMap: the next technician will be glad.

3. The work order

The technician’s list has twenty puskesmas. The round starts and ends at Puskesmas Balai Kota Bandung, which gets a visit too. The other nineteen are drawn with md5(), as in Chapter 4.

Chapter 4 also taught us not to trust a single set. So we draw a hundred work orders. Number 1 is the day that we plan, and the others will show whether it is a typical one.

ORDERS = 100

with connect() as conn:
    conn.execute(f"""
        DROP TABLE IF EXISTS work_order;
        CREATE TABLE work_order AS
        SELECT number, stop, node
        FROM (
            SELECT number, node,
                   row_number() OVER (
                       PARTITION BY number
                       ORDER BY name <> 'Balai Kota Bandung',  -- first
                                md5(number || '-' || full_name)
                   )::integer - 1 AS stop
            FROM generate_series(1, {ORDERS}) AS number, puskesmas
        ) AS shuffled
        WHERE stop < 20;
        ALTER TABLE work_order ADD PRIMARY KEY (number, stop)""")

stops = query("""
    SELECT stop, name, kecamatan, node,
           ST_X(geom) AS x_m, ST_Y(geom) AS y_m
    FROM work_order
    JOIN puskesmas USING (node)
    WHERE number = 1
    ORDER BY stop""")
stops[["stop", "name", "kecamatan"]]
stop name kecamatan
0 0 Balai Kota Bandung Sumur Bandung
1 1 Pasirkaliki Cicendo
2 2 Karang Setra Sukasari
3 3 Talaga Bodas Lengkong
4 4 Sukajadi Sukajadi
5 5 Sekeloa Coblong
6 6 Kopo Bojongloa Kidul
7 7 Ahmad Yani Batununggal
8 8 Babakan Surabaya Kiaracondong
9 9 Cipaku Cidadap
10 10 Dago Coblong
11 11 Cipamokolan Rancasari
12 12 Cinambo Cinambo
13 13 Panyileukan Panyileukan
14 14 Citarip Bojongloa Kaler
15 15 Astana Anyar Astanaanyar
16 16 Pasundan Regol
17 17 Arcamanik Arcamanik
18 18 Garuda Andir
19 19 Gumuruh Batununggal
INK, GREEN, GREY, AMBER = "#003A40", "#3E9A4B", "#7C8B8D", "#C4622D"
HALO = [withStroke(linewidth=2.5, foreground="white")]


def shapes(text, **params):
    """The geometries of a query that returns ST_AsBinary(geom) AS wkb."""
    return shapely.from_wkb(query(text, **params).wkb.map(bytes))


BORDERS = shapes("SELECT ST_AsBinary(geom) AS wkb FROM kecamatan WHERE regency = 'Kota Bandung'")
CITY = shapely.union_all(BORDERS)


def city_map(title, streets=False):
    """Kota Bandung with its kecamatan borders, or with its streets, and a 2 km scale bar."""
    fig, ax = plt.subplots(figsize=(9, 6.3))
    if streets:
        roads = shapes("SELECT ST_AsBinary(geom) AS wkb FROM road")
        ax.add_collection(LineCollection([shapely.get_coordinates(r) for r in roads], colors="#CBD3D4",
                                         linewidths=0.4, zorder=1, rasterized=True))
    else:
        for part in shapely.get_parts(BORDERS):
            ax.plot(*part.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.5, zorder=1)
    west, south, east, north = CITY.bounds
    ax.set_xlim(west - 300, east + 300)
    ax.set_ylim(south - 900, north + 200)
    x0, y0 = west, south - 600
    ax.plot([x0, x0 + 2000], [y0, y0], color=INK, lw=2, zorder=6)
    ax.text(x0 + 1000, y0 + 110, "2 km", ha="center", fontsize=8.5, color=INK, zorder=6, path_effects=HALO)
    ax.set_title(title, loc="left", fontsize=11.5, color=INK)
    ax.set_aspect("equal")
    ax.axis("off")
    fig.subplots_adjust(left=0.01, right=0.99, bottom=0.03, top=0.95)
    fig.text(0.99, 0.012, "Data © OpenStreetMap contributors. Borders: Badan Informasi Geospasial", ha="right", fontsize=7.5, color=GREY)
    return ax


def draw_stops(ax, numbers):
    """A dot for each stop of the work order, with a number in it."""
    for s, number in list(zip(stops.itertuples(), numbers))[::-1]:
        ax.plot(s.x_m, s.y_m, "o", ms=14, color=GREEN if s.stop == 0 else INK, mec="white", mew=1, zorder=5)
        ax.text(s.x_m, s.y_m, number, color="white", ha="center", va="center_baseline", fontsize=7.5, weight="bold", zorder=5)


ax = city_map("Work order 1: twenty puskesmas in Kota Bandung")
others = query("SELECT ST_X(geom) AS x, ST_Y(geom) AS y FROM puskesmas WHERE node <> ALL(%(nodes)s)", nodes=stops.node.tolist())
ax.plot(others.x, others.y, "o", ms=6, color="#9FB0B2", zorder=3)
draw_stops(ax, stops.stop)
plt.show()

Map of Kota Bandung with its kecamatan. Twenty numbered dots are the puskesmas of work order 1. Most lie in the west and centre, and a few lie far in the east. Twelve small grey dots are the puskesmas that are not on the list.

Now the costs. One matrix holds the fastest route between all the puskesmas, at the speeds that Chapter 2 assumed, and every work order takes its part of it. We plan by time, because the question is about hours.

def matrix(roads):
    """Minutes between all puskesmas, one row and one column per node. `roads` is a query with the cost in seconds."""
    trips = query("""
        SELECT start_vid, end_vid, agg_cost / 60 AS minutes
        FROM pgr_dijkstraCostMatrix(
                 %(roads)s,
                 (SELECT array_agg(node) FROM puskesmas))""", roads=roads)
    return trips.pivot(index="start_vid", columns="end_vid", values="minutes").fillna(0)


trip = matrix("SELECT * FROM drive_seconds")
orders = query("SELECT number, array_agg(node ORDER BY stop) AS nodes FROM work_order GROUP BY number ORDER BY number")
orders = orders.set_index("number").nodes


def costs(number):
    """cost[i, j]: minutes from stop i to stop j of a work order."""
    return trip.loc[orders[number], orders[number]].to_numpy()


cost = costs(1)
pairs = cost[~np.eye(20, dtype=bool)]
print(f"{len(pairs)} trips of {pairs.min():.0f} to {pairs.max():.0f} minutes, median {np.median(pairs):.0f}")
380 trips of 3 to 44 minutes, median 16

4. Why not the SQL query again?

The query of Chapter 1 keeps one route for every set of visited stops and every last stop. The formula in the next cell counts them.

for n in [9, 15, 20, 32]:
    print(f"{n:2} stops: {(n - 1) * 2 ** (n - 2):>14,} routes to keep")
 9 stops:          1,024 routes to keep
15 stops:        114,688 routes to keep
20 stops:      4,980,736 routes to keep
32 stops: 33,285,996,544 routes to keep

One more stop more than doubles the work. For our twenty stops the query still finishes: on our computer it took a minute and a half (ledger L27). But we want to ask for hundreds of tours, and for all the puskesmas at once the table would need billions of rows.

5. Let a solver do it

Say what a tour is

HiGHS does not know what a tour is. It finds numbers that make a sum as small as possible while they obey a list of rules, and it can keep them whole (ledger L28). So we have to say what we want in that language.

For every pair of stops there is one choice: do we drive from i to j? It is 1 for yes and 0 for no. The sum to make small is the time of all the trips that are chosen. Two rules are clear:

  • you leave each stop exactly once;
  • you arrive at each stop exactly once.

They are not enough. The solver may answer with several small loops, because each stop in them is left once and reached once. So we look at the answer. If there is a small loop that does not contain the start, we add a rule for it: you must also leave this group of stops. Then we solve again, and repeat until one loop remains.

Left: eight stops joined into three separate small loops. Middle: a dashed line around one small loop, and an arrow that leaves it. Right: one loop through all eight stops.
The solver first answers with small loops. A rule says that the group must be left again, and in the end one loop remains.

We add only a few of all the possible rules. Why is the final loop still the best one? Every rule is true for every real tour, so no tour is ever ruled out. Each time, the solver returns the cheapest answer that obeys the rules so far, and that answer cannot cost more than the best tour. When it is itself a tour, nothing can beat it.

The approach is seventy years old. George Dantzig, Ray Fulkerson and Selmer Johnson solved a tour of 49 cities in 1954 by starting with few rules and adding others when they were needed (ledger L29).

We give the function one more ability for section 7: a tour may leave stops out. The choice “from i to i” costs nothing and means “stay away from stop i”. One more rule says how many stops to leave out, which is none for now.

def best_loop(cost, visits=None, log=False):
    """The exact cheapest loop from stop 0 through `visits` of the stops (all of them if not given)."""
    n = len(cost)
    i, j = np.divmod(np.arange(n * n), n)              # choice number i * n + j: drive from i to j
    away = i == j                                      # from i to i: stay away from stop i
    price = np.where(away, 0, cost[i, j])
    most = np.where(away & (i == 0), 0, 1)             # the start is never left out
    rules = [LinearConstraint([i == s for s in range(n)], 1, 1),          # leave every stop once
             LinearConstraint([j == s for s in range(n)], 1, 1),          # arrive at every stop once
             LinearConstraint([away], n - (visits or n), n - (visits or n))]
    while True:
        answer = milp(price, integrality=1, bounds=Bounds(0, most), constraints=rules,
                      options={"mip_rel_gap": 0})      # stop only when the best is proven
        if not answer.success:
            raise RuntimeError(answer.message)
        chosen = answer.x > 0.5
        go, loops = dict(zip(i[chosen].tolist(), j[chosen].tolist())), []
        while go:                                      # follow the trips until each loop closes
            loop = [min(go)]
            while (following := go.pop(loop[-1])) != loop[0]:
                loop.append(following)
            loops.append(loop)
        small = [loop for loop in loops if 0 not in loop and len(loop) > 1]
        if log:
            print(f"{answer.fun:7.2f} minutes in {len(small) + 1} loop(s)")
        if not small:
            return loops[0], answer.fun
        for loop in small:                             # leave this group, or stay away from stop s of it
            leave = np.isin(i, loop) & ~np.isin(j, loop)
            rules.append(LinearConstraint([leave | (away & (i == s)) for s in loop], 1, np.inf))

A detail that matters. By default the solver stops when its answer is proven to be within 0.01% of the best one (ledger L28). That is fine for most work. We set mip_rel_gap to 0, because “exact” should mean exact.

Check it first

A new tool gets a test with a known answer. The SQL query of Chapter 2 found the exact fastest tour of the fifteen cafes.

cafe_leg = query("SELECT i, j, seconds / 60 AS minutes FROM road_leg")
cafe_cost = np.zeros((15, 15))
cafe_cost[cafe_leg.i, cafe_leg.j] = cafe_leg.minutes
cafe_loop, cafe_minutes = best_loop(cafe_cost)

from_sql = query("SELECT path FROM road_tour WHERE name = 'exact, fastest'").path[0]
print("HiGHS:", *cafe_loop, f"  {cafe_minutes:.1f} minutes")
print("SQL:  ", *from_sql)
HiGHS: 0 3 14 1 2 13 9 7 5 6 12 10 11 4 8   142.9 minutes
SQL:   0 3 14 1 2 13 9 7 5 6 12 10 11 4 8

The same tour from two very different methods. Now the twenty puskesmas.

t = time.perf_counter()
loop, minutes = best_loop(cost, log=True)
print(f"solved in {time.perf_counter() - t:.2f} s")
print(*loop, 0)
 134.02 minutes in 10 loop(s)
 146.01 minutes in 4 loop(s)
 149.28 minutes in 3 loop(s)
 154.11 minutes in 2 loop(s)
 156.24 minutes in 2 loop(s)
 156.96 minutes in 1 loop(s)
solved in 0.14 s
0 7 8 17 13 12 11 19 3 16 15 14 6 18 1 4 2 9 10 5 0

Read the lines from top to bottom. The first answer is the cheapest and useless, because it falls apart into small loops. With new rules the answers become more expensive, until one loop is left. The SQL query found the same loop (ledger L27).

And all the puskesmas at once, the case with billions of routes?

t = time.perf_counter()
everything, all_minutes = best_loop(trip.to_numpy())
print(f"{len(everything)} puskesmas: {all_minutes:.0f} minutes of driving, solved in {time.perf_counter() - t:.2f} s")
32 puskesmas: 211 minutes of driving, solved in 0.89 s

The two methods differ in kind. The SQL query keeps every route that might still turn out to be the best, and their number explodes. The solver proves for large groups of routes at once that they cannot be the best. The price is that you cannot tell in advance how long the proof takes. Some problems of the same size are much harder than others.

6. The timetable

Now the day itself. It needs three numbers that are not in any map:

  • Office hours. We take those of Indonesian government offices: five days and 37.5 hours a week, from 07:30, with a break of 60 minutes (ledger L30). That is 7.5 hours of work a day, so the day ends at 16:00.
  • The break. The technician takes it after the first visit that ends at 12:00 or later.
  • The visits. We assume 15 minutes at each puskesmas, to park, find the equipment, check it and write it down. This is a guess, and section 7 takes it apart.

A tour has two directions, and Chapter 4 showed that the wrong one is expensive. The exact loop already comes in its better direction, because the solver knew the cost of every trip both ways.

DAY, BREAK, VISIT = 450, 60, 15                # minutes of work, of rest, and at each stop
START, NOON = 7 * 60 + 30, 12 * 60


def clock(m):
    return f"{int(m) // 60:02d}:{int(m) % 60:02d}"


rows, now, rested = [], START, False
for here, following in zip(loop, loop[1:] + [0]):
    arrive, now = now, now + VISIT
    rows.append([here, stops.name[here], clock(arrive), clock(now), round(cost[here, following], 1), ""])
    if now >= NOON and not rested:
        now, rested = now + BREAK, True
        rows[-1][-1] = f"break until {clock(now)}"
    now += cost[here, following]
finish, closing = now, START + DAY + BREAK

print(f"back at {clock(finish)}; the day ends at {clock(closing)}")
pd.DataFrame(rows, columns=["stop", "puskesmas", "arrive", "leave", "minutes_to_next", ""], index=range(1, 21))
back at 16:06; the day ends at 16:00
stop puskesmas arrive leave minutes_to_next
1 0 Balai Kota Bandung 07:30 07:45 7.9
2 7 Ahmad Yani 07:52 08:07 6.8
3 8 Babakan Surabaya 08:14 08:29 11.1
4 17 Arcamanik 08:40 08:55 17.5
5 13 Panyileukan 09:13 09:28 7.7
6 12 Cinambo 09:36 09:51 6.5
7 11 Cipamokolan 09:57 10:12 16.1
8 19 Gumuruh 10:28 10:43 4.9
9 3 Talaga Bodas 10:48 11:03 5.3
10 16 Pasundan 11:08 11:23 3.3
11 15 Astana Anyar 11:27 11:42 8.0
12 14 Citarip 11:50 12:05 4.1 break until 13:05
13 6 Kopo 13:09 13:24 8.7
14 18 Garuda 13:32 13:47 6.9
15 1 Pasirkaliki 13:54 14:09 2.8
16 4 Sukajadi 14:12 14:27 5.8
17 2 Karang Setra 14:33 14:48 7.8
18 9 Cipaku 14:56 15:11 14.3
19 10 Dago 15:25 15:40 4.4
20 5 Sekeloa 15:44 15:59 7.2

So close. The best possible round is a few minutes too long, and that is without any traffic.

The map shows the round along the streets, drawn with pgr_dijkstraVia as in Chapter 2. The numbers now give the order of the visits, which is the first column of the timetable.

legs = shapes("""
    SELECT 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_seconds',
             %(nodes)s::integer[]) AS via
    JOIN road ON road.id = via.edge
    GROUP BY path_id""", nodes=stops.node[[*loop, 0]].tolist())

km = sum(leg.length for leg in legs) / 1000
ax = city_map(f"The fastest round: {minutes:.0f} minutes and {km:.0f} km of driving", streets=True)
for leg in legs:
    ax.plot(*leg.xy, color=GREEN, lw=2.4, zorder=3)
    a, b = (leg.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": GREEN, "mutation_scale": 22, "lw": 0})
draw_stops(ax, np.argsort(loop) + 1)
plt.show()

Street map of Bandung with the round of twenty puskesmas as a green line with arrows. It starts in the centre, covers the north and west of the city and makes a long loop to the far east.

Look before moving on. Follow the numbers. Which stop makes the round long? If you could leave one out, which would it be? The next section computes it.

7. Does it fit?

Is this a typical work order?

We solve all hundred work orders and count how many fit in the day with 15 minutes per visit.

t = time.perf_counter()
driving = pd.Series({number: best_loop(costs(number))[1] for number in orders.index})
print(f"{ORDERS} exact tours in {time.perf_counter() - t:.0f} s")
print(f"driving: {driving.min():.0f} to {driving.max():.0f} minutes, median {driving.median():.0f}; work order 1: {driving[1]:.0f}")
print(f"work orders that fit with {VISIT} minutes per visit: {(driving + 20 * VISIT <= DAY).sum()} of {ORDERS}")
100 exact tours in 14 s
driving: 138 to 178 minutes, median 161; work order 1: 157
work orders that fit with 15 minutes per visit: 15 of 100

Work order 1 is an ordinary one. Most lists of twenty do not fit in a day, even without traffic and with the best possible tour.

How many do fit?

If twenty are too many, the useful question is how many are possible, and which ones to keep for another day. This is where the function may leave stops out. For each number of visits it finds the fastest loop, and it chooses the stops itself.

Slow cell: under a minute. It solves fifteen harder problems.

t = time.perf_counter()
shorter = {k: best_loop(cost, visits=k) for k in range(20, 5, -1)}
drive = pd.Series({k: m for k, (_, m) in shorter.items()})
print(f"done in {time.perf_counter() - t:.0f} s")

for k in [19, 18, 17]:
    left_out = sorted(set(range(20)) - set(shorter[k][0]))
    print(f"{k} visits: {drive[k]:.0f} minutes of driving without", ", ".join(stops.name[left_out]))
done in 12 s
19 visits: 143 minutes of driving without Panyileukan
18 visits: 131 minutes of driving without Cipaku, Panyileukan
17 visits: 124 minutes of driving without Cipaku, Cipamokolan, Panyileukan

Leaving out the right stop saves its visit and the detour to it. With one stop less, the technician is back in time.

How many visits fit depends on two guesses: how long a visit takes, and how much slower the traffic is than our empty streets. If all streets are slower by the same factor, every loop takes longer by that factor, so the best loop stays the best and we only have to multiply.

def visits_per_day(visit, slower):
    """The largest number of visits that fits, if one takes `visit` minutes and driving takes `slower` times as long."""
    fits = drive.index[slower * drive + drive.index * visit <= DAY]
    return max(fits, default=0)


pd.DataFrame({f"{v} min per visit": {f"driving x {f}": visits_per_day(v, f) for f in [1, 1.5, 2]}
              for v in [10, 15, 20, 30, 45]})
10 min per visit 15 min per visit 20 min per visit 30 min per visit 45 min per visit
driving x 1 20 19 16 12 8
driving x 1.5 20 17 15 11 8
driving x 2 18 15 13 10 7
minutes_per_visit = np.arange(5, 45.1, 0.25)
fig, ax = plt.subplots(figsize=(9, 4.2))
for slower, color, label in [(1, GREEN, "empty streets"), (1.5, AMBER, "driving takes 1.5 times as long"), (2, INK, "driving takes twice as long")]:
    y = [visits_per_day(v, slower) for v in minutes_per_visit]
    ax.step(minutes_per_visit, y, where="post", color=color, lw=2.2, label=label)
ax.axhline(20, color=GREY, lw=1, ls=(0, (4, 4)), zorder=1)
ax.text(45, 20.25, "the work order", ha="right", fontsize=9, color=GREY)
ax.set(xlim=(5, 45), ylim=(5, 21.5), yticks=range(6, 21, 2))
ax.set_xlabel("minutes per visit")
ax.set_ylabel("puskesmas in one day")
ax.grid(color="#E3E8E9", lw=0.8)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, fontsize=9, loc="upper right", bbox_to_anchor=(1, 0.93))
fig.tight_layout()
plt.show()

Step chart of puskesmas in one day against the minutes per visit, with one line each for empty streets, driving 1.5 times as long and driving twice as long. All lines fall from twenty on the left to seven or eight at 45 minutes, and they come closer together.

Look before moving on. All twenty fit only at the left edge, with short visits. With half an hour per visit, a day holds about half of the list. So the answer to the title is: plan two days, unless the visits are very short.

What is the best tour worth?

Was it worth the effort to find the exact tour? Compare it with two easier plans for the same twenty stops: always driving to the nearest one next, and the best loop in the wrong direction.

def length(path):
    return sum(cost[a, b] for a, b in zip(path, path[1:] + path[:1]))


path, left = [0], set(range(1, 20))
while left:                                            # nearest next, as in Chapter 4
    path.append(min(left, key=lambda s: cost[path[-1], s]))
    left.remove(path[-1])

plans = pd.DataFrame({"driving": {"exact best": length(loop), "best loop, wrong way": length(loop[::-1]),
                                  "nearest next": min(length(path), length(path[::-1]))}})
plans["extra"] = plans.driving - length(loop)
plans["extra_per_visit"] = plans.extra / 20
plans.round(1)
driving extra extra_per_visit
exact best 157.0 0.0 0.0
best loop, wrong way 166.6 9.6 0.5
nearest next 195.7 38.8 1.9

The last column spreads the extra minutes over the twenty visits. The poor tour costs as much as visits that take two minutes longer. That is worth having, because it is free. But nobody knows the length of a visit to within two minutes. So for the question “one day or two?”, the guess matters more than the solver.

Does the plan survive wrong speeds?

The speeds in Chapter 2 were round numbers that we made up. Perhaps the real city is slower, and not evenly: the main roads may be jammed while the side streets are free. Would we have planned a different round?

We can test that. The next cell makes twenty imaginary cities. In each of them, every class of road gets a random speed between half of our assumption and all of it. For each city we compute all the routes again, find the exact best loop, and see how much longer our plan is there. One work order could be a lucky one, so we test the plans for the first ten.

Slow cell: about a minute.

rng = np.random.default_rng(5)
classes = query("SELECT highway FROM speed ORDER BY highway").highway
with connect() as conn:
    conn.execute("""
        DROP TABLE IF EXISTS slow_city;
        CREATE TABLE slow_city (city integer, highway text, factor float8)""")
    conn.cursor().executemany("INSERT INTO slow_city VALUES (%s, %s, %s)",
                              [(city, c, rng.uniform(0.5, 1)) for city in range(1, 21) for c in classes])

t = time.perf_counter()
plan = {number: best_loop(costs(number))[0] for number in range(1, 11)}      # made with our own speeds
cities = []
for city in range(1, 21):
    there = matrix(f"""
        SELECT id, source, target, seconds / factor AS cost,
               CASE WHEN one_way THEN -1 ELSE seconds / factor
               END AS reverse_cost
        FROM road JOIN slow_city USING (highway)
        WHERE city = {city}""")
    for number, ours in plan.items():
        c = there.loc[orders[number], orders[number]].to_numpy()
        best, best_minutes = best_loop(c)
        our_minutes = sum(c[a, b] for a, b in zip(ours, ours[1:] + [0]))
        cities.append([city, number, best_minutes, 100 * (our_minutes / best_minutes - 1), best == ours])
cities = pd.DataFrame(cities, columns=["city", "work_order", "best", "percent_over", "same_loop"])
print(f"{len(cities)} cases in {time.perf_counter() - t:.0f} s")

first = cities[cities.work_order == 1]
print(f"work order 1 takes {first.best.min():.0f} to {first.best.max():.0f} minutes of driving, depending on the city")
print(f"all ten: our plan is the best loop in {cities.same_loop.mean():.0%} of the cases")
print(f"percent over the best loop: median {cities.percent_over.median():.1f}, "
      f"one in ten worse than {cities.percent_over.quantile(0.9):.1f}, worst {cities.percent_over.max():.1f}")
200 cases in 45 s
work order 1 takes 180 to 282 minutes of driving, depending on the city
all ten: our plan is the best loop in 38% of the cases
percent over the best loop: median 0.1, one in ten worse than 1.2, worst 3.9

This is the most useful result of the chapter. The order of the visits can stand a lot of error in the speeds, and the length of the day cannot. The driving time of work order 1 differs by more than an hour and a half between these cities. Often another loop becomes the best one. Yet the round that we planned with made-up speeds is usually a fraction of a percent longer than that loop, and a few percent at worst.

So the two results deserve different trust. You can hand out the order of the visits today. Before you promise to be back by four, go out with a watch.

The test has limits. It slows down whole classes of roads, not one blocked bridge or the streets around a school at noon. A jam in a single place can change more.

Try it yourself

  • Plan work order 2. Does it fit better or worse than number 1?
  • Split the twenty stops into two days. Take the loop of ten visits from shorter, and find the best loop through the stops that it leaves out, with stop 0 as the start again. Are the two days equally long? How would you make them fairer?
  • Measure something. Time a few real trips and visits in your city, put them in place of our guesses, and see whether the answer changes.
  • Add a missing puskesmas to OpenStreetMap.

Checkpoint

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

assert cafe_loop == from_sql                                              # the solver agrees with the SQL query
assert sorted(loop) == list(range(20)) and abs(length(loop) - minutes) < 1e-6
assert length(loop) <= length(loop[::-1])                                 # the better direction
assert drive.is_monotonic_decreasing                                      # fewer visits, less driving
assert len(cities) == 200 and cities.percent_over.min() > -1e-6           # nothing beats an exact loop
# the author's results
assert len(everything) == 32 and abs(minutes - 156.96) < 0.1 and abs(all_minutes - 211.47) < 0.1
assert [visits_per_day(v, 1) for v in (10, 15, 30)] == [20, 19, 12]
print("checkpoint passed")
checkpoint passed

Troubleshooting

Symptom Cause Fix
relation "drive_seconds" does not exist Chapter 2 has not been run in this database Run Chapters 1 and 2 first
could not create unique index "puskesmas_pkey" Two places in your own data share a network node Keep one of them: a trip from a node to itself is no trip
best_loop runs for minutes Some problems are hard to prove, above all when stops may be left out Set mip_rel_gap to 0.01 to accept an answer within 1% of the best
Another loop with the same time Two loops can cost the same Both are right. Compare the minutes, not the order
The driving times differ a little from this page Other streets, or other speeds in the table speed Expected if you changed them in Chapter 2

What comes next

That closes the series. You have met the same puzzle five times: every route in one SQL query, real roads in pgRouting, a growing loop in GRASS, a scoreboard of seven methods, and a solver for a working day.

The steps work for any city with mapped streets. Change the box in sample-data/make_streets.py, pick your own stops, and start again at Chapter 1. Meter readings, school visits, food parcels, rain gauges: each is a list of places and a person who wants to be home in time.