openmobisim tutorials · 00 · overview · ← 08 · Performance · documentation
09 · Five minimal studies#
What the simulator is for: studies. This notebook runs five of them, each small but honest, on one starter case — Delft’s morning — and says for each what it leaves out. They are starting points to copy and extend, not results about Delft.
Transit frequency: every bus, tram and metro line twice as often in the morning peak — the scenario sections 2 to 4 also compare with the base.
Your own utility: a choice model written in Python, with a term the built-in models cannot express.
Accessibility: the logsum (what the choice set is worth to each traveller) and travel-time matrices.
Emissions: CO₂ and NOₓ of the cars from their kilometres and speeds, with the European guidebook’s factors.
A road closed for an hour: a critical street closed in the peak, once unannounced and once announced.
Terms used here.
The base run is the case as it comes; a scenario changes one thing, and its effect is the difference from the base. Both use the same travellers and the same random draws (common random numbers), so a difference comes from the change, not from chance.
A starter case is a network with what runs on it — a timetable, parkings, a demand and its traveller classes — prepared, checked and versioned (
examples.case). Delft’s demand is a synthetic morning (06:30–09:30, about 66 000 people; the runs here take the departures from 07:30 to 08:30 and simulate them to 09:30), made from open data and travel surveys to look like a morning, not to forecast one (notebook 02). Every traveller is simulated on their own (the case’sweightis 1: the complete run).A traveller class groups travellers who may use the same modes, own the same vehicles and weigh alternatives the same way (notebook 04). Delft’s are the package’s example classes (
examples.traveller_classes()): four, by what people own — a car and a bike, a bike only, a car only, neither — each free to use every mode its vehicles allow, all weighing alike, with illustrative constants; and three for what enters from outside the city and does not choose here (cars, transit riders, goods vehicles: notebook 02).
Scale up: Amsterdam. Every study here also runs on the bigger starter cities: name "amsterdam" (or "paris",
"lyon") instead of "delft" in the next cell and run the notebook again. Their mornings simulate one traveller for
every five people (the case’s weight 5, the fast run: each simulated car a platoon of five, counted at full size
on the network’s real capacities), so a run takes minutes instead of seconds; weight=1 in case.demand() gives the
complete run (notebook 08 measures both).
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]"
import collections
import numpy as np
import pandas as pd
import openmobisim as ms
from openmobisim import choice, viz
case = ms.examples.case("delft") # found in the cache, or downloaded once and checked
net = case.network()
transit = case.transit(net)
parkings = case.parkings()
classes = case.classes() # the example classes, and those of what enters from outside (above)
trips = case.demand() # the complete run: one simulated traveller per person
print(case.info["title"], net, transit, parkings, f"{len(trips)} trips simulated", sep="\n")
Delft
Network(19947 nodes, 42699 links, with street geometry)
Transit(2026-10-09: 869 runs, 255 stops, 24 lines)
Parkings(2 car, 190 bike)
65956 trips simulated
Every run below goes through one function, so each scenario differs from the base only in what it is given. Each run
records link bins (link_bin_s=900): per road, bike and walk link and per 15 minutes, the traffic that left the
link and the time it took — what sections 4 and 5 read. The run’s convergence verdict says whether the iterations
settled (notebook 03), and reads “poor” whatever the gap when more than 5 % of the trips had not arrived by the end of
the window: a jammed run’s few finishers should not pass for a settled one.
MODES = {
"walk": "walk", "bike": "bike", "car": "car", "transit": "transit",
"car_transit": "park-and-ride", "bike_transit": "bike-and-ride", None: "no alternative",
} # fmt: skip
runs = {}
def simulate(name, network=net, timetable=transit, traveller_classes=classes, **options):
# The case's settings (link bins, shared searches, a good gap) and its window (07:30-09:30), then the options.
settings = case.info["scenarios"]["base"] | {"window": tuple(case.info["window"])} | options
run = ms.Scenario.from_parts(
network, trips, classes=traveller_classes, transit=timetable, parkings=parkings, **settings,
).run(name, output_dir=f"runs/{name}", quiet=True) # fmt: skip
runs[name] = run
return run
def row(run):
"""One scenario's line in the tables: mode shares by people, the mean trip and the run time."""
modes = run.trip_modes()
people = collections.Counter()
for mode, weight in zip(modes["mode"], modes["weight"]):
people[MODES[mode]] += weight
total = sum(people.values())
return {f"{label} (%)": 100 * people[label] / total for label in MODES.values()} | {
"mean trip (min)": run.mean_travel_time_s / 60,
"run time (s)": run.timings()["seconds"][-1],
}
def table(*names):
return pd.DataFrame([row(runs[n]) for n in names], index=pd.Index(names, name="run")).round(2)
base = simulate("base")
table("base")
| walk (%) | bike (%) | car (%) | transit (%) | park-and-ride (%) | bike-and-ride (%) | no alternative (%) | mean trip (min) | run time (s) | |
|---|---|---|---|---|---|---|---|---|---|
| run | |||||||||
| base | 3.16 | 18.85 | 53.66 | 24.32 | 0.0 | 0.01 | 0.0 | 22.94 | 10.15 |
1 · Transit frequency#
transit_edit returns a changed copy of the timetable: a line cancelled, or run at another headway (the time
between two departures) within a window. The study: every bus, tram and metro line twice as often from 07:00 to
09:00, its headway halved; the trains and ferries as they are. Each line’s headway in the base is counted from its
runs that start within the window (Run.transit_calls, every run’s calls at the stops).
calls = base.transit_calls()
first, line_of = {}, {}
for run, name, kind, departs in zip(calls["run"], calls["line"], calls["kind"], calls["scheduled_departure_s"]):
if run not in first or departs < first[run]:
first[run] = departs # the run's first call in the study area
line_of[run] = (name, kind)
in_peak = collections.Counter(line_of[r] for r, s in first.items() if 7 * 3600 <= s < 9 * 3600)
lines = transit.lines()
route_ids = collections.defaultdict(list)
for route_id, name, kind in zip(lines["route_id"], lines["name"], lines["kind"]):
route_ids[(name, kind)].append(route_id)
headways, rows = {}, []
for (name, kind), runs_in_peak in in_peak.items():
if kind in ("bus", "tram", "metro") and runs_in_peak >= 2 and len(route_ids[(name, kind)]) == 1:
now = 2 * 7200 / runs_in_peak # seconds between departures: two directions over two hours
headways[route_ids[(name, kind)][0]] = (max(60, round(now / 2)), 7 * 3600, 9 * 3600)
rows.append({"kind": kind, "headway, base (min)": now / 60, "twice as often (min)": now / 120})
double = ms.transit_edit(transit, headway=headways)
pd.DataFrame(rows).groupby("kind").agg(
lines=("kind", "size"), **{c: (c, "mean") for c in ("headway, base (min)", "twice as often (min)")}
).round(1)
| lines | headway, base (min) | twice as often (min) | |
|---|---|---|---|
| kind | |||
| bus | 19 | 28.7 | 14.3 |
| tram | 1 | 10.9 | 5.5 |
The table gives the lines changed and their mean headways. Then the run, and what it changes for the people who rode
transit in the base: every run has the same travellers, so each trip compares with itself (Run.trip_results, one row
per trip, in the same order in every run).
more = simulate("transit twice as often", timetable=double)
before, after = base.trip_results().to_pandas(), more.trip_results().to_pandas()
rode = (before["mode"] == "transit") & (before["outcome"] == "completed") & (after["outcome"] == "completed")
def mean_min(trips_table, rows):
"""The people-weighted mean trip, in minutes, of the given rows that completed."""
t = trips_table.loc[rows]
t = t[t["outcome"] == "completed"]
return (t["travel_time_s"] * t["weight"]).sum() / t["weight"].sum() / 60
def transit_row(run, trips_table):
m = run.completion_by_mode["transit"]
return {
"people taking transit": m["people"],
"boardings": run.transit_summary["boardings"],
"mean transit trip (min)": m["total_travel_time_s"] / m["completed_people"] / 60,
"the base's transit riders: mean trip (min)": mean_min(trips_table, rode),
}
saved = (before["travel_time_s"] - after["travel_time_s"])[rode] / 60
weight = before["weight"][rode]
print(f"the base's transit riders saving 5 minutes or more: {100 * weight[saved >= 5].sum() / weight.sum():.0f} %, "
f"10 minutes or more: {100 * weight[saved >= 10].sum() / weight.sum():.0f} %")
pd.DataFrame(
[transit_row(base, before), transit_row(more, after)], index=pd.Index(["base", "transit twice as often"], name="run")
).round(1)
the base's transit riders saving 5 minutes or more: 23 %, 10 minutes or more: 6 %
| people taking transit | boardings | mean transit trip (min) | the base's transit riders: mean trip (min) | |
|---|---|---|---|---|
| run | ||||
| base | 16042.0 | 18521.0 | 28.5 | 28.5 |
| transit twice as often | 16258.0 | 19594.0 | 26.3 | 26.3 |
Halving the headways of 88 bus, 15 tram and 4 metro lines (their mean headway from 23.6 to 11.8 minutes for buses, 10.1 to 5.0 for trams, 10.5 to 5.3 for metros) shortens the trips of the people who rode transit in the base from 39.8 to 37.3 minutes on average: a quarter of them save 5 minutes or more, 7 % save 10 or more, in waits and transfers. Transit carries 81 070 people instead of 79 800, and its boardings rise from 131 905 to 139 735 (6 %). Where the new riders came from, by the mode they took in the base (people):
label = lambda m: MODES.get(m if isinstance(m, str) else None) # noqa: E731
new = (after["mode"] == "transit") & (before["mode"] != "transit")
before[new].groupby(before["mode"][new].map(label))["weight"].sum().sort_values(ascending=False).rename("people")
mode
walk 341
car 22
bike 11
Name: people, dtype: uint32
Most new riders walked before (1 020 people); 235 drove, 185 cycled, and 180 had no alternative at all before (a transit journey now fits within its limits). The mode shares of everyone move little — transit from 27.8 % to 28.3 %, the mean trip from 25.4 to 24.8 minutes — because those who own a car or a bike seldom take transit in this morning, which is mostly slower for them door to door:
table("base", "transit twice as often")
| walk (%) | bike (%) | car (%) | transit (%) | park-and-ride (%) | bike-and-ride (%) | no alternative (%) | mean trip (min) | run time (s) | |
|---|---|---|---|---|---|---|---|---|---|
| run | |||||||||
| base | 3.16 | 18.85 | 53.66 | 24.32 | 0.0 | 0.01 | 0.0 | 22.94 | 10.15 |
| transit twice as often | 2.86 | 18.83 | 53.65 | 24.65 | 0.0 | 0.01 | 0.0 | 22.44 | 10.27 |
What this leaves out. No crowding and no vehicle capacity: a more frequent line shortens waits and transfers, and nothing else (no relief of crowded vehicles, no cost of the extra service). Trams and metros keep to the timetable; buses ride the roads among the cars, so twice as many buses also add to the road traffic they share.
2 · Your own utility#
In section 1 the built-in model weighs a walk to the stop by its minutes, each alike. Many people weigh a long walk more than its minutes — the tenth minute on foot is not the first.
A choice model is any Python object with a choose(batch) method: the batch holds every alternative’s attributes as
NumPy arrays (time_min, walk_min, wait_min, transfers, bike_mixed_km, the mode dummies mode_bike …), the
traveller’s class, and the random draws the built-in models use. The model below is the built-in logit rewritten in
Python — the same coefficients, each class’s own from the class table — plus one term the built-in linear models
cannot express: for the travellers who own no vehicle (who walk to every stop), every minute on foot beyond the
first ten costs twice its weight (a threshold, so not linear). A logsum method
(section 3) and the probabilities (for the convergence measure) come with it.
DEFAULTS = {"time_min": -0.2, "ln_path_size": 1.0, "transfers": -1.0, "wait_min": -0.09, "walk_min": -0.13}
class LongWalkAversion:
name = "long_walk_aversion"
def __init__(self, classes, free_min=10.0, factor=2.0, who="no_vehicle"):
self.betas = {
name: DEFAULTS | {k[len("beta_"):]: v for k, v in c.get("betas", {}).items()}
for name, c in classes.items()
}
self.free_min, self.factor, self.who = free_min, factor, who
# In the run's fingerprint: change it whenever the model's behaviour changes.
self.descriptor = f"long_walk_aversion;v1;x{factor} beyond {free_min} min;{who}"
def utility(self, batch):
cls = batch.user_class[batch.situation_of] # each alternative's traveller class
u = np.zeros(len(cls))
for k, name in enumerate(batch.class_names):
mine = cls == k
for attribute, beta in self.betas.get(name, DEFAULTS).items():
u[mine] += beta * batch.attributes[attribute][mine]
if self.who in batch.class_names:
walker = cls == batch.class_names.index(self.who)
beyond = np.maximum(batch.attributes["walk_min"] - self.free_min, 0.0)
u[walker] += (self.factor - 1.0) * self.betas[self.who]["walk_min"] * beyond[walker]
return u
def choose(self, batch):
return choice.sample_random_utility(batch, self.utility(batch))
def probabilities(self, batch):
return choice.segment_softmax(self.utility(batch), batch.offsets)
def logsum(self, batch):
u = self.utility(batch)
starts = np.asarray(batch.offsets[:-1], dtype=np.int64)
top = np.maximum.reduceat(u, starts)
return top + np.log(np.add.reduceat(np.exp(u - top[batch.situation_of]), starts))
# The model holds the classes' coefficients itself, so the runs get the classes without them.
modes_only = {name: {k: v for k, v in c.items() if k != "betas"} for name, c in classes.items()}
model = LongWalkAversion(classes)
averse = simulate("own model", choice_model=model, traveller_classes=modes_only)
averse_double = simulate(
"own model, transit twice as often", timetable=double, choice_model=model, traveller_classes=modes_only
)
table("base", "transit twice as often", "own model", "own model, transit twice as often")
| walk (%) | bike (%) | car (%) | transit (%) | park-and-ride (%) | bike-and-ride (%) | no alternative (%) | mean trip (min) | run time (s) | |
|---|---|---|---|---|---|---|---|---|---|
| run | |||||||||
| base | 3.16 | 18.85 | 53.66 | 24.32 | 0.0 | 0.01 | 0.0 | 22.94 | 10.15 |
| transit twice as often | 2.86 | 18.83 | 53.65 | 24.65 | 0.0 | 0.01 | 0.0 | 22.44 | 10.27 |
| own model | 2.92 | 18.89 | 53.66 | 24.50 | 0.0 | 0.02 | 0.0 | 23.10 | 9.91 |
| own model, transit twice as often | 2.53 | 18.90 | 53.62 | 24.93 | 0.0 | 0.01 | 0.0 | 22.64 | 10.20 |
The modes chosen by the travellers who own no vehicle, in the four runs (other classes face the same utilities as in the base run):
def shares_by_class(run):
ch = run.itinerary_choices()
counts = collections.defaultdict(collections.Counter)
for cls, mode, chose in zip(ch["user_class"], ch["mode"], ch["mode_choice"]):
if chose:
counts[cls][MODES[mode]] += 1
t = pd.DataFrame(counts).T.fillna(0)
return (100 * t.div(t.sum(axis=1), axis=0)).round(1)
four = ["base", "transit twice as often", "own model", "own model, transit twice as often"]
pd.DataFrame({n: shares_by_class(runs[n]).loc["no_vehicle"] for n in four}).T.rename_axis("run")
| bike | bike-and-ride | car | transit | walk | |
|---|---|---|---|---|---|
| run | |||||
| base | 0.0 | 0.0 | 0.0 | 71.0 | 29.0 |
| transit twice as often | 0.0 | 0.0 | 0.0 | 73.9 | 26.1 |
| own model | 0.0 | 0.0 | 0.0 | 72.9 | 27.1 |
| own model, transit twice as often | 0.0 | 0.0 | 0.0 | 76.8 | 23.2 |
With the built-in model this class’s transit share is 89.1 %, and 90.6 % with transit twice as often: travellers who own no vehicle already take transit for nearly every trip they do not walk (2.2 % have no alternative at all). With the aversion to long walks, walking falls from 8.8 % to 7.6 % and transit rises to 90.3 %, and to 91.5 % with transit twice as often: the aversion and the frequency add up. How much a change matters depends on the tastes the model carries — which is what data on route and mode choice is for.
What this leaves out. The coefficients are illustrative. A model in Python is called once per batch of up to
32 768 choices, so vectorised NumPy costs little; a loop over travellers would not. This model leaves money out: every
alternative carries what it costs (cost_eur and its parts: running costs, tolls, parking fees, fares, at the prices
of price_options, all 0 by default: having a car or a pass is what a class has), and a model weighs it like any
attribute.
3 · Accessibility#
Geurs and van Wee (2004) describe accessibility by four components: land use (where the opportunities are), transport (how long and how costly it is to reach them), time (when) and the individual (who travels, with which means). Two common measures, both available after a run:
The logsum: the expected utility of the best alternative in a traveller’s choice set,
ln Σ exp(utility). It grows when an alternative improves or is added, and divided by the time coefficient’s size (0.2 per minute here) it reads in minutes: how many minutes of travel time the change is worth. It is utility-based and individual: it reflects each class’s modes and tastes.Cumulative opportunities: how many opportunities are reached within a time limit, from a skim (a matrix of travel times between zones, by mode and departure time). It is location-based: one number per zone and mode.
def logsum_min(run):
ch = run.itinerary_choices()
t = pd.DataFrame({"class": ch["user_class"], "logsum": ch["logsum"], "chose": ch["mode_choice"]})
return t[t["chose"]].groupby("class")["logsum"].mean() / 0.2
access = pd.DataFrame({"base (min)": logsum_min(base), "transit twice as often (min)": logsum_min(more)})
access["change (min)"] = access["transit twice as often (min)"] - access["base (min)"]
access.round(3)
| base (min) | transit twice as often (min) | change (min) | |
|---|---|---|---|
| class | |||
| bike_only | -4.807 | -4.801 | 0.005 |
| car_and_bike | -3.787 | -3.780 | 0.007 |
| car_only | -13.989 | -13.920 | 0.070 |
| no_vehicle | -45.247 | -42.464 | 2.783 |
The levels are not meaningful on their own (a logsum is defined up to a constant); the change is. Transit twice as often is worth 4.15 minutes per trip to those who own no vehicle; to those who own one, a tenth of a minute or less (0.10 with a bike only, 0.09 with a car only, 0.02 with both): they seldom take transit, and what else moves their logsum is the traffic, which shifts a little from run to run.
The same by origin-destination pair, the zones of the demand: Run.logsum_od averages the trips’ logsums over each
pair (weighted by the people they stand for), so two designs compare pair by pair. The pairs that gain most:
pairs = [pd.DataFrame(r.logsum_od(trips, case.zones())).set_index(["origin", "destination"]) for r in (base, more)]
gain = pd.DataFrame({"trips": pairs[0]["trips"], "change (min)": (pairs[1]["logsum"] - pairs[0]["logsum"]) / 0.2})
gain[gain["trips"] >= 20].sort_values("change (min)", ascending=False).head(5).round(3)
| trips | change (min) | ||
|---|---|---|---|
| origin | destination | ||
| st002 | r07c01 | 132 | 13.503 |
| go001 | 24 | 10.622 | |
| go004 | 43 | 10.355 | |
| st000 | go004 | 53 | 10.110 |
| r04c06 | 25 | 9.621 |
Now the skims, from the base run, leaving at 08:00: car on the loaded link times (congestion included), bike and walk on their layers, transit on the timetable with its walks. As opportunities, the morning’s arrivals per zone stand in for jobs and schools (the demand is synthetic, so this is a placeholder for real land-use data).
zones = case.zones()
arrivals = collections.Counter()
for r in ms.demand_read_od(case.path(case.info["demand"]["od"])):
arrivals[r["destination_zone"]] += float(r["trips"])
opportunities = np.array([arrivals[z] for z in zones])
reach = {}
for mode in ("walk", "bike", "transit", "car"):
minutes = base.skim(mode, zones, departure_s=8 * 3600, max_s=2 * 3600) / 60
within = np.nan_to_num(minutes, nan=np.inf) <= 30
reach[mode] = 100 * (within * opportunities).sum(axis=1) / opportunities.sum()
pd.DataFrame(
{
"mean (%)": [reach[m].mean() for m in reach],
"lowest zone (%)": [reach[m].min() for m in reach],
"highest zone (%)": [reach[m].max() for m in reach],
},
index=pd.Index(list(reach), name="mode, leaving at 08:00"),
).round(1)
| mean (%) | lowest zone (%) | highest zone (%) | |
|---|---|---|---|
| mode, leaving at 08:00 | |||
| walk | 15.6 | 0.1 | 34.5 |
| bike | 92.0 | 60.4 | 100.0 |
| transit | 17.8 | 0.0 | 55.4 |
| car | 88.5 | 8.0 | 100.0 |
The table gives, over the case’s 354 zones (its 1-km grid, its stations and gateways), the share of all the morning’s destinations reachable within 30 minutes: from the average zone, 27.5 % by bike, 7.6 % by transit, 2.7 % on foot and 86.5 % by car (see below what the car skim leaves out). A skim runs one search per origin, so the four matrices take seconds; skims by time of day, or before and after a change, are as cheap.
What this leaves out. Opportunities here are a stand-in; the logsum covers the trips simulated, not every zone pair; skims ignore the classes’ own limits and car ownership (the individual component is in the logsum, not the skim); a car skim runs from the nearest drivable point to the nearest, with no walk to the car and no parking, so it flatters the car.
4 · Emissions#
Road traffic’s exhaust emissions are estimated by multiplying vehicle-kilometres (one vehicle driving one
kilometre) by an emission factor (grams per kilometre) that depends on the vehicle and on how it is driven.
The EMEP/EEA air pollutant emission inventory guidebook (2023, chapter 1.A.3.b.i-iv, its Appendix 4; the factors of
the COPERT model) gives the factors as functions of the average speed v in km/h:
EF(v) = (α v² + β v + γ + δ / v) / (ε v² + ζ v + η) · (1 − reduction)
for energy use (MJ/km, from which CO₂ follows by the fuel’s carbon) and for each pollutant. Two levels:
E0, distance only: every kilometre at one typical urban speed (30 km/h here);
E2, speed per link and time: each link’s mean speed in each 15 minutes (its length over its mean traversal time), so congestion raises the factor where traffic is slow.
The fleet: medium passenger cars of the newest standard (Euro 6 d/e), 60 % petrol, 25 % diesel and 15 % battery electric — illustrative shares: use the study area’s registrations. CO₂ is tank-to-wheel (69.3 g/MJ for petrol, 74.1 g/MJ for diesel, the IPCC 2006 defaults); an electric car emits none at the exhaust.
# Appendix 4, sheet HOT_EMISSIONS_PARAMETERS: Passenger Cars, Medium, Euro 6 d/e (petrol GDI+GPF, diesel DPF+SCR).
FACTORS = pd.DataFrame(
[
("petrol", "EC", 5, 130, 0.000131723006778538, 0.0054859592952839, 2.6191950512566,
1.72774612390592e-09, -8.50415012699799e-05, 0.023584384067406, 0.344297577833879, 0.23196729231897276),
("petrol", "NOx", 5, 130, -0.000314540672240406, 0.103056777252331, 0.239056575951972,
-0.3392791490405, 0.0345358283618128, 1.98601274556741, 1.26376326022528, 0.0),
("diesel", "EC", 10, 130, -0.00129911063069031, 0.221624989207713, 16.4359146120605,
5.66298857668099e-09, -0.00184467928314896, 0.292347275962134, 2.37716402519569, 0.08086995278390967),
("diesel", "NOx", 10, 130, 6.67136e-05, -0.011381467, 0.945951727, 1.923608149, -5.15046e-05, 0.004264272,
1.0, 0.92),
],
columns=["fuel", "quantity", "v_min", "v_max", "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta",
"reduction"],
) # fmt: skip
FLEET = {"petrol": 0.60, "diesel": 0.25, "electric": 0.15}
CO2_G_PER_MJ = {"petrol": 69.3, "diesel": 74.1}
def factor(fuel, quantity, v):
f = FACTORS[(FACTORS["fuel"] == fuel) & (FACTORS["quantity"] == quantity)].iloc[0]
v = np.clip(v, f["v_min"], f["v_max"])
top = f["alpha"] * v**2 + f["beta"] * v + f["gamma"] + f["delta"] / v
return top / (f["epsilon"] * v**2 + f["zeta"] * v + f["eta"]) * (1 - f["reduction"])
def per_km(v):
"""The fleet's mean CO₂ and NOₓ in g/km at speed v (km/h)."""
co2 = sum(FLEET[f] * factor(f, "EC", v) * CO2_G_PER_MJ[f] for f in ("petrol", "diesel"))
nox = sum(FLEET[f] * factor(f, "NOx", v) for f in ("petrol", "diesel"))
return co2, nox
speeds = np.array([10.0, 20.0, 30.0, 50.0, 80.0, 100.0])
co2, nox = per_km(speeds)
pd.DataFrame(
{"CO₂ (g/km)": co2, "NOₓ (g/km)": nox}, index=pd.Index(speeds, name="average speed (km/h)")
).round(3)
| CO₂ (g/km) | NOₓ (g/km) | |
|---|---|---|
| average speed (km/h) | ||
| 10.0 | 211.766 | 0.049 |
| 20.0 | 159.880 | 0.039 |
| 30.0 | 134.365 | 0.033 |
| 50.0 | 111.881 | 0.025 |
| 80.0 | 105.390 | 0.020 |
| 100.0 | 110.442 | 0.019 |
road_km = net.link_length_m() / 1000
def emissions(run):
bins = run.link_bins("road")
links, pcu, pcu_s = bins.links(), bins.pcu(), bins.pcu_seconds()
vkm = pcu * road_km[links]
speed = road_km[links] / (pcu_s / pcu / 3600)
co2_0, nox_0 = per_km(np.full(len(vkm), 30.0))
co2_2, nox_2 = per_km(speed)
return {
"vehicle-km": vkm.sum(),
"mean speed (km/h)": vkm.sum() / (pcu_s.sum() / 3600),
"CO₂, E0 (t)": (vkm * co2_0).sum() / 1e6,
"CO₂, E2 (t)": (vkm * co2_2).sum() / 1e6,
"NOₓ, E0 (kg)": (vkm * nox_0).sum() / 1e3,
"NOₓ, E2 (kg)": (vkm * nox_2).sum() / 1e3,
}
pd.DataFrame([emissions(runs[n]) for n in ("base", "transit twice as often")],
index=pd.Index(["base", "transit twice as often"], name="run")).round(1) # fmt: skip
| vehicle-km | mean speed (km/h) | CO₂, E0 (t) | CO₂, E2 (t) | NOₓ, E0 (kg) | NOₓ, E2 (kg) | |
|---|---|---|---|---|---|---|
| run | ||||||
| base | 319266.7 | 21.1 | 42.9 | 40.3 | 10.6 | 8.1 |
| transit twice as often | 321284.7 | 21.3 | 43.2 | 40.7 | 10.7 | 8.2 |
E2 gives less than E0 here (157.9 against 180.4 tonnes of CO₂ in the base) because the cars’ mean speed, 38.2 km/h,
is above the 30 km/h E0 assumes, and the factors fall with speed up to about 80 km/h (the table of factors above).
Transit twice as often adds road vehicle-kilometres, 1 364 530 against 1 342 575 (+1.6 %), and CO₂ with them
(E2: 160.7 against 157.9 tonnes): the buses ride the roads, and 3 233 bus runs take them instead of 2 184, each
counted here as two cars with a car’s factors, while only 460 fewer people drive (Run.transit_summary,
completion_by_mode). Whether a frequency increase lowers emissions depends on the buses’ own fleet and load, which
this minimal study leaves out.
What this leaves out. Hot exhaust only: no cold starts (the guidebook’s own correction for the first kilometres), no evaporation, tyre or brake wear. Buses on the roads are counted with the cars, in passenger-car units, not with their own factors. An average speed misses stop-and-go driving within a link (the guidebook’s higher tiers, and emission models fed with speed profiles, are later steps). The fleet shares are illustrative.
References.
European Environment Agency (2023). EMEP/EEA air pollutant emission inventory guidebook 2023, EEA Report 06/2023. Part B, chapter 1.A.3.b.i-iv Road transport, and its Appendix 4 (the emission factors: sheet
HOT_EMISSIONS_PARAMETERS, used above). https://www.eea.europa.eu/publications/emep-eea-guidebook-2023Ntziachristos, L., Gkatzoflias, D., Kouridis, C. and Samaras, Z. (2009). COPERT: a European road transport emission inventory model. In Information Technologies in Environmental Engineering, Springer, 491–504. https://doi.org/10.1007/978-3-540-88351-7_37
IPCC (2006). 2006 IPCC Guidelines for National Greenhouse Gas Inventories, Volume 2 Energy, chapter 3 Mobile combustion, Table 3.2.1 (road transport’s default CO₂ factors: 69 300 kg/TJ for motor gasoline, 74 100 kg/TJ for gas/diesel oil). Eggleston, H.S., Buendia, L., Miwa, K., Ngara, T. and Tanabe, K. (eds), IGES, Japan. https://www.ipcc-nggip.iges.or.jp/public/2006gl/
5 · A road closed for an hour#
A disruption is something that happens at a time of day: a road narrowed or closed for a while, a line’s runs late
or cancelled (disruptions=). Travellers either do not know of it in advance — an accident: the run reaches its
equilibrium without it, then loads the day once more with it, every choice kept, and only what happens within the
day reacts (a driver stuck behind the closure for five minutes is offered another route from where they are, a
passenger whose run never comes plans again at the stop) — or know (disruptions_known=True: works announced, a
strike): every loading has it, and routes, modes and departures adapt over the iterations as to anything that happens
every day. The study: a critical street closed from 07:30 to 08:30, once unannounced and once announced.
Which street. A link is critical when many travellers have no route around it in their choice set and would lose much time without it:
an origin-destination pair depends on a link when every route of its car choice set (
Run.route_sets, the routes its car travellers choose among) uses that link;the link’s importance is the people of the pairs that depend on it, times the time each would lose at free flow: the shortest route with the link closed (
network_edit) less the shortest with it (route_sets_build, the"shortest"method).
The residents’ trips are counted, not the trips entering from outside: both their ends are inside the study area, so their detours are inside the network too. Each trip’s pair is found from its ends, snapped to the nodes the run routes them from.
OUTSIDE = {"from_outside_car", "from_outside_transit", "goods"} # the classes entering from beyond the edge
before = base.trip_results().to_pandas()
sets = base.route_sets()
set_start, route_start = np.asarray(sets.set_offsets()), np.asarray(sets.route_offsets())
route_links = np.asarray(sets.links())
origin_nodes, destination_nodes = sets.keys()
nodes = {}
def node(lon, lat):
"""The node a trip end is routed from, as the run snaps it."""
if (lon, lat) not in nodes:
nodes[lon, lat] = net.node_nearest(lon, lat)
return nodes[lon, lat]
def with_pairs(table):
"""The trips with their pair's position in the route sets (a trip without a car route set is left out)."""
table = table.copy()
table["pair"] = [sets.find(node(a, b), node(c, d)) for a, b, c, d in
zip(table["origin_lon"], table["origin_lat"], table["destination_lon"], table["destination_lat"])] # fmt: skip
return table[table["pair"].notna()].astype({"pair": int})
car = with_pairs(before[before["mode"] == "car"])
every = {} # each pair: the links every one of its routes uses
for p in car["pair"].unique():
routes = [set(route_links[route_start[r]:route_start[r + 1]].tolist()) for r in range(set_start[p], set_start[p + 1])]
every[p] = set.intersection(*routes)
car["resident"] = ~car["user_class"].isin(OUTSIDE)
people = car[car["resident"]].groupby("pair")["weight"].sum().astype(float)
depend = collections.defaultdict(list)
for p in people.index:
for link in every[p]:
depend[link].append(p)
ends = car.groupby("pair")[["origin_lon", "origin_lat", "destination_lon", "destination_lat"]].first()
def shortest_s(network, pairs):
"""Each pair's shortest free-flow time on `network`, in seconds (inf: no route at all)."""
found = ms.route_sets_build(network, [tuple(ends.loc[p]) for p in pairs], method="shortest")
at = {(int(o), int(d)): k for k, (o, d) in enumerate(zip(*found.keys()))}
start, cost = np.asarray(found.set_offsets()), np.asarray(found.costs())
times = []
for p in pairs:
k = at.get((int(origin_nodes[p]), int(destination_nodes[p])))
times.append(cost[start[k]] if k is not None and start[k + 1] > start[k] else np.inf)
return np.array(times)
rows = []
for link in sorted(depend, key=lambda k: -people[depend[k]].sum())[:60]: # the 60 links with most dependants
pairs = depend[link]
lost = shortest_s(ms.network_edit(net, close=[link]), pairs) - shortest_s(net, pairs)
w = people[pairs].to_numpy()
ok = np.isfinite(lost) # a pair the closure cuts off has no detour to count
reached = w[ok].sum()
rows.append({
"link": net.link_ids()[link], "road": ms.LINK_CLASSES[net.link_class()[link]], "lanes": net.link_lanes()[link],
"people depending on it": w.sum(), "OD pairs": len(pairs),
"mean detour (min)": (lost[ok] * w[ok]).sum() / reached / 60 if reached else np.nan,
"importance (person-hours)": (lost[ok] * w[ok]).sum() / 3600, "index": link,
}) # fmt: skip
critical_links = pd.DataFrame(rows).sort_values("importance (person-hours)", ascending=False).set_index("link")
critical = int(critical_links["index"].iloc[0])
# Consecutive links of one road have the same dependants and detour: one row for each such stretch.
stretches = critical_links.drop_duplicates(["people depending on it", "OD pairs", "importance (person-hours)"])
stretches.drop(columns="index").head(5).round(2)
| road | lanes | people depending on it | OD pairs | mean detour (min) | importance (person-hours) | |
|---|---|---|---|---|---|---|
| link | ||||||
| 48204096:00004115 | tertiary | 1 | 217.0 | 149 | 6.47 | 23.39 |
| 738589112:00005418 | trunk | 2 | 304.0 | 211 | 3.89 | 19.70 |
| 116139713:00002238 | residential | 1 | 161.0 | 93 | 6.87 | 18.42 |
| 858881954:00008452 | trunk | 3 | 221.0 | 184 | 4.13 | 15.22 |
| 133905122:00005298 | trunk | 3 | 200.0 | 157 | 2.36 | 7.85 |
The first row is the one-way Delftsestraatweg north of the centre (one lane): about 220 residents, from some 60 origin-destination pairs, have no route in their choice set that avoids it and would lose six and a half minutes each at free flow without it. It closes from 07:30 to 08:30, once unannounced and once announced. Its users are the residents of the pairs that depend on it, whatever mode they take.
closure = [{"links": [critical], "capacity_factor": 0.0, "from_s": 7.5 * 3600, "to_s": 8.5 * 3600}]
unwarned = simulate("closed, unannounced", disruptions=closure)
warned = simulate("closed, announced", disruptions=closure, disruptions_known=True)
CLOSURE = ["base", "closed, unannounced", "closed, announced"]
trips_of = {n: with_pairs(runs[n].trip_results().to_pandas()) for n in CLOSURE}
users = {n: t[t["pair"].isin(depend[critical]) & ~t["user_class"].isin(OUTSIDE)] for n, t in trips_of.items()}
def mean_min(t):
"""The mean trip of the completed trips in `t`, in minutes, weighted by the people they stand for."""
done = t[t["outcome"] == "completed"]
return (done["travel_time_s"] * done["weight"]).sum() / done["weight"].sum() / 60
print(f"users: {users['base']['weight'].sum():.0f} people, {users['base']['pair'].nunique()} OD pairs; "
f"{(users['base']['mode'] == 'car').sum()} of them drove in the base")
pd.DataFrame({
n: {"users' mean trip (min)": round(mean_min(users[n]), 1),
"their car trips (min)": round(mean_min(users[n][users[n]["mode"] == "car"]), 1),
"every car trip in the city (min)": round(runs[n].completion_by_mode["car"]["total_travel_time_s"]
/ runs[n].completion_by_mode["car"]["completed_people"] / 60, 1),
"trips not arrived by 09:30": runs[n].completion["truncated"],
"re-routed on the way": len(runs[n].route_changes()["trip"]),
"verdict": runs[n].convergence_verdict}
for n in CLOSURE
}).T.rename_axis("run") # fmt: skip
users: 780 people, 149 OD pairs; 217 of them drove in the base
| users' mean trip (min) | their car trips (min) | every car trip in the city (min) | trips not arrived by 09:30 | re-routed on the way | verdict | |
|---|---|---|---|---|---|---|
| run | ||||||
| base | 20.6 | 11.8 | 25.3 | 231 | 0 | good |
| closed, unannounced | 29.8 | 34.3 | 26.0 | 443 | 385 | good |
| closed, announced | 23.4 | 19.5 | 25.8 | 108 | 413 | good |
Unannounced, the users keep their routes: those who drove reach the closed street, wait, and after five minutes
are offered another route from where they are (en-route re-routing, loading_options reroute, on in a loading with
road disruptions); their car trips go from 11.5 to about 34 minutes on average, while the mean of every car trip in
the city hardly moves — a city-wide average hides who bears a closure. Announced, they take other streets or
another mode and their car trips take about 20 minutes: the warning saves them most of the delay, and the closure
still costs them some. By when they left (the users’ car trips, minutes):
quarters = pd.DataFrame({
n: {f"{q // 3600:02d}:{q % 3600 // 60:02d}": mean_min(u[(u["mode"] == "car") & (u["departure_s"] >= q) & (u["departure_s"] < q + 900)])
for q in range(27000, 30600, 900)}
for n, u in users.items()
}).rename_axis("left at").round(1) # fmt: skip
quarters
| base | closed, unannounced | closed, announced | |
|---|---|---|---|
| left at | |||
| 07:30 | 10.7 | 35.9 | 19.2 |
| 07:45 | 12.5 | 34.5 | 20.8 |
| 08:00 | 12.3 | 32.4 | 20.2 |
| 08:15 | 12.0 | 32.9 | 16.4 |
Unannounced, the earliest to leave lose most: they are at the closure when it happens and drive the detour among those who re-route after them; by 08:15 the detour is known and the street reopens as they arrive. The modes the users took in the three runs (% of people): announced, some leave the car for the bike.
pd.DataFrame({n: 100 * u.groupby(u["mode"].map(MODES))["weight"].sum() / u["weight"].sum() for n, u in users.items()}).round(1)
| base | closed, unannounced | closed, announced | |
|---|---|---|---|
| mode | |||
| bike | 46.7 | 46.7 | 50.1 |
| car | 27.8 | 27.8 | 24.2 |
| transit | 19.2 | 19.2 | 18.7 |
| walk | 6.3 | 6.3 | 6.9 |
What this leaves out. A driver re-routes only once at the front of the queue behind the closure, from where
they are: at the default loading (a point queue, which takes no road space) a queue never backs up past the junction
behind it, so a driver whose only way on is the closed street waits for it to reopen, and nobody learns of the
closure before reaching it (a knowledge horizon, and drivers warned part-way through the morning, are later steps).
The importance uses free-flow detours; the runs then measure them with the congestion they cause. The choice set is
the base run’s: an announced closure adds routes to it over the iterations (Run.route_sets’s stamps say when).
6 · All scenarios#
The same columns for every run, the base first.
table(*runs)
| walk (%) | bike (%) | car (%) | transit (%) | park-and-ride (%) | bike-and-ride (%) | no alternative (%) | mean trip (min) | run time (s) | |
|---|---|---|---|---|---|---|---|---|---|
| run | |||||||||
| base | 3.16 | 18.85 | 53.66 | 24.32 | 0.0 | 0.01 | 0.0 | 22.94 | 10.15 |
| transit twice as often | 2.86 | 18.83 | 53.65 | 24.65 | 0.0 | 0.01 | 0.0 | 22.44 | 10.27 |
| own model | 2.92 | 18.89 | 53.66 | 24.50 | 0.0 | 0.02 | 0.0 | 23.10 | 9.91 |
| own model, transit twice as often | 2.53 | 18.90 | 53.62 | 24.93 | 0.0 | 0.01 | 0.0 | 22.64 | 10.20 |
| closed, unannounced | 3.16 | 18.85 | 53.66 | 24.32 | 0.0 | 0.01 | 0.0 | 23.61 | 11.05 |
| closed, announced | 3.19 | 18.94 | 53.56 | 24.30 | 0.0 | 0.01 | 0.0 | 23.27 | 14.16 |
viz.map_link(base, title="Delft's morning")
Every speed, coefficient, factor and share above is an uncalibrated default or an illustration; notebook 06 shows how to change them, and each study’s own data — counts, surveys, the fleet — is what turns a minimal study into a real one.
That was the last tutorial. Next: your own notebook, from the skeleton at the end of 00 · overview. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.