openmobisim tutorials · 00 · overview · ← 03 · Car assignment: routes, choice and the iterations · 05 · Results and figures → · documentation
04 · Bikes, walking, transit and the choice of mode#
The same toy network as notebook 00, now with everything else that moves: cyclists and pedestrians on their own layers, a tram and a bus on a timetable, two parkings for park-and-ride and bike-and-ride, and travellers who choose their mode.
Terms used here.
A layer is the network one mode travels on. The road network is the cars’ (and the buses’); the bike layer has every street in its legal direction plus what only cyclists may use (a contraflow street, a cycle track), and the walk layer every street both ways plus footpaths. Cyclists and pedestrians do not queue: each takes the best route of its layer at its own speed.
An itinerary is a trip made of legs: walk to a stop, ride, maybe change, walk on. Park-and-ride drives to a parking and continues by transit; bike-and-ride cycles to one. Which parking, which stop and which run are chosen by the choice model among the alternatives found, not fixed in advance.
A mode constant is a number added to the utility of every alternative of one mode: positive makes the mode more attractive. A traveller class groups travellers who may use the same modes, own the same vehicles and weigh alternatives the same way.
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 viz
net = ms.examples.toy_network()
transit = ms.examples.toy_network_transit()
parkings = ms.examples.toy_network_parkings()
bike, walk = net.layer("bike"), net.layer("walk")
print(net, bike, walk, transit, parkings, sep="\n")
Network(16 nodes, 16 links)
Network(bike layer: 17 nodes, 21 links)
Network(walk layer: 16 nodes, 36 links)
Transit(2026-10-09: 54 runs, 5 stops, 2 lines)
Parkings(2 car, 1 bike)
The toy’s multimodal parts. On the bike layer, s1 can be cycled the wrong way (S → N1, which no car may do),
and a two-way cycle track runs beside a3 from M to X0 (520 m against the street’s 400 m). The walk layer adds two
footpaths: W ↔ N1 (424 m on the diagonal, against 600 m by the streets) and N1 ↔ N2. The tram T1 runs from stop
N1 to stop H at D2 and back, and the bus B1 along the arterial (W, M, D1), both every 10 minutes for three
hours from midnight: the trips below use the toy’s clock and leave in its first hour. Hub H at D2 has 6 car and
3 bike spaces next to the tram stop; car park P2 (20 spaces) is a 300 m walk away.
def trip(who, origin, destination, depart_s, mode=None, user_class="everyone"):
o, d = net.node_lonlat(origin), net.node_lonlat(destination)
return (who, 0, o[0], o[1], d[0], d[1], depart_s, user_class, None, mode)
owns_all = {"everyone": (True, True, True)} # a car, a bike and a transit pass
def mean_min(by_mode, mode):
m = by_mode[mode]
return m["total_travel_time_s"] / m["completed_people"] / 60
1 · Bike assignment#
Cyclists ride at 15 km/h in mixed traffic and 18 km/h on infrastructure of their own. By default they choose their
route with every minute in mixed traffic counting 1.2 times (bike_cost="dedicated"), so they go a little out of their
way for a cycle track; bike_cost="time" takes the fastest route. Here 40 cyclists ride from M to X0 and 20 from
W to N1 (through the contraflow on s1); 5 drivers try W → N1 too.
rows = [trip(f"track{i}", "M", "X0", 30 * i, "bike") for i in range(40)]
rows += [trip(f"contra{i}", "W", "N1", 30 * i, "bike") for i in range(20)]
rows += [trip(f"drive{i}", "W", "N1", 30 * i, "car") for i in range(5)]
infrastructure = {0: "mixed traffic", 1: "lane", 2: "track"}
uses, bike_runs = {}, {}
for cost in ("dedicated", "time"):
r = ms.Scenario.from_parts(
net, rows, classes=owns_all, bike_cost=cost, link_bin_s=3600
).run(f"bikes-{cost}", output_dir=f"runs/bikes-{cost}", quiet=True)
bins = r.link_bins("bike")
riders = np.zeros(bike.link_count)
np.add.at(riders, bins.links(), bins.pcu())
uses[cost] = riders
bike_runs[cost] = r
print({mode: (v["completed"], v["no_feasible_path"]) for mode, v in r.completion_by_mode.items()})
pd.DataFrame(
{
"length (m)": bike.link_length_m(),
"infrastructure": [infrastructure[int(x)] for x in bike.link_infrastructure()],
"cyclists, bike_cost='dedicated'": uses["dedicated"].astype(int),
"cyclists, bike_cost='time'": uses["time"].astype(int),
},
index=pd.Index(range(bike.link_count), name="bike link"),
).loc[lambda t: (t.iloc[:, 2] > 0) | (t.iloc[:, 3] > 0)]
{'car': (0, 5), 'bike': (60, 0)}
| length (m) | infrastructure | cyclists, bike_cost='dedicated' | cyclists, bike_cost='time' | |
|---|---|---|---|---|
| bike link | ||||
| 0 | 300.0 | mixed traffic | 20 | 20 |
| 2 | 400.0 | mixed traffic | 0 | 40 |
| 16 | 300.0 | mixed traffic | 20 | 20 |
| 17 | 260.0 | track | 40 | 0 |
| 19 | 260.0 | track | 40 | 0 |
Under the default cost the 40 cyclists take the cycle track (two 260 m links); by time alone they take the street
(400 m). The 20 cyclists to N1 ride W → S and then the contraflow; the 5 drivers have no route at all (cars may not
use s1 that way) and are reported as such, not dropped.
viz.map_link(bike_runs["dedicated"], layer="bike", title="Cyclists on the toy network's bike layer",
note="bike_cost='dedicated': the cycle track rather than the street") # fmt: skip
2 · Walking, transit, park-and-ride and bike-and-ride#
Trips with a stated mode: 20 walkers W → N1; 10 transit riders N1 → D2 (the tram); 8 drivers W → N1 by
park-and-ride (drive to D2, tram to N1); 4 cyclists S → N1 by bike-and-ride. The toy is built to check the
mechanics, so these are not sensible journeys (by bike, W → N1 takes 2.4 minutes).
rows = [trip(f"walk{i}", "W", "N1", 60 * i, "walk") for i in range(20)]
rows += [trip(f"tram{i}", "N1", "D2", 60 * i, "transit") for i in range(10)]
rows += [trip(f"pr{i}", "W", "N1", 60 * i, "car_transit") for i in range(8)]
rows += [trip(f"br{i}", "S", "N1", 60 * i, "bike_transit") for i in range(4)]
run = ms.Scenario.from_parts(
net, rows, classes=owns_all, transit=transit, parkings=parkings, link_bin_s=900
).run("modes", output_dir="runs/modes", quiet=True)
by_mode = run.completion_by_mode
pd.DataFrame(
{
"trips": [by_mode[m]["total_trips"] for m in by_mode],
"completed": [by_mode[m]["completed"] for m in by_mode],
"mean trip (min)": [mean_min(by_mode, m) for m in by_mode],
},
index=pd.Index(list(by_mode), name="mode"),
).round(1)
| trips | completed | mean trip (min) | |
|---|---|---|---|
| mode | |||
| walk | 20 | 20 | 5.3 |
| transit | 10 | 10 | 10.5 |
| car_transit | 8 | 8 | 20.2 |
| bike_transit | 4 | 4 | 18.5 |
walkers = run.link_bins("walk")
on_link = np.zeros(walk.link_count)
np.add.at(on_link, walkers.links(), walkers.pcu())
print("walk links used (length in m: walkers):",
{round(float(walk.link_length_m()[i])): int(n) for i, n in enumerate(on_link) if n})
print("transit:", {k: run.transit_summary[k] for k in ("boardings", "bus_runs_on_roads")})
p = run.parking_summary
print("parkings: cars arrived", p["car_arrivals"], "of which over capacity", p["car_overflow_arrivals"],
"| bikes arrived", p["bike_arrivals"], "of which over capacity", p["bike_overflow_arrivals"])
ch = run.itinerary_choices()
collections.Counter(zip(ch["mode"], ch["parking_id"]))
walk links used (length in m: walkers): {424: 20}
transit: {'boardings': 22.0, 'bus_runs_on_roads': 18}
parkings: cars arrived 8.0 of which over capacity 2.0 | bikes arrived 4.0 of which over capacity 1.0
Counter({('transit', None): 10,
('car_transit', 'H-car'): 8,
('bike_transit', 'H-bike'): 4})
The walkers take the 424 m footpath (the one traveller on a 300 m walk link is the driver who parked at P2, walking
to the tram stop). The buses ride the roads among the cars (their times come from the loading, not
only the timetable). Of the 8 park-and-ride drivers, 7 chose hub H and one car park P2 — chosen by the model,
among the parkings it found — and the hub’s 6 spaces were one short, which the run counts rather than hides; likewise
the fourth bike at a 3-space bike parking.
viz.map_transit(run, colour="line", title="The toy network's transit, by line")
viz.map_parking(run, title="The toy network's parkings")
3 · Choosing the mode, by class#
A trip without a stated mode chooses one, with its route or itinerary, among the modes its class may use.
examples.traveller_classes() is an example table of four classes by what people own (car and bike, car only, bike
only, no vehicle; illustrative constants, not calibrated);
demand_assign_classes draws a class for each traveller by the classes’ shares. The model is the nested logit:
each mode’s alternatives in a nest of their own, so a mode with many routes does not outweigh a mode with one.
classes = ms.examples.traveller_classes()
pd.DataFrame(
{
"share": [c["share"] for c in classes.values()],
"modes": [", ".join(c["modes"]) for c in classes.values()],
"constants": [
", ".join(f"{k[len('beta_mode_'):]} {v:g}" for k, v in c["betas"].items()) for c in classes.values()
],
},
index=pd.Index(list(classes), name="class"),
)
| share | modes | constants | |
|---|---|---|---|
| class | |||
| car_and_bike | 0.4 | car, bike, walk, transit, car_transit, bike_tr... | bike 1.23 |
| no_vehicle | 0.3 | walk, transit | |
| bike_only | 0.2 | bike, walk, transit, bike_transit | bike 1.23 |
| car_only | 0.1 | car, walk, transit, car_transit |
pairs = [("W", "D2"), ("N1", "D2"), ("W", "D1"), ("N2", "D2")]
base = [trip(f"t{i}", *pairs[i % 4], 9 * i) for i in range(400)]
demand = ms.demand_assign_classes(base, classes, seed=0)
choice = ms.Scenario.from_parts(
net, demand, classes=classes, transit=transit, parkings=parkings,
choice_model="nested_logit", link_bin_s=900,
).run("mode-choice", output_dir="runs/mode-choice", quiet=True)
ch = choice.itinerary_choices()
shares = collections.defaultdict(collections.Counter)
for cls, mode in zip(ch["user_class"], ch["mode"]):
shares[cls][mode or "no alternative"] += 1
table = pd.DataFrame(shares).T.fillna(0).astype(int)
table.loc["all classes"] = table.sum()
table
| transit | walk | bike | car | |
|---|---|---|---|---|
| no_vehicle | 97 | 23 | 0 | 0 |
| car_and_bike | 10 | 1 | 127 | 22 |
| bike_only | 3 | 0 | 77 | 0 |
| car_only | 14 | 0 | 0 | 26 |
| all classes | 124 | 24 | 204 | 48 |
Car captives drive, bike enthusiasts cycle, the classes without a car take transit or walk, and the class open to every mode splits between car and bike on these short trips. The figure shows the shares by departure time.
viz.chart_mode_share(choice, bin_s=600, title="Mode shares on the toy network")
4 · When a trip has no alternative#
To keep choice sets small and runs fast, mode choice offers a walk only up to walk_max_s (30 minutes by default),
a bike ride only up to bike_max_s (60 minutes), and transit only within its access walk to and from the stops
(transit_options={"access_walk_max_s": ...}, 30 minutes). These choice-set limits bound what is offered; the
minutes within them are weighed by the model. A class may give its own, in its row of the class table (the same
names): the example classes let bike enthusiasts ride up to 90 minutes and walkers walk up to 45. A trip whose class
may use none of the modes within its limits has no alternative: it is counted as no_feasible_path, not
simulated, and the summary page (viz.summary) shows how many, by class, with the limits used. The limits are
parameters like any other.
Here: 3 000 trips of 1–6 km on a 12 × 12 grid of 300 m blocks, a third each walkers (walk only), cyclists (bike or walk) and drivers; the walk limit at 30, 60 and 90 minutes.
grid = ms.examples.manhattan_grid(n=12, block_metres=300.0, signals=True)
kinds = {
"walker": {"modes": ["walk"], "share": 1},
"cyclist": {"modes": ["bike", "walk"], "share": 1},
"driver": {"modes": ["car"], "share": 1},
}
far = ms.examples.trips_random(grid, 3000, seed=4, spread_s=3600, min_m=1000, max_m=6000)
far = ms.demand_assign_classes(far, kinds, seed=0)
rows = []
for minutes in (30, 60, 90):
r = ms.Scenario.from_parts(
grid, far, classes=kinds, mode_options={"walk_max_s": 60.0 * minutes}
).run(f"limit-{minutes}", output_dir=f"runs/limit-{minutes}", quiet=True)
ch = r.itinerary_choices()
stuck = collections.Counter(c for c, m in zip(ch["user_class"], ch["mode"]) if m is None)
size = collections.Counter(ch["user_class"])
rows.append({"walk limit (min)": minutes} | {
f"{c}s with no alternative (%)": 100 * stuck[c] / size[c] for c in ("walker", "cyclist", "driver")
} | {"run time (s)": r.timings()["seconds"][-1]})
pd.DataFrame(rows).set_index("walk limit (min)").round(2)
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_84565/684342451.py:13: NoAlternativeWarning: 642 trips (642 people, 21.4% of run 'limit-30') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 642 'walker' (choosing). Why, by mode offered (trips): walk: walk_too_long 642. Most between (latitude, longitude, about 1 km): 10 people from (45.71, 4.82) to (45.72, 4.83); 9 people from (45.72, 4.81) to (45.71, 4.83); 8 people from (45.70, 4.83) to (45.71, 4.80); 8 people from (45.73, 4.82) to (45.71, 4.81); 7 people from (45.71, 4.80) to (45.72, 4.82). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s. Run.report_no_alternative() lists every trip with its reasons.
).run(f"limit-{minutes}", output_dir=f"runs/limit-{minutes}", quiet=True)
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_84565/684342451.py:13: NoAlternativeWarning: 32 trips (32 people, 1.1% of run 'limit-60') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 32 'walker' (choosing). Why, by mode offered (trips): walk: walk_too_long 32. Most between (latitude, longitude, about 1 km): 4 people from (45.73, 4.84) to (45.71, 4.80); 3 people from (45.73, 4.83) to (45.70, 4.80); 2 people from (45.70, 4.80) to (45.72, 4.83); 2 people from (45.73, 4.81) to (45.70, 4.84); 1 people from (45.70, 4.81) to (45.72, 4.84). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s. Run.report_no_alternative() lists every trip with its reasons.
).run(f"limit-{minutes}", output_dir=f"runs/limit-{minutes}", quiet=True)
| walkers with no alternative (%) | cyclists with no alternative (%) | drivers with no alternative (%) | run time (s) | |
|---|---|---|---|---|
| walk limit (min) | ||||
| 30 | 64.2 | 0.0 | 0.0 | 0.07 |
| 60 | 3.2 | 0.0 | 0.0 | 0.09 |
| 90 | 0.0 | 0.0 | 0.0 | 0.07 |
At 30 minutes most walkers’ trips are too long to walk (at the default 4.8 km/h, 30 minutes is 2.4 km); at 90 minutes all have their walk. Cyclists ride up to 15 km within their hour, so none is stuck here. Raising a limit costs longer searches; on this grid nothing noticeable. On a city’s network, the access walk to transit is often the limit that leaves travellers without a car or a bike with no alternative.
The same 90 minutes for the walkers alone, as their class’s own limit, with the run’s 30 minutes for everyone else:
own = {**kinds, "walker": {**kinds["walker"], "walk_max_s": 90 * 60}}
r = ms.Scenario.from_parts(grid, far, classes=own).run(
"limit-own", output_dir="runs/limit-own", quiet=True
)
ch = r.itinerary_choices()
stuck = collections.Counter(c for c, m in zip(ch["user_class"], ch["mode"]) if m is None)
print("walkers with no alternative:", stuck["walker"], "| classes' own limits:", r.manifest()["class_limits"])
walkers with no alternative: 0 | classes' own limits: {'walker': {'walk_max_s': 5400}}
viz.map_link(run, layer="walk", title="Walkers on the toy network's walk layer")
Every speed, constant and capacity above is a named, uncalibrated default; notebook 06 shows how to change them.
Next: 05 · Results and figures: everything a run leaves: its files, the indicators, the figures and the interactive map. The whole series: 00 · overview. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.