openmobisim tutorials · 01 · Networks → · documentation
00 · Getting started#
openmobisim simulates how people move through a city — by car, by bicycle, on foot, by public transport, and in combinations (park-and-ride, bike-and-ride) — on one network, with travellers who choose their routes and their modes, and roads that queue. It is a Python package on a fast Rust core.
This notebook is where the tutorials start: a first look at a whole city’s morning, what the other notebooks cover and in which order, how to set up, then a first run from start to finish on a network small enough to check by hand.
Alpha (0.1). This version is for testing by students and colleagues: its tests are not complete, and names may still change. Use it, and please report anything that goes wrong or is unclear: github.com/bahmanmdd/openmobisim/issues.
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 openmobisimalready 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 notebooksA new venv on macOS or Linux (in a terminal):
python3 -m venv openmobisim source openmobisim/bin/activate pip install "openmobisim[all]" openmobisim notebooksA new venv on Windows (in the Command Prompt):
py -m venv openmobisim openmobisim\Scripts\activate pip install "openmobisim[all]" openmobisim notebooksThe last line copies these ten notebooks into
./openmobisim-notebooksand opens them in JupyterLab. In VS Code or PyCharm, open a notebook and choose theopenmobisimenvironment’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]"
1 · A taste of what is ahead#
Before the basics, a look at where they lead. The next two cells simulate the morning of Delft, a city of about 100 000 people in the Netherlands: over a hundred thousand trips by car, bike, foot and public transport, each traveller choosing a mode and a route, with queues where the roads fill up: its whole morning, every departure from 06:30 to 09:30, run on to 10:30 so that the late ones arrive. The city is downloaded once (18 MB); here each simulated traveller stands for two people, so that the morning runs in seconds (the cell prints how long it took on your machine). You need not follow the code yet: the notebooks after this one build it up step by step, and by notebook 04 you will run models like this yourself.
import warnings
import openmobisim as ms
from openmobisim import viz
with warnings.catch_warnings(): # two trips have no way to their destination: notebook 04 says why
warnings.simplefilter("ignore", ms.NoAlternativeWarning)
delft = ms.examples.case("delft").scenario("base", departures="all", window=("06:30", "10:30"), weight=2).run(
"delft-first-look", output_dir="runs/delft-first-look", quiet=True, overwrite=True
)
done = delft.completion
print(f"{done['completed']:,} of {done['total_trips']:,} simulated trips arrived, "
f"in {delft.mean_travel_time_s / 60:.0f} minutes on average")
print(f"the run took {delft.timings()['seconds'][-1]:.0f} s on this machine")
56,848 of 56,854 simulated trips arrived, in 25 minutes on average
the run took 11 s on this machine
viz.map_link(delft, title="Delft: the morning's traffic") # each road as wide as its traffic, coloured by its delay
2 · The tutorials#
Notebook |
What it covers |
Data it downloads (once) |
Runs in |
|
|---|---|---|---|---|
00 |
a first look at Delft’s morning, this overview, then a first run end to end on sixteen links you can check by hand |
delft (18 MB) |
under a minute |
|
01 |
networks from OpenStreetMap, what the reader assumed and how to change it, checks, GMNS and link tables |
Amsterdam (60 MB), Sioux Falls |
under a minute |
|
02 |
demand: trips tables, OD matrices, traveller classes, persons, samples; the starter cases’ morning |
Amsterdam (60 MB) |
under a minute |
|
03 |
cars: route sets, route choice, the iterations towards an equilibrium and when they stop |
none |
under a minute |
|
04 |
bikes, walking, a timetable, park-and-ride and bike-and-ride, and the choice of mode |
none |
under a minute |
|
05 |
everything a run leaves: its files, the indicators, the figures and the interactive map |
none |
under a minute |
|
06 |
every default by name, seeds and replications, samples, sweeps; a city’s mode shares moved |
Amsterdam (60 MB) |
about 2 min |
|
07 |
validation: the mechanisms against hand calculations, queueing theory and the benchmarks |
Sioux Falls |
under a minute |
|
08 |
performance: a city’s run time, where the time goes, samples for speed |
Amsterdam (60 MB), Paris (91 MB), Lyon (37 MB), Sioux Falls, Nguyen–Dupuis |
about 4 min |
|
09 |
five minimal studies to copy and extend: transit frequency, your own utility, accessibility, emissions, a road closed for an hour |
delft (18 MB) |
about 1 min |
Runs in: the wall-clock time of the last build, on a MacBook Pro with an Apple M2 Pro (8 performance and 4 efficiency cores), 32 GB of memory, macOS 26, with nothing else running; your machine’s times will differ.
The recommended path.
This notebook, to the end: a minute.
The others in order: 01–02 the inputs (networks, demand), 03–04 the models (cars; bikes, walking, transit and the choice of mode), 05–06 the outputs and the settings, 07–08 how far to trust it and how fast it is, 09 whole studies. Each also stands on its own: jump to the one you need.
The documentation, openmobisim.github.io: these tutorials, guides to each task, how the models work and the reference of every function, parameter and file. In a notebook, every function’s documentation is also in its docstring —
help(ms.Scenario), or Shift+Tab after a name in Jupyter;ms.parameters()lists every default with its source; the repository has the code and the issues.Your own first notebook: the last section here is a skeleton to start from.
3 · Setting up#
The Installation cell under this notebook’s title (every tutorial has the same one) gives the commands for each
case: a conda environment, a venv on macOS, Linux or Windows, or the environment the notebook already runs in. 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 and the Parquet
files); nothing more is installed in any notebook. The simulator itself needs only NumPy: pip install openmobisim
is enough for a script or an optimisation loop, and pip install "openmobisim[viz]" adds the figures without
Jupyter. openmobisim notebooks copies these ten notebooks into ./openmobisim-notebooks and opens this one in
JupyterLab.
Data. Notebooks 03–05 build their networks themselves, and so does this one after its first look at Delft. The
others use the starter cases (Delft, Amsterdam, Paris, Lyon, Sioux Falls, Nguyen–Dupuis): each is downloaded once, when first asked for, checked against the checksums
the package carries, and kept in a cache (~/.cache/openmobisim); OPENMOBISIM_DATA names another folder.
openmobisim cases in a terminal lists them. Every unit is metric: metres, seconds, km/h.
Files. Each run writes its files in a folder of its own; the notebooks put them under runs/ beside them.
import openmobisim as ms
print(ms.__version__)
print(ms.build_info())
0.1.0
{'version': '0.1.0', 'git_sha': 'f036acd815fa', 'code_version': 1, 'rng_scheme_version': 1, 'parallel': True, 'target': 'aarch64-apple-darwin', 'profile': 'release'}
4 · The toy network#
examples.toy_network() is sixteen links laid out so that every number a run produces can be worked out on paper:
a signalised junction S, a merge M of a one-lane and a two-lane road, three links shorter than a car, a diverge
at X3 and a small roundabout. It also has a bike layer (with a cycle track and a contraflow street) and a walk
layer (with two footpaths), which notebook 04 uses.
N1 N2
│ s1 300 ║ m1 300, 2 lanes
▼ ▼
W ─a1 300─▶ S* ─a2 200─▶ M ─a3 400─▶ X0 ▷c1▷c2▷c3▷ X3 ─a4 300─▶ D1
│ a5 60
▼
roundabout R1–R4 ◀─n3 100─ N3
│ e2 300
▼
D2
Lengths are in metres; S* is signalised; c1–c3 are 4 m each. Nodes are named, so a trip can start at W and
end at D1.
net = ms.examples.toy_network()
print(net)
print("links (m):", net.link_length_m())
print("free-flow times (s):", net.link_free_flow_s().round(1))
print("capacities (PCU/h):", net.link_capacity_pcu_h())
Network(16 nodes, 16 links)
links (m): [300. 200. 400. 300. 60. 4. 4. 4. 300. 300. 100. 30. 30. 30.
30. 300.]
free-flow times (s): [56.6 24. 48. 36. 10.8 0.5 0.5 0.5 36. 36. 12. 3.6 3.6 3.6
3.6 56.6]
capacities (PCU/h): [1400. 1400. 1400. 1400. 800. 1400. 1400. 1400. 1400. 2800. 1400. 1400.
1400. 1400. 1400. 1400.]
5 · Trips#
Demand is a trips table: one row per trip, with the traveller, the trip’s place in their day, where it starts and
ends (longitude, latitude), when it leaves (seconds after midnight), the traveller’s class and, optionally, how
many people the row stands for and its mode. A row without a mode is a car trip. ms.Trip names the fields of a
row; a plain tuple of the same fields, a data frame or a dict of columns work as well.
Here: 450 drivers from W and 450 from N2, all to D1, one every 4 seconds from each between 07:00 and 07:30
(900 an hour from each): more than the signal at S lets through from W, and more than the road after the merge at
M carries, so queues form.
def trip(who, origin, destination, depart_s):
o, d = net.node_lonlat(origin), net.node_lonlat(destination)
return ms.Trip(who, 0, o[0], o[1], d[0], d[1], depart_s, "commuter")
trips = [trip(f"w{i}", "W", "D1", 7 * 3600 + 4 * i) for i in range(450)]
trips += [trip(f"n{i}", "N2", "D1", 7 * 3600 + 4 * i) for i in range(450)]
print(len(trips), "trips; the first:", trips[0])
900 trips; the first: Trip(traveller_id='w0', trip_seq=0, origin_lon=4.8, origin_lat=45.7, destination_lon=4.81558890772869, destination_lat=45.7, departure_time_s=25200, user_class='commuter', weight=None, mode=None)
6 · A run#
A scenario is a network, the demand and the settings; .run() simulates it and writes its files. The class
commuter is given a car (the tuple says what the class owns: a car, a bike, a transit pass).
The defaults are the ones a planning study wants: travellers choose among routes (a logit model), the network is
loaded with queues at every bottleneck (a point queue: a queue delays everyone in it but takes no road space), and
choice and loading are repeated until the pattern settles (the method of successive averages, msa). The run says
in one line how long it took and how it ended; run.timings() has every stage.
run = ms.Scenario.from_parts(
net, trips, classes={"commuter": (True, False, False)}, link_bin_s=300
).run("getting-started", output_dir="runs/getting-started")
Run 'getting-started': 0.0 s, window 07:00–10:00, 900 of 900 trips completed, mean trip 6.6 min, verdict good (run.timings() has every stage)
7 · What it produced#
The Run answers the usual questions directly. Completion says how many trips arrived; the mean and total
travel time are in seconds (the total counts each trip as many times as the people it stands for, 1 here); convergence says how far each iteration was from an equilibrium, and the verdict judges the
last one.
print(run.completion)
print(f"mean trip: {run.mean_travel_time_s / 60:.2f} min")
print("iterations:", len(run.convergence()["gap"]), "verdict:", run.convergence_verdict)
print("fingerprint:", run.fingerprint)
{'total_trips': 900, 'completed': 900, 'truncated': 0, 'no_vehicle_available': 0, 'no_feasible_path': 0, 'mode_not_available': 0}
mean trip: 6.63 min
iterations: 4 verdict: good
fingerprint: cb0fbe47df3691bd
On this network each trip has a single route, so the iterations have nothing to settle: the gap is 0 throughout, and
the run stops as soon as its stopping rule can judge (the average of the last three iterations, so after four
loadings). Notebook 03 uses a grid, where trips have many routes. How much the queues cost shows against the same trips at free flow,
where no vehicle delays another (flow_level=0, one loading):
free = ms.Scenario.from_parts(
net, trips, classes={"commuter": (True, False, False)}, flow_level=0, equilibration="free_flow"
).run("getting-started-free-flow", output_dir="runs/getting-started-free-flow", quiet=True)
print(f"mean trip at free flow: {free.mean_travel_time_s / 60:.2f} min")
mean trip at free flow: 2.38 min
Each run writes its files to its folder: kpis.parquet (the indicators), events.parquet (what happened to one trip
in a hundred), link_bins.parquet (each link’s flow and time in five-minute bins, because we asked for link_bin_s=300),
manifest.json (every input and setting, so the run can be reproduced) and timings.csv (where its time went).
import os
for name in sorted(os.listdir("runs/getting-started")):
print(name)
diagnostics.parquet
events.parquet
kpis.parquet
link_bins.parquet
manifest.json
timings.csv
trip_results.parquet
kpis = run.kpis().to_pandas() # one row per indicator, iteration and mode
last = kpis[(kpis["iteration"] == kpis["iteration"].max()) & (kpis["mode"] == "all")]
last[["metric", "value"]]
| metric | value | |
|---|---|---|
| 40 | total_travel_time_s | 357770.000000 |
| 41 | completed_trips | 900.000000 |
| 42 | truncated_trips | 0.000000 |
| 43 | completed_people | 900.000000 |
| 44 | reselected_share | 0.258889 |
| 45 | changed_share | 0.000000 |
| 46 | time_change | 0.000000 |
| 47 | gap | 0.000000 |
| 48 | gap_expected | 0.000000 |
| 49 | gap_excess | 0.000000 |
| 50 | incomplete_share | 0.000000 |
| 51 | gap_network | 0.000000 |
| 52 | gap_network_excess | 0.000000 |
| 53 | gap_flow | 0.000000 |
| 54 | gap_flow_floor | 0.000000 |
| 55 | gap_flow_excess | 0.000000 |
| 56 | trips | 900.000000 |
| 57 | people | 900.000000 |
| 58 | no_vehicle_available_trips | 0.000000 |
| 59 | no_feasible_path_trips | 0.000000 |
| 60 | mode_not_available_trips | 0.000000 |
| 61 | completion_rate | 1.000000 |
8 · A figure#
openmobisim.viz draws the run. map_link draws each link as a ribbon as wide as its volume and coloured by its
delay over free flow, over the busiest part of the day (the subtitle says which). The delays are on a1 and a2,
behind the signal at S and the merge at M, where the road from S gets a share of the road ahead in proportion
to its capacity (one lane against the two of m1); links nobody used are thin grey lines.
from openmobisim import viz
viz.map_link(run, title="The toy network")
9 · The same inputs, the same results#
A run’s fingerprint is a short hash of everything that went in: the network, the trips, every setting and every default. The same inputs give the same fingerprint on any machine, and on the same machine the same results, to the last bit.
again = ms.Scenario.from_parts(
net, trips, classes={"commuter": (True, False, False)}, link_bin_s=300
).run("getting-started-again", output_dir="runs/getting-started-again", quiet=True)
print(again.fingerprint == run.fingerprint, again.total_travel_time_s == run.total_travel_time_s)
True True
10 · Your own first notebook#
Start a new notebook from this skeleton: a starter case (or your own network and demand, notebooks 01 and 02), a run, its summary page and its interactive map, both linked when written. Delft’s morning takes about ten seconds, Amsterdam’s about a minute.
import openmobisim as ms
from openmobisim import viz
case = ms.examples.case("delft") # or Amsterdam, Paris, Lyon; or your own: ms.network_read_osm, ms.demand_read_trips, …
run = case.scenario("base").run("my-study", output_dir="runs/my-study")
print(run.completion, run.mean_travel_time_s / 60)
viz.summary(run) # one page: the headline numbers, the flows, the modes, the convergence
viz.map_interactive(run, "runs/my-study/map.html") # zoom, time, colour, routes
Then change one thing at a time — a parameter (06), the network (01), the demand (02), a scenario (09) — and compare with the base.
Next: 01 · Networks: networks from OpenStreetMap, what the reader assumed and how to change it, checks, GMNS and link tables. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.