A duckOSM network is a DuckDB file, and many tools cannot read it. An export writes the network in the format of such a tool: SUMO, MATSim, GMNS, OpenDRIVE, a GIS file or vector tiles. In each format, the id of a road is the edge_id, so the results of each tool join back to the network.
# 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,sim] @ {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")
6.1 Why a network needs exports
A duckOSM network is a DuckDB file. Many tools cannot read it: a traffic simulator reads its own XML, a planning tool reads GMNS tables, a GIS reads a GeoPackage. An export writes the network in the format of such a tool. Each export is one call of the Network, and each call writes the files and gives a dict of their paths and their numbers.
Format
Who uses it
The call
Module
How this chapter checks the file
Chapter
SUMO
traffic engineers who simulate each vehicle (microscopic simulation)
net.to_sumo
duckosm.sim
SUMO’s netconvert reads the plain XML and writes the .net.xml
12
MATSim
researchers who simulate the trips of a whole population (agent-based simulation)
net.to_matsim
duckosm.sim
the XML has one link for each edge
12
GMNS
transport planners (path4gmns, AequilibraE, DTALite)
net.to_gmns
duckosm.planning
duckosm.planning.check_gmns runs its checks on the tables
13
OpenDRIVE
driving simulators and HD-map tools (CARLA, esmini)
net.to_opendrive
duckosm.hdmap
the XML has one road for each edge
14
GeoPackage, GeoParquet, shapefile
GIS users (QGIS, ArcGIS, GeoPandas)
net.to_gis
duckosm.gis
DuckDB reads each layer back and counts its rows
10
QuackOSM table
data engineers who want all OSM features with their tags
duckosm.gis.quack
duckosm.gis
DuckDB reads the table and counts the features of each OSM type
10
PMTiles
web maps (MapLibre, OpenLayers)
duckosm quack --pmtiles
the command
the file starts with the text PMTiles
10
The chapters in the last column use each format in its own field. This chapter writes each format one time and checks it.
ImportantKey idea
In each format, the id of a road is the duckOSM edge_id: the id of a SUMO edge, of a MATSim link, of a GMNS link, of an OpenDRIVE road and of a row of the GIS layer. So the results of each tool (a flow, a speed, a count) join back to the network and to your own data by edge_id.
6.1.1 The five levels of the outputs
The manual sorts all outputs into five levels, from the OSM file to the lanes. This chapter shows the outputs of levels 1 to 4; level 0 is in chapter 1, and chapter 10 has more of level 1.
Level
Name
One unit is
In this chapter
0
OSM file
the .osm.pbf, cut to your area
(chapter 1)
1
OSM data
an OSM feature, with no network
QuackOSM table, PMTiles
2
Routable network
one edge for each road direction, with its edge_id and turns
the exact shape of each lane, in 3D (experimental)
OpenDRIVE
Each level keeps the edge_id of level 2, so a result at any level joins back to the network.
6.2 The parts of an export call
The export calls of a Network have the same form:
Part
Does
the first argument
the output: a folder (to_sumo) or a file (to_matsim, to_gmns, to_opendrive, to_gis)
mode
the mode to export. net.driving.to_sumo(...) is the same as net.to_sumo(..., mode="driving")
progress
the progress line. False shows nothing
the other keywords
the options of the format, from the function of its module
the result
a dict: the paths of the files and the numbers (nodes, edges, links, layers)
Each call is a function of a module too: net.to_sumo(...) is duckosm.sim.to_sumo(net, ...). Some formats are of one mode, and some take all modes:
Call
Without mode
to_sumo, to_opendrive
the driving network
to_matsim
the driving network. mode can also be a list of modes
to_gmns, to_gis
all the modes of the file
6.3 Open the network of chapter 1
Chapter 1 builds Monaco with three modes (driving, walking and cycling) and saves it as monaco.duckdb. This chapter opens that file with duckosm.open. The exports of this chapter use the driving network. Its summary gives the number of edges and nodes, so you can compare each export with it.
net = duckosm.open("monaco.duckdb")net.driving.summary()
mode
edges
nodes
km
oneway_km
0
driving
2840
1768
96.2
35.5
The driving network of Monaco has 2,840 edges and 1,768 nodes, 96.2 km of road. Each export below gives its own count, and the count must agree with these numbers.
6.4 SUMO
SUMO (Simulation of Urban MObility) simulates each vehicle on each lane, second by second. Its network file is .net.xml. SUMO’s program netconvert makes it from plain XML files: the nodes (.nod.xml), the edges (.edg.xml) and the connections between lanes (.con.xml).
to_sumo writes the plain files and a netconvert config (.netccfg), the input of netconvert. You can change the config, and then you run netconvert. The plain files have all that netconvert takes from an OSM file for the network: the lanes, their widths and vehicle classes, the speeds, the road classes, the names, the shapes, the legal turns, the traffic lights and the stop signs. Thus you do not give netconvert the OSM file, which has no fixes and no edge_id.
network.nod.xml ─┐
network.edg.xml ─┼─ named in network.netccfg ──> netconvert -c network.netccfg ──> network.net.xml
network.con.xml ─┘
network.add.xml ─── the bus stops, for SUMO itself (sumo --additional-files)
Argument
Default
Does
net_name
"network"
the start of each file name
run_netconvert
False
True: duckOSM also runs netconvert, and writes the .net.xml and the signal programs (.tll.xml)
connections
True
writes the connections of the lanes at each junction (from the turn graph and the turn lanes)
config
none
a dict of options that change the default config, or the path of your own .netccfg
The dict has the paths of the three plain files, of the bus stops (add) and of the netconvert config (netccfg). There is no .net.xml: netconvert did not run. The plain files have 1,768 nodes, 2,840 edges and 5,082 connections: the same nodes and edges as the network, and one connection for each arc of the turn graph that a car can use (chapter 7). The nodes have 18 traffic lights and 12 stop signs, and the additional file has 106 bus stops.
The check: each SUMO edge must be a duckOSM edge. duckosm.sim.edge_map reads the .edg.xml and gives the edge_id of each SUMO edge.
The .edg.xml has 2,840 edges, and they are 2,840 different edge ids: each duckOSM edge is one SUMO edge, with its edge_id as its SUMO id.
6.4.1 Traffic lights and stop signs
OSM often puts a traffic light or a stop sign on a node of the way before the junction, not on the junction. duckOSM moves the sign to the nearest junction of the same way, if it is 25 m or nearer, as netconvert does with its option tls.guess-signals. The traffic lights within 20 m of each other get one program: the node attribute tl.
OSM tag
SUMO node type
highway=traffic_signals
traffic_light
highway=stop
priority_stop: the vehicles of the minor road stop
highway=stop with stop=all
allway_stop: all vehicles stop
highway=give_way
no change: a SUMO priority junction makes the minor road wait
import xml.etree.ElementTree as ETfrom collections import CounterCounter(n.get("type") for n in ET.parse(sumo["nod"]).getroot() if n.get("type"))
yes: true gives metres in the UTM zone of the area
geometry.remove = false
no: with true, netconvert joins the edges between two junctions, and a SUMO edge is no longer one edge_id
junctions.join = false
no: with true, the short edges inside a joined junction go, and the turns through them are lost. If you need it, use to_sumo(..., config={"junctions.join": "true"}, run_netconvert=True): duckOSM then keeps the turns
numerical-ids = false
no: with true, netconvert gives new ids
no-turnarounds.except-deadend
yes: true gives no U-turns, except at a dead end
tls.default-type = actuated
yes: OSM has no signal timings, so the default program follows the traffic. static gives fixed times
The three lines in bold keep the edge_id as the SUMO id. You can change the config in two ways:
Edit the file as text, then run netconvert -c on it.
Give config={...} to to_sumo: duckOSM writes the options into the file. For example net.driving.to_sumo("out/sumo", config={"tls.default-type": "static"}).
6.4.3 The extra files
network.add.xml: the bus stops, for SUMO itself (sumo --additional-files network.add.xml), not for netconvert. Each OSM bus stop is a <busStop> on the right-most lane that buses can use, on the nearest edge of a bus route. The lane id is <edge_id>_<index>, index 0 on the right. lines has the bus routes on that edge.
network.tll.xml: the signal programs. OSM seldom has signal timings, and a program must have one signal for each lane connection of its junction, in the order of netconvert. Thus only run_netconvert=True writes this file: it copies the programs that netconvert built, and adds the file to the config. Edit the phases in it, and run netconvert -c again: netconvert then uses your programs.
Run netconvert on the config. It writes out/sumo/network.net.xml, the file that SUMO reads. The extra sim installs netconvert (the Python package eclipse-sumo). Chapter 12 does this step and runs a simulation.
netconvert-c out/sumo/network.netccfg
6.5 GMNS
GMNS (General Modeling Network Specification) is a standard set of tables for transport planning: node, link, lane, movement (a turn at a junction) and more. Planning tools such as path4gmns, AequilibraE and DTALite read it.
to_gmns writes the tables into a DuckDB file, one schema for each mode (gmns_driving …). to_csv also writes each table as a CSV file, the form of the standard.
Argument
Default
Does
to_csv
none
a folder: the CSV files too
modes
all
the modes, when you call it on the network (mode gives one)
GMNS out/gmns.duckdb: done in 15.2 s
{'driving': {'node': 1772,
'link': 2858,
'lane': 3318,
'movement': 3755,
'signal_controller': 1,
'curb_seg': 0}}
NoteWhat the output shows
The GMNS network of driving has 1,772 nodes, 2,858 links, 3,318 lanes and 3,755 movements. It has 18 links and 4 nodes more than driving.edges (2,840 edges, 1,768 nodes). The 18 links are the bus-only edges of driving.private_edges: a bus lane against a one-way street, or a road for buses only. A car route does not use them, but they are lanes on the road, so GMNS keeps them, with allowed_usesbus or bus,bike. The 4 nodes are their ends that are not in the driving network.
The check: duckosm.planning.check_gmns runs the rules of the standard on the tables. Examples: each link starts at its from_node, each lane number is correct, each movement turns where its inbound link ends. It gives one row for each rule: the schema, the rule, the number of bad rows and the number of rows.
checks = duckosm.planning.check_gmns("out/gmns.duckdb")len(checks), [c for c in checks if c[2] >0]
(17, [])
check_gmns ran 17 checks, and no check found a bad row (the empty list).
6.6 MATSim
MATSim simulates the trips of each person of a population for a whole day. Its network is one XML file (network.xml, gzip by default) with <node> and <link> elements. A link has its length, its free speed (m/s), its capacity and its lanes.
Argument
Default
Does
crs
the UTM zone of the area
the coordinate system of the nodes (MATSim needs metres)
MATSim out/matsim_network.xml.gz: done in 0.1 s
{'nodes': 1768, 'links': 2840, 'crs': 'EPSG:32632'}
The MATSim network has 1,768 nodes and 2,840 links, in UTM zone 32N (EPSG:32632, in metres).
The check: Python’s XML reader opens the file and counts its <link> elements. gzip.open reads the compressed file.
import gzipimport xml.etree.ElementTree as ETtree = ET.parse(gzip.open("out/matsim_network.xml.gz"))len(tree.findall(".//link"))
2840
The file has 2,840 <link> elements: one link for each edge.
6.7 OpenDRIVE (experimental)
ASAM OpenDRIVE (.xodr) describes roads for driving simulators: the reference line of each road, its lanes and their widths. Simulators such as CARLA and esmini read it. The export is experimental: it writes one road for each edge, and the junctions only with junctions=True.
OpenDRIVE out/monaco.xodr: done in 0.1 s
{'roads': 2840, 'crs': 'EPSG:32632'}
2840
The OpenDRIVE file has 2,840 roads, in UTM zone 32N. The XML has 2,840 <road> elements: one road for each edge.
6.8 GeoPackage, GeoParquet and shapefiles
A GIS (QGIS, ArcGIS) and GeoPandas read standard GIS files. to_gis writes the edges and the nodes of each mode as layers (edges_driving, nodes_driving …) and the boundary of the area.
Argument
Default
Does
fmt
"gpkg"
"gpkg": one GeoPackage file; "geoparquet": a folder of GeoParquet files; "shp": a folder of shapefiles
GIS out/monaco.gpkg: done in 0.1 s
{'edges_driving': 2840, 'nodes_driving': 1768, 'boundary': 1}
The GeoPackage has three layers: 2,840 edges, 1,768 nodes and the boundary (1 row).
The check: DuckDB reads each layer back and counts its rows. The function st_read of the DuckDB extension spatial reads one layer of a GIS file.
import duckdbcon = duckdb.connect()con.load_extension("spatial")for layer in gis["layers"]: rows = con.sql(f"SELECT count(*) FROM st_read('out/monaco.gpkg', layer='{layer}')").fetchone()[0]print(layer, rows)
edges_driving 2840
nodes_driving 1768
boundary 1
DuckDB reads each layer with the same number of rows as the network.
GeoParquet is a Parquet file with a geometry column. It is fast to read for DuckDB, GeoPandas and the cloud data tools. fmt="geoparquet" writes one file for each layer into a folder.
pq = net.driving.to_gis("out/geoparquet", fmt="geoparquet")print(len(pq["files"]), "files")con.sql("SELECT count(*) FROM 'out/geoparquet/edges_driving.parquet'").fetchone()[0]
GIS out/geoparquet: done in 0.1 s
15 files
2840
NoteWhat the output shows
The folder has 15 files. DuckDB reads 2,840 rows from the edges file. The folder also has the layers of the base map (features_buildings, features_streets …), which the GeoPackage of the cell before does not have.
TipTip
A shapefile cuts each column name to 10 characters, and each layer is a set of files. Use GeoPackage or GeoParquet when the tool can read them.
6.9 QuackOSM table and PMTiles
The calls above export the network. duckosm.gis.quack exports the OSM data: it reads the OSM file, not the network, and gives all OSM features (nodes, ways, relations) with all their tags, in the format of QuackOSM. It takes the Area of duckosm.get (or the path of an OSM file).
Argument
Default
Does
out, name
".", "area"
the folder and the start of the file name (<name>_quack.parquet)
formats
GeoParquet
the formats of the table: "geoparquet", "gpkg" …
gdal
False
True: the five layers of GDAL’s OSM driver in place of the table
fixes
none
the fixes file (chapter 5)
area = duckosm.get(osm_id=2220322, name="monaco", out="data")quack = duckosm.gis.quack(area, out="out", name="monaco", formats=["geoparquet"])quack
The result is the list of the files that quack wrote: here one GeoParquet file. Each row of the table is one OSM feature. Its feature_id is the OSM type and the id, for example way/4230891. The check counts the features of each OSM type: split_part(feature_id, '/', 1) is the text before the /.
con.sql(f""" SELECT split_part(feature_id, '/', 1) AS type, count(*) AS features FROM '{quack[0]}' GROUP BY type ORDER BY type""").df()
type
features
0
node
3994
1
relation
59
2
way
5606
The QuackOSM table of Monaco has 3,994 nodes (points with tags: shops, stops, trees …), 5,606 ways and 59 relations. This is all of the OSM data with tags, not only the roads: a building, a park and a bench are features too.
PMTiles is one file of vector tiles: a base map that a web map (MapLibre, OpenLayers) reads directly from a web server, with no tile server. The command duckosm quack --pmtiles makes it. The SDK has no Python call for it yet, so the cell runs the command.
exit code 0
0.0 s quack --pmtiles: the boundaries
0.0 s quack 1: the ways and the relations
0.1 s quack 2: the nodes and the points
0.1 s quack 3: the ways
0.1 s quack 4a: the lines of the relations
0.1 s quack 4b: the relations
0.1 s quack --pmtiles: the rows of the tiles
0.1 s quack --pmtiles: the tiles
quack --pmtiles: 9659 features, 59 tiles, 0.2 MB in 0.09 s
out/monaco.pmtiles
The command made 59 tiles of 9,659 features. The file is 0.2 MB (219,713 bytes), and its first seven bytes are PMTiles.
6.10 The fix of chapter 5 in every output
Chapter 5 fixes the OSM data in a fixes file: road works lower the speed limit of Boulevard Louis II (the OSM way 4230891) to 10 km/h. Each export of a fixed network takes the fix. The cells below build the network with that fixes file, write five outputs and read the speed of one edge of Boulevard Louis II back from each file.
Output
Where the speed is
the database
maxspeed_kmh of driving.edges
GeoPackage
maxspeed_kmh of the layer edges_driving
SUMO
the attribute speed (m/s) of the <edge>
MATSim
the attribute freespeed (m/s) of the <link>
GMNS
free_speed (km/h) of the table link
QuackOSM table
the tag maxspeed of the way
In each file, the id of the edge (or of the link) is the edge_id. So the cells find the same edge in each output.
The cell below takes one edge of Boulevard Louis II and starts the dict speeds: its speed in each output. The first entry is the database.
louis = fixed.driving.edges(where="osm_id = 4230891")edge =int(louis.edge_id.iloc[0])speeds = {"database (km/h)": float(louis.maxspeed_kmh.iloc[0])}speeds
{'database (km/h)': 10.0}
Each cell below writes one output and reads the speed of the edge back from it. SUMO and MATSim keep the speed in m/s, so the cells multiply it by 3.6 to get km/h. The ? in a query is a parameter: DuckDB puts the value of the list ([edge]) in its place.
fixed.driving.to_gis("out/fixed.gpkg")query ="SELECT maxspeed_kmh FROM st_read('out/fixed.gpkg', layer='edges_driving') WHERE edge_id = ?"speeds["GeoPackage (km/h)"] = con.execute(query, [edge]).fetchone()[0]
The largest file is the GMNS database (approximately 9 MB): it has the lanes, the movements and a line for each lane. The OpenDRIVE file (2.10 MB) has the reference line and the lanes of each road. The MATSim network is the smallest file (0.10 MB), because it is compressed with gzip.
6.12 Try it yourself
1. Export the walking network of Monaco to MATSim, and compare its number of links with the number of walking edges.