openmobisim.choice ================== .. py:module:: openmobisim.choice .. autoapi-nested-parse:: 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 with ``choice_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`` — situation ``s`` owns alternatives ``offsets[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_eur`` and its parts (see ``ROUTE_ATTRIBUTES`` and ``Scenario.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_values`` and ``trip_values``) are attributes too, ``person_`` and ``trip_``: the same for every alternative of one situation. * ``batch.user_class`` — each situation's traveller class, an index into ``batch.class_names`` (the demand's ``user_class`` values), 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 ---------- .. autoapisummary:: openmobisim.choice.ROUTE_ATTRIBUTES openmobisim.choice.SERVICE_ATTRIBUTES openmobisim.choice.TAXI_ATTRIBUTES Classes ------- .. autoapisummary:: openmobisim.choice.ChoiceModel Functions --------- .. autoapisummary:: openmobisim.choice.choice_model_register openmobisim.choice.choice_models openmobisim.choice.sample_random_utility openmobisim.choice.segment_argmax openmobisim.choice.segment_softmax Module Contents --------------- .. py:class:: ChoiceModel What a choice model looks like: a ``choose(batch)`` method. .. py:method:: choose(batch) The chosen alternative of each situation, as an index within it. .. py:function:: 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 as ``factory(choice_options)`` (a dict, empty when none are given) and runs it; the scenario keeps the name, so ``replace`` and a plain design can name it. The model is shown in the manifest by its ``name`` (the registered name unless it has its own) and identified in the fingerprint by its ``descriptor``, which should hold every option it read. A name is registered once per session: registering it again replaces the factory. :param name: Letters, digits and underscores, not a built-in model's name. :param factory: 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. .. py:function:: choice_models() The choice models that can be selected by name. The built-in ones (``"deterministic"``, ``"logit"``, ``"nested_logit"``), then those registered with ``choice_model_register``, in the order registered. Which built-in one a ``Scenario`` uses unless told: ``"nested_logit"`` when it offers more than one mode, ``"logit"`` otherwise. .. py:function:: sample_random_utility(batch, utility) Sample the logit of ``utility`` with 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 from ``choose``. .. py:function:: segment_argmax(values, offsets) The index within each situation of its largest value (the first of a tie). :param values: One number per alternative. :param offsets: The batch's ``offsets``: situation ``s`` owns ``values[offsets[s]:offsets[s + 1]]``; every situation has at least one. :returns: An ``int64`` array, one index per situation. .. py:function:: 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. .. py:data:: ROUTE_ATTRIBUTES :type: tuple[str, ...] :value: ('time_min', 'length_km', 'detour', 'overlap', 'ln_path_size', 'n_links', 'car_min', 'bike_min',... .. py:data:: SERVICE_ATTRIBUTES :type: tuple[str, ...] :value: ('mode_bike_share', 'dock_min', 'mode_bike_share_transit') .. py:data:: TAXI_ATTRIBUTES :type: tuple[str, ...] :value: ('mode_taxi', 'fail_prob')