Simulation¶
-
class passengersim.driver.Simulation(config: Config, output_dir: Path | None =
None)[source]¶ Bases:
BaseSimulation,CallbackMixin,FirehoseInitialize a Simulation instance.
- Parameters:
Notes
This initializes the simulation with default parameters including DCP lists, choice models, and various data structures for tracking simulation results.
Methods
__init__(config[, output_dir])Initialize a Simulation instance.
Add callback events to the simulation event queue.
attach_firehose(topic, destination)Attach a firehose logger destination for a topic.
backup_db(dst)Back up this database to another copy.
begin_sample([sample])Begin processing a new sample in the simulation.
begin_sample_callback(callback)Register a function to be triggered at the beginning of each sample.
begin_trial(trial)Beginning of trial processing.
Get all callback functions.
Capture competitor pricing data for all markets.
capture_dcp_data(dcp_index[, closures_only])Capture data control point (DCP) data for revenue management.
daily_callback(callback)Register a function to be triggered each day during a sample.
End processing of the current sample.
end_sample_callback(callback)Register a function to be triggered at the end of each sample.
End of trial processing.
from_yaml(filenames[, output_dir])Create a Simulation object from a YAML file.
generate_dcp_rm_events([debug])Pushes an event per reading day (DCP) onto the queue.
Generate demands following the procedure used in PODS.
generate_demands_gamma([system_rn, debug])Using this as a quick test
get_choice_parameters(choicemodel)Get the parameters for a choice model.
get_firehose(topic)Return the cached writable firehose destination for a topic.
get_restriction_name(restriction_num)Convert restriction number to a restriction name.
license_info([certificate_filename])parse_restriction_flags(restriction_flags)Convert restriction flags to a list of restriction names.
Get a mapping of path IDs to path names.
pathclasses_for_carrier(carrier)Generator of all path classes for a given carrier.
reseed([seed])Reseed the simulation's random number generator.
rm_data(carrier, kind[, set_value])Access RM data (forecasts, optimizers, etc.) from the simulation.
run([log_reports, single_trial, summarizer, ...])Run the simulation and compute reports.
Context manager to run the next sample in the current trial.
run_trial(trial[, summarizer])save_simulation_state([force])set_choice_parameters(choicemodel, values)Set the parameters for a choice model.
set_classes(leg, _cabin[, debug])Set up the scenario for the simulation.
Adopt all globally registered callbacks.
validate_license([certificate_filename, future])vn_initial_mapping(carrier_code)Set up initial virtual nesting mapping for a carrier.
Attributes
The base time for the simulation.
The configuration used for this Simulation.
Generator of all demands in the simulation.
Generator of all fares in the simulation.
Access markets in the simulation.
Generator of all path classes in the simulation.
Generator of all paths in the simulation.
Get the snapshot filters for the simulation.
Bookings and revenue segmentation by timeframe.
Bid price traces for each carrier.
Displacement cost traces for each carrier.
Data stored from callbacks.
-
__init__(config: Config, output_dir: Path | None =
None)[source]¶ Initialize a Simulation instance.
- Parameters:
Notes
This initializes the simulation with default parameters including DCP lists, choice models, and various data structures for tracking simulation results.
- segmentation_data_by_timeframe : dict[int, pd.DataFrame]¶
Bookings and revenue segmentation by timeframe.
The key is the trial number, and the value is a DataFrame with a breakdown of bookings and revenue by timeframe, customer segment, carrier, and booking class.
- bid_price_traces : dict[int, Any]¶
Bid price traces for each carrier.
The key is the trial number, and the value is a dictionary with carrier names as keys and bid price traces as values.
- displacement_traces : dict[int, Any]¶
Displacement cost traces for each carrier.
The key is the trial number, and the value is a dictionary with carrier names as keys and displacement cost traces as values.
- callback_data¶
Data stored from callbacks.
This allows a user to store arbitrary data during a simulation using callbacks, and access it later.
- property base_time : int¶
The base time for the simulation.
- Returns:
int – The base time in seconds since the epoch.
- property snapshot_filters : list[SnapshotFilter] | None¶
Get the snapshot filters for the simulation.
- Returns:
list[SnapshotFilter] or None – List of snapshot filter objects, or None if simulation is not initialized.
- property db_writer¶
- parse_restriction_flags(restriction_flags: int) list[str][source]¶
Convert restriction flags to a list of restriction names.
- Parameters:
- restriction_flags : int¶
Integer bit flags representing which restrictions are active.
- Returns:
list[str] – List of restriction names corresponding to the set flags.
- get_restriction_name(restriction_num: int) str[source]¶
Convert restriction number to a restriction name.
- Parameters:
- restriction_num : int¶
The numeric identifier for the restriction (must be >= 1).
- Returns:
str – The name of the restriction.
- Raises:
IndexError – If restriction_num is less than 1 or exceeds the number of defined restrictions.
- setup_scenario() None[source]¶
Set up the scenario for the simulation.
This will delete any existing data in the database under the same simulation name, build the connections if needed, and then call the vn_initial_mapping method to set up the initial mapping for the carriers using virtual nesting.
- vn_initial_mapping(carrier_code)[source]¶
Set up initial virtual nesting mapping for a carrier.
- Parameters:
- carrier_code : str¶
The carrier code to set up virtual nesting mapping for.
Notes
This method assigns index values to path classes for carriers using virtual nesting, which allows revenue management systems to map between physical and virtual booking classes.
-
begin_sample(sample: int | None =
None)[source]¶ Begin processing a new sample in the simulation.
- Parameters:
- sample : int or None, optional¶
The sample number to set. If None, the current sample number will be incremented by 1.
Notes
This method handles sample initialization including setting the random seed (if configured) and preparing the simulation state for the new sample.
- end_sample()[source]¶
End processing of the current sample.
Notes
This method records departure statistics to carrier-level counters, handles choice set and competitor data capture if configured, and performs other end-of-sample cleanup and data collection tasks.
- begin_trial(trial: int)[source]¶
Beginning of trial processing.
- Parameters:
- trial : int¶
The trial number.
- run_single_sample() int[source]¶
Context manager to run the next sample in the current trial.
On entry, the sample number is run through to departure, so all sales have happened, but per-sample wrap up (e.g. rolling history forward, resetting counters) is deferred until exit. This is useful for running a single sample in a testing framework.
- Yields:
int – The sample number just completed.
- capture_competitor_data()[source]¶
Capture competitor pricing data for all markets.
Notes
This method shops for the lowest prices in each market and stores competitor pricing information that can be used by revenue management systems for competitive analysis.
-
capture_dcp_data(dcp_index, closures_only=
False)[source]¶ Capture data control point (DCP) data for revenue management.
- Parameters:
Notes
This method captures seat availability, booking data, and other metrics at specific time points (DCPs) before departure, which is essential for revenue management decision-making.
-
generate_dcp_rm_events(debug=
False)[source]¶ Pushes an event per reading day (DCP) onto the queue.
In older versions of PassengerSim, the DCP events activated a variety of processes, including carrier RM system updates, internal simulation data capture, and database writes. In the current version, carrier RM systems are triggered via callback events, but data capture and database writes are still tied to DCP events.
-
reseed(seed: int | list[int] | None =
42)[source]¶ Reseed the simulation’s random number generator.
- Parameters:
- seed : int, list[int], or None, default 42¶
Seed value(s) for the random number generator. Can be a single integer, a list of integers, or None.
Notes
This method updates the random seed for the simulation’s internal random number generator, affecting all subsequent random operations.
- add_callback_events()¶
Add callback events to the simulation event queue.
- apply_callback_functions(sim: CallbackMixin)¶
- attach_firehose(topic: str, destination: str | bool | TextIO | None) None¶
Attach a firehose logger destination for a topic.
- Parameters:
- topic : str¶
Firehose topic name to route from the simulation engine.
- destination : str or bool or file-like or None¶
Destination passed through to the engine. Writable destinations are also stored locally so they can be returned by
get_firehose().
- begin_sample_callback(callback: Callable[[CallbackMixin], dict | None] | GenericTracer)¶
Register a function to be triggered at the beginning of each sample.
The callback function will be triggered after initial setup including all RM steps for the initial DCP, but before any customers can arrive.
- Parameters:
- callback : Callable[[Simulation], dict | None]¶
The callback function to register. It should accept a single argument, which will be the Simulation object, and return a dictionary of interesting things to store, or nothing.
- callback_functions() dict[str, list[Callable]]¶
Get all callback functions.
- daily_callback(callback: collections.abc.Callable[[CallbackMixin, int], dict | None] | GenericTracer | RmSys)¶
Register a function to be triggered each day during a sample.
The callback function will be triggered after all RM steps when the day coincides with a DCP.
- Parameters:
- callback : Callable[[Simulation, int], dict | None]¶
The callback function to register. It should accept two arguments, which will be the Simulation object and the days_prior, and return None.
- property demands¶
Generator of all demands in the simulation.
- Returns:
DemandIterator – Iterator object for accessing demand data.
- end_sample_callback(callback: Callable[[CallbackMixin], dict | None] | GenericTracer)¶
Register a function to be triggered at the end of each sample.
The callback function will be triggered before counters are reset or history buffers are rolled over.
- Parameters:
- callback : Callable[[Simulation], None]¶
The callback function to register. It should accept a single argument, which will be the Simulation object, and return a dictionary of interesting things to store, or nothing.
- property fares¶
Generator of all fares in the simulation.
- Returns:
FareIterator – Iterator object for accessing fare data.
-
classmethod from_yaml(filenames: Path | list[Path], output_dir: Path | None =
None)¶ Create a Simulation object from a YAML file.
- get_firehose(topic: str) TextIO | None¶
Return the cached writable firehose destination for a topic.
- Parameters:
- topic : str¶
Firehose topic name to look up.
- Returns:
TextIO or None – The cached writable destination for
topic, if one was attached.
Notes
Pending firehose log output is flushed from the engine before the cached destination is returned.
- property markets : Mapping[str, Market]¶
Access markets in the simulation.
- Returns:
Mapping[str, Market] – A mapping of market names to Market objects.
- path_names()¶
Get a mapping of path IDs to path names.
- Returns:
dict – Dictionary mapping path IDs to string representations of paths.
- property pathclasses¶
Generator of all path classes in the simulation.
- Yields:
pathclass – Path class objects from all paths in the simulation.
- pathclasses_for_carrier(carrier: str)¶
Generator of all path classes for a given carrier.
- Parameters:
- carrier : str¶
The carrier name to filter path classes by.
- Yields:
pathclass – Path class objects for the specified carrier.
- property paths¶
Generator of all paths in the simulation.
- Returns:
generator – Generator yielding path objects from the simulation.
- use_registered_callbacks()¶
Adopt all globally registered callbacks.
-
validate_license(certificate_filename=
None, future: int =0)[source]¶
- eng : SimulationEngine¶
-
license_info(certificate_filename=
None)[source]¶
-
run(log_reports: bool =
False, *, single_trial: int | None =None, summarizer: type[SimulationTablesT] | SimulationTablesT | None =None, rich_progress: Progress | None =None) SimulationTablesT[source]¶ Run the simulation and compute reports.
- Parameters:
- log_reports : bool¶
- single_trial : int, optional¶
Run only a single trial, with the given trial number (to get the correct fixed random seed, for example).
- summarizer : type[SimulationTables] | SimulationTables, optional¶
Use this summarizer to compute the reports. A valid summarizer must be a subclass or instance of GenericSimulationTables. If not provided, the default summarizer will be used.
- rich_progress : Progress, optional¶
A rich Progress object to use for displaying progress. If not provided, a new Progress object will be created unless the simulation configuration specifies not to show progress.
- Returns:
SimulationTables
-
run_trial(trial: int, summarizer: type[SimulationTablesT] | SimulationTablesT | None =
None) SimulationTablesT[source]¶
- backup_db(dst: Path | str | Connection)[source]¶
Back up this database to another copy.
- Parameters:
- dst : Path-like or sqlite3.Connection¶
- get_choice_parameters(choicemodel: str | ChoiceModel)[source]¶
Get the parameters for a choice model.
- Parameters:
- choicemodel : str or ChoiceModel¶
The choice model name (string) or ChoiceModel object to get parameters from.
- Returns:
dict – Dictionary containing the choice model parameters, including restrictions and their associated sigma values.
- set_choice_parameters(choicemodel: str | ChoiceModel, values: dict[str, float])[source]¶
Set the parameters for a choice model.
- Parameters:
- choicemodel : str or ChoiceModel¶
The choice model name (string) or ChoiceModel object to update.
- values : dict[str, float]¶
Dictionary of parameter names and their new values. Can include restriction parameters using the format ‘restrictions_{name}’.
-
rm_data(carrier: str, kind: str, set_value: Any =
None) Any[source]¶ Access RM data (forecasts, optimizers, etc.) from the simulation.
If the requested data for the carrier and kind do not exist, an empty dictionary is returned.
- Parameters:
- Returns:
Any – The existing value for this carrier and data type, or an empty dict.