Amsterdam: a case built in Python#

run_file (the first tutorial) does three things before it runs: it builds a network, a timetable and the demand from the case’s files. This tutorial does the same steps one by one in Python on a larger case, Amsterdam’s morning (198 252 travellers), the way you would with tables of your own.

pip install openmobisim pandas pyarrow

The travellers are synthetic and the choice coefficients are the defaults, not fitted to Amsterdam: the results show the tool at work and are not a description of the city.

import urllib.request, zipfile

urllib.request.urlretrieve("https://zenodo.org/records/24585967/files/amsterdam.zip", "amsterdam.zip")
zipfile.ZipFile("amsterdam.zip").extractall()

The settings#

The case’s run.toml holds the window, the traveller classes and every parameter. It is plain TOML.

import tomllib

with open("amsterdam/run.toml", "rb") as f:
    settings = tomllib.load(f)
window = (settings["window_start_s"], settings["window_end_s"])   # seconds after midnight: 07:30 to 09:30
classes = settings["demand"]["classes"]
print(window, classes)
print({name: value for name, value in settings["parameters"].items() if name != "coefficients"})
(27000, 34200) ['bike_only', 'car_and_bike', 'car_only', 'from_outside_car', 'from_outside_transit', 'goods', 'no_vehicle']
{'capacity_per_lane': 1800.0, 'bike_speed': 15.0, 'walk_speed': 4.8, 'stop_walk_max': 1500.0, 'transfer_walk_max': 400.0, 'boarding_slack': 60, 'max_rides': 4, 'nearby_stops': 3, 'max_car_routes': 6, 'max_transit_journeys': 10, 'choice': 'logit', 'nest_scale': 0.5, 'step_exponent': 0.75, 'iteration_cap': 50, 'iteration_floor': 0, 'link_bin': 300, 'seed': 0}

Every parameter in the file is at its default (Parameters), and so are the choice coefficients of every class, so the calls below give none of them: a keyword left out takes its default.

The network, the timetable, the demand#

A table is given in memory (a dict of lists, a pandas or polars frame, a pyarrow table) or, as here, as the path of a Parquet file. The timetable is read on the network, and the demand on both: each trip end is linked to the network per mode and to the stops within walking distance.

import time
import openmobisim as oms

start = time.perf_counter()
network = oms.Network.from_tables("amsterdam/nodes.parquet", "amsterdam/links.parquet")
transit = oms.Transit.from_gtfs("amsterdam/gtfs.zip", network)
demand = oms.Demand.from_table("amsterdam/trips.parquet", classes, network, transit=transit)
print(f"built in {time.perf_counter() - start:.1f} s")
print("repairs:", network.repairs, transit.repairs, demand.repairs)
built in 3.2 s
repairs: {} {} {}

A reader sets right or leaves out what it cannot read instead of refusing the whole table (a link naming a node the nodes table does not hold is left out, a trip of a class not given is dropped), says so in a warning and counts it in repairs; these files need none (Troubleshooting).

The run#

start = time.perf_counter()
run = oms.run(network, demand, transit, window=window, out="amsterdam-run")
print(f"run time {time.perf_counter() - start:.1f} s; ended by the stopping rule: {run.stopped_by_rule}")
run time 57.1 s; ended by the stopping rule: True
import pandas as pd

trips = pd.read_parquet(run.trips)

def by_mode(trips):
    """Per mode: the travellers who took it, their share and their mean door-to-door time."""
    table = trips.groupby("mode").agg(travellers=("trip_id", "count"), mean_time_min=("travel_time_s", "mean"))
    table["mean_time_min"] /= 60
    table.insert(1, "share_pct", 100 * table["travellers"] / len(trips))
    return table.loc[["car", "bike", "walk", "transit"]].round(1)

by_mode(trips)
travellers share_pct mean_time_min
mode
car 93729 47.3 11.7
bike 41725 21.0 22.7
walk 6254 3.2 26.7
transit 56544 28.5 36.1
print("unfinished at 09:30:", (~trips["finished"]).sum())
unfinished at 09:30: 0

These are the results oms.run_file("amsterdam", out=...) gives: the same inputs and settings give the same trips, links and routes tables.

Who takes what, by class#

A traveller class has its own choice coefficients (here all classes have the default ones), and each traveller has the modes open to it (the column modes of the trips table); in these cases the modes follow the class. The shares by class show what the modes open to a traveller do to the choice.

shares = pd.crosstab(trips["class_id"], trips["mode"], normalize="index").mul(100)[["car", "bike", "walk", "transit"]]
shares.insert(0, "travellers", trips.groupby("class_id").size())
shares.round(1)
mode travellers car bike walk transit
class_id
bike_only 30926 0.0 90.9 1.3 7.7
car_and_bike 59002 74.6 22.6 0.7 2.1
car_only 14721 95.9 0.0 1.1 3.0
from_outside_car 28856 100.0 0.0 0.0 0.0
from_outside_transit 14988 0.0 1.8 0.0 98.2
goods 6750 100.0 0.0 0.0 0.0
no_vehicle 43009 0.0 0.0 12.3 87.7

The shares are percentages of the class’s travellers. The classes from_outside_car and goods have the car alone; from_outside_transit has transit, and a few of its travellers also a bike. Among the others, a traveller with a car and a bike drives three times in four, one with a bike and no car cycles nine times in ten, and one with neither takes transit seven times in eight.

Distance travelled on the network#

links.parquet counts the cars, bikes and walkers that entered each link in each time bin. With the links’ lengths it gives the distance travelled on the network per mode. The walkers counted on links are those of walk trips; the walks to a stop or between a door and the network are not on links.

lengths = pd.read_parquet("amsterdam/links.parquet", columns=["link_id", "length_m"])
bins = pd.read_parquet(run.links, columns=["link_id", "cars", "bikes", "walkers"]).merge(lengths, on="link_id")
km = pd.Series({mode: (bins[column] * bins["length_m"]).sum() / 1000
                for mode, column in (("car", "cars"), ("bike", "bikes"), ("walk", "walkers"))})
pd.DataFrame({"km on the network": km.round(0), "km per traveller of the mode": (km / by_mode(trips)["travellers"]).round(2)}).loc[["car", "bike", "walk"]]
km on the network km per traveller of the mode
car 991629.0 10.58
bike 222087.0 5.32
walk 12822.0 2.05

The pages#

The map and the summary are written from the finished run. A title replaces the file’s name at the top of the page.

import os

run.map("amsterdam-map.html", title="Amsterdam, 07:30 to 09:30")
run.summary("amsterdam-summary.html", title="Amsterdam, 07:30 to 09:30")
for page in ("amsterdam-map.html", "amsterdam-summary.html"):
    print(f"{page}: {os.path.getsize(page) / 1e6:.1f} MB")
amsterdam-map.html: 16.8 MB
amsterdam-summary.html: 12.4 MB

The map page of the run, zoomed in on the centre of Amsterdam: one ribbon per direction of a road, coloured by volume over capacity

The map page, one zoom level in on the centre of the city (the network is from OpenStreetMap, © OpenStreetMap contributors).

The record#

run_record.toml holds the settings the run ran with, the defaults included, and what the run found. Its first part, copied into a run.toml, runs the same run again; the fingerprints of the inputs in its second part tell whether an input file has changed since.

record = open(run.record).read()
print(record[record.index("window_end_used_s"):record.index("[result.transit.gtfs_report]")].strip())
window_end_used_s = 34200  # s: window_end_s, moved up to a whole link_bin when it was not one
iterations = 9
stopped_by_rule = true

[result.network]
source = "tables"
nodes = 121502
links = 489167
fingerprint = "7d1318422a05ef4c"

[result.demand]
trips = 198252
fingerprint = "c25b5ba10e7574ad"

[result.transit]
stops = 4003
runs = 7703
fingerprint = "f6f58a602c2f86ee"

Where to go from here#

  • Guides: one task per page, such as a case from your own data, the settings file, reading the results, or the window.

  • Concepts and methods: how the model works, starting with How a run works.

  • Reference: every function, parameter, input column and output column.