A route in duckOSM goes from edge to edge on the turn graph. In this graph a node is a road in one direction, and an arc is a legal turn. So every route obeys the one-way rules and the turn restrictions of OSM. A route can start at an edge id, a point or a street name, and it can change mode on the way.
# Install duckOSM when it is not installed (for example in Colab). It takes approximately 1 minute.# Until duckOSM 0.9.0 is on PyPI, the SDK of these notebooks is in the nightly wheel of main (the GitHub pre-release "nightly").# roadstyle (the maps) also comes from its nightly wheel, so the newest roadstyle parts work with no roadstyle release.import importlib.util, json, os, urllib.requestdef nightly_wheel(repo="Khoshkhah/duckOSM", name=".whl"): # the address of the newest nightly wheel of a repository release = json.load(urllib.request.urlopen(f"https://api.github.com/repos/{repo}/releases/tags/nightly"))returnnext(a["browser_download_url"] for a in release["assets"] if name in a["name"] and a["name"].endswith(".whl"))if importlib.util.find_spec("duckosm") isNone: # not installed: install it with the extras of this notebook%pip install -q "duckosm[widget,viz,graph] @ {nightly_wheel()}"%pip install -q --force-reinstall --no-deps "roadstyle @ {nightly_wheel('Khoshkhah/roadstyle', 'manylinux')}"import duckosm # the SDKifnothasattr(duckosm, "network"): # an old duckOSM (0.8.0 or older), without the SDK%pip install -q --force-reinstall --no-deps "duckosm @ {nightly_wheel()}"raiseSystemExit("duckOSM is updated: restart the session (in Colab: Runtime > Restart session), then run this cell again")print("duckosm", duckosm.__version__) # the version# The network of chapter 1 (monaco.duckdb). The chapter opens it. When you run this chapter alone (in Colab), the file# is not there, so this cell makes it one time.ifnot os.path.exists("monaco.duckdb") ornot duckosm.open("monaco.duckdb").has_mode("driving", "walking", "cycling"): duckosm.network(osm_id=2220322, modes=["driving", "walking", "cycling"], path="monaco.duckdb")
7.1 How duckOSM finds a route
A road network looks like a graph of junctions and roads. But a route on that graph can break the rules of the real road: it can turn left where a sign forbids it, or make a U-turn in the middle of a junction. To obey the turn rules, duckOSM routes on another graph, the turn graph (also called the edge graph):
In the turn graph
Is
a node
one edge of the network (one direction of a road), with its edge_id
an arc
a legal turn from one edge to the next edge: the turn restrictions of OSM and the one-way rules are in it
the cost of an arc
the time (cost_s) or the length (length_m) of the edge before the turn
The table <mode>.edge_graph of the database holds the arcs. The picture shows one junction. The road from the west (edge 1) has a sign “no left turn”. In the turn graph, edge 1 has an arc to edge 2 and to edge 3, but no arc to edge 4. So a route cannot make that turn.
A junction and its turn graph: each edge is a node, each legal turn is an arc, the forbidden left turn has no arc
The search is a bidirectional Dijkstra search, in Rust.
ImportantKey idea
A route goes from edge to edge on the turn graph. Each arc is a legal turn, so every route of duckOSM obeys the turn restrictions and the one-way rules of its mode.
7.2 The routing graphs and the network of this chapter
7.2.1 The routing graphs in the file
The routing calls of this chapter search graphs that are tables of the network file. There are two kinds:
Graph
Table
Made by default?
Rows in Monaco
one mode: the turns of driving
driving.edge_graph
yes, for each mode that you build
6,754 turns
one mode: the turns of walking
walking.edge_graph
yes, for each mode that you build
35,074 turns
one mode: the turns of cycling
cycling.edge_graph
yes, for each mode that you build
31,366 turns
multimodal: the edges of all modes
mm.edges
no, see below
26,083 rows: 13,302 edges, many in more than one mode
multimodal: the changes of mode
mm.transfers
no, see below
12,140 changes
The build makes the two mm tables only when the config has multimodal: {enabled: true}. Without it, the file has no schema mm, and a route across modes is not possible.
The graph of one mode is the table edge_graph in the schema of the mode. Each row is one turn that the mode can make, from one edge to the next edge:
Column
Type
Means
from_edge
BIGINT
the edge that you come from (an edge_id of edges)
to_edge
BIGINT
the edge that you go on to. Its start is the end of from_edge
via_edge
BIGINT
the same as to_edge
cost
FLOAT
the cost of the turn: cost_s of from_edge, in seconds
uses
VARCHAR
who can make the turn: the mode itself (car, walk, bike), or an access label (bus, private, pedestrian, delivery) when one of the edges is in private_edges
The multimodal graph is a schema of its own, mm, with two tables:
Table
Holds
Columns
mm.edges
a view: the edges of all modes in one table, with their mode. An edge that two or three modes use has one row for each mode, with the same edge_id
A route across modes uses mm.edges to move in each mode and mm.transfers to change mode, for example to park the car and walk on. The graphs of the modes stay as they are.
7.2.2 Open the network of chapter 1 and add the multimodal graph
Chapter 1 builds Monaco with three modes and saves it as monaco.duckdb. This chapter opens that file with duckosm.open: it builds nothing. The file has no multimodal graph yet, so net.add_multimodal() adds it to the same file. It reads the three networks that are in the file and writes mm.edges and mm.transfers. It needs walking and one more mode: net.has_mode("walking") tells you if the file has walking.
net = duckosm.open("monaco.duckdb")net.has_mode("walking"), net.has_multimodal()
multimodal graph: done in 0.1 s
wrote mm.edges (26083 edges) and mm.transfers (12140 arcs)
(True,
mode edges nodes km oneway_km
0 driving 2840 1768 96.2 35.5
1 walking 11938 4589 260.6 0.0
2 cycling 11305 4650 250.0 35.5)
The file has three networks: 2,840 driving edges, 11,938 walking edges and 11,305 cycling edges. The mm tables are not in the summary, because they join the three modes and are not a mode. To see them, use net.tables() and net.columns("mm.transfers") (chapter 2).
The cost of a change of mode
A route across modes can change mode at a junction that two modes share: you park the car and walk on, or you take your bike. Each change has a cost in seconds. It stands for the time to park, to lock the bike or to walk to the car. The router adds it to the time of the route, so a change is only worth it when it saves more time than it costs.
Argument
Default
Does
transfer_s
60
the cost of each change of mode, in seconds
pair_costs
none
another cost for one direction, for example {"walking->driving": 120}: to take the car costs 120 s, and the other changes keep transfer_s
The costs go into the column cost_s of mm.transfers: one row for each junction and each change. A high cost (300 s) gives routes that change mode less often. A cost of 0 lets a route change mode at almost every junction, which is not real. To give a cost to the changes at each junction (for example, park only at car parks), see 8. Advanced routing, “Your own cost”.
TipTip
A build can also make the multimodal graph at once: duckosm.network(..., config={"multimodal": {"enabled": True}}). The same build from a config file: write the keys to monaco.yaml (modes: [driving, walking, cycling], multimodal: {enabled: true}) and call duckosm.build(config="monaco.yaml"). The file config/template.yaml of the repository lists every key.
7.3 The three kinds of place
Each routing call takes its start and its end as a place. A place is one of three things:
Place
Example
How it joins the network
an edge id
240162084728701473
that edge: the route starts at the start of the edge and ends at the end of the edge
a (lon, lat) point
(7.4155, 43.7285)
the nearest road within radius_m, plus the walk from the point to the road
a place name
"Boulevard Albert 1er"
the middle of the longest edge with that name; else the first answer of Nominatim in the box of the network
A point is (lon, lat), in this order, as in GeoJSON. Write a point with decimals: two integers, for example (7, 43), are not a point.
7.4 One call, three ways to write it
The routing calls are functions of the module duckosm.routing. Each function is also a method of the network and of a mode view. These three forms give the same route:
Form
When to use it
net.driving.route(a, b)
the short form: the mode view gives the mode
net.route(a, b, mode="driving")
the mode is in a variable
duckosm.routing.route(net.driving, a, b)
in a library, or with a path or a DuckDB connection in place of the network
With a path or a connection, the default mode is "driving". The rest of the chapter uses the short form.
7.5 Between two roads
A route between two edge ids is the most direct call: no point to join, no name to find. The cell takes one edge of Boulevard du Larvotto and one edge of Avenue Princesse Grace from the table driving.edges, then finds the fastest route between them.
q ="SELECT min(edge_id) AS edge_id FROM driving.edges WHERE name = ?"start =int(net.sql(q, ["Boulevard du Larvotto"]).edge_id[0])end =int(net.sql(q, ["Avenue Princesse Grace"]).edge_id[0])r = net.driving.route(start, end)r
Route (driving)
edges
29
length
1,513 m
time
1.9 min
The route from Boulevard du Larvotto to Avenue Princesse Grace has 29 edges, 1,513 m, and takes 114 s (1.9 minutes).
The result is a Route. r.edge_ids is its list of edges, r.time_s and r.length_m are its sums. Chapter 8 shows all the parts of a Route. When no route connects the two places (for example an edge that has no exit), the call gives None.
With two (lon, lat) points, route joins each point to its nearest road. The time of the route includes the walk from the point to the road, at 4.5 km/h. The cell finds the route from Fontvieille to Larvotto by car and on foot.
a, b = (7.4155, 43.7285), (7.4335, 43.7468)drive = net.driving.route(a, b)walk = net.walking.route(a, b)round(drive.time_s /60, 1), round(walk.time_s /60, 1)
(3.8, 36.4)
The car takes 3.8 minutes and the walk takes 36.4 minutes. Each time includes the short walk from the point to its nearest road.
7.6.2route_points: the options of the join
route with two points calls route_points. Call it yourself to set the options of the join:
Argument
Default
Does
radius_m
50.0
the largest distance from the point to its road, in metres; no road nearer: None
access_kmh
4.5
the speed of the walk from the point to the road
weight
"time"
"time": the fastest route; "length": the shortest
The Route of route_points also has start and end: where each point joins the road.
p = net.driving.route_points(a, b, radius_m=100, access_kmh=5)p["start"]
The first point joins the road at road_point, 10.3 m away (access_m). The walk to the road takes 7.4 s at 5 km/h (access_s). edge_id is the first edge of the route, and fraction is where the point joins it: 0.0 is the start of the edge, 1.0 its end.
7.7 Between two place names
A place can be a street name. duckosm.routing.geocode turns the name into a point. It first looks in the network: the point is the middle of the longest edge with that name. When the network has no road with the name, it asks Nominatim (the search of OpenStreetMap, on the internet) for a place in the box of the network.
duckosm.routing.geocode(net.driving, "Boulevard Albert 1er")
(7.421134960833079, 43.73590722783044)
by_name = net.driving.route("Boulevard Albert 1er", "Avenue Princesse Grace")by_name
Route (driving)
edges
33
length
1,350 m
time
2.0 min
The point of Boulevard Albert 1er is (7.4211, 43.7359), in the middle of the longest edge of the street. The route by name has 33 edges, 1,350 m, and takes 122 s.
WarningWarning
A name gives one point. A long street has many points, and the route starts at the middle of its longest edge. Use a point or an edge id when the exact start is important.
Nominatim needs the internet. When it finds nothing in the box of the network, the call stops with the error no place ... in the network or in Nominatim inside the box of the network.
7.8 Draw routes on the map
net.map(routes=...) draws routes on the roadstyle map of the network. routes is a dict: each name becomes an item of the legend, and each route gets its own color. Run the cell to see the live map: you can zoom, and click a road to see its columns. The manual page shows a picture of the map.
The car route uses the tunnels and the large boulevards along the coast. The walking route is more direct: it uses the steps and footways that a car cannot use.
7.9 Turn-by-turn steps
route.directions() gives the steps of a route, as a navigation app says them. Each step is a dict:
Key
Is
text
the step in words
type
depart, turn, roundabout, continue, arrive …
modifier
the direction of the turn: left, right, straight …
name
the name of the road after the step
length_m
the length of the road until the next step
at
the point of the step, (lon, lat)
duckosm.routing.directions(net.driving, r) and net.driving.directions(r) give the same steps.
[step["text"] for step in drive.directions()]
['Head northwest on Avenue des Castelans',
'At the roundabout, take the 1st exit onto Avenue Albert II',
'At the roundabout, take the 3rd exit onto Avenue Albert II',
'Continue onto Tunnel Rocher Palais',
'Continue onto Tunnel Rocher Albert Ier',
'Continue onto Tunnel Rocher Palais',
'Continue onto Boulevard Albert 1er',
'At the roundabout, take the 1st exit onto Avenue John F. Kennedy',
'Continue onto Boulevard Louis II',
'At the roundabout, take the 2nd exit onto Avenue Princesse Grace',
'Arrive at your destination']
NoteWhat the output shows
The car route has eleven steps, from “Head northwest on Avenue des Castelans” to “Arrive at your destination”. A roundabout step gives the number of the exit. A new street name gives a “Continue onto” step, also in the tunnels.
7.10 Across modes
7.10.1 Between two points
net.route_multimodal_points(a, b) finds the fastest trip that can change mode: walk to a car, drive, and walk from the car. It routes on the multimodal graph:
Part
Is
a leg
one part of the trip in one mode, with its edges, its seconds and its metres
a transfer
a change of mode at a shared junction: park, retrieve (driving), bike_park, bike_unpark (cycling); each costs 60 s
A trip starts and ends on foot, and it has one vehicle leg at most (enforce_sequence=True). Each leg obeys the turn rules of its mode.
m = net.route_multimodal_points(a, b)[(leg["mode"], len(leg["edges"]), round(leg["time_s"])) for leg in m["legs"]], round(m["time_s"])
The trip has three legs: a walk on 1 edge (3 s), a drive on 75 edges (220 s) and a walk on 1 edge (0 s). The total is 350 s. It includes two transfers of 60 s, into the car and out of it, and the walks from the points to the roads. The car route drive takes 229 s, so the trip across modes is slower: the two transfers cost 120 s.
WarningWarning
The multimodal graph has a car waiting at each shared junction, and no public transport (OSM has no timetables). Use it to compare the modes, not as a trip planner.
allowed_modes limits the trip to some modes. A trip between two points must include walking. Here the trip has no car: it can walk and cycle.
bike = net.route_multimodal_points(a, b, allowed_modes=["walking", "cycling"])[(leg["mode"], len(leg["edges"]), round(leg["time_s"])) for leg in bike["legs"]], round(bike["time_s"])
The trip without a car cycles on 76 edges for 705 s. The total is 830 s (13.8 minutes), with the two transfers of the bicycle. The walk alone takes 36.4 minutes, so the bicycle is much faster.
7.10.2 Between two junctions
duckosm.routing.route_multimodal(net, src_node, dst_node) is the same search between two junctions, by their node_id. It has the arguments start_mode and end_mode (default "walking"), allowed_modes and enforce_sequence. The result has the same legs, and also the list of transfers.
ends = net.sql("SELECT min(node_id) AS a, max(node_id) AS b FROM walking.nodes WHERE node_id > 0")j = duckosm.routing.route_multimodal(net, int(ends.a[0]), int(ends.b[0]))[(leg["mode"], round(leg["time_s"])) for leg in j["legs"]], [t["kind"] for t in j["transfers"]]
The trip has two legs: a drive (195 s) and a walk (38 s), with two transfers, park and retrieve. The trip starts at a junction where a car can wait, so it changes to the car at once, with no walking leg before it.
7.11 As a graph
The turn graph is also a graph object for your own algorithms:
Call
Gives
Needs
net.driving.to_networkx()
a networkx.DiGraph: a node is an edge_id, an arc a legal turn with its weight
networkx
net.driving.to_rustworkx()
the same graph as a rustworkx.PyDiGraph; g.attrs["index"] gives the node index of an edge_id
rustworkx
Both take weight="time" (seconds) or weight="length" (metres). The weight of an arc is the cost of the edge before the turn. So the cost of a path in the graph does not include the last edge, and the route adds it.
import networkx as nxg = net.driving.to_networkx()g.number_of_nodes(), g.number_of_edges()
The networkx graph has 2,840 nodes (one for each driving edge) and 5,082 arcs. The table driving.edge_graph has 6,754 arcs, but the graph keeps only the 5,082 turns that a car can make. The other arcs are for buses and other vehicles (8. Advanced routing, section “The graph of all calls: routed_graph”). The shortest path between the two edges is the path of the route: True.
The shortest time in the rustworkx graph is 113.2 s. With the time of the last edge, it is 114.1 s, the time of the route.
TipTip
Use networkx for its many algorithms on a small area, and rustworkx for speed on a large area. For many routes or a travel time matrix, the calls of chapter 8 run in Rust and are faster than both.
7.12 What chapter 8 adds
This chapter finds one route at a time. 8. Advanced routing uses the same turn graph for more:
Call
Gives
the Route object
the edges as a GeoDataFrame, the geometry, a map of the route
weight="length"
the shortest route in place of the fastest
routes
many routes, in parallel
k_shortest_paths
the next best routes
matrix
the travel time from each origin to each destination
isochrones, accessibility
the area that you reach in a time, and the targets in reach
7.13 Try it yourself
1. Find the fastest route by bicycle from Fontvieille to Larvotto, and compare its time with the car route.
TipShow the answer
bike_route = net.cycling.route(a, b)round(bike_route.time_s /60, 1), round(drive.time_s /60, 1) # minutes by bicycle and by car
2. Find a walking route between two street names, and print its first three steps.
TipShow the answer
w = net.walking.route("Boulevard Albert 1er", "Avenue de la Costa")[s["text"] for s in w.directions()][:3]
3. Find the length in km of the shortest walk from Fontvieille to Larvotto with networkx, on the graph with weight="length", between the edges of the route walk.
TipShow the answer
gw = net.walking.to_networkx(weight="length")s, t = walk.edge_ids[0], walk.edge_ids[-1]nx.shortest_path_length(gw, s, t, weight="weight") /1000# without the last edge
7.14 Words in this chapter
Word
Meaning
route
a list of edges from a start to an end, with its time and its length
turn graph
the graph whose nodes are edges and whose arcs are legal turns (<mode>.edge_graph)
arc
one legal turn from an edge to the next edge
place
the start or the end of a route: an edge id, a (lon, lat) point or a name
geocode
to find the point of a place name
multimodal graph
the tables mm.*: the networks of the modes, joined at shared junctions
leg
the part of a trip in one mode
transfer
a change of mode at a junction, for example park
7.15 Summary
Call
Does
net.driving.route(a, b, weight="time")
the fastest (or shortest) route between two places; a Route or None
The reference: duckosm.routing. Next:8. Advanced routing, the Route object, the fastest or the shortest route, the k best routes, the matrix and isochrones.