You will build: the same street network as a GRASS vector map, and three tours from v.net.salesman, with their visiting orders
You need: Chapter 2 completed, in the same database, and GRASS 8.5. Section 5 needs a GRASS that can store attribute tables
Time to run: about two minutes
Level: first steps in GRASS; some Python
In Chapter 2, the answer of pgr_TSP changed with the way the stops were numbered. GRASS has a solver of its own, v.net.salesman, which works by a different idea. This chapter gives it the same streets, the same one-way rules and the same costs as Chapter 2, so the two can be compared fairly.
The chapter then opens the solver up. Its method fits in about ten lines of Python, and we check that those lines give the same tours as GRASS.
NoteLearning objectives
By the end of this chapter you will be able to:
bring a street network and a set of stops into a GRASS project;
explain where the nodes of a GRASS network come from;
run v.net and v.net.salesman, with one cost for each direction of a street;
check the result of one program against the costs of another;
explain farthest insertion, the method behind v.net.salesman, and write it yourself.
1. Setup
GRASS is already in the environment of this repository. Two lines in config.yml belong to it: the command that starts GRASS, and the folder for its projects. A GRASS project is a folder that holds maps with one coordinate system. Ours is called bandung and uses the coordinate system of the earlier chapters, EPSG:32748.
Before running on Windows, read this. The conda-forge build of GRASS 8.5.0 for Windows cannot open attribute tables. The bug is fixed in the source code since 3 December 2026, and the fix is marked for the 8.5 series (ledger L14). Until a release contains it, sections 1 to 4 and section 6 work, because they need no tables, and section 5 stops with the message db_open_database() not implemented. The outputs on this page come from a GRASS 8.5.0 in which the author had repaired the table driver.
import osos.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL") # before numpy is imported (ledger L3)import ioimport randomimport shutilimport subprocessimport sysimport timefrom pathlib import Pathimport geopandas as gpdimport matplotlib.pyplot as pltimport pandas as pdimport psycopgimport shapelyimport yaml# The repository root, whether the notebook runs from en/, id/ or the root itselfROOT = Path.cwd() if (Path.cwd() /"tutorial.yml").exists() else Path.cwd().parentCONFIG = yaml.safe_load((ROOT /"config.yml").read_text(encoding="utf-8"))DB = CONFIG["database"]defconnect():"""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."""withconnect() as conn: cur = conn.execute(text, params orNone)return pd.DataFrame(cur.fetchall(), columns=[c.name for c in cur.description])# the cost of every trip between two stops on real roads, from Chapter 2leg = query("SELECT i, j, metres, seconds FROM road_leg").set_index(["i", "j"])print(f"{len(leg)} trips in road_leg")
210 trips in road_leg
The next cell finds GRASS, asks it where its Python package is, creates the project if there is none yet, and starts a session. From then on, gs.run_command("tool", option=value) runs a GRASS tool, with the same names and options as on the command line.
command = shutil.which(CONFIG["grass"]["command"])if command isNone:raiseFileNotFoundError("GRASS not found: check grass: command: in config.yml")python_path = subprocess.run([command, "--config", "python_path"], capture_output=True, text=True, check=True).stdout.strip()if python_path notin sys.path: sys.path.append(python_path)import grass.jupyter as gjimport grass.script as gsPROJECTS = Path(CONFIG["grass"]["projects"]).expanduser()PROJECTS.mkdir(parents=True, exist_ok=True)ifnot (PROJECTS /"bandung"/"PERMANENT").exists(): gs.create_project(PROJECTS /"bandung", epsg="32748")session = gj.init(PROJECTS /"bandung")os.environ["GRASS_OVERWRITE"] ="1"# a second run replaces the maps of the firstprint("GRASS", gs.version()["version"])
GRASS 8.5.0
2. The streets in GRASS
The streets leave the database as a GeoPackage, a single file that GRASS, QGIS and most other GIS programs can read.
Chapter 2 wrote a cost of -1 for a direction that is not allowed. v.net.salesman uses the same rule (ledger L15), so each road gets two costs per measure: metres and seconds along its line, metres_back and seconds_back against it. The stops are the network nodes that Chapter 2 found for them.
EXCHANGE = PROJECTS /"bandung-roads.gpkg"def export(layer, text):"""Write the rows of a query to the GeoPackage. The query returns its geometry as ST_AsBinary(...) AS wkb.""" table = query(text) lines = shapely.from_wkb(table.pop("wkb").map(bytes)) gpd.GeoDataFrame(table, geometry=lines, crs=32748).to_file(EXCHANGE, layer=layer)returnlen(table)roads = export("road", """ SELECT id, metres, CASE WHEN one_way THEN -1 ELSE metres END AS metres_back, seconds, CASE WHEN one_way THEN -1 ELSE seconds END AS seconds_back, ST_AsBinary(geom) AS wkb FROM road""")points = export("stop", """ SELECT stop AS number, ST_AsBinary(node.geom) AS wkb FROM stop_node JOIN node ON node.id = stop_node.node""")print(f"{roads:,} roads and {points} stops written")
77,550 roads and 15 stops written
v.in.ogr imports them. The flag -t leaves the attributes out, and only the lines and points come in. That is enough for a first tour, because without other information GRASS uses the length of each line as its cost.
Every object in a GRASS vector map can carry a number, called its category. The option key says which column to take it from, so the categories of the stops are our stop numbers, 0 to 14.
gs.run_command("v.in.ogr", input=EXCHANGE, layer="road", output="street", key="id", type="line", flags="t")gs.run_command("v.in.ogr", input=EXCHANGE, layer="stop", output="stop", key="number", type="point", flags="t")in_grass = gs.parse_command("v.info", map="street", flags="t")in_postgis = query("SELECT (SELECT count(*) FROM node) AS nodes, (SELECT count(*) FROM road) AS lines").iloc[0]pd.DataFrame({"GRASS": {k: int(in_grass[k]) for k in ("nodes", "lines")}, "Chapter 2": in_postgis})
GRASS
Chapter 2
nodes
65182
65182
lines
77550
77550
Look before moving on. We exported roads and no nodes, and yet GRASS reports exactly as many nodes as Chapter 2. GRASS stores vector maps with their topology: when it builds a map, it records which lines end at the same point, and those points are the nodes. Chapter 2 needed two queries for this. But GRASS could only do it because the lines were already cut at the junctions. A street that runs through a junction without a cut has no node there.
3. Connect the stops
v.net prepares a network. Its operation connect adds the stops to the map of the streets, so that the solver can find them. Our stops lie exactly on nodes, so a threshold of 1 metre is enough. The streets stay in layer 1 of the new map and the stops go to layer 2. A layer is a separate set of categories in the same map.
One map with two layers: the streets in layer 1 and the stops in layer 2, at the same positions.
The number of nodes has not changed: no street was cut, and no new line was added. v.net can also connect points that lie beside the streets, by drawing a short line from each to the nearest street. We do not use that here, because the costs would then differ a little from those of Chapter 2.
4. A first tour: every street both ways
v.net.salesman takes the network and the categories of the stops. It writes the tour as a new vector map, and with sequence="-" it also prints the visiting order.
def salesman(network, output, **costs):"""Run v.net.salesman. Returns the visiting order and the cost of the loop that GRASS reports.""" text = gs.read_command("v.net.salesman", input=network, output=output, center_cats="0-14", sequence="-", **costs) table = pd.read_csv(io.StringIO(text.strip()), sep=";")return table.category.tolist(), table.cost_to_next.sum()t = time.perf_counter()both_ways, reported = salesman("network", "tour_both_ways")print(f"solved in {time.perf_counter() - t:.1f} s")print(*both_ways, both_ways[0])print(f"{reported /1000:.2f} km, if every street could be driven both ways")
solved in 2.8 s
2 1 14 3 0 11 8 4 10 6 12 5 7 9 13 2
57.65 km, if every street could be driven both ways
This is the simplified city of Chapter 2 again, where one-way rules do not exist. So we do the same as with pgr_TSP: store the loop in road_tour and score it on the real costs, in both directions.
def from_stop_0(path):"""The same loop, written so that it begins at stop 0.""" k = path.index(0)return path[k:] + path[:k]def save_road_tour(name, path):"""Store a loop in the table of Chapter 2.""" path = [int(i) for i in path]ifsorted(path) !=list(range(15)):raiseValueError("a tour visits every stop once")withconnect() as conn: conn.execute(""" INSERT INTO road_tour VALUES (%s, %s) ON CONFLICT (name) DO UPDATE SET path = excluded.path""", [name, from_stop_0(path)])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_backwardsFROM stepJOIN road_leg AS go ON go.i = step.i AND go.j = step.jJOIN road_leg AS back ON back.i = step.j AND back.j = step.iGROUP BY nameORDER BY least(sum(go.metres), sum(back.metres)), name"""withconnect() as conn: # remove the rows of an earlier run conn.execute("DELETE FROM road_tour WHERE name LIKE 'GRASS%'")save_road_tour("GRASS, both ways", both_ways)query(SCORES)[["name", "km", "km_backwards"]].round(2)
name
km
km_backwards
0
exact, shortest
61.26
66.34
1
pgr_TSP, best of 200
61.26
66.34
2
GRASS, both ways
66.34
61.26
3
loop of Chapter 1
66.22
61.51
4
exact, fastest
61.94
67.02
5
pgr_TSP, one answer
66.86
67.50
Look before moving on. Compare the row GRASS, both ways with exact, shortest: the same two numbers, the other way round. GRASS has found the best possible loop, but it cannot know in which direction to drive it, because it was not told about the one-way streets. Our score in both directions gives that answer.
5. One-way streets
Now GRASS gets the costs. The same import without -t also brings in the attributes, as a table that belongs to the map. v.net.salesman then takes the cost of each road from a column: arc_column for the direction in which the line was drawn, and arc_backward_column for the other. The manual marks the second one as experimental (ledger L15), which is one more reason to check the result.
Slow cell: about a minute and a half. Most of it is reading and copying the table for all the roads.
done in 80 s
by distance: 61.26 km 1 2 13 9 7 5 12 6 10 4 8 11 0 3 14 1
by time: 146.7 min 10 6 12 5 7 9 1 2 13 0 3 14 11 8 4 10
Do the two programs agree?
GRASS searched the routes itself. It has never seen the table road_leg, which pgRouting made. So we can add up the same trips in road_leg and compare the totals.
def total(path, cost):"""The cost of a loop in road_leg, in the given direction."""returnsum(leg.at[(i, j), cost] for i, j inzip(path, path[1:] + path[:1]))compare = pd.DataFrame({"GRASS": [metres, seconds],"pgRouting": [total(by_metres, "metres"), total(by_seconds, "seconds")]}, index=["distance tour, metres", "time tour, seconds"])compare["difference"] = compare["GRASS"] - compare["pgRouting"]compare.round(2)
GRASS
pgRouting
difference
distance tour, metres
61263.92
61264.32
-0.40
time tour, seconds
8800.10
8800.48
-0.38
The totals differ by less than one metre and less than one second. GRASS keeps the cost of each road as a whole number of thousandths and drops the rest (ledger L16). On a loop of several hundred roads, those small losses add up to the difference in the table.
Here is the tour as GRASS draws it, with the streets in grey below.
pgr_TSP starts from a tree. v.net.salesman grows a loop. Its source code (ledger L17) does this:
Take the two stops that are farthest apart, and make a loop of them.
Of the stops that are left, pick the one that is farthest from the loop. Far means that even the nearest stop in the loop is a long way off, there and back added together.
Insert it into the loop where it adds the least.
Repeat from step 2 until no stop is left.
It sounds backwards to begin with the most awkward stops. But they decide the overall shape of the loop. The stops in the middle are easy to add later, because something always passes nearby.
Step 3: the new cafe could go into any leg of the loop. Farthest insertion takes the leg where the detour is smallest.
We have all the costs, so we can do the same by hand.
def farthest_insertion(cost, stops):"""Grow a loop like v.net.salesman. `cost[i, j]` is the cost from stop i to stop j. Returns every stage.""" loop =list(max(cost, key=cost.get)) # step 1: the two stops farthest apart stages = [loop.copy()]whilelen(loop) <len(stops): new =max((s for s in stops if s notin loop), # step 2: the stop farthest from the loop key=lambda s: min(cost[s, v] for v in loop) +min(cost[v, s] for v in loop)) detour = [cost[a, new] + cost[new, b] - cost[a, b] # step 3: where does it add the least?for a, b inzip(loop, loop[1:] + loop[:1])] loop.insert(detour.index(min(detour)) +1, new) stages.append(loop.copy())return stagestwo_way = query("SELECT i, j, metres FROM two_way_leg")costs = {"both ways": {(r.i, r.j): r.metres for r in two_way.itertuples()},"distance": leg.metres.to_dict(),"time": leg.seconds.to_dict(),}by_hand = {name: farthest_insertion(cost, range(15)) for name, cost in costs.items()}grass_tours = query("SELECT name, path FROM road_tour WHERE name LIKE 'GRASS%'").set_index("name").pathfor name, stages in by_hand.items(): mine = from_stop_0(stages[-1])print(f"{name:10}", *mine, " same as GRASS:", mine == grass_tours.get(f"GRASS, {name}"))
both ways 0 11 8 4 10 6 12 5 7 9 13 2 1 14 3 same as GRASS: True
distance 0 3 14 1 2 13 9 7 5 12 6 10 4 8 11 same as GRASS: True
time 0 3 14 11 8 4 10 6 12 5 7 9 1 2 13 same as GRASS: True
The three tours are the same as those of GRASS, stop for stop. (If section 5 did not run on your computer, the last two lines say False, because there is no GRASS tour to compare with. The orders on the left are still the ones that GRASS finds.) That is a strong check on both sides: we have read the method correctly, and GRASS has used the one-way costs as we meant them.
The figure shows the loop by distance as it grows. The lines are straight here, only to show the order.
INK, GREEN, GREY ="#003A40", "#3E9A4B", "#7C8B8D"xy = query("SELECT id, ST_X(geom) AS x, ST_Y(geom) AS y FROM stop ORDER BY id").set_index("id")fig, axes = plt.subplots(2, 2, figsize=(9, 6.6))for ax, size inzip(axes.flat, [2, 4, 8, 15]): loop = by_hand["distance"][size -2] ax.plot(xy.x, xy.y, "o", ms=6, color="#C3CCCE", zorder=1) ring = xy.loc[loop + loop[:1]] ax.plot(ring.x, ring.y, color=GREEN, lw=2, zorder=2)for s insorted(loop, reverse=True): # stop 0 last, so nothing covers it ax.plot(*xy.loc[s], "o", ms=13, color=GREEN if s ==0else INK, mec="white", mew=1, zorder=3) ax.text(*xy.loc[s], s, color="white", ha="center", va="center_baseline", fontsize=7.5, weight="bold", zorder=4) km =sum(costs["distance"][e] for e inzip(loop, loop[1:] + loop[:1])) /1000 ax.set_title(f"{size} stops: {km:.1f} km by road", loc="left", fontsize=10.5, color=INK) ax.set_aspect("equal") ax.margins(0.06) ax.axis("off")fig.tight_layout()plt.show()
Look before moving on. Compare the lengths. The first two stops alone make up more than half of the final loop. The other thirteen are picked up on the way.
Does the numbering matter?
It did for pgr_TSP. Farthest insertion looks at costs only, so the numbering could matter only where two costs are exactly equal. The cell gives our own version the stops in two hundred different orders and counts the different loops.
rng = random.Random(1)loops =set()for attempt inrange(200): order = rng.sample(range(15), 15) shuffled = {(i, j): costs["distance"][i, j] for i in order for j in order if i != j} loops.add(tuple(from_stop_0(farthest_insertion(shuffled, order)[-1])))print(f"different loops from 200 orders: {len(loops)}")
different loops from 200 orders: 1
This is good and bad. The answer is stable, and you can repeat it. But there is also no second ticket in this lottery: if the one loop is not good, asking again does not help.
7. All the tours so far
over_best_km and over_best_min say by how many percent each loop, in its better direction, is longer or slower than the exact best one.
With the right costs, GRASS finds the shortest loop. Its loop by time is good but not the best one, so farthest insertion is an approximate method too. The manual says the same (ledger L15).
Remember that this is one set of fifteen cafes. Chapter 4 asks how these methods do in general.
The same steps on the command line
Everything GRASS did here are ordinary commands. This is the one-way tour by distance, for a terminal in which GRASS is running in the project bandung:
Add --overwrite to replace maps that exist already. The GeoPackage is in the folder of your GRASS projects. In the Windows command prompt, write the last command on one line, without the \.
Checkpoint
The cell stops with an error if the results are not what this chapter expects. If section 5 did not run on your computer, it stops at the line about the one-way tours, and you can go on to Chapter 4.
assert (int(in_grass["nodes"]), int(in_grass["lines"])) ==tuple(in_postgis)assert (int(info["nodes"]), int(info["points"])) == (in_postgis.nodes, 15)table = scores.set_index("name")assertabs(table.km_backwards["GRASS, both ways"] - table.km["exact, shortest"]) <1e-6# the author's resultassertlen(loops) ==1assert"GRASS, distance"in table.index and"GRASS, time"in table.index, "section 5 (one-way tours) did not run"assert compare.difference.abs().max() <1# GRASS and pgRouting agreeassert by_hand["distance"][-1] == by_metres and by_hand["time"][-1] == by_secondsassert scores[["over_best_km", "over_best_min"]].min().min() >-1e-6# nothing beats the exact loopsassertabs(metres -61263.9) <1andabs(seconds -8800.1) <1# the author's resultsprint("checkpoint passed")
checkpoint passed
Troubleshooting
Symptom
Cause
Fix
GRASS not found
The environment is not active, or GRASS is installed elsewhere
Activate the environment, or put the full path of your GRASS command in config.yml
db_open_database() not implemented
The conda-forge build of GRASS 8.5.0 for Windows (ledger L14)
Go on with section 6, or use a later release. The bug affects only Windows builds made with Microsoft’s compiler
relation "road_tour" does not exist
Chapter 2 has not been run in this database
Run Chapters 1 and 2 first
Destination node ... is unreachable
The network is not strongly connected, or a stop is not on it
Run Chapter 2 again to the end; it keeps only the connected part
The import says that a map already exists
The setup cell was skipped
Run section 1 again: it allows GRASS to replace maps
What comes next
The table road_tour now holds the answers of three programs to the same question, and we know the best answer. Chapter 4 compares the methods on many different sets of stops.