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 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 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)
| 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 |