MultiSimulation¶
-
class passengersim.driver.MultiSimulation(config: Config, output_dir: Path | None =
None, *, database_initializer=None)[source]¶ Bases:
BaseSimulation,CallbackMixinInitialize a BaseSimulation instance.
- Parameters:
Methods
__init__(config[, output_dir, ...])Initialize a BaseSimulation instance.
Add callback events to the simulation event queue.
Attach this object's manual callbacks to another simulation.
begin_sample_callback([callback, priority, ...])Register a function to be triggered at the beginning of each sample.
Get all manually attached callback functions.
close()Close the current result and every database alias; preserve persistent files.
daily_callback([callback, priority, ...])Register a function to be triggered each day during a sample.
end_sample_callback([callback, priority, ...])Register a function to be triggered at the end of each sample.
finalize_sample_callback([callback, ...])Register a synchronous callback after sample bookkeeping finishes.
from_yaml(filenames[, output_dir])Create a Simulation object from a YAML file.
initialize_sample_callback([callback, ...])Register a synchronous callback before sample demand generation.
Get a mapping of path IDs to path names.
pathclasses_for_carrier(carrier)Generator of all path classes for a given carrier.
remove_callback(callback, *[, missing_ok])Detach manually attached callbacks or tracers.
run(*[, summarizer, output_dir, ...])sequential_run(*[, summarizer, fail_fast, ...])Run trials sequentially using the same closed-file handoff as workers.
Adopt all globally registered callbacks (deprecated).
Attributes
Every callback attached to the
begin_samplehook, in the order they run.Deprecated alias for the PassengerSim database wrapper.
Every callback attached to the
dailyhook, in the order they run.Whether this simulation has retained detail data.
Absolute consolidated result path, without opening its connection.
Completed, failed, and cancelled trials, plus whole-run completeness.
The shared consolidated database, opened on the consuming thread.
Generator of all demands in the simulation.
Every callback attached to the
end_samplehook, in the order they run.Generator of all fares in the simulation.
Every callback attached to the
finalize_samplehook, in the order they run.Every callback attached to the
initialize_samplehook, in the order they run.Access markets in the simulation.
Generator of all path classes in the simulation.
Generator of all paths in the simulation.
Completed trial descriptors; temporary trials share the consolidated path.
- property db¶
The shared consolidated database, opened on the consuming thread.
- property database_path¶
Absolute consolidated result path, without opening its connection.
- property database_available¶
Whether this simulation has retained detail data.
- property database_status¶
Completed, failed, and cancelled trials, plus whole-run completeness.
- property trial_databases¶
Completed trial descriptors; temporary trials share the consolidated path.
- sequential_run(*, summarizer: typing.Any = <class 'passengersim.summaries.SimulationTables'>, fail_fast: bool = True, rich_progress: Progress | None = None, run_id: str | None = None) GenericSimulationTables[source]¶
Run trials sequentially using the same closed-file handoff as workers.
- Parameters:
- summarizer : type, optional
Summary class used to collect and aggregate results.
- fail_fast : bool, default True
Stop after the first failed trial.
- rich_progress : rich.progress.Progress, optional
Shared display for trial progress and optional live diagnostics.
- run_id : str, optional
Diagnostic display key. Defaults to the configured scenario name, or a short random id if that is empty, as in
run(). Use distinct keys for runs sharing a progress display.
- add_callback_events()¶
Add callback events to the simulation event queue.
All callbacks due at the same timestamp are placed in one event. The native event queue orders events by time alone, so separate events at one timestamp would run in an arbitrary order. Within one event, they run in this order:
RM systems;
then the hooks in lifecycle order, so that at the first DCP every
begin_samplecallback runs before anydailyone, and at the final DCP everydailycallback runs before anyend_sampleone;within each hook, configured callbacks before manual ones, each in registration (or declaration) order.
RM systems stay first so that a priority of -1, the RM systems’ own, still runs a callback after them, as documented for each hook.
- apply_callback_functions(sim: CallbackMixin) None¶
Attach this object’s manual callbacks to another simulation.
- Parameters:
- sim : CallbackMixin¶
The simulation (or experiments) to receive the callbacks. Tracers are copied fresh; other callables are shared.
-
begin_sample_callback(callback: Callable[[CallbackMixin], dict | None] | GenericTracer | None =
None, *, priority: int | None =None, skip_burn: bool | None =None, name: str | None =None) 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.
It runs at an offset, in seconds, from the trigger time of the first DCP. The offset is the priority option if given, else the callback’s own
priorityattribute if it has one, and otherwise one second, which is after the first DCP’s RM systems (-1) and bookkeeping (0). A negativepriorityruns it before that bookkeeping, or, below -1, before the first DCP’s RM steps as well. No customer arrives within five seconds of a DCP, so apriorityfrom 1 to 4 always runs before the first arrival; a larger one may not. Apriorityof zero is not allowed, as for a daily callback.- Parameters:
- callback : Callable[[Simulation], dict | None] or GenericTracer, optional¶
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. Omit it to use this method as a decorator with options.
- priority : int, optional¶
Offset in seconds from the first DCP’s trigger time; see above.
- skip_burn : bool, optional¶
If True, the callback is not called during burn-in samples.
- name : str, optional¶
Store returned dictionaries under
callback_data.<name>instead of the shared hook key; for a tracer, its result name.
- Returns:
Callable or GenericTracer – The callback, or the fresh copy of a tracer. Without callback, a decorator that registers the function it decorates.
- property begin_sample_callbacks : tuple[Callable, ...]¶
Every callback attached to the
begin_samplehook, in the order they run.Includes RM systems and configured callbacks. This is a read-only snapshot: use the
begin_sample_callbackmethod to attach a callback.
- callback_functions() dict[str, list[Callable]]¶
Get all manually attached callback functions.
Callbacks constructed from
config.callbacksdeclarations are excluded. They are owned by this object’s config and are rebuilt by any simulation that runs that config, so copying them elsewhere (e.g. viaapply_callback_functions()or worker forwarding) would attach them twice. Carrier RM systems are excluded for the same reason: every simulation builds its own.- Returns:
dict[str, list[Callable]] – Mapping of
"<hook>_callbacks"to the manual callbacks for each hook, in registration order. A tracer is listed as itself under each hook it runs on.
- property cnx¶
Deprecated alias for the PassengerSim database wrapper.
-
daily_callback(callback: collections.abc.Callable[[CallbackMixin, int], dict | None] | GenericTracer | RmSys | None =
None, *, priority: int | None =None, skip_burn: bool | None =None, name: str | None =None) collections.abc.Callable[[CallbackMixin, int], dict | None] | GenericTracer¶ Register a function to be triggered each day during a sample.
The callback runs at an offset, in seconds, from the overnight trigger time. The offset is the priority option if given, else the callback’s own
priorityattribute if it has one, and otherwise one second. RM systems run at -1 and the simulation’s own DCP and daily data capture at 0, so by default a callback sees each day after both have finished. Use a negativepriorityto run it before the simulation’s bookkeeping, or below -1 to run it before the RM systems as well.A
priorityof zero is not allowed, because it would tie with the simulation’s own bookkeeping in an arbitrary order. It is rejected here, and again when a run starts if it was set after registration. Theprioritymust also be a whole number of seconds: a value that clearly names one, such as1.0or"1", is used as that integer, and anything else (0.5,"1.5",True,"high") is rejected rather than rounded. A callback attached while a sample is running takes effect from the next sample.The options can be given with the callback, or to use this method as a decorator:
@sim.daily_callback(priority=-5, skip_burn=True, name="nogo") def count_nogo(sim, days_prior): ...- Parameters:
- callback : Callable[[Simulation, int], dict | None] or GenericTracer, optional¶
The callback function to register. It should accept two arguments, which will be the Simulation object and the days_prior, and return a dictionary of interesting things to store, or nothing. Omit it to use this method as a decorator with options.
- priority : int, optional¶
Offset in seconds from the overnight trigger time; see above.
- skip_burn : bool, optional¶
If True, the callback is not called during burn-in samples.
- name : str, optional¶
Store returned dictionaries under
callback_data.<name>instead of the shareddailykey, so they cannot collide with other callbacks’ keys; for a tracer, its result name.
- Returns:
Callable or GenericTracer – The callback, or the fresh copy of a tracer. Without callback, a decorator that registers the function it decorates.
- Raises:
ValueError – If the priority is zero or not a whole number of seconds, the name is reserved or used by a tracer, or the callback is a tracer declaring a hook other than
daily.
- property daily_callbacks : tuple[Callable, ...]¶
Every callback attached to the
dailyhook, in the order they run.Includes RM systems and configured callbacks. This is a read-only snapshot: use the
daily_callbackmethod to attach a callback.
- 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 | None =
None, *, priority: int | None =None, skip_burn: bool | None =None, name: str | None =None) 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.
It runs at an offset, in seconds, from the trigger time of the final DCP (the day of departure). The offset is the priority option if given, else the callback’s own
priorityattribute if it has one, and otherwise one second, which is after the final DCP’s RM systems (-1) and bookkeeping (0). A negativepriorityruns it before that bookkeeping, or, below -1, before the RM systems as well. Apriorityof zero is not allowed, as for a daily callback.- Parameters:
- callback : Callable[[Simulation], dict | None] or GenericTracer, optional¶
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. Omit it to use this method as a decorator with options.
- priority : int, optional¶
Offset in seconds from the final DCP’s trigger time; see above.
- skip_burn : bool, optional¶
If True, the callback is not called during burn-in samples.
- name : str, optional¶
Store returned dictionaries under
callback_data.<name>instead of the shared hook key; for a tracer, its result name.
- Returns:
Callable or GenericTracer – The callback, or the fresh copy of a tracer. Without callback, a decorator that registers the function it decorates.
- property end_sample_callbacks : tuple[Callable, ...]¶
Every callback attached to the
end_samplehook, in the order they run.Includes RM systems and configured callbacks. This is a read-only snapshot: use the
end_sample_callbackmethod to attach a callback.
- property fares¶
Generator of all fares in the simulation.
- Returns:
FareIterator – Iterator object for accessing fare data.
-
finalize_sample_callback(callback: Callable[[CallbackMixin], dict | None] | GenericTracer | None =
None, *, skip_burn: bool | None =None, name: str | None =None) Callable[[CallbackMixin], dict | None] | GenericTracer¶ Register a synchronous callback after sample bookkeeping finishes.
Callbacks run after departure statistics, history rollover, database commit, and other bookkeeping updates. They observe post-bookkeeping state and cannot change statistics already recorded. Use
end_sampleto access pre-bookkeeping state. Their execution is included in sample timing, before diagnostics are published. They run only on successful completion, not as exception cleanup; callback failures propagate after bookkeeping has completed. Configured callbacks run first, followed by manual callbacks, each in registration order. Event priority does not apply. Exceptions propagate.- Parameters:
- callback : Callable[[Simulation], dict | None] or GenericTracer, optional¶
Callback receiving the simulation. Returned dictionaries are stored under
callback_data.finalize_samplewith trial/sample keys. Omit it to use this method as a decorator with options.- skip_burn : bool, optional¶
If True, the callback is not called during burn-in samples.
- name : str, optional¶
Store returned dictionaries under
callback_data.<name>instead of the shared hook key; for a tracer, its result name.
- Returns:
Callable or GenericTracer – The callback, or the fresh copy of a tracer. Without callback, a decorator that registers the function it decorates.
- property finalize_sample_callbacks : tuple[Callable, ...]¶
Every callback attached to the
finalize_samplehook, in the order they run.Includes RM systems and configured callbacks. This is a read-only snapshot: use the
finalize_sample_callbackmethod to attach a callback.
-
classmethod from_yaml(filenames: Path | list[Path], output_dir: Path | None =
None)¶ Create a Simulation object from a YAML file.
-
initialize_sample_callback(callback: Callable[[CallbackMixin], dict | None] | GenericTracer | None =
None, *, skip_burn: bool | None =None, name: str | None =None) Callable[[CallbackMixin], dict | None] | GenericTracer¶ Register a synchronous callback before sample demand generation.
The sample number, random seed, and counters have been initialized, but the new sample’s RM steps have not run. Changes to demand inputs affect this sample. Callbacks run in registration order, with configured callbacks first; event priority does not apply.
- Parameters:
- callback : Callable[[Simulation], dict | None] or GenericTracer, optional¶
Callback receiving the simulation. Returned dictionaries are stored under
callback_data.initialize_samplewith trial/sample keys. Omit it to use this method as a decorator with options.- skip_burn : bool, optional¶
If True, the callback is not called during burn-in samples.
- name : str, optional¶
Store returned dictionaries under
callback_data.<name>instead of the shared hook key; for a tracer, its result name.
- Returns:
Callable or GenericTracer – The callback, or the fresh copy of a tracer. Without callback, a decorator that registers the function it decorates.
- property initialize_sample_callbacks : tuple[Callable, ...]¶
Every callback attached to the
initialize_samplehook, in the order they run.Includes RM systems and configured callbacks. This is a read-only snapshot: use the
initialize_sample_callbackmethod to attach a callback.
- 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.
-
remove_callback(callback: Callable | GenericTracer | str, *, missing_ok: bool =
False) int¶ Detach manually attached callbacks or tracers.
- Parameters:
- callback : Callable or GenericTracer or str¶
What to remove:
a function (or other callable) previously attached, with or without options, is removed from every hook it is attached to; a bound method matches when it binds the same function to the same object, even if it is a new
obj.methodexpression;a tracer, or a tracer’s result name, removes the attached tracer of that name from all its hooks;
a name given to callbacks with
name=removes those callbacks.
- missing_ok : bool, default False¶
Return 0 instead of raising if nothing matches.
- Returns:
int – The number of hook registrations removed.
- Raises:
ValueError – If nothing matches and missing_ok is False. Callbacks built from
config.callbacksand carrier RM systems cannot be removed this way: disable a configured callback in the configuration instead.
Notes
A callback removed while a sample is running may still be called for the rest of that sample; the removal takes effect from the next one.
-
run(*, summarizer: type[SimulationTablesT] | SimulationTablesT | None =
None, output_dir: pathlib.Path | None =None, max_processes: int | None =None, fail_fast: bool =True, rich_progress: Progress | None =None, cache_dir: pathlib.Path | None =None, run_id: str | None =None)[source]¶
- use_registered_callbacks() None¶
Adopt all globally registered callbacks (deprecated).
Warning
This method emits a DeprecationWarning. For reusable callbacks, register them with
register_callback(functions) orregister_tracer(tracer classes) and select them inconfig.callbacks; those register for configuration rather than attaching to every simulation. For development and testing, attach callbacks directly with the simulation’s hook methods, or use an explicitCallbackMixinbundle andbundle.apply_callback_functions(sim). Registration APIs, including the factory ones, are not deprecated.