Source code for passengersim.callbacks.tracer

"""Base class for tracers, the stateful collectors attached to a simulation.

This module belongs to the callback machinery, which uses it to recognize,
attach, set up, and finalize tracers. It does not import the concrete tracers
in :mod:`passengersim.tracers`; that package builds on it. The base class is
also available as ``passengersim.tracers.generic.GenericTracer``.
"""

from __future__ import annotations

import copy
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, ClassVar, Literal

from .registry import HOOKS

if TYPE_CHECKING:
    import pandas as pd
    from pydantic import BaseModel

    from passengersim import Simulation


def _overridden_hooks(tracer: GenericTracer | type[GenericTracer]) -> tuple[str, ...]:
    """The hooks whose ``on_<hook>`` method the tracer's class overrides, in lifecycle order."""
    cls = tracer if isinstance(tracer, type) else type(tracer)
    return tuple(h for h in HOOKS if getattr(cls, f"on_{h}") is not getattr(GenericTracer, f"on_{h}"))


[docs] def tracer_hooks(tracer: GenericTracer | type[GenericTracer]) -> tuple[str, ...]: """Get the lifecycle hooks a tracer runs on. A tracer written in the hook-method form runs on every hook whose ``on_<hook>`` method its class overrides. A tracer written in the legacy form runs on its single declared :attr:`~GenericTracer.hook`, calling ``__call__``. Parameters ---------- tracer : GenericTracer or type[GenericTracer] A tracer, or a tracer class. Returns ------- tuple[str, ...] The hooks, in lifecycle order. Empty for a legacy tracer that declares no ``hook``, which may then be attached to any one hook. Raises ------ TypeError If the tracer overrides ``on_<hook>`` methods and also declares a ``hook``, so that it is ambiguous which form applies. """ cls = tracer if isinstance(tracer, type) else type(tracer) overridden = _overridden_hooks(cls) # Read the legacy hook from the object given, so that an instance-level # hook (allowed before hook methods existed) is still honored. declared = getattr(tracer, "hook", None) if overridden: if declared is not None: raise TypeError( f"{cls.__name__} declares hook={declared!r} and also overrides " f"{', '.join(f'on_{h}' for h in overridden)}; a tracer uses either a hook " "attribute with __call__, or on_<hook> methods, not both" ) return overridden return () if declared is None else (declared,)
[docs] def uses_hook_methods(tracer: GenericTracer | type[GenericTracer]) -> bool: """Whether a tracer is written in the hook-method form. Parameters ---------- tracer : GenericTracer or type[GenericTracer] A tracer, or a tracer class. Returns ------- bool True if the class overrides at least one ``on_<hook>`` method, and False for a legacy tracer that runs ``__call__`` on one hook. """ return bool(_overridden_hooks(tracer))
[docs] class GenericTracer(ABC): """Base class for tracers that collect detail while a simulation runs. A tracer accumulates what it observes while a simulation runs, and :meth:`finalize` turns that into a table stored under ``summary.callback_data.<name>``. A tracer is written in one of two forms: - **Hook methods.** Override one or more of :meth:`on_initialize_sample`, :meth:`on_begin_sample`, :meth:`on_daily`, :meth:`on_end_sample`, and :meth:`on_finalize_sample`. The tracer is attached to every hook whose method it overrides, and one copy of the tracer receives all of them, so it can, for example, compare the start and end of each sample. - **Legacy.** Set the class attribute :attr:`hook` and define ``__call__``, which runs on that one hook. The time at which a queued hook (``begin_sample``, ``daily``, or ``end_sample``) runs can be shifted with an offset in seconds, as for a plain callback, by setting a ``priority`` attribute. A hook-method tracer has just one ``priority``, which applies to all of its queued hooks, so it observes every DCP from the same side of the RM systems and the simulation's bookkeeping. Subclasses must implement :meth:`reset` and :meth:`finalize`. The :meth:`fresh`, :meth:`attach`, and :meth:`setup` methods have working defaults. For each run, a tracer is reset, then set up once the scenario is built, then called at its hooks for every trial and sample, and finally finalized after the last trial. See the user guide for the full lifecycle. :func:`passengersim.callbacks.register_tracer` registers a subclass under its :attr:`name` and infers its configuration options from the annotated constructor. A subclass can supply an explicit :attr:`options_model` when configuration needs different validation. """ name: str = "generic_tracer" """Result key in ``callback_data``. The class value is the canonical name. An instance may set its own name, so that two tracers of one class can be attached to the same simulation without overwriting each other's results. """ hook: ClassVar[Literal["initialize_sample", "begin_sample", "daily", "end_sample", "finalize_sample"]] """Lifecycle hook at which a legacy-form tracer's ``__call__`` runs. Leave this unset for a tracer written with ``on_<hook>`` methods. """ skip_burn: ClassVar[bool] = False """Whether the simulation skips calling this tracer during burn-in samples. The check is made by the simulation before each call, so a tracer setting this does not need to test for burn-in itself. It defaults to False so that tracers written before this flag existed behave as they always have. """ options_model: ClassVar[type[BaseModel] | None] = None """Pydantic model of the constructor's keyword options, for configured callbacks. By default, registration derives the model from the annotated constructor. """ options_version: ClassVar[str] = "1" """Configured-callback implementation version; bump when results change meaning.""" def _set_name(self, name: str | None) -> None: """Give this instance its own result name, if one is given. Constructors of the built-in tracers call this with their ``name`` keyword. Validation of the name happens when the tracer is attached. """ if name is not None: self.name = name
[docs] @abstractmethod def reset(self) -> None: """Reset the internal counters on this tracer to a null state.""" raise NotImplementedError()
[docs] def fresh(self) -> GenericTracer: """Return a fresh copy of this tracer, tracing the same targets but not sharing state. The default makes a deep copy of this tracer and then calls :meth:`reset` on the copy. Override it if a tracer holds something that cannot be deep-copied, or that is expensive to copy. Returns ------- GenericTracer A new tracer of the same type and configuration, with no accumulated data. """ clone = copy.deepcopy(self) clone.reset() return clone
[docs] def attach(self, sim: Simulation) -> None: """Attach a fresh copy of this tracer to a simulation, on all its hooks. Parameters ---------- sim : Simulation or MultiSimulation or Experiments The object to attach to. The simulation stores a copy made with :meth:`fresh`, so this tracer object itself is never modified by a run and can be attached to several simulations. Raises ------ TypeError If the tracer declares no hook and overrides no hook method. """ hooks = tracer_hooks(self) if not hooks: raise TypeError( f"{type(self).__name__} declares no hook; override one or more on_<hook> " "methods, or set the class attribute 'hook'" ) # Attaching through any one of its hooks registers the tracer on all of # them. Going through the public method lets subclass overrides apply. getattr(sim, f"{hooks[0]}_callback")(self)
[docs] def setup(self, sim: Simulation) -> None: # noqa: B027 (an optional hook, not abstract) """Prepare to trace a run, once its scenario has been built. Called once per run (``run`` or ``run_trial``), after :meth:`reset` and after the simulation has built its network, fares, and demands, but before the first sample. Override it to look up what the tracer will observe and to allocate its accumulators, so that problems are reported before the run starts. The default does nothing. An exception raised here stops the run; nothing is finalized, and the next run starts from a fresh reset. Parameters ---------- sim : Simulation The simulation about to run. """
[docs] def on_initialize_sample(self, sim: Simulation) -> dict | None: # noqa: B027 """Observe the start of a sample, before its demand is generated. Override this to attach the tracer to the ``initialize_sample`` hook. A returned dictionary is stored under ``callback_data.initialize_sample``, as for a plain callback. Parameters ---------- sim : Simulation The running simulation. """
[docs] def on_begin_sample(self, sim: Simulation) -> dict | None: # noqa: B027 """Observe a sample after its first DCP, before any customer arrives. Override this to attach the tracer to the ``begin_sample`` hook. Its time is set by the tracer's ``priority`` attribute, if it has one, as for a plain begin-sample callback. Parameters ---------- sim : Simulation The running simulation. """
[docs] def on_daily(self, sim: Simulation, days_prior: int) -> dict | None: # noqa: B027 """Observe each day of a sample. Override this to attach the tracer to the ``daily`` hook. The time of day is set by the tracer's ``priority`` attribute, if it has one, as for a plain daily callback. Parameters ---------- sim : Simulation The running simulation. days_prior : int Days remaining before departure. """
[docs] def on_end_sample(self, sim: Simulation) -> dict | None: # noqa: B027 """Observe the end of a sample, before counters are reset. Override this to attach the tracer to the ``end_sample`` hook. Its time is set by the tracer's ``priority`` attribute, if it has one, as for a plain end-sample callback. Parameters ---------- sim : Simulation The running simulation. """
[docs] def on_finalize_sample(self, sim: Simulation) -> dict | None: # noqa: B027 """Observe a sample after its events and bookkeeping have finished. Override this to attach the tracer to the ``finalize_sample`` hook. Parameters ---------- sim : Simulation The running simulation. """
[docs] @abstractmethod def finalize(self) -> pd.DataFrame: """Convert the internal counters on this tracer to a dataframe.""" raise NotImplementedError()