openmobisim tutorials · 00 · overview · ← 00 · Getting started · 02 · Demand → · documentation

01 · Networks#

A run needs a network: the roads, with a bike layer and a walk layer beside them. This notebook reads one from OpenStreetMap, shows what the reader assumed and how to change it, checks it, and reads and writes the two file formats a network you already have is likely to be in: a plain table of links (the TNTP benchmarks) and GMNS.

The data come from the starter bundle: six cases (Delft, Amsterdam, Paris, Lyon, Sioux Falls, Nguyen–Dupuis), each its network, a timetable where there is one, and a morning’s demand. examples.case finds a case on this machine, or downloads it once into a cache, and checks every file against the checksums the package carries.

Download this notebook or all ten (a zip), without their outputs. The Installation section below installs openmobisim; its last command, openmobisim notebooks, copies the same ten into a folder and opens the first in JupyterLab.


Installation#

Skip this if import openmobisim already works in this notebook. One install is all there is: pip install "openmobisim[all]" brings the simulator and everything the ten tutorials use (JupyterLab, matplotlib for the figures, pandas, polars and pyarrow for the tables); nothing is installed later. Find the case that matches yours and copy its commands, in order. Each needs Python 3.11 or newer.

A new conda environment (any system; openmobisim is on PyPI, so pip installs it into the environment):

conda create -y -n openmobisim python=3.12
conda activate openmobisim
pip install "openmobisim[all]"
openmobisim notebooks

A new venv on macOS or Linux (in a terminal):

python3 -m venv openmobisim
source openmobisim/bin/activate
pip install "openmobisim[all]"
openmobisim notebooks

A new venv on Windows (in the Command Prompt):

py -m venv openmobisim
openmobisim\Scripts\activate
pip install "openmobisim[all]"
openmobisim notebooks

The last line copies these ten notebooks into ./openmobisim-notebooks and opens them in JupyterLab. In VS Code or PyCharm, open a notebook and choose the openmobisim environment’s Python as its kernel instead.

Into the environment this notebook already runs in: paste this into a new code cell, run it, then restart the kernel.

%pip install "openmobisim[all]"

import time

import numpy as np
import openmobisim as ms
import pandas as pd

print(ms.examples.case_names())
['amsterdam', 'delft', 'lyon', 'nguyendupuis', 'paris', 'siouxfalls']

1 · Start small: Delft#

The smallest city, Delft (the Netherlands), reads whole — roads, bike and walk layers — in a second or two, and its morning runs in a few seconds (notebook 08): the quickest way to a real city. The rest of this notebook works on Amsterdam.

delft = ms.examples.case("delft")
started = time.perf_counter()
small = delft.network()
print(small)
print(f"read in {time.perf_counter() - started:.1f} s")
Network(19947 nodes, 42699 links, with street geometry)
read in 2.1 s

2 · Amsterdam#

Each case says where its data come from and under which licence.

case = ms.examples.case("amsterdam")
pd.DataFrame(case.info["sources"])
what from licence
0 the road, bike and walk networks and the parkings OpenStreetMap ODbL 1.0: © OpenStreetMap contributors (https:...
1 the timetable of 2026-10-09, its runs from 05:... the Dutch national GTFS feed (gtfs.ovapi.nl, p... CC0 1.0 (OVapi)
2 each zone's residents and non-residential buil... the Global Human Settlement Layer R2023A, epoc... CC BY 4.0, (c) European Union, 1995-2026 (http...
3 the motorway gateways' morning counts (demand/... Rijkswaterstaat, INWEVA 2025, morning peak (ht... CC0 1.0 (https://creativecommons.org/publicdom...
4 the morning (zones, OD matrix, trips from outs... synthetic: openmobisim's morning recipe (cases... CC BY 4.0

3 · From OpenStreetMap#

network_read_osm reads an .osm.pbf extract. region cuts a study area out of it (a rectangle (west, south, east, north) in degrees, or a polygon); the bundle’s file is already cut to Amsterdam and its surroundings, and here we take the city centre, inside the canal ring and a little beyond, to keep the notebook quick. The reader keeps the largest part of the network that every car can leave and reach (it is strongly connected), merges car links across nodes that only footways touch, and reads the bike and walk layers from the same ways.

CENTRE = (4.865, 52.355, 4.935, 52.385)
net = ms.network_read_osm(str(case.path("network.osm.pbf")), region=CENTRE)
print(net)
print(f"read in {net.read_s:.1f} s")
Network(10862 nodes, 22697 links, with street geometry)
read in 5.3 s

Every link carries its road class (from the OSM highway tag), its length, lanes, free-flow speed and capacity, read as arrays indexed by link. A table by class shows what the reader made of the centre: kilometres, the speeds (the OSM maxspeed where tagged, the class’s default otherwise; most of Amsterdam is tagged 30 km/h) and the capacities (from the lanes and the class’s saturation flow per lane).

length, speed, capacity = net.link_length_m(), net.link_speed_km_h(), net.link_capacity_pcu_h()
drive = net.link_drivable()
links = pd.DataFrame({
    "class": np.array(ms.LINK_CLASSES)[net.link_class()],
    "km": length / 1000,
    "speed_km_h": speed,
    "lanes": net.link_lanes(),
    "capacity_pcu_h": capacity,
    "drivable": drive,
})  # fmt: skip
by_class = links[links["drivable"]].groupby("class").agg(
    links=("km", "size"), km=("km", "sum"), speed_km_h=("speed_km_h", "median"),
    lanes=("lanes", "median"), capacity_pcu_h=("capacity_pcu_h", "median"),
)  # fmt: skip
by_class.sort_values("km", ascending=False).round(1)
links km speed_km_h lanes capacity_pcu_h
class
residential 2342 200.2 30.0 1.0 1400.0
tertiary 749 41.5 30.0 1.0 1700.0
primary 411 25.5 30.0 2.0 3000.0
service 434 19.1 20.0 1.0 800.0
unclassified 339 16.4 30.0 1.0 1600.0
secondary 211 10.3 30.0 1.0 1800.0
living_street 56 4.2 15.0 1.0 900.0
trunk 13 4.0 50.0 2.0 3600.0
primary_link 7 0.8 30.0 1.0 1500.0
tertiary_link 11 0.1 30.0 1.0 1400.0
secondary_link 7 0.1 30.0 1.0 1500.0
trunk_link 2 0.0 50.0 1.0 1500.0

Signals add a control delay to the links that enter them (a fixed number of seconds from Webster’s formula, with an assumed cycle and green share: OpenStreetMap maps where the signals are, not their timings). A link’s free-flow time is its length at its speed plus that delay.

delay = net.link_free_flow_s() - length / (speed / 3.6)
print("signalised nodes:", int(net.node_signalised().sum()))
print("car links ending at a signal:", int((delay[drive] > 0.5).sum()), "of", int(drive.sum()))
print(f"their control delay: {np.median(delay[drive & (delay > 0.5)]):.1f} s")
signalised nodes: 624
car links ending at a signal: 225 of 4582
their control delay: 20.6 s

4 · What the reader assumes, and how to change it#

Every number the reader fills in when OpenStreetMap is silent is a default: uncalibrated, named, and replaceable. network_options() lists them all; network_options= on any reader overrides them by name (a misspelt name is refused, with the list). Here: the residential streets’ default speed, and the green share of every signal.

options = ms.network_options()
print(len(options), "network parameters, for example:")
{k: options[k] for k in ("residential.free_flow_km_h", "primary.saturation_flow_veh_h_lane", "signal_cycle_s",
                         "signal_green_fraction", "bike_dedicated_km_h", "bike_mixed_km_h", "walk_km_h")}  # fmt: skip
95 network parameters, for example:
{'residential.free_flow_km_h': 30.0,
 'primary.saturation_flow_veh_h_lane': 1900.0,
 'signal_cycle_s': 90.0,
 'signal_green_fraction': 0.48,
 'bike_dedicated_km_h': 18.0,
 'bike_mixed_km_h': 15.0,
 'walk_km_h': 4.8}
slower = ms.network_read_osm(
    str(case.path("network.osm.pbf")),
    region=CENTRE,
    network_options={"signal_green_fraction": 0.40, "residential.free_flow_km_h": 25.0},
)
print(f"free-flow time of every car link, summed: {net.link_free_flow_s()[drive].sum() / 3600:.1f} h, "
      f"with the changes {slower.link_free_flow_s()[slower.link_drivable()].sum() / 3600:.1f} h")  # fmt: skip
free-flow time of every car link, summed: 12.2 h, with the changes 12.5 h

A default changes only the links that took it: a street tagged maxspeed=30 keeps 30 km/h whatever the residential default says. ms.parameters() lists every parameter of the whole simulator (network, loading, choice, transit, parking) in one table; notebook 06 uses it.

5 · The bike and walk layers#

net.layer("bike") and net.layer("walk") are networks of their own, read from the same ways: a one-way street is ridden both ways where contraflow cycling is allowed and walked both ways everywhere; footways and cycleways are in them, motorways are not. Each bike link says its infrastructure: 0 mixed traffic (or a path shared with pedestrians), 1 a painted lane or a cycle street, 2 a track or cycleway of its own. A ferry crossing has none (its class tells it apart).

bike, walk = net.layer("bike"), net.layer("walk")
infra = pd.Series(bike.link_infrastructure()).map({0: "mixed traffic", 1: "painted lane", 2: "separated"})
ferry = np.array(ms.LINK_CLASSES)[bike.link_class()] == "ferry"
infra[ferry] = "ferry"
bike_km = (pd.Series(bike.link_length_m() / 1000).groupby(infra).sum()).rename("km")
pd.DataFrame({"km": bike_km, "share (%)": 100 * bike_km / bike_km.sum()}).round(1)
km share (%)
ferry 6.7 1.2
mixed traffic 403.3 72.7
painted lane 33.2 6.0
separated 111.6 20.1
print(f"bike layer: {bike.link_count} links, median speed {np.median(bike.link_speed_km_h()):.0f} km/h")
print(f"walk layer: {walk.link_count} links, median speed {np.median(walk.link_speed_km_h()):.1f} km/h")
bike layer: 9076 links, median speed 15 km/h
walk layer: 30320 links, median speed 4.8 km/h

A map of the centre’s bike layer, drawn with matplotlib from link_geometry() (every link’s polyline; the package’s own figures, in notebook 05, draw runs rather than networks):

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

coords, offsets = bike.link_geometry()
colour = {0: "#b8b8b8", 1: "#e3a33b", 2: "#2f7d4f"}
fig, ax = plt.subplots(figsize=(18 / 2.54, 12 / 2.54), dpi=200)
for kind, label in ((0, "mixed traffic"), (1, "painted lane"), (2, "separated")):
    keep = np.flatnonzero((bike.link_infrastructure() == kind) & ~ferry)
    ax.add_collection(LineCollection([coords[offsets[i]:offsets[i + 1]] for i in keep], colors=colour[kind],
                                     linewidths=0.4 if kind == 0 else 0.9, label=label))  # fmt: skip
ax.set_xlim(CENTRE[0], CENTRE[2])
ax.set_ylim(CENTRE[1], CENTRE[3])
ax.set_aspect(1 / np.cos(np.radians(52.37)))
ax.set_axis_off()
ax.legend(loc="lower right", frameon=False)
ax.set_title("Amsterdam centre: the bike layer by infrastructure", loc="left")
plt.show()
../_images/f9edc9ab4d0b8e78423651547d8d85acf1346b30a2e255e604b6fa0da6c20207.png

6 · Checking a network#

network_check looks for what would make trips fail (pieces a car cannot leave, links of zero length) and for what is worth a look (a class whose median speed suggests a unit mix-up, very short links, dead ends). Each check is pass, warn or fail, with the rule it applied. A network read from OpenStreetMap passes the hard checks by construction; a network you bring may not.

check = ms.network_check(net)
print("verdict:", check["verdict"])
pd.DataFrame(check["checks"])[["layer", "check", "status", "value"]]
verdict: warn
layer check status value
0 road strongly connected pass 1 piece(s), the largest 2532 of 2532 nodes; 0 ...
1 road no self-loops pass 0
2 road lengths and times positive pass 0 links
3 road length not below the straight line pass 0.0% of links more than 1% shorter than the st...
4 road very short links warn 3.7% under 5 m
5 road parallel links pass 0.5%
6 road speeds plausible by class pass every class
7 road capacity per lane plausible pass 0.0% outside 500-2400 PCU/h per lane
8 road lanes per direction pass 0 links with more than 6
9 road dead ends pass 10.2% of nodes
10 road stop lines stop one direction pass 0.0% of 38 two-way stop lines stop both direct...
11 bike strongly connected pass 1 piece(s), the largest 3937 of 3937 nodes; 0 ...
12 bike no self-loops pass 0
13 bike lengths and times positive pass 0 links
14 bike length not below the straight line pass 0.0% of links more than 1% shorter than the st...
15 bike speed plausible pass median 15.0 km/h
16 walk strongly connected pass 1 piece(s), the largest 10482 of 10482 nodes; ...
17 walk no self-loops pass 0
18 walk lengths and times positive pass 0 links
19 walk length not below the straight line pass 0.0% of links more than 1% shorter than the st...
20 walk speed plausible pass median 4.8 km/h

7 · Clipping a study area#

Cutting a study area out of a larger network breaks the roads that cross its edge, and keeping only the strongly connected part would then drop whatever those roads served. The reader keeps stubs, the parts of roads that cross the edge, up to their first junction outside, and a buffer of main roads around the area (2 km by default), so a ring road just outside stays. Without them:

bare = ms.network_read_osm(str(case.path("network.osm.pbf")), region=CENTRE, region_stubs=False, region_buffer_m=0.0)
pd.DataFrame(
    {"links": [bare.link_count, net.link_count],
     "drivable km": [bare.link_length_m()[bare.link_drivable()].sum() / 1000, length[drive].sum() / 1000]},
    index=pd.Index(["the area only", "with stubs and a 2 km buffer"], name="clip"),
).round(1)  # fmt: skip
links drivable km
clip
the area only 22480 313.5
with stubs and a 2 km buffer 22697 322.2

9 · GMNS#

GMNS (the General Modeling Network Specification, by the Zephyr Foundation) is a plain-CSV standard for networks: node.csv, link.csv, and optional tables. network_write_gmns writes a network and its layers as three GMNS networks (road/, bike/, walk/), with each link’s polyline so that GIS tools can draw them; network_read_gmns reads them back, or reads a single GMNS network from another tool (deriving the layers).

import tempfile
from pathlib import Path

folder = Path(tempfile.mkdtemp()) / "centre"
written = ms.network_write_gmns(net, str(folder))
print(written)
print(sorted(p.relative_to(folder).as_posix() for p in folder.rglob("*.csv")))
back = ms.network_read_gmns(str(folder))
print("the same classes, lanes, capacities and bike infrastructure:", all([
    np.array_equal(back.link_class(), net.link_class()),
    np.array_equal(back.link_lanes(), net.link_lanes()),
    np.array_equal(back.link_capacity_pcu_h(), net.link_capacity_pcu_h()),
    np.array_equal(back.layer("bike").link_infrastructure(), bike.link_infrastructure()),
]))  # fmt: skip
print(f"lengths differ by at most {np.abs(back.link_length_m() - length).max() * 1e6:.2f} micrometres")
{'road': 22697, 'bike': 9076, 'walk': 30320}
['bike/config.csv', 'bike/link.csv', 'bike/node.csv', 'road/config.csv', 'road/link.csv', 'road/node.csv', 'walk/config.csv', 'walk/link.csv', 'walk/node.csv']
the same classes, lanes, capacities and bike infrastructure: True
lengths differ by at most 0.50 micrometres

The files keep lengths to the micrometre (six decimals), so a network read back is the same network, though not the same bits: a run on it has its own fingerprint. Keep the original files (the extract, or your own GMNS) as the reference for a study.

10 · Changing a network for a scenario#

A study compares the network as it is with the network as it could be. network_edit returns a changed copy (a road closed, a lane added or taken away, a capacity scaled, a cycle track built) whose links keep their indices, so two runs’ per-link results line up. Here, a cycle track on every bike link in mixed traffic along a primary, secondary or tertiary road (a bike link shares its way id with the road: link_ids()); notebook 09 runs a study with it.

road_class = np.array(ms.LINK_CLASSES)[net.link_class()]
main_ways = {lid.split(":")[0] for lid, c in zip(net.link_ids(), road_class, strict=True)
             if c in ("primary", "secondary", "tertiary")}  # fmt: skip
upgrade = [i for i, (lid, kind) in enumerate(zip(bike.link_ids(), bike.link_infrastructure(), strict=True))
           if kind == 0 and lid.split(":")[0] in main_ways and not ferry[i]]  # fmt: skip
tracks = ms.network_edit(net, bike_facility={i: "separated" for i in upgrade})


def separated_km(layer):
    return layer.link_length_m()[layer.link_infrastructure() == 2].sum() / 1000


print(f"{len(upgrade)} bike links, {bike.link_length_m()[upgrade].sum() / 1000:.1f} km, made separated")
print(f"separated: {separated_km(bike):.1f} km before, {separated_km(tracks.layer('bike')):.1f} km after")
134 bike links, 6.2 km, made separated
separated: 111.6 km before, 117.8 km after

Next: 02 · Demand: demand: trips tables, OD matrices, traveller classes, persons, samples; the starter cases’ morning. The whole series: 00 · overview. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.