Leg

class passengersim.core.Leg

Bases: object

Leg objects

Methods

__init__(*args, **kwargs)

add_bucket

Add one or more inventory control buckets to this leg.

add_cabin

Add one or more cabins to this leg.

adjust_forecast_means

Scale the forecast means of this leg's buckets by a ratio.

allocate_q_demand

Split the leg's Q demand forecast among its buckets.

avg_load_factor

Get this leg's average load factor, in percent.

avg_local

Get the percentage of this leg's passengers who were local.

bucket_number

Get one of this leg's buckets.

capture_dcp

Record booking history for this leg at a data collection point (DCP).

clear_forecast_means_adjustment

Remove the forecast mean multiplier from all of this leg's buckets.

combine_forecasts

Combine each bucket's Y and Q forecasts into a total forecast.

compute_conditional_q_forecast

Compute the leg-level conditional Q (priceable) demand forecast.

compute_fare_adjustments

Compute the adjusted fares for this leg's buckets.

compute_forecasts

Compute the yieldable (Y) demand forecast for each of this leg's buckets.

compute_hybrid_forecasts

Compute the hybrid forecasts for this leg: Y for each bucket, and Q for the leg.

compute_simple_fare_adjustments

Compute the raw adjusted fares and sell-up probabilities for this leg's buckets.

detruncate_demand

Untruncate (detruncate) the historical demand for this leg's buckets.

emsrb

Set booking limits on this leg's buckets using EMSR-b.

emsrc

Compute the EMSR-c critical value and store it as the leg's bid price.

get_bid_price_array

Get a copy of the bid price array for this leg.

get_bucket_auth

Get the authorization (booking limit) for one of this leg's buckets.

get_bucket_fcst_mean

Get the forecast demand mean for one of this leg's buckets.

get_bucket_fcst_revenue

Get the forecast revenue for one of this leg's buckets.

get_bucket_fcst_std_dev

Get the forecast demand standard deviation for one of this leg's buckets.

get_bucket_revenue

Get the revenue from sales in one of this leg's buckets.

get_bucket_sold

Get the number of seats sold in one of this leg's buckets.

get_cabin

Get one of this leg's cabins by position.

get_forecast_data

Get this leg's bucket forecasts and booking history as tables.

get_num_buckets

Get the number of buckets on this leg.

get_num_cabins

Get the number of cabins on this leg.

info

Get a short description of this leg.

littlewood

Compute a protection level using Littlewood's rule.

new_forecast

Create a new ForecastGroup that follows this leg.

next_departure

Move this leg's history buffers on to the next departure.

print_bucket_detail

Get a table of this leg's buckets, for debugging.

print_bucket_history

Print the booking history of one of this leg's buckets, for debugging.

reset_counters

Reset this leg's sales counters for a new sample.

sales_by_demand

Get the seats sold on this leg, broken down by demand.

set_bid_price_array

Set the bid price array for this leg.

set_bucket_auth

Set the authorization (booking limit) for one of this leg's buckets.

set_bucket_blank_value

Set the default value of one of this leg's buckets.

set_bucket_fcst_mean

Set the forecast demand mean for one of this leg's buckets.

set_bucket_fcst_revenue

Set the forecast revenue for one of this leg's buckets.

set_bucket_fcst_std_dev

Set the forecast demand standard deviation for one of this leg's buckets.

set_bucket_revenue

Set the revenue from sales in one of this leg's buckets.

set_bucket_sold

Set the number of seats sold in one of this leg's buckets.

update_forecasts

Set each bucket's forecast mean and standard deviation from its total forecast.

Attributes

action_state

Direction of the leg's most recent forecast mean adjustment.

action_timestamp

Simulation time, in seconds, of the leg's most recent forecast mean adjustment.

arr_time

Arrival time, as a Unix timestamp (seconds since 1970-01-01).

arr_time_offset

Difference between local arrival time and GMT, in minutes.

bid_price

The leg-level bid price for one more seat.

bid_price_gradient

How much the scalar bid price rises per seat sold.

bp_index

Which column of the bid price array to use.

buckets

Iterator over this leg's buckets, in the order they were added.

cabins

Iterator over this leg's cabins, in the order they were added.

capacity

Total number of seats on the leg.

capacity_sharing

Whether cabin capacity sharing is used on this leg.

carrier

The carrier that operates this leg, or None if it has none.

carrier_name

The code of the carrier that operates this leg.

dep_time

Departure time, as a Unix timestamp (seconds since 1970-01-01).

dep_time_offset

Difference between local departure time and GMT, in minutes.

dest

Destination airport code.

displacement

Displacement cost of this leg.

distance

Distance of the leg, usually in nautical miles.

duration

Scheduled flight time, in minutes.

equipment

Equipment (aircraft type) code, such as "744" or "738".

flt_no

Flight number.

forecast

Access to this leg's bucket forecasts through the ForecastGroup API.

gt_capacity

Total seats offered over the departures counted in the grand totals.

gt_n

Number of departures counted in the grand totals.

gt_revenue

Grand total revenue from this leg, over all samples after burn-in.

gt_sold

Grand total of seats sold on this leg, over all samples after burn-in.

gt_sold_local

Grand total of seats sold to local passengers, over all samples after burn-in.

history

Not available on a leg.

leg_id

Integer ID for this leg.

local_revenue

Revenue from local passengers on this leg in the current sample.

local_sold

Number of seats sold to local passengers on this leg in the current sample.

num_objects

Number of Leg Python objects currently alive.

orig

Origin airport code.

pathclass_identifiers

Iterator over the identifiers of the path classes that use this leg.

q_demand

A Q-equivalent demand value stored on the leg.

q_forecast

The leg-level Q (priceable) demand forecast, or None if there isn't one.

report_bid_price

The leg-level bid price, as used for reporting.

revenue

Revenue from this leg in the current sample.

sold

Number of seats sold on this leg in the current sample.

tags

Arbitrary string metadata for the leg.

action_state

Direction of the leg’s most recent forecast mean adjustment.

This is "above" or "below" after adjust_forecast_means scales the forecasts up or down, and "none" otherwise. clear_forecast_means_adjustment sets it back to "none". Setting it requires one of those three strings (ValueError otherwise).

action_timestamp

Simulation time, in seconds, of the leg’s most recent forecast mean adjustment.

adjust_forecast_means uses it to enforce its minimum number of days between adjustments. It is 0 if there hasn’t been one. clear_forecast_means_adjustment sets it back to 0. Setting it requires a non-negative number.

add_bucket()

Add one or more inventory control buckets to this leg.

Each bucket is appended to the leg’s list of buckets, in the order given, and linked to this leg’s carrier. It is also added to the leg’s cabin whose name matches the bucket’s cabin, so that cabin must already have been added with add_cabin. RM steps such as EMSR-b expect the buckets to be added from the highest value to the lowest.

Parameters:
*buckets : Bucket

The buckets to add. This is positional-only.

Returns:

int – Always 0.

Raises:
  • TypeError – If any argument is not a Bucket.

  • RuntimeError – If a bucket’s cabin is not on this leg. The bucket (and any before it) has already been added to the leg’s list of buckets when this is raised.

add_cabin()

Add one or more cabins to this leg.

The cabins are appended to the leg’s list of cabins, in the order given. Add a cabin before adding any buckets that belong to it.

Parameters:
*cabins : Cabin

The cabins to add. This is positional-only.

Returns:

int – Always 0.

Raises:

TypeError – If any argument is not a Cabin.

adjust_forecast_means()

Scale the forecast means of this leg’s buckets by a ratio.

This works through each bucket’s forecast mean multiplier (see get_bucket_fcst_mean), so the stored base forecasts don’t change and clear_forecast_means_adjustment can undo it. The multiplier scales the forecast standard deviation as well as the mean.

  • If stack is True, ratio multiplies any multiplier already in place. If it is False, existing multipliers are cleared first.

  • If minimum_days_between_adjustments is positive and fewer than that many days have passed since the leg’s last adjustment, nothing is changed.

  • A ratio of 1.0 changes nothing when stack is True. When stack is False it just clears any multipliers, without the minimum days check.

After an adjustment with a ratio other than 1.0, the leg records current_simulation_time as its action_timestamp, and sets its action_state to above or below depending on whether ratio is above 1.

Parameters:
ratio : float

The factor to scale the forecast means by.

current_simulation_time : float, default 0.0

The current simulation time, in seconds.

minimum_days_between_adjustments : int, default 0

The minimum number of days between adjustments. Zero means no minimum.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

stack : bool, default True

Whether to apply ratio on top of existing multipliers.

Returns:

int – 1 if any multiplier changed, otherwise 0.

allocate_q_demand()

Split the leg’s Q demand forecast among its buckets.

This takes the leg-level Q forecast, for example from compute_conditional_q_forecast. For each timeframe from the last back to dcp_index, the buckets are sorted from the highest fare to the lowest, and each gets a share of the leg’s Q demand equal to its increase in sell-up probability over the next higher bucket. The sell-up probabilities are the ones cached by compute_simple_fare_adjustments (or compute_fare_adjustments). A bucket gets no share in a timeframe if its adjusted fare is not positive, or it is closed by an advance purchase restriction. Timeframes before dcp_index are set to zero. The results are stored in each bucket’s Q forecast.

Parameters:
frat5 : Frat5

The Frat5 curve. This is required.

dcp_index : int, default 0

The first DCP index to allocate.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

allocation_algorithm : str, optional

How to build each bucket’s standard deviation to departure. A string containing "tf" allocates the variance within each timeframe and rolls it up. A string containing "dep" scales the leg’s variance to departure directly. The default is "tf". This is keyword-only.

Raises:
  • TypeError – If frat5 is not a Frat5.

  • IndexError – If dcp_index is negative or beyond the leg’s Q forecast.

  • ValueError – If allocation_algorithm is not recognized.

  • RuntimeError – If the leg has no Q forecast, a bucket has no history or no cached sell-up probabilities, or the allocated total does not match the leg’s Q demand.

arr_time

Arrival time, as a Unix timestamp (seconds since 1970-01-01).

It reads as a float, but setting it requires a non-negative int.

arr_time_offset

Difference between local arrival time and GMT, in minutes.

Setting it requires an int.

avg_load_factor()

Get this leg’s average load factor, in percent.

This is the grand total of seats sold, divided by the capacity and by the number of departures counted (both after burn-in), times 100.

Returns:

float – The average load factor, in percent. This is NaN or infinite if no departures have been counted yet.

avg_local()

Get the percentage of this leg’s passengers who were local.

Local passengers are those whose whole trip is this one leg, with no connection. This uses the grand totals after burn-in.

Returns:

float – Local seats sold as a percentage of all seats sold. This is NaN if no seats have been sold yet.

bid_price

The leg-level bid price for one more seat.

When read, the value depends on whether the leg has a bid price array (see set_bid_price_array):

  • With an array, it is the entry at row sold and column bp_index. It is 9.999e9 if the leg is full, and 0 if bp_index is past the last column.

  • Without one, it is the stored scalar bid price plus bid_price_gradient (the bid price of one seat).

With more than one cabin, this is the leg’s own bid price, not a cabin’s.

Setting it stores the scalar bid price, which must be non-negative. This is not allowed (ValueError) once the leg has a bid price array. Because of the gradient, reading it back gives the value set plus bid_price_gradient. emsrc also sets it.

bid_price_gradient

How much the scalar bid price rises per seat sold.

After each sale, the core adds this gradient times the number of seats sold to the scalar bid price, and bid_price includes one seat’s worth of it. ProBP can set it. It has no effect while the leg has a bid price array. Setting it requires a non-negative number.

bp_index

Which column of the bid price array to use.

This is normally the current timeframe (DCP index). Callers that store a single column, as ProBP does, leave it at 0. Past the last column, the bid price is 0. Setting it requires a non-negative int.

bucket_number()

Get one of this leg’s buckets.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

Bucket – The bucket. It shares its data with the leg, so changes made through it affect this leg.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

buckets

Iterator over this leg’s buckets, in the order they were added.

Read-only. Use add_bucket to add buckets.

cabins

Iterator over this leg’s cabins, in the order they were added.

Read-only. Use add_cabin to add cabins.

capacity

Total number of seats on the leg.

With cabins, a sale is limited by the seats left on both the leg and the cabin (except with capacity_sharing, where Y-cabin bookings can use any seat left on the leg). reset_counters also resets each bucket’s authorization to this capacity. Setting it requires a non-negative int.

capacity_sharing

Whether cabin capacity sharing is used on this leg.

This only matters when the leg has more than one cabin. When it is True:

  • Y-cabin bookings can use any seat left on the leg, not just the Y cabin’s seats.

  • Bid prices follow the PODS “effective bid price” rule. For the Y cabin, the bid price is the lower of the cabin and leg bid prices, or just the leg bid price once the Y cabin itself is full. For other cabins, it is the higher of the two.

Setting it accepts any value and uses its truth value.

capture_dcp()

Record booking history for this leg at a data collection point (DCP).

The simulation driver calls this for every leg at each DCP. It closes out the timeframe that just ended and starts the next one in each bucket’s history buffer for the current departure.

For each bucket on the leg, the core:

  • Records the bucket’s cumulative sold and sold_priceable counts for the timeframe that is ending.

  • Records whether the bucket was closed. A bucket counts as closed if it was forced closed, its allocation is zero or less, the leg is sold out, or (for carriers using bid price controls) its price is below the leg or cabin bid price. Under strict bid price control a price equal to the bid price also counts as closed; under loose control it does not. Those closure flags are what demand untruncation later uses to decide which observations were constrained.

  • If the leg is sold out and dcp_index is greater than zero, marks the previous timeframe as closed as well.

If the carrier stores Q (priceable) history, the core also converts this leg’s priceable sales into Q-equivalent demand using the carrier’s Frat5 curve, and stores that in the leg-level Q history. If the Frat5’s max_cap is not set, a default cap of 10 is used and a warning is printed.

Parameters:
dcp_index : int

Index of the DCP being captured (0 is the first DCP of the booking horizon). This is positional-only.

Raises:
  • IndexError – If dcp_index is negative.

  • RuntimeError – If a bucket has no history buffer, if the carrier stores Q history but has no Frat5 curve, if Q history is requested for a classless carrier, or another error occurs in the core.

carrier

The carrier that operates this leg, or None if it has none.

Read-only; it is set when the Leg is constructed.

carrier_name

The code of the carrier that operates this leg.

This is "??" if the leg has no carrier. Read-only.

clear_forecast_means_adjustment()

Remove the forecast mean multiplier from all of this leg’s buckets.

This undoes adjust_forecast_means: each bucket’s forecast mean and standard deviation go back to their base values. It also resets the leg’s action_state to none and its action_timestamp to 0.

Parameters:
snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

combine_forecasts()

Combine each bucket’s Y and Q forecasts into a total forecast.

For each bucket and each timeframe, the total forecast mean is the sum of the Y and Q forecast means. The Q part is left out where the bucket has a raw adjusted fare that is zero or less, and the total is zero once the bucket is closed by an advance purchase restriction. How the standard deviations combine depends on rollup_algorithm. The total forecast becomes the bucket’s active forecast. This does not change the buckets’ forecast mean and standard deviation; use update_forecasts for that.

Parameters:
dcp_index : int, default 0

Accepted but currently unused; all timeframes are combined.

rollup_algorithm : str, optional

A string containing "tf" adds the Y and Q variances within each timeframe, then rolls them up to departure. A string containing "dep" rolls up the Y and Q variances to departure separately, then adds them. The default is "tf". This is keyword-only.

snapshot_instruction : SnapshotInstruction or bool, optional

Accepted but currently unused. This is keyword-only.

Raises:

ValueError – If a bucket has no Y or Q forecast, or rollup_algorithm is not recognized.

compute_conditional_q_forecast()

Compute the leg-level conditional Q (priceable) demand forecast.

Working back from the last timeframe to dcp_index, the core takes the priceable sales in every bucket for each historical departure and converts them to Q-equivalent demand using the sell-up probabilities from frat5 (inflating by the inverse sell-up probability, capped at max_cap if it is set). When a timeframe has no sales at all, the lowest open bucket is assumed to be where sales would have happened. A regression over all the departures and buckets then gives the leg’s Q demand mean for the timeframe, and its mean squared error gives the standard deviation, unless variance_is_ratio_of_mean is set.

The results are stored in the leg’s own Q forecast, as means and standard deviations in each timeframe and to departure. They are not assigned to the buckets; use allocate_q_demand for that.

Parameters:
frat5 : Frat5

The Frat5 curve that gives the sell-up probabilities.

dcp_index : int, default 0

The first DCP index to forecast. Earlier timeframes are set to zero.

regression_weight : {'sellup', 'sellup^2', 'fare', 'none'} or None, optional

How to weight the regression: by the inverse sell-up probability, by its square, or by fare. None or "none" means no weighting, which is the default.

max_cap : float, default 0.0

The cap on the inverse sell-up probability used to inflate sales. Zero means no cap. This is keyword-only.

snapshot_instruction : SnapshotInstruction or bool, optional

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

partial_tf_weight_adjustment : bool, default False

If True, adjust the regression weights for the fraction of each timeframe in which each bucket was the lowest open one. This is keyword-only.

variance_is_ratio_of_mean : float, default 0.0

If nonzero, the variance in each timeframe is set to this value times the mean, instead of coming from the regression error. This is keyword-only.

Raises:
  • TypeError – If frat5 is not a Frat5.

  • ValueError – If regression_weight is not recognized, the leg has no buckets, or the number of timeframes in the history does not match frat5.

  • IndexError – If dcp_index is out of range, or the buckets’ history has no stored departures.

compute_fare_adjustments()

Compute the adjusted fares for this leg’s buckets.

This first calls compute_simple_fare_adjustments to get the raw adjusted fares (reusing them if they were already computed). Then, for each DCP and each bucket from the highest down, it sets the bucket’s adjusted fare. On a leg, a bucket’s fare is its forecast revenue.

  • The highest bucket keeps its fare.

  • Every other bucket gets its raw adjusted fare. If weighted_by_ratio is True, this is instead blended with the unadjusted fare, weighted by the bucket’s Q and Y demand forecasts to departure at that DCP: (raw * Q + fare * Y) / (Q + Y). If both forecasts are zero, the raw adjusted fare is used.

  • Adjusted fares are never negative, and are NaN once the bucket is closed by an advance purchase restriction.

Parameters:
algorithm : {'MR', 'mr', 'KI', 'ki'} or None

The fare adjustment method: marginal revenue ("MR") or "KI". If None, all adjusted fares are cleared and nothing else is done.

frat5 : Frat5

The Frat5 curve used for the adjustment. Required even when algorithm is None.

scale_factor : float, default 1.0

Scaling factor passed on to the raw fare adjustment.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

sort_pathclasses : bool, default True

If True, first sort the buckets by forecast revenue, from highest to lowest. This is keyword-only.

weighted_by_ratio : bool, default True

Whether to blend each raw adjusted fare with the unadjusted fare, as described above. If True, every bucket must already have both a Q and a Y forecast. This is keyword-only.

Raises:
  • TypeError – If frat5 is not a Frat5.

  • ValueError – If algorithm is not recognized.

  • RuntimeError – If weighted_by_ratio is True and a bucket has no Q or Y forecast.

compute_forecasts()

Compute the yieldable (Y) demand forecast for each of this leg’s buckets.

For each bucket, the core creates a Y forecast from the bucket’s booking history if there isn’t one yet. If recompute is True, it then runs the chosen forecasting algorithm on that history for the timeframes from dcp_index to departure, taking any advance purchase restriction on the bucket into account. Whether or not it recomputes, it then sets the bucket’s forecast mean and standard deviation (see get_bucket_fcst_mean) to the Y forecast’s mean and standard deviation of demand to departure at dcp_index, or zero if there is no value there. These are the unmultiplied values; any forecast mean multiplier stays in effect.

Parameters:
dcp_index : int

The DCP index to forecast from.

algorithm : {'exp_smoothing', 'additive_pickup'} or None, optional

The forecasting algorithm. Required if recompute is True, and ignored otherwise.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

recompute : bool, default False

If True, recompute the forecasts from history. If False, only refresh each bucket’s forecast mean and standard deviation from its existing forecast at dcp_index.

alpha : float, default 0.15

Smoothing factor for exponential smoothing. This is keyword-only.

event_time : int, optional

Accepted but currently unused. This is keyword-only.

which_data : str, optional

Which sales to forecast from: a string containing "tot" (or exactly "all") for total sales, "price" for priceable sales, or "yield" for yieldable sales. None or "none" also mean total sales, which is the default. This is keyword-only.

return_vectors : bool, default False

If True, return each bucket’s forecast vectors. This is mostly used for debugging and testing. This is keyword-only.

Returns:

None or dict[str, ForecastVectors] – None, unless return_vectors is True. Then a dictionary mapping each bucket’s booking class to its forecast vectors: the mean and standard deviation in each timeframe and to departure, and the closure probabilities. These come from the bucket’s active forecast, which is its total (hybrid) forecast if it has one, and otherwise its Y forecast.

Raises:
  • ValueError – If recompute is True and algorithm is missing or unknown, or if which_data is not recognized.

  • TypeError – If which_data is not a string, or snapshot_instruction is neither a bool nor a SnapshotInstruction.

compute_hybrid_forecasts()

Compute the hybrid forecasts for this leg: Y for each bucket, and Q for the leg.

Hybrid forecasting splits demand in two. Yieldable demand, from customers who want a particular product, is forecast for each bucket from its yieldable sales history. Priceable demand, from customers who buy the cheapest product available, is forecast for the leg as a whole from the leg’s Q-equivalent history (see capture_dcp).

For each bucket, the core creates a Y forecast if there isn’t one yet, caches the sell-up probabilities from frat5 if they are not cached yet, and runs algorithm on the yieldable history for the timeframes from dcp_index to departure. It then runs algorithm on the leg’s Q forecast using the priceable history. Use allocate_q_demand to split the Q forecast among the buckets, and combine_forecasts to combine the two.

Parameters:
dcp_index : int

The DCP index to forecast from.

algorithm : {'exp_smoothing', 'additive_pickup'}

The forecasting algorithm.

frat5 : Frat5

The Frat5 curve for the sell-up probabilities.

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.

recompute : bool, default True

Accepted but currently unused; the forecasts are always recomputed.

pods_init : bool, default False

Accepted but currently unused.

alpha : float, default 0.15

Smoothing factor for exponential smoothing. This is keyword-only.

debug : object, optional

Accepted but currently unused. This is keyword-only.

Raises:
  • TypeError – If algorithm is not a str or frat5 is not a Frat5.

  • ValueError – If algorithm is not recognized.

  • IndexError – If dcp_index is past the last timeframe of the Q history.

  • RuntimeError – If the leg has no Q forecast, or another error occurs in the core.

compute_simple_fare_adjustments()

Compute the raw adjusted fares and sell-up probabilities for this leg’s buckets.

For each DCP in frat5, the core works through the buckets from the highest down. On a leg, a bucket’s fare is its forecast revenue. The highest bucket’s raw adjusted fare is its fare. Each lower bucket’s raw adjusted fare comes from the Frat5 curve’s fare adjustment, relative to the lowest fare on the leg. Once a bucket is closed by an advance purchase restriction, its raw adjusted fare is NaN. Along the way, the core also caches each bucket’s sell-up probability (from frat5, relative to the lowest fare), which allocate_q_demand needs.

The raw adjusted fares are computed only once: if every bucket already has a value for each DCP, nothing is recomputed. To force a new calculation, first call this with algorithm set to None.

Parameters:
algorithm : {'MR', 'mr', 'KI', 'ki'} or None

The fare adjustment method: marginal revenue ("MR") or "KI". If None, the raw adjusted fares are cleared, and only the sell-up probabilities are computed.

frat5 : Frat5

The Frat5 curve used for the adjustment and the sell-up probabilities.

scale_factor : float, default 1.0

Scaling factor applied to the fare adjustment.

snapshot_instruction : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

Raises:
  • TypeError – If frat5 is not a Frat5.

  • ValueError – If algorithm is not recognized.

dep_time

Departure time, as a Unix timestamp (seconds since 1970-01-01).

It reads as a float, but setting it requires a non-negative int.

dep_time_offset

Difference between local departure time and GMT, in minutes.

Setting it requires an int.

dest

Destination airport code.

Read-only; it is set when the Leg is constructed.

detruncate_demand()

Untruncate (detruncate) the historical demand for this leg’s buckets.

Sales recorded while a bucket was closed understate the true demand, because some customers were turned away. Untruncation estimates what demand would have been in those constrained observations, and stores the result in a “detruncated” history that forecasting can use in place of the raw sales.

What the core does depends on algorithm:

  • "em" (or "EM"): for each bucket, and separately for each timeframe, runs the Expectation-Maximization algorithm across the stored departures. Departures where the bucket was closed are treated as censored observations of a normal distribution. EM estimates that distribution’s mean and standard deviation, and replaces each censored value with its expected value given that demand was at least the sales observed (never less than the sales themselves). When only one or two departures were open in a timeframe, EM is skipped and each closed value is raised to the mean of the open ones instead. If the history holds fewer than 3 departures, nothing is done.

  • "external": no calculation is done. The detruncated history is taken directly from external (see below).

  • Any other name (for example "none"): nothing is done.

Parameters:
dcp_index : int

The DCP index at which untruncation is being run. This is required but is currently not used by the core, which processes every timeframe.

algorithm : str

The untruncation algorithm, as described above.

snapshot_instruction : SnapshotInstruction, optional

If given, and it is triggered, the EM working is written to the snapshot output.

maxiter : int, default 20

Maximum number of EM iterations for each timeframe.

tolerance : float, default 0.01

EM stops once the estimated mean changes by less than this fraction between iterations.

pods_initialization : bool, default False

Use the PODS method to choose the EM starting values.

minimum_mu : float, default 0.01

If the estimated mean falls below this value, closed observations in that timeframe are left at their observed sales.

minimum_sigma : float, default 0.1

Lower limit for the estimated standard deviation.

which_data : str, optional

Which sales history to untruncate. The value is matched as follows: containing "tot" or equal to "all" means total sales; containing "price" means priceable sales; containing "yield" means yieldable sales. For priceable sales, only the leg-level Q forecast history is untruncated, not the buckets.

If omitted (or None or "none"), no data type is selected and "em" does no untruncation: the detruncated history just equals the raw sales. In practice this argument should always be given.

external : dict or numpy.ndarray, optional

Detruncated history to store directly when algorithm is "external"; it must not be given for any other algorithm. When which_data is priceable, it is a 2-D array of floats for the leg-level Q history. Otherwise it is a dict mapping each bucket’s booking class to a 2-D array of floats. Each value must be a NumPy float array with one row per stored departure and one column per timeframe, matching the shape of the corresponding history.

Raises:
  • ValueError – If which_data is not recognized; if external is missing when algorithm is "external" or given when it is not; if external is missing a booking class or an array has the wrong shape; or if priceable data is requested but the history does not store it.

  • TypeError – If which_data is not a string, external is not a dict when one is required, or an external array is not a NumPy array of floats.

  • RuntimeError – If priceable data is requested but the leg has no Q forecast, or another error occurs in the core.

displacement

Displacement cost of this leg.

It is used for displacement-adjusted fares (UDP): on a connecting path, the fare used for one leg is reduced by the displacement of the path’s other legs. Setting it requires a non-negative number.

distance

Distance of the leg, usually in nautical miles.

When a carrier prorates the revenue of connecting itineraries by distance, the core uses this to split the revenue across the legs. Setting it requires a non-negative number.

duration

Scheduled flight time, in minutes.

This is informational: where the core needs elapsed time (for example in the choice model), it works it out from dep_time and arr_time instead. It reads as a float, but setting it requires a non-negative int.

emsrb()

Set booking limits on this leg’s buckets using EMSR-b.

The buckets are treated as ordered from highest to lowest value, in the order they were added. Working down the list, for each bucket the core combines the forecasts of that bucket and all the buckets above it into a single normal demand (summing the means and the variances) with a demand-weighted average fare (from forecast revenue). It then uses Littlewood’s rule against the next bucket’s forecast revenue to find how many seats to protect for that group. Protection never decreases going down the list. If the next bucket’s forecast revenue is zero or less, all the remaining seats are protected.

Each bucket’s protection level is stored, and its authorization (see get_bucket_auth) becomes the leg capacity minus the seats already sold minus the protection for the buckets above it, but not less than zero. The last bucket gets whatever is left. A bucket with a positive forecast mean but a forecast revenue of zero or less gets an authorization of zero.

Parameters:
forecast_group : ForecastGroup, optional

If given, the forecast means, variances and prices are taken from this forecast group’s class forecasts instead of from the buckets. It must have exactly the same booking classes as this leg’s buckets.

debug : SnapshotInstruction or bool, optional

Controls debugging output. If True, a trace of the calculation is written to standard output; if a SnapshotInstruction, the trace is written as it directs.

Raises:
  • TypeError – If forecast_group is not a ForecastGroup, or debug is neither a bool nor a SnapshotInstruction.

  • RuntimeError – If the leg has no buckets, or the booking classes in forecast_group do not match this leg’s buckets.

emsrc()

Compute the EMSR-c critical value and store it as the leg’s bid price.

Over the buckets that are currently open (authorization above zero), the core forms a single normal demand (summing the forecast means and variances) with a demand-weighted average fare (from forecast revenue). The critical value is that fare times the chance that this demand exceeds the leg capacity. If the standard deviation is zero, 0.3 + mean is used in its place. If the critical value is NaN or below 0.1, the forecast revenue of the lowest open bucket is used instead. The result is written to bid_price as well as returned.

Parameters:
debug : bool, default False

If True, print the intermediate values to standard output.

Returns:

float – The EMSR-c critical value.

equipment

Equipment (aircraft type) code, such as "744" or "738".

This is only a label; the core does not use it. Setting it requires a str.

flt_no

Flight number.

An integer, not limited to 4 digits. Setting it requires an int.

forecast

Access to this leg’s bucket forecasts through the ForecastGroup API.

This works on the buckets’ own forecasts, unlike new_forecast, which creates a separate forecast group. Read-only.

get_bid_price_array()

Get a copy of the bid price array for this leg.

The bid price array has one row per number of seats already sold (from 0 up to at least the leg capacity) and one column per timeframe (DCP). The core reads the bid price for the next sale from row sold and column bp_index. It reports a very large sentinel (9.999e9) when not enough seats are left, and zero when bp_index is past the last column. The array is created by bid price RM steps such as ProBP, or by set_bid_price_array.

Changing the returned array does not change the leg; use set_bid_price_array to store new values.

Returns:

numpy.ndarray of float, shape (n_rows, n_dcps) – A new array holding a copy of the leg’s bid prices.

Raises:

ValueError – If the leg has no bid price array.

get_bucket_auth()

Get the authorization (booking limit) for one of this leg’s buckets.

A request for some number of seats in this bucket’s booking class can be accepted on this leg only if the bucket’s authorization is at least that number (and the leg has that many seats left). An authorization of zero or less means the bucket is closed. RM steps such as EMSR-b set it, and reset_counters sets it back to the leg capacity.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

int – The bucket’s authorization.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_bucket_fcst_mean()

Get the forecast demand mean for one of this leg’s buckets.

This is the mean of the bucket’s demand forecast from “now” until departure, where “now” is the most recent DCP, or the time of the most recent forecast adjustment if one has been applied since then. It is stored on the bucket, not looked up in the forecast vectors, so forecast adjustments can change it.

If a forecast mean multiplier has been applied to the bucket (for example by a forecast adjustment user action), the returned value includes that multiplier.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

float – The bucket’s forecast demand mean.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_bucket_fcst_revenue()

Get the forecast revenue for one of this leg’s buckets.

The forecast revenue is the revenue value per passenger that leg-level optimization uses for the bucket. EMSR-b uses it as the bucket’s fare when it builds the demand-weighted average fare of the buckets above each protection level. It starts at zero and is set either by the carrier’s RM steps or by set_bucket_fcst_revenue.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

float – The bucket’s forecast revenue.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_bucket_fcst_std_dev()

Get the forecast demand standard deviation for one of this leg’s buckets.

This is the standard deviation of the bucket’s demand forecast from “now” until departure; see get_bucket_fcst_mean. Like the mean, it is stored on the bucket so forecast adjustments can change it.

If a forecast mean multiplier has been applied to the bucket (for example by a forecast adjustment user action), the returned value includes that multiplier. The multiplier scales the standard deviation by the same factor as the mean.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

float – The bucket’s forecast demand standard deviation.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_bucket_revenue()

Get the revenue from sales in one of this leg’s buckets.

This is the bucket’s total revenue in the current sample: each sale adds the revenue allocated to this leg times the number of seats sold. reset_counters sets it back to zero.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

float – The bucket’s revenue.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_bucket_sold()

Get the number of seats sold in one of this leg’s buckets.

This is the bucket’s count of seats sold in the current sample. reset_counters sets it back to zero.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

Returns:

int – The number of seats sold.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

get_cabin()

Get one of this leg’s cabins by position.

Parameters:
index : int

The zero-based position of the cabin, in the order the cabins were added. This is positional-only.

Returns:

Cabin – The cabin. It shares its data with the leg, so changes made through it affect this leg.

Raises:

IndexError – If index is out of range.

get_forecast_data()

Get this leg’s bucket forecasts and booking history as tables.

This calls the function registered with _set_func_get_forecast_data, passing this leg first and then any arguments given here. The default function returns a ForecastData object. It holds DataFrames, indexed by timeframe and with one column per booking class, of the forecast mean and standard deviation in each timeframe and to departure. It also holds each bucket’s average priceable and yieldable sales and closures from its history, and the carrier’s DCP days prior.

Parameters:
*args

Passed on to the registered function. The default function takes none.

**kwargs

Passed on to the registered function. The default function takes none.

Returns:

ForecastData – The forecast data, when the default function is registered.

Raises:
  • Exception – If no function is registered.

  • ValueError – With the default function, if the leg’s carrier has no DCP days prior.

get_num_buckets()

Get the number of buckets on this leg.

Returns:

int – The number of buckets, across all cabins.

get_num_cabins()

Get the number of cabins on this leg.

Returns:

int – The number of cabins.

gt_capacity

Total seats offered over the departures counted in the grand totals.

This is gt_n times capacity. Read-only.

gt_n

Number of departures counted in the grand totals.

The simulation adds one for each sample after burn-in. Setting it requires a non-negative int.

gt_revenue

Grand total revenue from this leg, over all samples after burn-in.

reset_counters does not change it. Setting it requires a non-negative number.

gt_sold

Grand total of seats sold on this leg, over all samples after burn-in.

reset_counters does not change it. Setting it requires a non-negative int.

gt_sold_local

Grand total of seats sold to local passengers, over all samples after burn-in.

See local_sold. reset_counters does not change it. Setting it requires a non-negative int.

history

Not available on a leg.

Reading it always raises AttributeError, because booking history is kept on each bucket (see buckets).

info()

Get a short description of this leg.

Returns:

str – A multi-line string with the leg ID, carrier and flight number, origin and destination, capacity, duration in minutes, and departure and arrival times.

leg_id

Integer ID for this leg.

It should be unique within a simulation, since RM steps and results use it as a key. Setting it requires an int.

littlewood()

Compute a protection level using Littlewood’s rule.

This is a math helper: it does not use or change the leg. Demand for the higher fare class is treated as normal with mean mu and standard deviation sigma. The result is the number of seats to protect for it, which is the point where the chance that its demand exceeds the protection equals rev_lo / rev_hi.

The special cases are:

  • If sigma is below 0.001, 0.2 * mu is used instead.

  • If mu is 0.01 or less, the result is 0.

  • Seats are protected only when 1 < rev_lo < rev_hi. Otherwise (for example with an inverted fare pair) the result is 0.

  • The result is never negative, and a NaN result becomes 0.

Parameters:
mu : float

Mean demand for the higher fare class.

sigma : float

Standard deviation of that demand.

rev_lo : float

Revenue of the lower fare class.

rev_hi : float

Revenue of the higher fare class.

cv100 : float, optional

Accepted but currently unused.

positional-only. : All arguments are

Returns:

float – The number of seats to protect for the higher fare class.

local_revenue

Revenue from local passengers on this leg in the current sample.

See local_sold. reset_counters sets it back to zero. Setting it requires a non-negative number.

local_sold

Number of seats sold to local passengers on this leg in the current sample.

Local passengers are those whose whole trip is this one leg, with no connection. reset_counters sets it back to zero. Setting it requires a non-negative int.

new_forecast()

Create a new ForecastGroup that follows this leg.

The new forecast group has one class forecast per bucket. Each one shares its bucket’s booking history but keeps its own forecast values, so changing the group’s forecasts does not change the buckets’ forecasts. The group can be passed to emsrb to set booking limits from its forecasts.

Returns:

ForecastGroup – The new forecast group.

next_departure()

Move this leg’s history buffers on to the next departure.

History is kept in ring buffers holding a fixed number of past departures. This call finishes the current departure and makes room for the next one. SimulationEngine.next_departure calls it for every leg, so it is rarely called directly.

For each bucket’s history (and for the leg’s Q forecast history, if there is one), the core:

  • Stores zero sales and an “open” closure flag for any timeframes of the current departure that were never captured with capture_dcp.

  • Advances to the next departure slot, wrapping round to the oldest slot when the buffer is full, and resets the timeframe counter to the start of the booking horizon.

Raises:

RuntimeError – If a bucket has no history buffer, or another error occurs in the core.

num_objects

Number of Leg Python objects currently alive.

This is a count over all legs, not a property of this one. It was used to find memory leaks. Read-only.

orig

Origin airport code.

Read-only; it is set when the Leg is constructed.

pathclass_identifiers

Iterator over the identifiers of the path classes that use this leg.

It is empty until an RM step, such as ProBP, links path classes to the leg. Read-only.

print_bucket_detail()

Get a table of this leg’s buckets, for debugging.

Despite the name, this returns the table rather than printing it. The first line identifies the leg and gives its capacity, seats sold and bid price. Then there is one row per bucket with its booking class, seats sold, average revenue per seat sold, forecast mean, forecast standard deviation, forecast revenue, protection level and authorization.

Returns:

str – The formatted table.

print_bucket_history()

Print the booking history of one of this leg’s buckets, for debugging.

This prints a table to standard output with one row per DCP and one column per departure stored in the bucket’s history. Each cell is the number of seats sold in that timeframe for that departure.

Parameters:
bucket_index : int

The zero-based position of the bucket. Booking class names are not accepted. This is positional-only.

Returns:

int – Always 0.

Raises:

Exception – If bucket_index is out of range.

q_demand

A Q-equivalent demand value stored on the leg.

The core does not read or set it; it is there for RM code to use. Setting it requires a non-negative number.

q_forecast

The leg-level Q (priceable) demand forecast, or None if there isn’t one.

compute_conditional_q_forecast creates it. The returned Forecast shares its data with the leg. Read-only.

report_bid_price

The leg-level bid price, as used for reporting.

This is the same as bid_price, except when the leg has a bid price array and is full. Then, instead of the very large sentinel value, it is the bid price that applied to the most recent sale, so that it doesn’t skew average bid prices. Read-only.

reset_counters()

Reset this leg’s sales counters for a new sample.

This sets the current-sample counters (seats sold, priceable seats sold, revenue, local seats sold and local revenue) back to zero on the leg and on each of its buckets and cabins. It also resets each bucket’s authorization: first to the leg capacity, then, for buckets in a cabin, to that cabin’s capacity. The grand totals over all samples (the gt_ counters) are not changed.

revenue

Revenue from this leg in the current sample.

Each sale adds the revenue allocated to this leg times the number of seats sold. reset_counters sets it back to zero. Setting it requires a non-negative number.

sales_by_demand()

Get the seats sold on this leg, broken down by demand.

These are grand totals after burn-in. They are only recorded when the simulation is set to count leg sales by demand (the count_leg_sales_by_demand option); otherwise the result is empty.

Returns:

dict[str, int] – A dictionary mapping each demand’s identifier, in the form "ORIG~DEST@segment", to the number of seats it bought on this leg.

set_bid_price_array()

Set the bid price array for this leg.

The bid price array has one row per number of seats already sold (from 0 up to the leg capacity) and one column per timeframe (DCP). The bid price used for the next sale is read from row sold and column bp_index. Callers that only set a single timeframe, as ProBP does, can pass an array with one column and leave bp_index at 0.

Parameters:
values : array-like of float, shape (n_rows, n_dcps)

The bid prices to store. Must be two-dimensional, and every value must be non-negative (positive infinity is allowed; NaN is not).

  • If the leg already has a bid price array, values must have exactly the same shape, and its contents are copied into the existing array.

  • If the leg has no bid price array yet, a new one is created with the shape of values. It must then have at least capacity + 1 rows and at least one column.

Raises:

ValueError – If values cannot be converted to a two-dimensional array of floats, its shape does not match the existing bid price array, it is too small to create a new one, or it contains negative or NaN values.

set_bucket_auth()

Set the authorization (booking limit) for one of this leg’s buckets.

See get_bucket_auth for how the authorization is used.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

auth : int

The new authorization. This is positional-only.

Returns:

str – Always the string "Set auth".

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_blank_value()

Set the default value of one of this leg’s buckets.

This sets two values on the bucket to the same number: its forecast revenue (see get_bucket_fcst_revenue), and the “blank value” of its prorated value estimate, which is the value that estimate reports while it has no sales data.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

value : float

The new default value. This is positional-only.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_fcst_mean()

Set the forecast demand mean for one of this leg’s buckets.

This sets the stored mean of the bucket’s demand forecast from “now” until departure; see get_bucket_fcst_mean. It sets the base value and leaves any forecast mean multiplier on the bucket unchanged. So if a multiplier is active, get_bucket_fcst_mean will return value times that multiplier, not value itself.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

value : float

The new (unmultiplied) forecast demand mean. This is positional-only.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_fcst_revenue()

Set the forecast revenue for one of this leg’s buckets.

This overwrites the revenue value per passenger that leg-level optimization (such as EMSR-b) uses for the bucket; see get_bucket_fcst_revenue. It does not change the bucket’s prorated value estimate. Use set_bucket_blank_value to set both at once.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

value : float

The new forecast revenue. This is positional-only.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_fcst_std_dev()

Set the forecast demand standard deviation for one of this leg’s buckets.

This sets the stored standard deviation of the bucket’s demand forecast from “now” until departure; see get_bucket_fcst_std_dev. It sets the base value and leaves any forecast mean multiplier on the bucket unchanged. So if a multiplier is active, get_bucket_fcst_std_dev will return value times that multiplier.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

value : float

The new (unmultiplied) forecast demand standard deviation. This is positional-only.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_revenue()

Set the revenue from sales in one of this leg’s buckets.

This overwrites the bucket’s revenue counter for the current sample (see get_bucket_revenue). It does not change the bucket’s forecast revenue.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

revenue : float

The new revenue. This is positional-only.

Returns:

int – Always 0.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

set_bucket_sold()

Set the number of seats sold in one of this leg’s buckets.

This overwrites the bucket’s count of seats sold in the current sample. It does not change the leg’s own sold count. It is mostly used in unit tests.

Parameters:
bkt_ref : int or str

The bucket to use, given either as its zero-based position on the leg or as its booking class name (for example "Y"). This is positional-only.

sold : int

The new number of seats sold. This is positional-only.

Returns:

int – Always 0.

Raises:

IndexError – If bkt_ref is out of range, names a booking class that is not on this leg, or is neither an int nor a str.

sold

Number of seats sold on this leg in the current sample.

reset_counters sets it back to zero. It reads as a float, but setting it requires a non-negative int.

tags

Arbitrary string metadata for the leg.

Reading it gives a dict-like view; changes made through it update the leg. Setting it replaces all of the leg’s tags, either with a dict whose keys and values are all strings, or with another leg’s tags. If a key or value in the dict is not a string, TypeError is raised, but only after the existing tags have already been cleared.

update_forecasts()

Set each bucket’s forecast mean and standard deviation from its total forecast.

For each bucket that has both a total (hybrid) forecast and a Q forecast, the core sets the bucket’s forecast mean and standard deviation (see get_bucket_fcst_mean) to the total forecast’s mean and standard deviation of demand to departure at dcp_index, or zero if there is no value there. Buckets without those forecasts are skipped. These are the unmultiplied values; any forecast mean multiplier stays in effect.

Parameters:
dcp_index : int, default 0

The DCP index whose to-departure values are used.

snapshot_instruction : SnapshotInstruction or bool, optional

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

Raises:

RuntimeError – If a bucket’s forecast mean would be negative.