openmobisim.choice#
Choice models: what to write to add your own.
A choice model says which alternative each traveller takes: a route among the
routes of the trip’s origin-destination pair, an itinerary (a transit journey, a
park-and-ride or bike-and-ride chain), or, with mode choice, a mode together with its
route or itinerary. The alternatives of every kind carry the same named attributes, so
one model serves them all. openmobisim ships three models, selected by name
(choice_models()):
"deterministic": everyone takes the alternative with the least travel time. All-or-nothing; no randomness. Useful for debugging or an upper bound."logit"(Scenario.from_parts’s default when the run offers one mode): a random utility model, linear in named attributes and sampled exactly (Gumbel-max). With its defaults it is the standard path-size logit for route choice:U = -0.2 · time_min + 1 · ln_path_size. Set any coefficient withchoice_options:{"beta_time_min": -0.3, "beta_length_km": -0.1}. The defaults are an assumption, not a calibration; pass estimated coefficients for real work."nested_logit"(the default when the run offers more than one mode): the same utility, with the alternatives of each mode in a nest of their own (mu, 0.5), so a mode’s share does not grow with the number of its routes or journeys.
Your own model is any object with a choose(batch) method (no base class
needed), passed as Scenario.from_parts(..., choice_model=my_model). It is
called once per batch of up to 32 768 trips and returns, for each situation,
the index of the alternative taken:
import numpy as np
from openmobisim import choice
class ShortAndSimple:
name = "short_and_simple" # shown in the manifest
descriptor = "short_and_simple;v1" # anything that identifies your settings
attributes = ["time_min", "length_km"] # what you read (optional)
def choose(self, batch):
utility = -0.3 * batch.attributes["time_min"] - 0.1 * batch.attributes["length_km"]
return choice.sample_random_utility(batch, utility)
What the batch holds (all NumPy arrays; a indexes alternatives, s
situations, one situation being one traveller’s one trip):
batch.offsets— situationsowns alternativesoffsets[s]:offsets[s+1].batch.attributes— a dict of float arrays, one value per alternative:time_min,length_km,detour,overlap,ln_path_size,n_links,car_min,bike_min,walk_min,wait_min,ride_min,transfers,parking_min, the bike leg’s kilometres by facility, a transit itinerary’s walks, waits and rides split, and what the alternative costs in euros,cost_eurand its parts (seeROUTE_ATTRIBUTESandScenario.from_parts’price_options). Routes and the itineraries of transit, park-and-ride and bike-and-ride trips carry the same names, so one model serves both.batch.gumbel— each alternative’s standard Gumbel error, keyed on (traveller, trip, iteration, alternative identity), so a model that adds it to a utility gets exactly the common random numbers the built-in models use.batch.traveller,batch.trip(per situation),batch.identity(per alternative; stable when other alternatives come and go),batch.situation_of(per alternative),batch.iteration.The user’s traveller and trip values (
Scenario.from_parts’person_valuesandtrip_values) are attributes too,person_<name>andtrip_<name>: the same for every alternative of one situation.batch.user_class— each situation’s traveller class, an index intobatch.class_names(the demand’suser_classvalues), so a model may weigh classes differently:batch.class_names[batch.user_class[s]].
Return the chosen indices within each situation (an integer array, one per
situation), or (indices, probabilities) when the model knows how likely each
choice was. A model may also have a probabilities(batch) method returning the
probability of every alternative (one number per alternative, summing to one
within each situation): it lets an iterated run (equilibration="msa") measure
how far the pattern is from equilibrium; without it those measures are nan.
And it may have a logsum(batch) method returning one number per situation, the
expected utility of its best alternative: Run.itinerary_choices()["logsum"],
for accessibility; without it that column is nan.
Optional attributes of the model: name, descriptor (both in
the manifest and part of the run’s fingerprint: change the descriptor when the
model’s behaviour changes, or two different models look like one run),
sampled (False if it never uses batch.gumbel; default True) and
attributes (the ones it reads; default all).
The helpers below do the array bookkeeping so a model is a few lines.
Attributes#
Classes#
What a choice model looks like: a |
Functions#
|
Make a Python choice model usable by name, like the built-in ones. |
The choice models that can be selected by name. |
|
|
Sample the logit of |
|
The index within each situation of its largest value (the first of a tie). |
|
The logit probabilities of each situation's utilities, one per alternative. |
Module Contents#
- class openmobisim.choice.ChoiceModel#
What a choice model looks like: a
choose(batch)method.- choose(batch)#
The chosen alternative of each situation, as an index within it.
- Parameters:
batch (Any)
- Return type:
Any
- openmobisim.choice.choice_model_register(name, factory)#
Make a Python choice model usable by name, like the built-in ones.
After
choice_model_register("my_model", MyModel),Scenario.from_parts(..., choice_model="my_model", choice_options={...})builds the model asfactory(choice_options)(a dict, empty when none are given) and runs it; the scenario keeps the name, soreplaceand a plain design can name it. The model is shown in the manifest by itsname(the registered name unless it has its own) and identified in the fingerprint by itsdescriptor, which should hold every option it read. A name is registered once per session: registering it again replaces the factory.- Parameters:
name (str) – Letters, digits and underscores, not a built-in model’s name.
factory (collections.abc.Callable[[dict[str, float]], Any]) – Called with the options dict; returns an object with
choose(batch).
- Raises:
ValueError – If the name is a built-in model’s or not a plain identifier.
- Return type:
None
- openmobisim.choice.choice_models()#
The choice models that can be selected by name.
The built-in ones (
"deterministic","logit","nested_logit"), then those registered withchoice_model_register, in the order registered. Which built-in one aScenariouses unless told:"nested_logit"when it offers more than one mode,"logit"otherwise.- Return type:
list[str]
- openmobisim.choice.sample_random_utility(batch, utility)#
Sample the logit of
utilitywith the batch’s common random numbers.Each situation takes the alternative with the largest
utility + gumbel, which is an exact draw from the logit. Returns(chosen, probability): the index within each situation and the logit probability of the alternative taken. Give this straight back fromchoose.- Parameters:
batch (Any)
utility (Any)
- Return type:
tuple[numpy.ndarray, numpy.ndarray]
- openmobisim.choice.segment_argmax(values, offsets)#
The index within each situation of its largest value (the first of a tie).
- Parameters:
values (Any) – One number per alternative.
offsets (Any) – The batch’s
offsets: situationsownsvalues[offsets[s]:offsets[s + 1]]; every situation has at least one.
- Returns:
An
int64array, one index per situation.- Return type:
numpy.ndarray
- openmobisim.choice.segment_softmax(values, offsets)#
The logit probabilities of each situation’s utilities, one per alternative.
Computed with each situation’s largest utility subtracted, so it cannot overflow.
- Parameters:
values (Any)
offsets (Any)
- Return type:
numpy.ndarray
- openmobisim.choice.ROUTE_ATTRIBUTES: tuple[str, ...] = ('time_min', 'length_km', 'detour', 'overlap', 'ln_path_size', 'n_links', 'car_min', 'bike_min',...#
- openmobisim.choice.SERVICE_ATTRIBUTES: tuple[str, ...] = ('mode_bike_share', 'dock_min', 'mode_bike_share_transit')#
- openmobisim.choice.TAXI_ATTRIBUTES: tuple[str, ...] = ('mode_taxi', 'fail_prob')#