openmobisim tutorials · 00 · overview · ← 01 · Networks · 03 · Car assignment: routes, choice and the iterations → · documentation

02 · Demand#

Demand is a trips table: one row per trip a traveller makes. This notebook writes one by hand, reads and writes it as a file, turns an origin–destination (OD) matrix into trips, gives travellers classes (what they own, which modes they may use, their own preferences), says what a traveller owns one by one with a persons table, and samples a large demand for quick runs. It ends with the synthetic morning commute that ships with the starter cases.

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 numpy as np
import openmobisim as ms
import pandas as pd

1 · Start small: Delft’s morning#

A city’s morning is one table, one row per trip. Delft’s, the smallest starter case, has some 114 000 rows over its morning (one per traveller) and runs in about twenty seconds; the sections below build such a table piece by piece, and the last one says how the starter cases’ mornings were made.

delft = ms.examples.case("delft")
pd.DataFrame(delft.demand(departures="all")[:5], columns=["traveller_id", "trip_seq", "origin_lon", "origin_lat", "destination_lon",
                                          "destination_lat", "departure_time_s", "user_class", "weight", "mode"])
traveller_id trip_seq origin_lon origin_lat destination_lon destination_lat departure_time_s user_class weight mode
0 od0000001 0 4.403118 51.972044 4.391040 51.967999 28015 car_and_bike None None
1 od0000002 0 4.402377 51.966274 4.406858 51.968952 26188 bike_only None None
2 od0000003 0 4.406858 51.968952 4.403942 51.968401 28646 no_vehicle None None
3 od0000004 0 4.406858 51.968952 4.386361 51.978421 29661 car_and_bike None None
4 od0000005 0 4.406858 51.968952 4.343050 51.987576 31298 car_and_bike None None

2 · The trips table#

Each row is (traveller_id, trip_seq, origin_lon, origin_lat, destination_lon, destination_lat, departure_time_s, user_class, weight, mode):

  • trip_seq orders a traveller’s trips through their day (0, 1, 2 …): a chain home → work → home is three rows, and a car or bike left at work is there for the next trip;

  • departure_time_s is in seconds after midnight;

  • user_class names the traveller’s class (below);

  • weight is how many people the row stands for (None: the scenario’s default_weight, 1 unless set);

  • mode is "car", "bike", "walk", "transit", "car_transit" (park and ride) or "bike_transit" (bike and ride), or None: the trip chooses its mode when the run offers several (modes=), and is a car trip otherwise.

Points are WGS84 longitude and latitude; a trip starts at the network node nearest its origin.

case = ms.examples.case("amsterdam")
net = case.network()
dam, zuid = (4.8926, 52.3731), (4.8722, 52.3389)  # the Dam square; Amsterdam Zuid station
trips = [
    ("ana", 0, *dam, *zuid, 8 * 3600, "commuter", None, "bike"),
    ("ana", 1, *zuid, *dam, 17 * 3600 + 1800, "commuter", None, "bike"),
    ("ben", 0, *zuid, *dam, 8 * 3600 + 600, "commuter", None, None),
    ("cas", 0, *dam, *zuid, 8 * 3600 + 900, "commuter", None, "car"),
]
pd.DataFrame(trips, columns=["traveller_id", "trip_seq", "origin_lon", "origin_lat", "destination_lon",
                             "destination_lat", "departure_time_s", "user_class", "weight", "mode"])  # fmt: skip
traveller_id trip_seq origin_lon origin_lat destination_lon destination_lat departure_time_s user_class weight mode
0 ana 0 4.8926 52.3731 4.8722 52.3389 28800 commuter None bike
1 ana 1 4.8722 52.3389 4.8926 52.3731 63000 commuter None bike
2 ben 0 4.8722 52.3389 4.8926 52.3731 29400 commuter None NaN
3 cas 0 4.8926 52.3731 4.8722 52.3389 29700 commuter None car

As a file, the table is trips.csv (or trips.parquet, the same columns): demand_write_trips and demand_read_trips write and read it, and Scenario.from_parts takes the rows or the path.

import tempfile
from pathlib import Path

work = Path(tempfile.mkdtemp())
ms.demand_write_trips(trips, work / "trips.csv")
print((work / "trips.csv").read_text())
assert ms.demand_read_trips(work / "trips.csv") == trips
traveller_id,trip_seq,origin_lon,origin_lat,destination_lon,destination_lat,departure_time_s,user_class,weight,mode
ana,0,4.8926,52.3731,4.8722,52.3389,28800,commuter,,bike
ana,1,4.8722,52.3389,4.8926,52.3731,63000,commuter,,bike
ben,0,4.8722,52.3389,4.8926,52.3731,29400,commuter,,
cas,0,4.8926,52.3731,4.8722,52.3389,29700,commuter,,car
run = ms.Scenario.from_parts(net, trips, modes=["car", "bike"]).run("demand-three", quiet=True)
pd.DataFrame(run.trip_modes())
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_84146/1109563442.py:1: WindowWarning: 1 of the demand's 4 trips (1 of 4 people, 25.0%) depart outside the simulation window 08:00–11:00 and are left out of run 'demand-three': 1 at or after its end (17:30–17:30). They are not simulated and not counted in any result (not as completed, unfinished or without an alternative). The window is a window set from the earliest departure (rounded down to the quarter hour), 3 hours long, as no window was given. To run them, widen it, for example Scenario(..., window=('08:00', '18:30')), leaving each trip time to finish before the end; or take them out of the demand.
  run = ms.Scenario.from_parts(net, trips, modes=["car", "bike"]).run("demand-three", quiet=True)
traveller_id trip_seq departure_s mode mode_choice weight
0 ana 0 28800 bike False 1
1 ben 0 29400 bike True 1
2 cas 0 29700 car False 1

Ben’s trip stated no mode and chose one, between the car and the bike; Ana’s and Cas’s kept theirs. A class that no table lists (here commuter) may use every mode the run offers, and owns a car, a bike and a transit pass.

3 · An OD matrix#

Most studies start from zones and a matrix rather than from individual trips. zones.csv gives each zone a point (zone_id, x_coord, y_coord, GMNS’s names, or lon, lat); od.csv gives the trips between zones (origin_zone, destination_zone, trips, and optionally a departure window start_s, end_s, a user_class and a mode). The starter cases carry both:

zones = case.zones()
od = ms.demand_read_od(case.path("demand/od.csv"))
print(len(zones), "zones;", len(od), "OD cells;", round(sum(r["trips"] for r in od)), "trips in all")
pd.DataFrame(od[:5])
354 zones; 154430 OD cells; 495658 trips in all
origin_zone destination_zone trips start_s end_s user_class mode
0 r02c02 r02c02 5.5380 None None None None
1 r02c02 r02c03 20.4652 None None None None
2 r02c02 r02c04 5.5700 None None None None
3 r02c02 r02c05 1.6541 None None None None
4 r02c02 r02c06 2.5105 None None None None

demand_from_od turns the matrix into trips, in a way that does not depend on the order of the rows:

  1. Whole trips. Each cell gets the whole part of its value; the cells with the largest remainders get one more each until the total, rounded, is reached (so 0.4 trips in many cells become trips in some of them, and the total is kept).

  2. One traveller per trip, departing within the window by the time profile: "uniform", or "am_peak", a bell over the window (more trips in its middle).

  3. Places: each trip starts and ends at a point drawn within spread_m of its zone’s point, so the trips of one zone do not all load the network at one node.

The same seed gives the same trips.

morning = ms.demand_from_od(od, zones, start_s=7 * 3600, end_s=9 * 3600, profile="am_peak", spread_m=500, seed=1)
print(len(morning), "trips; the first:", morning[0])
departures = pd.Series([t[6] for t in morning]) / 3600
departures.groupby((departures * 4).astype(int) / 4).size().rename("trips per quarter hour").to_frame().T
495658 trips; the first: ('od0000001', 0, 4.743039667409141, 52.28581496272476, 4.748984499464438, 52.28576583060157, 28815, 'default', None, None)
7.00 7.25 7.50 7.75 8.00 8.25 8.50 8.75
trips per quarter hour 7886 43466 85224 111489 111376 85243 43026 7948

How far the trips go, in a straight line between their ends:

def crow_km(t):
    lon1, lat1, lon2, lat2 = map(np.radians, (t[2], t[3], t[4], t[5]))
    a = np.sin((lat2 - lat1) / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2
    return 2 * 6371.0088 * np.arcsin(np.sqrt(a))


km = pd.Series([crow_km(t) for t in morning])
pd.DataFrame({"straight-line km": km.describe(percentiles=[0.1, 0.5, 0.9])}).T.round(2)
count mean std min 10% 50% 90% max
straight-line km 495658.0 5.35 4.3 0.0 1.26 4.28 10.48 25.29

A figure of the matrix: desire lines between 500-metre cells, the busiest pairs drawn, each bending to the right of its direction so a pair and its reverse are two curves.

from openmobisim import viz

viz.map_demand(morning, network=net, title="Amsterdam: the morning commute", top=400)
../_images/e8b429a2054a76c32d5911d9cafd580be314f6cb3bfa4f44ed81b7e047dbfe4d.png

4 · Traveller classes#

A class says, for its travellers, which modes they may use, what they own (a car, a bike, a transit pass), their own coefficients in the choice model and their own limits on how long a walk or a ride may be. A classes.csv has one row per class; demand_read_classes reads it, and each starter city ships four classes by what people own (car and bike, car only, bike only, no vehicle):

classes = case.classes()
pd.DataFrame({name: {"share": c["share"], "modes": ", ".join(c["modes"] or ["every mode"]),
                     "owns": ", ".join(k for k in ("owns_car", "owns_bike", "has_transit_pass") if c[k]),
                     "coefficients": c["betas"], "limits (s)": c["limits"]}
              for name, c in classes.items()}).T  # fmt: skip
share modes owns coefficients limits (s)
car_and_bike 0.4 car, bike, walk, transit, car_transit, bike_tr... owns_car, owns_bike {'beta_mode_bike': 1.23} {}
no_vehicle 0.3 walk, transit {} {}
bike_only 0.2 bike, walk, transit, bike_transit owns_bike {'beta_mode_bike': 1.23} {}
car_only 0.1 car, walk, transit, car_transit owns_car {} {}
from_outside_car 0.0 car owns_car {} {}
from_outside_transit 0.0 transit {} {}
goods 0.0 car owns_car {} {}

These four are examples, not a calibration: their shares follow what people own, and a bike constant (in Paris and Lyon also a car constant) was fitted so that the morning comes out near the city’s split of cycling, transit and driving, with every trip choosing its mode. A study brings its own classes, from a survey or a population synthesiser.

demand_assign_classes gives every traveller a class by the shares: exactly as many people per class as its share says (to within one traveller), who falls in which drawn at random with the seed.

morning = ms.demand_assign_classes(morning, classes, seed=1)
pd.Series([t[7] for t in morning]).value_counts(normalize=True).rename("share of travellers").round(3).to_frame().T
car_and_bike no_vehicle bike_only car_only
share of travellers 0.4 0.3 0.2 0.1

5 · What one traveller owns: the persons table#

A class says what its travellers own by default; a persons table says it for each traveller who differs: (traveller_id, owns_car, owns_bike, has_transit_pass, user_class), None keeping the class’s value. Here Cas has no car, so her car trip cannot be made (a trip that states its mode keeps it), and the run counts it:

persons = [("cas", False, None, None, None)]
run = ms.Scenario.from_parts(net, trips, persons=persons, modes=["car", "bike"]).run("demand-persons", quiet=True)
run.completion
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_84146/1341485078.py:2: WindowWarning: 1 of the demand's 4 trips (1 of 4 people, 25.0%) depart outside the simulation window 08:00–11:00 and are left out of run 'demand-persons': 1 at or after its end (17:30–17:30). They are not simulated and not counted in any result (not as completed, unfinished or without an alternative). The window is a window set from the earliest departure (rounded down to the quarter hour), 3 hours long, as no window was given. To run them, widen it, for example Scenario(..., window=('08:00', '18:30')), leaving each trip time to finish before the end; or take them out of the demand.
  run = ms.Scenario.from_parts(net, trips, persons=persons, modes=["car", "bike"]).run("demand-persons", quiet=True)
{'total_trips': 3,
 'completed': 2,
 'truncated': 0,
 'no_vehicle_available': 1,
 'no_feasible_path': 0,
 'mode_not_available': 0}

6 · Sampling for quick runs#

demand_sample keeps one traveller in weight, each standing for weight people, within each class and each stated mode so that every group keeps its share. A run on a quarter of the demand is about four times faster; its queues are lumpier (a traveller of weight 4 is one vehicle of 4 passenger-car units), so a sample is for screening scenarios and the full demand is for the numbers a study reports (notebook 06 measures the difference).

sample = ms.demand_sample(morning, 4, seed=1)
print(len(morning), "travellers ->", len(sample), "kept, each of weight", sample[0][8])
pd.DataFrame({
    "full": pd.Series([t[7] for t in morning]).value_counts(normalize=True),
    "sample": pd.Series([t[7] for t in sample]).value_counts(normalize=True),
}).round(4)  # fmt: skip
495658 travellers -> 123919 kept, each of weight 4
full sample
car_and_bike 0.4 0.4
no_vehicle 0.3 0.3
bike_only 0.2 0.2
car_only 0.1 0.1

7 · The starter cases’ morning#

case.demand() makes a starter case’s trips in one call, from its files: the OD matrix (times multiple), the trips drawn from it, and the classes assigned. Its morning is synthetic (06:30–09:30), made from open data and the city’s travel survey: zones on a 1-km grid, each with its residents and its non-residential building volume (the JRC’s Global Human Settlement Layer); as many trips inside the city as the survey counts in the morning, distributed by a gravity model fitted to the survey’s trip lengths; and what comes from outside — cars entering at the roads that cross the study area’s edge (gateways), through traffic between them (at motorway gateways sized from traffic counts where they are open, in the Dutch cities, and from an assumed share of the road’s capacity in the French ones; demand/gateway_counts.csv), transit riders arriving at its stations, goods vehicles — each with a fixed mode and a class of its own. Each simulated traveller stands for several people (the case’s weight: five in Amsterdam): the fast run, whose totals are the whole morning’s; case.demand(weight=1) gives one traveller per person, the complete and slowest run. Trips start and end at the zone’s own points, where its residents live and its workplaces are (demand/zone_points.csv), so travellers between the same points share their routes; a few start and end in the same zone. By default the case’s own departures run (case.info["departures"], 07:30–08:30 in the cities), and departures="all" gives the whole morning. demand/morning.json in the case’s folder says how it was made. The case’s base scenario (case.info["scenarios"], printed below) records per-link results in 15-minute bins, shares its route searches by origin and half hour (tree_step_s, reach_car_step_s: approximate, much faster) and stops once its gap is good (5 %).

A small aggregation, not a rescaled network. A weight of five groups five travellers between the same zones who travel together and choose together: on the roads they are one platoon of five cars. Every car is counted, at its full size, on every link it uses, and the network keeps its real capacities, storage and signal timings, so the traffic dynamics are those of the real flows. Agent-based tools such as MATSim often take another, well-established route: they simulate a sample of the travellers on a network whose capacities are scaled down to match. Here nothing about the network is scaled. What a group gives up is its members’ individuality — one choice, one platoon in the queues — which is why the complete run, one traveller per person, is there to compare (notebook 09). It puts a realistic amount of traffic in realistic places, so that the congestion, the figures and their cost are like a real morning’s; it is not a forecast, and a study replaces it with its own matrix or trips.

starter = case.demand()
people = sum(t[8] for t in starter)
first, last = case.info["departures"]
print(f"{len(starter)} travellers simulated, standing for {people:,} people; departing {first}-{last}")
print(pd.Series([t[7] for t in starter]).value_counts())  # the classes: drawn by share, and fixed for what enters
print(case.info["scenarios"])
57381 travellers simulated, standing for 286,905 people; departing 07:30-08:30
car_and_bike            17037
no_vehicle              12821
bike_only                8650
from_outside_car         8372
from_outside_transit     4291
car_only                 4255
goods                    1955
Name: count, dtype: int64
{'base': {'link_bin_s': 900, 'route_update_options': {'tree_step_s': 1800}, 'parking_options': {'reach_car_step_s': 1800}, 'equilibration_options': {'gap_tolerance': 0.05}}}

Next: 03 · Car assignment: routes, choice and the iterations: cars: route sets, route choice, the iterations towards an equilibrium and when they stop. The whole series: 00 · overview. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.