SimulationEngine

class passengersim.core.SimulationEngine

Bases: object

The simulation engine: the network, the event queue and the simulation state.

A SimulationEngine holds everything a simulation run needs: carriers, airports, legs, fares, demands, markets and paths, the booking curves and Frat5 curves, the DCPs, and the queue of events. The PassengerSim driver builds it from a configuration, then runs each sample by creating booking events, calling go to work through the event queue, and running RM steps at the DCPs and other user events that go returns.

Parameters:
name : str, default "Incognito"

The scenario name; see name.

random_generator : Generator, optional

The random number generator for the simulation. By default a new one is created.

Raises:

TypeError – If name is not a str.

Methods

__init__(*args, **kwargs)

add_airport

Add an airport to the simulation.

add_booking_event

Add a booking event for a demand to the event queue.

add_carrier

Add a carrier to the simulation.

add_circuity_rule

Add a circuity rule, used when building connections.

add_curve

Add a booking curve to the simulation.

add_dcp

Add a DCP (data collection point).

add_demand

Add demands to the simulation.

add_event

Add user events to the event queue.

add_fare

Add fares to the simulation.

add_frat5

Add Frat5 curves to the simulation.

add_leg

Add legs to the simulation.

add_path

Add explicit paths to the simulation.

additional_settings

Set additional settings, by keyword.

allocate_demand_to_tf

Create booking events for one demand, spread over the timeframes.

allocate_demand_to_tf_pods

Create booking events for one demand, spread over the timeframes, as PODS does.

attach_firehose_logger

Send one topic of detailed simulation logging (a firehose) somewhere.

avg_local_by_carrier

The fraction of a carrier's leg passengers who are local, over all its legs.

build_connections

Build connecting paths for the markets in the simulation.

build_expiration

When this build of PassengerSim expires.

capture_forecast_accuracy

Add a summary of path class forecast accuracy to each carrier.

choice_set_columns

The column names for the rows from get_choice_set.

clear_choice_set

Clear the captured choice set data.

compute_hhi

Compute the Herfindahl-Hirschman index (HHI) of each carrier at each airport.

connect_markets

Make sure every demand is linked to the simulation's market.

create_events

Create booking events for every demand's scenario demand.

distribution_local_leg_passengers

Count of a carrier's legs by their percentage of local passengers.

fare_segment_counters

Get current-sample sales and revenue by segment for many fares at once.

flush_firehoses

Flush all the attached firehose loggers.

fraction_local_by_carrier_and_place

The fraction of a carrier's leg passengers who are local, by airport.

get_airport_carrier_share

Get a carrier's seat share at an airport, from compute_hhi.

get_choice_set

Get the captured choice set data, as a list of tuples.

get_days_prior

Get the days prior to departure of a DCP.

get_preferred_carrier

Choose a demand's preferred carrier from a random draw.

get_random_generator

Get the random number generator for one stream.

go

Run the simulation until the next user event, or until the queue is empty.

initialize_bucket_ap_rules

Set each bucket's advance purchase DCP index from the fares.

initialize_histories

Set up the booking histories of the legs, buckets, paths and path classes.

initialize_nonstop_path_linkage

Link each leg to its nonstop path.

initialize_pathclasses

Create the path classes for the paths in every market.

leg_id_exists

Check whether a leg with this leg ID has been added.

license_info

A description of this build and its license.

next_departure

Move every leg's and path's history buffers on to the next departure.

nonbookings_by_segment_dcp

The number of customers who bought nothing, by segment and DCP, in this trial.

num_events

The number of events on the event queue.

path_2_leg

Add up a carrier's path class forecasts to its leg buckets.

print_demand_by_tf

Print each demand's generated passengers by timeframe, for debugging.

record_daily_statistics

Record carrier daily statistics and optional leg and path bid-price statistics.

record_dcp_statistics

Record the statistics for a DCP.

record_departure_statistics

Record the statistics for the departure that just finished.

reseed

Reseed all the random number streams.

reset_counters

Reset the counters for a new sample.

reset_trial_counters

Reset the counters and forecasts for a new trial.

set_parm

Set a simulation parameter by name.

shop

Shop a market, as competitive fare data services do.

summary_demand_to_come

Statistics of the demand still to come at each DCP, by segment.

validate_license

Check that this build and the license are valid.

write_to_firehose

Write a message to a firehose topic.

Attributes

airports

A mapping of the airports added with add_airport, keyed by airport code.

base_time

The base time for the simulation controller, as a Unix timestamp.

bucketnames

An iterator over the booking class names of the buckets.

buckets

An iterator over the buckets on all the legs.

burn_samples

The number of samples used for the RM system to warm up.

carriers

An iterator over the carriers added with add_carrier.

choice_set_mkts

The (orig, dest) markets whose choices are captured in the choice set data.

choice_set_sampling_probability

The probability that each choice is captured in the choice set data.

config

The configuration object for the run, or None.

controller_time_zone

The time zone offset from UTC, in seconds, for the simulation controller.

dedupe_offers

Whether to drop duplicate offers in a customer's choice set.

demands

An iterator over the demands added with add_demand.

disable_ap

Whether to turn off the advance purchase rules for fares.

fares

An iterator over the fares added with add_fare.

iteration

No longer used (deprecated).

last_dcp

The days prior of the most recent DCP processed.

last_dcp_index

The index of the most recent DCP processed.

last_event_time

The time of the most recent event processed by go, as a Unix timestamp.

legs

An iterator over the legs added with add_leg.

manual_paths

Whether paths are provided explicitly, instead of built by the engine.

markets

A mapping of the markets in the simulation, keyed by Market.identifier.

max_connect_time

Legacy single global maximum connect time, in minutes.

max_connect_time_dd

Global default maximum connect time, in minutes, for domestic-to-domestic connections.

max_connect_time_di

Global default maximum connect time, in minutes, for domestic-to-international connections.

max_connect_time_id

Global default maximum connect time, in minutes, for international-to-domestic connections.

max_connect_time_ii

Global default maximum connect time, in minutes, for international-to-international connections.

min_connect_time_dd

Global default minimum connect time, in minutes, for domestic-to-domestic connections.

min_connect_time_di

Global default minimum connect time, in minutes, for domestic-to-international connections.

min_connect_time_id

Global default minimum connect time, in minutes, for international-to-domestic connections.

min_connect_time_ii

Global default minimum connect time, in minutes, for international-to-international connections.

mkt_k_factor

The market-level k-factor for demand variation.

name

The scenario name, an arbitrary string.

num_dcps

The number of DCPs (data collection points) added with add_dcp.

num_samples

The number of samples in each trial.

num_trials

The number of trials in the run.

num_trials_completed

The number of trials completed so far.

paths

An iterator over the paths in all the markets.

pax_type_k_factor

The passenger-type k-factor for demand variation.

preferred_airline_pct_share

Whether the preferred carrier is chosen by seat share.

prorate_revenue

Whether the revenue of connecting paths is prorated to their legs.

random_generator

The main random number generator for the simulation.

revenue

Total revenue for the simulation (not currently used).

rm_start_sample

The sample at which the RM steps start running.

sample

The current sample number within the trial.

save_all_offers

Whether to save all offers, including unavailable ones.

save_orders

Whether to save order data on each path.

save_timeframe_details

Whether to save timeframe details (not currently used).

snapshot_filters

The snapshot filters for debugging output, or None.

sys_k_factor

The system-level k-factor for demand variation.

tf_k_factor

The timeframe k-factor, which controls the variance of passenger arrivals.

tf_z_factor

The z-factor for timeframe demand variation in allocate_demand_to_tf_pods.

trial

The current trial number.

add_airport()

Add an airport to the simulation.

An airport with the same code replaces the earlier one.

Parameters:
airport : Airport

The airport. This is positional-only.

Returns:

str – A confirmation message.

Raises:

TypeError – If airport is not an Airport.

add_booking_event()

Add a booking event for a demand to the event queue.

When the event is reached, go processes it internally as a booking request for num_pax passengers from demand; it is not returned to the caller. The queued event shares the underlying demand object.

Parameters:
demand : Demand

The demand making the booking request.

event_time : float

Timestamp for the event, in Unix time.

num_pax : int

Number of passengers in the booking request, between 1 and 32767.

Raises:
  • TypeError – If demand is not a Demand, or num_pax is not an int.

  • ValueError – If num_pax is out of range, or demand is not initialized.

add_carrier()

Add a carrier to the simulation.

If the carrier has no dcp_days_prior yet, it is given the simulation’s DCPs (see add_dcp).

Parameters:
carrier : Carrier

The carrier. This is positional-only.

Returns:

str – A confirmation message.

Raises:

TypeError – If carrier is not a Carrier, or a carrier with the same name was already added.

add_circuity_rule()

Add a circuity rule, used when building connections.

Parameters:
rule : dict

The rule. The keys "name", "carrier", "orig_airport", "connect_airport", "dest_airport", "orig_state", "connect_state" and "dest_state" take a str, and "alpha" and "beta" take a number. Any of them can be None, which leaves the default. This is positional-only.

Returns:

int – Always 0.

Raises:
  • TypeError – If rule is not a dict, a key is not a str, or a value has the wrong type.

  • ValueError – If a key is not known.

add_curve()

Add a booking curve to the simulation.

Parameters:
curve : BookingCurve

The booking curve. This is positional-only.

Returns:

str – A confirmation message.

Raises:

TypeError – If curve is not a BookingCurve.

add_dcp()

Add a DCP (data collection point).

DCPs must be added in index order: 0, 1, 2 and so on. They are shared by carriers that do not set their own (see add_carrier).

Parameters:
dcp_index : int

The index of the DCP, which must be the number of DCPs added so far.

days_prior : int

The DCP’s days prior to departure.

Returns:

int – Always 0.

Raises:

TypeError – If dcp_index is not the next index.

add_demand()

Add demands to the simulation.

Each demand is linked to the simulation’s market for its origin and destination, which is created if needed. If the demand already belongs to a Market that the simulation does not have yet, that Market is used, along with its distance and paths.

Parameters:
*demands : Demand

The demands to add.

Returns:

str – A confirmation message.

Raises:
  • TypeError – If an argument is not a Demand.

  • ValueError – If the demand’s market and the simulation’s market have different nonzero distances, or another error occurs.

add_event()

Add user events to the event queue.

go returns each event’s payload when it reaches the event. The payload and time are copied when the event is added. All the events are checked before any is added.

Parameters:
*events : Event

The events to add.

Returns:

str – A confirmation message.

Raises:
  • TypeError – If an argument is not an Event.

  • ValueError – If an Event has no payload.

add_fare()

Add fares to the simulation.

Each fare is added to the simulation’s market for its origin and destination, which is created if needed. A fare’s advance purchase days must be one of the DCPs’ days prior; the fare’s advance purchase DCP index is set from it.

Parameters:
*fares : Fare

The fares to add.

Returns:

str – A confirmation message.

Raises:
  • TypeError – If an argument is not a Fare.

  • ValueError – If a fare’s advance purchase days do not match a DCP.

add_frat5()

Add Frat5 curves to the simulation.

The curves are stored by name; a curve with the same name replaces the earlier one.

Parameters:
*curves : Frat5

The Frat5 curves to add.

Returns:

int – Always 0.

Raises:

TypeError – If an argument is not a Frat5.

add_leg()

Add legs to the simulation.

Parameters:
*legs : Leg

The legs to add.

Returns:

str – A confirmation message.

Raises:

TypeError – If an argument is not a Leg.

add_path()

Add explicit paths to the simulation.

Each path is added to the simulation’s market for its origin and destination, which is created if needed. Unlike build_connections, alternate paths that share a first leg are all kept; a path with exactly the same legs as one already in the market is ignored. A new path with a negative path_id is given the next ID, and its carrier is set from its first leg’s carrier if that carrier has been added.

Parameters:
*paths : Path

The paths to add.

Returns:

int – Always 0.

Raises:
  • TypeError – If an argument is not a Path.

  • Exception – If an error occurs in the core.

additional_settings()

Set additional settings, by keyword.

Parameters:
count_leg_sales_by_demand : bool, optional

See _count_leg_sales_by_demand.

spill_counters : bool, optional

Accepted but currently unused: the spill counters are always kept.

**kwargs

Other keywords are ignored.

Raises:

TypeError – If positional arguments are given.

airports

A mapping of the airports added with add_airport, keyed by airport code.

Read-only.

allocate_demand_to_tf()

Create booking events for one demand, spread over the timeframes.

The demand’s passengers are allocated to the timeframes of its booking curve: in each timeframe, the expected number is the remaining demand times the curve’s conditional arrival probability, with random variation scaled by tf_k_factor. Each passenger gets a booking event at a time within the timeframe. Passengers after the burn period are added to the demand’s gt_demand.

Parameters:
demand : Demand

The demand.

num_pax : float

The number of passengers to allocate.

tf_k_factor : float

The timeframe k-factor; 0 means no random variation.

end_ts : int

The departure time, as a Unix timestamp.

debug : object, optional

Accepted but currently unused.

Returns:

tuple[int, …] – The number of passengers allocated to each timeframe.

Raises:
  • TypeError – If demand is not a Demand.

  • RuntimeError – If the engine has no random generator, the demand has no booking curve, or another error occurs in the core.

allocate_demand_to_tf_pods()

Create booking events for one demand, spread over the timeframes, as PODS does.

This is the version of allocate_demand_to_tf that follows PODS more closely, which the driver uses. The variation in each timeframe also uses tf_z_factor, and fractional demand that was not realized is carried forward to later timeframes.

Parameters:
demand : Demand

The demand.

num_pax : float

The number of passengers to allocate.

tf_k_factor : float

The timeframe k-factor; 0 means no random variation.

end_ts : int

The departure time, as a Unix timestamp.

positional-only. : All the arguments are

Returns:

tuple[int, …] – The number of passengers allocated to each timeframe.

Raises:
  • TypeError – If demand is not a Demand.

  • Exception – If the demand has no booking curve, or its curve has no DCPs.

attach_firehose_logger()

Send one topic of detailed simulation logging (a firehose) somewhere.

The topics are "choice", "events", "offers", "orders", "connections", "demand" and "proration". The "orders" firehose is written as CSV, with a header line when it is attached.

Parameters:
topic : str

The topic.

destination : bool, str or object, optional

Where to send it: True or "stdout" for standard output, "stderr" for standard error, any other str for a file name, or an object with a write method. None or False (the default) turns the topic off.

orig : str, optional

For the "choice" topic only, log only the choices for demands with this origin, destination or segment. These are keyword-only.

dest : str, optional

For the "choice" topic only, log only the choices for demands with this origin, destination or segment. These are keyword-only.

segment : str, optional

For the "choice" topic only, log only the choices for demands with this origin, destination or segment. These are keyword-only.

Raises:
  • ValueError – If topic is not known, or a filter is given for another topic.

  • TypeError – If destination is not one of the types above.

avg_local_by_carrier()

The fraction of a carrier’s leg passengers who are local, over all its legs.

Local passengers travel only on that one leg, with no connection. This uses the legs’ grand totals.

Parameters:
carrier : str or Carrier

The carrier, by code or as a Carrier. This is positional-only.

Returns:

float – Local leg passengers divided by all leg passengers, or 0.0 if the carrier’s legs have none.

Raises:
  • KeyError – If the carrier is not found.

  • TypeError – If carrier is neither a str nor a Carrier.

base_time

The base time for the simulation controller, as a Unix timestamp.

All bookings are final at this time, the departure time of the simulated departure. Setting it requires an int.

bucketnames

An iterator over the booking class names of the buckets.

Each read returns a new iterator. Read-only.

buckets

An iterator over the buckets on all the legs.

Each read returns a new iterator. Read-only.

build_connections()

Build connecting paths for the markets in the simulation.

This is the same as passengersim_core.build_connections(self, *args, **kwargs); see that function for the parameters and return value.

Notes

For minimum and maximum connection times, a flight is domestic when its endpoint airports share a country or a nonempty domestic_group. Country codes are unchanged, and same-country flights remain domestic regardless of group membership. With Schengen groups populated from a PassengerSim config, MAD-FRA-HEL uses DD thresholds, MAD-FRA-JFK uses DI, and JFK-FRA-HEL uses ID.

See passengersim.connection_builder.prebuild_connections() for automatic Schengen membership, place overrides, and rebuilding paths after changes. When configuring an engine directly, set airport domestic_group values explicitly; use existing_paths="replace" to rebuild existing paths.

build_expiration()

When this build of PassengerSim expires.

Returns:

datetime.datetime – The expiration time, in UTC.

burn_samples

The number of samples used for the RM system to warm up.

Grand totals and most statistics are only collected from samples at or after this one. The default is 100. Setting it requires a non-negative int.

capture_forecast_accuracy()

Add a summary of path class forecast accuracy to each carrier.

For each path class with a forecast, and each timeframe in which it was open, its sales from its most recent history entry and its forecast are added to its carrier’s totals for this trial, sample, booking class and timeframe. See Carrier.get_forecast_accuracy. This is based on United’s EDGAR presentation.

carriers

An iterator over the carriers added with add_carrier.

Each read returns a new iterator. Read-only.

choice_set_columns()

The column names for the rows from get_choice_set.

Returns:

list[str] – The column names.

Raises:

ValueError – If choice set capture is not turned on.

choice_set_mkts

The (orig, dest) markets whose choices are captured in the choice set data.

If it is empty, choices in all markets can be captured. Reading it returns a new list. Setting it takes an iterable of (orig, dest) tuples of str, which replaces the list; a bad item leaves the list unchanged.

choice_set_sampling_probability

The probability that each choice is captured in the choice set data.

For example, 0.1 captures 10% of the choices. The driver usually calculates this; large networks with many samples can produce millions of choice sets, so a small value saves memory and file space. Setting it requires a number from 0 to 1; other values raise TypeError.

clear_choice_set()

Clear the captured choice set data.

Returns:

int – Always 0.

Raises:

ValueError – If choice set capture is not turned on.

compute_hhi()

Compute the Herfindahl-Hirschman index (HHI) of each carrier at each airport.

The HHI measures market concentration, from 0 to 10000, using the carriers’ seat shares at each market’s origin airport. Each path gets its carrier’s HHI and the largest HHI at its origin (see Path.hhi), and the seat shares are stored for get_airport_carrier_share. Call this after the paths are created and before the simulation runs.

Parameters:
snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace is written to standard output; if a SnapshotInstruction, the trace is written as it directs. This is positional-only.

Returns:

int – Always 0.

config

The configuration object for the run, or None.

The driver stores its configuration here; go reads its license_certificate. Setting it accepts any object; deleting it clears it.

connect_markets()

Make sure every demand is linked to the simulation’s market.

A demand without a market is given the simulation’s market for its origin and destination. A demand whose own Market is not the simulation’s is moved to the simulation’s market, which takes the other Market’s distance (if it has none) and paths.

Parameters:
debug : bool, optional

If true, debugging output is written to standard output. This is positional-only.

Raises:

ValueError – If two Markets for the same airports have different nonzero distances.

controller_time_zone

The time zone offset from UTC, in seconds, for the simulation controller.

Setting it requires an int. A value from -12 to 12 is taken as hours and converted to seconds.

create_events()

Create booking events for every demand’s scenario demand.

For each demand, its scenario_demand (as an int) is split into groups of passengers, and each group gets a booking event at a time drawn from the demand’s booking curve. The driver usually uses allocate_demand_to_tf_pods instead.

Parameters:
end_time : float, default 0.0

The departure time, as a Unix timestamp. 0 uses a fixed default time. This is positional-only.

Returns:

int – The number of events created.

dedupe_offers

Whether to drop duplicate offers in a customer’s choice set.

Setting it uses the truth value of what is assigned.

demands

An iterator over the demands added with add_demand.

Each read returns a new iterator. Read-only.

disable_ap

Whether to turn off the advance purchase rules for fares.

This is only used while debugging and calibrating. Setting it uses the truth value of what is assigned.

distribution_local_leg_passengers()

Count of a carrier’s legs by their percentage of local passengers.

Each of the carrier’s legs adds one to the entry for its local passenger percentage, from its grand totals (floor(100 * local / total), limited to 0 to 100). Legs with no passengers count as 0.

Parameters:
carrier : str or Carrier

The carrier, by code or as a Carrier. This is positional-only.

Returns:

numpy.ndarray – A new int32 array of shape (101,). Entry i is the number of legs with i percent local passengers.

Raises:
  • KeyError – If the carrier is not found.

  • TypeError – If carrier is neither a str nor a Carrier.

fare_segment_counters()

Get current-sample sales and revenue by segment for many fares at once.

This is a bulk accessor intended for tracers and callbacks that need to read segment-level counters for a large number of fares at every DCP; it avoids a Python-level loop with one call per fare and segment.

Parameters:
fares : Sequence[Fare]

The fares to read.

segments : Sequence[str]

The demand segment names to read. A segment with no sales on a fare in the current sample reports zero sales and zero revenue.

Returns:

numpy.ndarray – A float64 array of shape (len(fares), len(segments), 2). The last axis holds (sold, revenue), both accumulated since the start of the current sample (i.e. cumulative within the sample, reset at the next sample). Revenue is the realized revenue, which is exact under continuous pricing.

Raises:

TypeError – If any element of fares is not a Fare, or any element of segments is not a string.

fares

An iterator over the fares added with add_fare.

Each read returns a new iterator. Read-only.

flush_firehoses()

Flush all the attached firehose loggers.

fraction_local_by_carrier_and_place()

The fraction of a carrier’s leg passengers who are local, by airport.

For each airport that the carrier’s legs touch, this is the fraction of the passengers on those legs who are local (see avg_local_by_carrier).

Parameters:
carrier : str or Carrier

The carrier, by code or as a Carrier. This is positional-only.

Returns:

dict[str, float] – Keyed by airport code.

Raises:
  • KeyError – If the carrier is not found, or has no legs.

  • TypeError – If carrier is neither a str nor a Carrier.

get_airport_carrier_share()

Get a carrier’s seat share at an airport, from compute_hhi.

This is used for unit testing.

Parameters:
airport : str

The airport code.

carrier : str

The carrier code.

positional-only. : Both arguments are

Returns:

float – The seat share.

Raises:
  • KeyError – If there is no share for this airport and carrier.

  • TypeError – If airport or carrier is not a str.

get_choice_set()

Get the captured choice set data, as a list of tuples.

Choice set capture must be turned on (with set_parm("capture_choice_set", 1)). Each captured choice gives one row per offer, then one “NO-GO” row per carrier (chosen if that carrier was not chosen) and one for buying nothing. The columns are given by choice_set_columns.

Parameters:
carrier : str, optional

Accepted but currently unused: the data for all carriers is returned. This is positional-only.

Returns:

list[tuple] – The rows.

Raises:
  • ValueError – If choice set capture is not turned on.

  • TypeError – If carrier is not a str.

get_days_prior()

Get the days prior to departure of a DCP.

Parameters:
dcp_index : int

The index of the DCP.

Returns:

int – The days prior.

Raises:

ValueError – If dcp_index is negative or past the last DCP.

get_preferred_carrier()

Choose a demand’s preferred carrier from a random draw.

This is used for unit testing. With preferred_airline_pct_share, the carriers’ seat shares at the origin are used; otherwise the demand’s prob_favored_carrier. The first carrier whose cumulative share exceeds random_draw is chosen and stored on the demand’s choice model.

Parameters:
demand : Demand

The demand, which must have a choice model.

random_draw : float

A number from 0 to 1.

debug : object, optional

Accepted but currently unused.

positional-only. : All the arguments are

Returns:

str – The preferred carrier, or an empty string if none was chosen.

Raises:
  • TypeError – If demand is not a Demand.

  • Exception – If the demand has no choice model.

get_random_generator()

Get the random number generator for one stream.

Parameters:
stream_name : {"choice", "demand"} or None, optional

The stream: the customer choice stream, the demand generation stream, or None (the default) for the main generator (see random_generator).

Returns:

Generator – The generator for the stream.

Raises:

ValueError – If stream_name is not known, or the stream is not set up.

go()

Run the simulation until the next user event, or until the queue is empty.

Events are processed in time order. Booking events are handled internally: the customer chooses among the offers and the sale is recorded. When a user event (see add_event) is reached, go returns its payload, so the caller can act on it (such as running RM at a DCP) and then call go again.

If the network has more legs than the license allows, the license from config or the passengersim_license package is checked first.

Parameters:
demand : object, optional

Accepted but currently unused. This is positional-only.

Returns:

object – The payload of the next user event, or ("Done", 0, -1) once the queue is empty.

Raises:

LicenseError – If the license is checked and is not valid.

initialize_bucket_ap_rules()

Set each bucket’s advance purchase DCP index from the fares.

For each path, and each fare in its market from the same carrier, every bucket with the fare’s booking class on the path’s legs (and in their cabins) gets the later of its own advance purchase DCP index and the fare’s. A path without a carrier of its own uses its first leg’s carrier.

Raises:

RuntimeError – If there are legs but no markets.

initialize_histories()

Set up the booking histories of the legs, buckets, paths and path classes.

For each carrier (or only carrier), the histories of its legs and its paths’ path classes are created, or replaced if they have a different size or wipe_existing is True.

Parameters:
carrier : str or Carrier, optional

Only set up this carrier’s histories. By default, every carrier’s.

num_departures : int, default 26

The number of past departures each history keeps.

num_timeframes : int, default 16

The number of timeframes in each departure.

truncation_rule : {"begin", "end", "either"} or {1, 2, 3}

When a timeframe counts as closed; see Carrier.truncation_rule. Although it can be omitted from the call, it is required: omitting it raises TypeError.

store_priceable : bool, default True

Whether the histories store priceable sales.

floating_closures : bool, default False

Whether the histories use floating closures.

wipe_existing : bool, default False

Whether to replace histories that already have the right size.

Raises:
  • TypeError – If truncation_rule is missing or of the wrong type, or carrier is neither a str nor a Carrier.

  • ValueError – If truncation_rule is not a valid value.

  • KeyError – If carrier is not found.

initialize_nonstop_path_linkage()

Link each leg to its nonstop path.

For each path with one leg, that leg’s nonstop_path is set to the path.

Parameters:
carrier_name : str, optional

Only link this carrier’s paths. This is positional-only.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace is written to standard output; if a SnapshotInstruction, the trace is written as it directs. This is positional-only.

Raises:

RuntimeError – If there are legs but no markets.

initialize_pathclasses()

Create the path classes for the paths in every market.

For each path, and each fare in its market from the same carrier, a path class for the fare’s booking class is added if the path does not have one yet. A path without a carrier of its own uses its first leg’s carrier. New path classes get a new History.

Parameters:
history_def : dict, optional

Arguments for creating each new History. By default a default History is used.

carrier_name : str, optional

Only create path classes for this carrier’s fares.

snapshot_instruction : bool, optional

If true, debugging output is written to standard output.

positional-only. : All three arguments are

Raises:
  • TypeError – If history_def is not a dict.

  • RuntimeError – If there are legs but no markets.

iteration

No longer used (deprecated).

It is still part of the key for daily bid price statistics. Setting it requires an int.

last_dcp

The days prior of the most recent DCP processed.

The driver sets it at each DCP; bookings are recorded against it. reset_counters sets it to 999. Setting it requires an int.

last_dcp_index

The index of the most recent DCP processed.

The driver sets it at each DCP; the choice model and continuous pricing use it to find the current timeframe. Setting it requires an int.

last_event_time

The time of the most recent event processed by go, as a Unix timestamp.

Setting it requires an int.

leg_id_exists()

Check whether a leg with this leg ID has been added.

Parameters:
leg_id : int

The leg ID. This is positional-only.

Returns:

bool – True if a leg with this ID has been added.

legs

An iterator over the legs added with add_leg.

Each read returns a new iterator. Read-only.

license_info()

A description of this build and its license.

Parameters:
user_cert : cryptography.x509.Certificate, optional

The license certificate. By default the one from the passengersim_license package is used, if it is installed.

Returns:

str – The PassengerSim version, when the build expires, and who the license is for and until when (or that there is no license).

manual_paths

Whether paths are provided explicitly, instead of built by the engine.

When it is True, markets without paths are not given paths automatically. Setting it uses the truth value of what is assigned.

markets

A mapping of the markets in the simulation, keyed by Market.identifier.

Read-only.

max_connect_time

Legacy single global maximum connect time, in minutes.

Setting it also sets all four per-connection-type maximum connect times (such as max_connect_time_dd). Setting it requires a non-negative int; a negative value raises TypeError.

max_connect_time_dd

Global default maximum connect time, in minutes, for domestic-to-domestic connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

max_connect_time_di

Global default maximum connect time, in minutes, for domestic-to-international connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

max_connect_time_id

Global default maximum connect time, in minutes, for international-to-domestic connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

max_connect_time_ii

Global default maximum connect time, in minutes, for international-to-international connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

min_connect_time_dd

Global default minimum connect time, in minutes, for domestic-to-domestic connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

min_connect_time_di

Global default minimum connect time, in minutes, for domestic-to-international connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

min_connect_time_id

Global default minimum connect time, in minutes, for international-to-domestic connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

min_connect_time_ii

Global default minimum connect time, in minutes, for international-to-international connections.

Airports can set their own values; this is the default where they don’t. Setting it requires a non-negative int; a negative value raises TypeError.

mkt_k_factor

The market-level k-factor for demand variation.

This is stored on the engine but not used by the core; the driver reads the value from its configuration. Setting it requires a number from 0 to 5; other values raise TypeError.

name

The scenario name, an arbitrary string.

It is used in some output messages. Setting it requires a str.

next_departure()

Move every leg’s and path’s history buffers on to the next departure.

See Leg.next_departure and Path.next_departure.

Raises:

RuntimeError – If a history buffer is missing, or another error occurs in the core.

nonbookings_by_segment_dcp()

The number of customers who bought nothing, by segment and DCP, in this trial.

Returns:

dict[str, dict[int, int]] – Keyed by segment, then by DCP days prior.

num_dcps

The number of DCPs (data collection points) added with add_dcp.

Read-only.

num_events()

The number of events on the event queue.

Returns:

int – The number of events.

num_samples

The number of samples in each trial.

Setting it requires an int from 1 to 10000; other values raise TypeError.

num_trials

The number of trials in the run.

Setting it requires an int from 1 to 1000; other values raise TypeError.

num_trials_completed

The number of trials completed so far.

Setting it requires an int.

path_2_leg()

Add up a carrier’s path class forecasts to its leg buckets.

The forecasts of the carrier’s buckets are first set to zero, then each of the carrier’s paths adds its path class forecasts to them (see Path.accumulate_forecasts). Finally each bucket’s standard deviation is taken as the square root of the summed variance, and its forecast revenue is divided by its forecast mean, giving the average revenue per passenger.

Parameters:
carrier : str

The carrier code.

dcp_index : int

The DCP index for the adjusted fares.

debug : bool, optional

If true, debugging output is written to standard output.

positional-only. : All the arguments are

Returns:

int – Always 0.

Raises:

TypeError – If carrier is not a str.

paths

An iterator over the paths in all the markets.

Each read returns a new iterator. Read-only.

pax_type_k_factor

The passenger-type k-factor for demand variation.

This is stored on the engine but not used by the core; the driver reads the value from its configuration. Setting it requires a number from 0 to 5; other values raise TypeError.

preferred_airline_pct_share

Whether the preferred carrier is chosen by seat share.

When it is True, a demand’s preferred carrier is drawn using the carriers’ seat shares at the origin airport (from compute_hhi). Otherwise it uses the demand’s prob_favored_carrier. Setting it uses the truth value of what is assigned.

print_demand_by_tf()

Print each demand’s generated passengers by timeframe, for debugging.

Each line shows the segment, market, timeframe days prior and passengers, written to the process’s standard output.

Returns:

int – Always 0.

prorate_revenue

Whether the revenue of connecting paths is prorated to their legs.

When it is True, each leg is credited with a share of the revenue, using its carrier’s proration_rule; otherwise each leg gets the full price. Setting it uses the truth value of what is assigned.

random_generator

The main random number generator for the simulation.

See also get_random_generator for the separate streams. Setting it requires a Generator.

record_daily_statistics()

Record carrier daily statistics and optional leg and path bid-price statistics.

The driver calls this every day it records, including DCPs. After the burn period, each leg’s bid price is added to its carrier’s bid price trace, and each fare’s sales so far to its carrier’s bookings by day.

Parameters:
days_prior : int

Current integer day before departure. Native leg collection requires a day between zero and the largest configured DCP, inclusive.

Returns:

int – Zero during burn-in, otherwise one. When enabled, native leg collection records only the first observation per iteration/trial/sample/day, using the leg-level reporting price, including for sold-out legs. Multi-cabin legs use their leg price without cabin capacity sharing. Optional path collection records paired total and effective reference-class thresholds per cabin for bid-price-controlled carriers. Both prices share one count; the reference is the lowest-decision-price class with a finite positive adjusted fare. Zero is allowed for bp_loose only when the total bid price is zero within 1e-9.

Raises:

RuntimeError – Native leg collection is enabled and the day is outside the DCP horizon, or the collection horizon changed after accumulator allocation.

record_dcp_statistics()

Record the statistics for a DCP.

Call this at each DCP. After the burn period, each leg’s displacement cost is added to its carrier’s displacement cost trace, and the demand still to come in each segment to the summary returned by summary_demand_to_come.

Parameters:
days_prior : int

The DCP’s days prior to departure.

Returns:

int – 0 during the burn period, otherwise 1.

record_departure_statistics()

Record the statistics for the departure that just finished.

Call this after the sample’s events are processed, before the counters are reset. After the burn period, each leg’s load factor is added to its carrier’s load factor distribution, cabin histories are captured, each carrier’s sales are added to its carrier history (and demand history if it is captured), and each fare’s sales are added to its carrier’s fare class distribution.

Returns:

int – 0 during the burn period, otherwise 1.

reseed()

Reseed all the random number streams.

The main generator is seeded with the arguments, and each other stream (see get_random_generator) with the arguments plus its stream number, so the streams stay independent.

Parameters:
*seed : int

The seed values, passed to Generator.seed as a tuple.

reset_counters()

Reset the counters for a new sample.

This resets the sales counters of every carrier, demand, fare, leg, market and path (see their reset_counters), sets last_dcp to 999, and clears the choice set data. Legs count the sample toward their grand totals if it is after the burn period.

Returns:

int – Always 0.

Raises:

RuntimeError – If the event queue is not empty.

reset_trial_counters()

Reset the counters and forecasts for a new trial.

This clears the trial counters of fares and demands, the carriers’ bookings by segment, the non-bookings by segment, the bid price statistics, and the forecasts and bid prices of every leg, bucket, path and path class.

Returns:

str – A confirmation message.

Raises:

RuntimeError – If the event queue is not empty.

revenue

Total revenue for the simulation (not currently used).

It is reset by reset_counters but nothing adds to it, so it stays 0. Use the carriers’ revenue instead. Read-only.

rm_start_sample

The sample at which the RM steps start running.

Untruncation and forecasting need some history before they work, so RM steps skip samples before this one. The default is 10. Setting it requires a non-negative int.

sample

The current sample number within the trial.

The driver sets it for each sample. Statistics are only collected once it reaches burn_samples. Setting it requires a non-negative int.

save_all_offers

Whether to save all offers, including unavailable ones.

Setting it uses the truth value of what is assigned.

save_orders

Whether to save order data on each path.

The orders are needed for classless continuous pricing, which saves them whether or not this is set; see Path.get_orders. Setting it uses the truth value of what is assigned.

save_timeframe_details

Whether to save timeframe details (not currently used).

Setting it uses the truth value of what is assigned.

set_parm()

Set a simulation parameter by name.

This lets a loader pass parameter values without knowing each one. The names are "max_connect_time", "num_trials", "num_samples", "burn_samples", "sys_k_factor", "mkt_k_factor", "tf_k_factor", "pax_type_k_factor", "tf_z_factor" and "controller_time_zone" (as for the properties of the same names), and these flags, which are True when value is above 0.001: "collect_path_bid_prices", "collect_leg_bid_prices", "prorate_revenue", "disable_ap", "save_timeframe_details", "manual_paths", "generate_3seg" (or "use_3seg"), "capture_choice_set", "capture_demand_history", "save_orders", "save_all_offers" and "dedupe_offers". Turning off bid price collection also clears the collected statistics. "min_connect_time" and the "debug_..." names are accepted and ignored.

Parameters:
name : str

The parameter name.

value : float

The value.

Returns:

str – Always "Set parm".

Raises:

TypeError – If name is not a str or not known, or max_connect_time is negative.

shop()

Shop a market, as competitive fare data services do.

The offers available to the first demand in the market are found and stored as the market’s competitor offers, which the contextual optimizer uses. The returned list of lowest fares is currently never filled in, so it is always empty.

Parameters:
orig : str

Origin airport code.

dest : str

Destination airport code.

Returns:

list[tuple[str, float]] – Meant to be (carrier, lowest fare) pairs; currently always empty.

Raises:

TypeError – If orig or dest is not a str.

snapshot_filters

The snapshot filters for debugging output, or None.

The driver stores them here. Setting it to None or an empty sequence clears them.

summary_demand_to_come()

Statistics of the demand still to come at each DCP, by segment.

record_dcp_statistics adds the demand still to come in each segment at each DCP after the burn period.

Returns:

dict[str, dict[int, dict[str, float]]] – Keyed by segment, then by DCP days prior. Each value has the keys "mean" and "stdev" (the sample standard deviation).

sys_k_factor

The system-level k-factor for demand variation.

This is stored on the engine but not used by the core; the driver reads the value from its configuration. Setting it requires a number from 0 to 5; other values raise TypeError.

tf_k_factor

The timeframe k-factor, which controls the variance of passenger arrivals.

The driver passes it to allocate_demand_to_tf_pods. Setting it requires a non-negative number; other values raise TypeError.

tf_z_factor

The z-factor for timeframe demand variation in allocate_demand_to_tf_pods.

The default is 2.0. Setting it requires a number from 0 to 100; other values raise TypeError.

trial

The current trial number.

The driver sets it at the start of each trial; it is recorded with the carrier, demand and forecast histories. Setting it requires a non-negative int.

validate_license()

Check that this build and the license are valid.

The build itself must not have expired. If no license certificate is given, the one from the passengersim_license package is used if it is installed. Without a license, the network is limited to 10 legs. With one, the certificate must be within its validity dates and issued for this build, and it sets the maximum number of legs.

Parameters:
user_cert : cryptography.x509.Certificate, optional

The license certificate. False means no license.

future : int, default 0

Check as if this many days in the future, for testing expiry.

Raises:

LicenseError – If the build or the license has expired or is not yet valid, the network has more than 10 legs without a license, or future is negative.

write_to_firehose()

Write a message to a firehose topic.

Nothing is written if the topic is not attached (see attach_firehose_logger). No newline is added.

Parameters:
topic : str

The topic. This is positional-only.

message : str or bytes

The message. If more arguments are given, a str message is formatted with them using str.format. This is positional-only.

*args

Arguments for formatting the message.

**kwargs

Arguments for formatting the message.

Raises:
  • TypeError – If topic or message is missing, topic is not a str, or message is neither a str nor bytes.

  • ValueError – If topic is not known.