openmobisim tutorials · 00 · overview · ← 05 · Results and figures · 07 · Validation → · documentation

06 · Parameters and experiments#

Every number openmobisim assumes has a name, a default and a way to change it. None is calibrated: the defaults are reasonable starting values from the literature or plain assumptions, to be replaced by a study’s own. This notebook lists them, changes some, and runs small experiments: seeds and replications, sampled demand, a sweep, and a city’s mode shares moved by one constant.

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 matplotlib.pyplot as plt
import pandas as pd

import openmobisim as ms

net = ms.examples.manhattan_grid(n=6, block_metres=250.0, signals=True)
cars = {"commuter": (True, False, False)}


def demand(count, seed=2):
    return ms.examples.trips_random(net, count, seed=seed, spread_s=3600, min_m=500, max_m=2000)


def mean_trip_min(run):
    return run.mean_travel_time_s / 60  # per person: a traveller may stand for several

1 · Every parameter in one table#

ms.parameters() lists them all at the defaults a Scenario uses: the group, the argument that changes it, its name, value and unit.

p = pd.DataFrame(ms.parameters())
print(len(p), "parameters")
p.groupby("group").size().rename("parameters").to_frame()
251 parameters
parameters
group
choice_model.logit 39
choice_model.nested_logit 40
equilibration.free_flow 2
equilibration.msa 8
loading 6
modes 6
network 95
parking 13
prices 7
route_method.montecarlo 7
route_method.penalty 5
route_update.best_response 4
scenario 8
transit 11
p[p["group"].isin(["loading", "modes"])][["argument", "name", "value", "unit", "note"]]
argument name value unit note
103 loading_options priority 0.0 0 or 1
104 loading_options reroute 1.0 0 or 1 on at flow_level 3 and 4; off at 2 unless aske...
105 loading_options reroute_after_s 300.0 s
106 loading_options reroute_max 3.0 count
107 loading_options reroute_min_gain 0.1 —
108 loading_options pocket_length_m 50.0 m
109 mode_options walk_max_s 1800.0 s
110 mode_options bike_max_s 3600.0 s
111 mode_options fallback_car 0.0 0 or 1
112 mode_options car_access_s 120.0 s
113 mode_options car_egress_s 180.0 s
114 mode_options car_snap_motorway_m 50.0 m

2 · Changing them by name#

Each group has its argument: choice_options, loading_options, equilibration_options, mode_options, transit_options, parking_options, route_options of Scenario.from_parts, and network_options of the network readers (network_read_osm, network_read_table, network_read_gmns). A name that does not exist is refused with the list of those that do, so a typo never passes silently.

try:
    ms.Scenario.from_parts(net, demand(10), classes=cars, choice_options={"beta_tim_min": -0.1}).run("typo")
except ValueError as e:
    print(e)
the choice model needs the attribute "tim_min"; the alternatives carry: time_min, length_km, detour, overlap, ln_path_size, n_links, car_min, bike_min, walk_min, wait_min, ride_min, transfers, parking_min, bike_separated_km, bike_lane_km, bike_mixed_km, walk_access_min, walk_egress_min, walk_transfer_min, wait_first_min, wait_transfer_min, ride_rail_min, ride_metro_min, ride_tram_min, ride_bus_min, ride_ferry_min, ride_other_min, cost_eur, cost_running_eur, cost_toll_eur, cost_parking_eur, cost_fare_eur, trip_departure_h, nest, mode_walk, mode_bike, mode_car, mode_transit, mode_car_transit, mode_bike_transit

Here, the value of time: the default logit weighs a minute at −0.2. Halving it makes travellers less sensitive to time, so more of them take routes a little slower than the best; doubling it, fewer.

trips = demand(20000)  # enough for queues, so that route choice matters
rows = []
for beta in (-0.1, -0.2, -0.4):
    run = ms.Scenario.from_parts(
        net, trips, classes=cars, choice_options={"beta_time_min": beta}
    ).run(f"beta{beta}", output_dir=f"runs/beta{beta}", quiet=True)
    c = run.convergence()
    rows.append({
        "beta_time_min": beta,
        "mean trip (min)": mean_trip_min(run),
        "gap": c["gap"][-1],
        "expected by the model": c["gap_expected"][-1],
        "fingerprint": run.fingerprint,
    })
pd.DataFrame(rows).set_index("beta_time_min").round(4)
mean trip (min) gap expected by the model fingerprint
beta_time_min
-0.1 2.5902 0.1104 0.0886 35a94d5fdd041eb7
-0.2 2.5682 0.1013 0.0846 3bc3c731f9d9b736
-0.4 2.5654 0.1029 0.0790 675309bfee2c6c78

The gap the model itself expects grows as time matters less: those travellers chose slower routes on purpose. Each setting is a different run, with its own fingerprint.

3 · Seeds and replications#

A logit model draws who takes which route. The draws come from one number, master_seed: the same seed repeats a run exactly; another seed is another sample of the same model, and the spread over seeds is the run’s sampling noise.

reps = []
for seed in range(5):
    run = ms.Scenario.from_parts(net, trips, classes=cars, master_seed=seed).run(
        f"seed{seed}", output_dir=f"runs/seed{seed}", quiet=True
    )
    reps.append({"master_seed": seed, "mean trip (min)": mean_trip_min(run)})
reps = pd.DataFrame(reps).set_index("master_seed")
print(reps.round(4))
print(f"mean {reps.iloc[:, 0].mean():.4f} min, standard deviation {reps.iloc[:, 0].std():.4f} min")
             mean trip (min)
master_seed                 
0                     2.5682
1                     2.5684
2                     2.5839
3                     2.5855
4                     2.5802
mean 2.5773 min, standard deviation 0.0084 min

4 · Fewer travellers, each standing for more people#

demand_sample(trips, weight) keeps one traveller in every weight, each standing for weight people (their vehicle counts as that many PCU in the loading). The draw keeps each class’s and each mode’s share to within one traveller. The run is cheaper, though by less than the weight (what does not grow with demand stays). The mean trip is per person (Run.mean_travel_time_s).

big = demand(20000)
rows = []
for weight in (1, 2, 4, 8):
    sample = ms.demand_sample(big, weight, seed=0)
    run = ms.Scenario.from_parts(net, sample, classes=cars).run(
        f"weight{weight}", output_dir=f"runs/weight{weight}", quiet=True
    )
    t = run.timings().to_pandas()
    rows.append({
        "weight": weight,
        "travellers simulated": len(sample),
        "mean trip (min)": mean_trip_min(run),
        "run time (s)": float(t.loc[t["stage"] == "total", "seconds"].iloc[0]),
    })
pd.DataFrame(rows).set_index("weight").round(3)
travellers simulated mean trip (min) run time (s)
weight
1 20000 2.568 0.379
2 10000 2.875 0.197
4 5000 3.338 0.144
8 2500 4.193 0.084

Under congestion a sample overstates the delays, and more so the coarser it is: a traveller of weight 8 is one vehicle of 8 PCU, so its queues form and clear in lumps (a known effect of sampled demand in traffic simulation). On this busy, signalised grid the mean trip is 63 % too high at weight 8; on a city’s network at mild congestion the bias measured a few per cent at weights 5 to 10. A sample is for screening many scenarios quickly; a result to report comes from the full demand, or from a weight whose bias has been checked against it, as here.

5 · A small sweep#

How the mean trip grows with demand on this grid, at free flow and with queues: a loop over scenarios is all an experiment needs.

counts = [2000, 6000, 10000, 14000, 18000, 22000]
free, loaded = [], []
for n in counts:
    trips_n = demand(n)
    free.append(mean_trip_min(ms.Scenario.from_parts(
        net, trips_n, classes=cars, flow_level=0, equilibration="free_flow", choice_model="deterministic"
    ).run(f"free{n}", output_dir=f"runs/free{n}", quiet=True)))
    loaded.append(mean_trip_min(ms.Scenario.from_parts(net, trips_n, classes=cars).run(
        f"loaded{n}", output_dir=f"runs/loaded{n}", quiet=True
    )))

fig, ax = plt.subplots(figsize=(16 / 2.54, 8 / 2.54), dpi=200)
ax.plot(counts, free, marker="o", label="free flow")
ax.plot(counts, loaded, marker="o", label="with queues (default)")
ax.set_xlabel("trips in the hour")
ax.set_ylabel("mean trip (min)")
ax.legend()
ax.set_title("A 6 x 6 grid under growing demand")
plt.show()
pd.DataFrame({"free flow (min)": free, "with queues (min)": loaded}, index=pd.Index(counts, name="trips")).round(2)
../_images/b9f4e8eb9db68a1574016b5d8d078b9b14f820674c7870fe1369aabd77f87720.png
free flow (min) with queues (min)
trips
2000 2.01 2.02
6000 2.00 2.02
10000 2.01 2.07
14000 2.01 2.15
18000 2.01 2.37
22000 2.01 3.69

6 · Mode shares: plausible defaults, yours to change#

The starter cities’ traveller classes carry mode constants fitted so that each city’s residents drive on the share of their trips its survey gives: Amsterdam’s 23 % (residents’ trips; they cycle on 38 %), Paris’s of trips within Paris (EMG 2023, https://www.paris.fr/pages/inedit-le-velo-surpasse-la-voiture-a-paris-et-en-petite-couronne-et-de-loin-26832), Lyon’s (Enquête Déplacements 2015, https://www.urbalyon.org/sites/default/files/productions/publications/imports/2019-11/m-emd-agglo.pdf). They are chosen to be logical and to fit those numbers, not calibrated: a study sets them to its own city and survey.

Start small: Delft. The smallest starter city runs its whole morning in about twenty seconds — the split its example classes give (the case’s own travellers and what enters from outside, by people):

# Delft's whole morning: every departure (06:30-09:30), run on to 10:30 so the late ones arrive.
delft_scenario = ms.examples.case("delft").scenario("base", departures="all", window=("06:30", "10:30"))
delft_run = delft_scenario.run("delft-base", output_dir="runs/delft-base", quiet=True)
delft_modes = delft_run.trip_modes()
delft_people = pd.Series(delft_modes["weight"], index=pd.Index(delft_modes["mode"], name="mode")).groupby(level=0).sum()
print(f"run in {delft_run.timings()['seconds'][-1]:.1f} s")
(100 * delft_people / delft_people.sum()).round(1).rename("Delft (%)")
run in 19.1 s
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_91464/3408348870.py:3: NoAlternativeWarning: 3 trips (3 people, 0.0% of run 'delft-base') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 2 'no_vehicle' (choosing), 1 'from_outside_transit' (transit). Why, by mode offered (trips): walk: walk_too_long 2; transit: no_stop_in_reach 3. Most between (latitude, longitude, about 1 km): 1 people from (51.98, 4.38) to (51.98, 4.40); 1 people from (51.98, 4.40) to (51.98, 4.37); 1 people from (52.01, 4.36) to (51.97, 4.39). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s; no_stop_in_reach: transit_options['access_walk_max_s'] or the class's access_walk_max_s. Run.report_no_alternative() lists every trip with its reasons.
  delft_run = delft_scenario.run("delft-base", output_dir="runs/delft-base", quiet=True)
mode
bike            18.8
bike_transit     0.0
car             53.5
transit         24.5
walk             3.3
Name: Delft (%), dtype: float64

One constant moves a split. Here, Amsterdam’s morning with the bike constant of the two classes that own a bike at its fitted value (1.23) and one unit either side, on the case’s fast run (each simulated traveller five people), counting the city’s own travellers (the survey’s), not what enters from outside. A secant step or two on such a constant fits any target; a car or transit constant works the same way.

import collections
import copy

case = ms.examples.case("amsterdam")
city = case.network()
timetable = case.transit(city)
parks = case.parkings()
example = case.classes()  # the package's example classes, and those of what enters from outside (notebook 02)
sample = case.demand()  # the fast run: five people a simulated traveller
outside = {"from_outside_car", "from_outside_transit", "goods"}  # fixed modes: not the survey's travellers
own = {t[0] for t in sample if t[7] not in outside}


def with_bike_constant(value):
    """The example classes, the bike constant of those that own a bike set to ``value``."""
    classes = copy.deepcopy(example)
    for c in classes.values():
        if "beta_mode_bike" in c["betas"]:
            c["betas"]["beta_mode_bike"] = value
    return classes


rows = []
for value in (0.23, 1.23, 2.23):
    run = ms.Scenario.from_parts(
        city, sample, classes=with_bike_constant(value), transit=timetable, parkings=parks,
        **case.info["scenarios"]["base"],  # the case's settings: shared searches, stop at a good gap
    ).run(f"bike{value}", output_dir=f"runs/bike{value}", quiet=True)  # fmt: skip
    modes = run.trip_modes()
    people = collections.Counter()
    for who, mode, weight in zip(modes["traveller_id"], modes["mode"], modes["weight"]):
        if who in own:
            people[mode] += weight
    total = sum(people.values())
    rows.append({
        "bike constant": value,
        "bike (%)": 100 * people["bike"] / total,
        "car (%)": 100 * people["car"] / total,
        "transit (%)": 100 * people["transit"] / total,
        "bike : car": people["bike"] / people["car"],
    })
pd.DataFrame(rows).set_index("bike constant").round(2)
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_91464/3235198120.py:28: NoAlternativeWarning: 293 trips (1,465 people, 0.5% of run 'bike0.23') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 258 'no_vehicle' (choosing), 33 'from_outside_transit' (transit), 1 'bike_only' (choosing), 1 'car_and_bike' (choosing). Why, by mode offered (trips): car: no_road_route 1; bike: ride_too_long 2; walk: walk_too_long 260; transit: no_stop_in_reach 206, no_transit_journey 87; car_transit: too_short 1; bike_transit: no_transit_journey 1, too_short 1. Most between (latitude, longitude, about 1 km): 25 people from (52.39, 4.84) to (52.41, 4.85); 15 people from (52.38, 4.90) to (52.40, 4.87); 15 people from (52.40, 4.91) to (52.41, 4.85); 10 people from (52.35, 4.81) to (52.40, 4.87); 10 people from (52.35, 4.85) to (52.41, 4.82). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s; ride_too_long: mode_options['bike_max_s'] or the class's bike_max_s; no_road_route: the road network between the two (network_check); no_stop_in_reach: transit_options['access_walk_max_s'] or the class's access_walk_max_s; no_transit_journey: transit_options['journey_max_s'], the window, or the timetable; too_short: parking_options['pr_min_km']. Run.report_no_alternative() lists every trip with its reasons.
  ).run(f"bike{value}", output_dir=f"runs/bike{value}", quiet=True)  # fmt: skip
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_91464/3235198120.py:28: NoAlternativeWarning: 303 trips (1,515 people, 0.5% of run 'bike1.23') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 269 'no_vehicle' (choosing), 33 'from_outside_transit' (transit), 1 'car_and_bike' (choosing). Why, by mode offered (trips): car: no_road_route 1; bike: ride_too_long 1; walk: walk_too_long 270; transit: no_stop_in_reach 206, no_transit_journey 97; car_transit: too_short 1; bike_transit: too_short 1. Most between (latitude, longitude, about 1 km): 25 people from (52.39, 4.84) to (52.41, 4.85); 15 people from (52.38, 4.90) to (52.40, 4.87); 15 people from (52.40, 4.91) to (52.41, 4.85); 15 people from (52.41, 4.81) to (52.42, 4.82); 10 people from (52.35, 4.81) to (52.40, 4.87). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s; ride_too_long: mode_options['bike_max_s'] or the class's bike_max_s; no_road_route: the road network between the two (network_check); no_stop_in_reach: transit_options['access_walk_max_s'] or the class's access_walk_max_s; no_transit_journey: transit_options['journey_max_s'], the window, or the timetable; too_short: parking_options['pr_min_km']. Run.report_no_alternative() lists every trip with its reasons.
  ).run(f"bike{value}", output_dir=f"runs/bike{value}", quiet=True)  # fmt: skip
/var/folders/q0/vjghqqvj4dvcq_z2rjmvd0jmw3f5y2/T/ipykernel_91464/3235198120.py:28: NoAlternativeWarning: 288 trips (1,440 people, 0.5% of run 'bike2.23') had no alternative — no mode they may use reached their destination within the limits — and were not simulated. By class (stated mode): 254 'no_vehicle' (choosing), 33 'from_outside_transit' (transit), 1 'car_and_bike' (choosing). Why, by mode offered (trips): car: no_road_route 1; bike: ride_too_long 1; walk: walk_too_long 255; transit: no_stop_in_reach 206, no_transit_journey 82; car_transit: too_short 1; bike_transit: too_short 1. Most between (latitude, longitude, about 1 km): 25 people from (52.39, 4.84) to (52.41, 4.85); 15 people from (52.38, 4.90) to (52.40, 4.87); 15 people from (52.40, 4.91) to (52.41, 4.85); 10 people from (52.35, 4.81) to (52.40, 4.87); 10 people from (52.35, 4.85) to (52.41, 4.82). To change: walk_too_long: mode_options['walk_max_s'] or the class's walk_max_s; ride_too_long: mode_options['bike_max_s'] or the class's bike_max_s; no_road_route: the road network between the two (network_check); no_stop_in_reach: transit_options['access_walk_max_s'] or the class's access_walk_max_s; no_transit_journey: transit_options['journey_max_s'], the window, or the timetable; too_short: parking_options['pr_min_km']. Run.report_no_alternative() lists every trip with its reasons.
  ).run(f"bike{value}", output_dir=f"runs/bike{value}", quiet=True)  # fmt: skip
bike (%) car (%) transit (%) bike : car
bike constant
0.23 39.81 28.14 27.55 1.41
1.23 45.22 23.33 27.31 1.94
2.23 49.54 19.32 27.25 2.56

A unit of constant is five minutes of riding at the default time weight (−0.2 per minute), so the fitted 1.23 says that Amsterdam’s cyclists prefer the bike by about six minutes over what times alone would give. It was fitted on this morning so that the city’s residents drive on 23 % of their trips, the survey’s share (the middle row), and the table shows how far a unit of constant moves them. The bike then takes more than the survey’s 38 %, and walking much less than a real morning has: the synthetic demand lacks most of the short trips people walk, a known limit of its recipe. Fit the constants on the demand you will run.

Next: 07 · Validation: validation: the mechanisms against hand calculations, queueing theory and the benchmarks. The whole series: 00 · overview. The documentation: openmobisim.github.io. Something wrong or unclear? Report it.