Source code for passengersim.callbacks.bid_price_detail

"""Daily tracer collecting bid prices for selected legs.

Attach a :class:`LegBidPriceDetailTracer` manually, or enable it in a configuration as the ``leg_bid_price_detail``
configured callback. The results are available on summaries as
``leg_bid_price_detail``, ``fig_leg_bid_price_detail_rake``, and
``fig_leg_bid_price_history`` (see
:class:`passengersim.summaries.leg_callback_detail.SimTabLegCallbackDetail`).

Results saved before this collector became a tracer hold the same values as
rows of ``callback_data.daily``, with keys such as ``leg-101-bidprice``; the
readers in this module accept both.
"""

from __future__ import annotations

import typing
import warnings
from collections.abc import Iterable
from typing import Any, ClassVar

import altair as alt
import numpy as np
import pandas as pd

from passengersim.utils.colors import DarkOrange, DarkPurple

# Relative imports: this module is loaded while ``passengersim.callbacks`` is
# still initializing (by the built-in registrations), so it must not import
# from the package namespace or from the summaries package at runtime.
from .base import CallbackData
from .booking_detail import LegDetailTracer, _summarize_leg_detail, detail_table
from .configured import register_tracer

if typing.TYPE_CHECKING:
    from typing import Literal

    from passengersim.summaries import SimulationTables

_SOLD_OUT_BID_PRICE = 9.9e9
"""Bid prices above this mark a sold-out leg."""


[docs] @register_tracer class LegBidPriceDetailTracer(LegDetailTracer): """Daily tracer recording the bid price of selected legs in every sample.""" name: str = "leg_bid_price_detail" """Identifier used to store results in ``callback_data``.""" options_version: ClassVar[str] = "2" """Version 2 stores results under ``leg_bid_price_detail``, not in ``daily`` rows."""
[docs] def __init__( self, leg_ids: list[int], *, include_sold_out: bool = True, priority: int = 1, name: str | None = None, ) -> None: """Initialize the tracer. Parameters ---------- leg_ids : list[int] The legs to record. IDs not found in the simulation are ignored. include_sold_out : bool, default True If True, record each leg's reported bid price, including sold-out legs. If False, a sold-out leg's value is missing for that day. priority : int, default 1 Daily offset in seconds from the overnight trigger; zero is not allowed. name : str, optional Key for the results in ``callback_data``; defaults to ``"leg_bid_price_detail"``. The summary accessors read only the default name. """ self.include_sold_out = include_sold_out """Whether sold-out legs are recorded.""" super().__init__(leg_ids, priority=priority, name=name)
def _value(self, leg: Any) -> float: if self.include_sold_out: return leg.report_bid_price return np.nan if leg.bid_price > _SOLD_OUT_BID_PRICE else leg.bid_price
[docs] def collect_leg_bid_price_detail(leg_ids: Iterable[int], *, include_sold_out: bool = True) -> LegBidPriceDetailTracer: """Build a tracer recording bid prices for selected legs. .. deprecated:: Use :class:`LegBidPriceDetailTracer` directly. The tracer stores its results in ``callback_data.leg_bid_price_detail`` rather than in ``callback_data.daily`` rows; the summary accessors read either. Parameters ---------- leg_ids : Iterable[int] The legs to record. include_sold_out : bool, default True If True, record each leg's reported bid price, including sold-out legs. If False, a sold-out leg's value is missing for that day. Returns ------- LegBidPriceDetailTracer A tracer to attach with ``sim.daily_callback``. """ warnings.warn( "collect_leg_bid_price_detail() is deprecated; use LegBidPriceDetailTracer(leg_ids) instead", DeprecationWarning, stacklevel=2, ) return LegBidPriceDetailTracer(list(leg_ids), include_sold_out=include_sold_out)
[docs] def process_leg_bid_price_detail(data: CallbackData | SimulationTables) -> pd.DataFrame: """Get the recorded bid prices, one row per trial, sample, and day. .. deprecated:: Use :func:`~passengersim.callbacks.booking_detail.detail_table` with ``LegBidPriceDetailTracer.name``, or the summary accessor ``leg_bid_price_detail`` for the daily statistics. Parameters ---------- data : CallbackData or SimulationTables Callback data, or a summary holding it. Returns ------- pd.DataFrame Indexed by ``(trial, sample, days_prior)``, one column per leg. """ warnings.warn( "process_leg_bid_price_detail() is deprecated; " "use detail_table(data, LegBidPriceDetailTracer.name, 'bidprice')", DeprecationWarning, stacklevel=2, ) return detail_table(data, LegBidPriceDetailTracer.name, "bidprice")
[docs] def summarize_leg_bid_price_detail(data: CallbackData | SimulationTables) -> pd.DataFrame: """Summarize the observed bid prices for each leg and day.""" return _summarize_leg_detail(detail_table(data, LegBidPriceDetailTracer.name, "bidprice"))
[docs] def fig_leg_bid_price_detail_rake( data: CallbackData | SimulationTables, *, leg_id: int, raw_df: bool = False, color: str = DarkPurple, mean_color: str | None = DarkOrange, ): df = summarize_leg_bid_price_detail(data) df = df.query(f"leg_id == {leg_id}").droplevel("leg_id") if raw_df: return df quartiles = "25th and 75th percentiles" deciles = "10th and 90th percentiles" groups = {"q50": "Median", "q10": deciles, "q90": deciles, "q25": quartiles, "q75": quartiles} # Use the same categories for all stroke encodings so Vega-Lite draws one legend. styles = { "Median": (color, 2, []), quartiles: (color, 1, [5, 1]), deciles: (color, 1, [3, 1]), } if mean_color: groups["mean"] = "Mean" styles["Mean"] = (mean_color, 3, [1, 1, 4, 1, 1, 4]) dfc = df[list(groups)].stack(future_stack=True).rename("value").reset_index() dfc["statistic"] = dfc["metric"].map(groups) colors, widths, dashes = zip(*styles.values(), strict=True) domain = list(styles) return alt.layer( alt.Chart(dfc) .mark_line() .encode( x=alt.X("days_prior:Q", title="Days Prior to Departure", scale=alt.Scale(reverse=True)), y=alt.Y("value:Q", title="Bid Price", axis=alt.Axis(format="$,.0f")), detail="metric:N", color=alt.Color("statistic:N", title="Statistic", scale=alt.Scale(domain=domain, range=list(colors))), strokeWidth=alt.StrokeWidth( "statistic:N", title="Statistic", scale=alt.Scale(type="ordinal", domain=domain, range=list(widths)) ), strokeDash=alt.StrokeDash( "statistic:N", title="Statistic", scale=alt.Scale(domain=domain, range=list(dashes)) ), tooltip=[ alt.Tooltip("days_prior:Q", title="Days Prior to Departure"), alt.Tooltip("metric:N", title="Statistic"), alt.Tooltip("value:Q", title="Bid Price", format="$,.2f"), ], ) )
[docs] def fig_leg_bid_price_history( summary: SimulationTables, carrier: str, *, measure: Literal["mean", "q10", "q25", "q50", "q75", "q90", "median"], haul_category_labels: tuple[str, ...] | None = ("a. Short: ", "b. Medium: ", "c. Long: ", "d. Longest: "), opacity: float = 0.25, max_rows: int = 5000, ) -> alt.Chart: """Plot one bid-price statistic over days prior for every collected leg of a carrier. Usually called as the summary method of the same name; see :meth:`passengersim.summaries.leg_callback_detail.SimTabLegCallbackDetail.fig_leg_bid_price_history` for the parameters. Returns ------- altair.Chart The faceted (or single) line chart. """ if measure == "median": measure = "q50" measure_labels = { "mean": "Mean", "q10": "10th Percentile", "q25": "25th Percentile", "q50": "Median", "q75": "75th Percentile", "q90": "90th Percentile", } measure_label = measure_labels.get(measure, measure) title = f"{measure_label} Leg Bid Prices by Days Prior to Departure ({carrier})" defs = summary.leg_defs.query(f"carrier == {carrier!r}").copy() defs["leg_label"] = defs["carrier"] + defs["fltno"].astype(str) + ":" + defs["orig"] + "-" + defs["dest"] if haul_category_labels is not None: defs["haul"] = pd.qcut(summary.leg_defs["distance"], q=len(haul_category_labels)) df = summary.leg_bid_price_detail.join(defs[["haul", "leg_label"]], on="leg_id", how="inner") df["haul"] = df["haul"].cat.rename_categories( pd.Index(haul_category_labels) + df["haul"].cat.categories.astype(str) ) facet = dict(facet=alt.Facet("haul", columns=2)) title = f"{measure_label} Leg Bid Prices by Days Prior to Departure and Length of Haul ({carrier})" else: df = summary.leg_bid_price_detail.join(defs[["leg_label"]], on="leg_id", how="inner") facet = dict() if len(df) > max_rows: df = df.query("days_prior in @summary.config.dcps") if len(df) > max_rows: df = df.sample(max_rows) chart = ( alt.Chart(df.reset_index()) .mark_line(opacity=opacity) .encode( x=alt.X("days_prior", scale=alt.Scale(reverse=True), title="Days Prior to Departure"), y=alt.Y(measure, title=f"{measure_label} Bid Price", axis=alt.Axis(format="$,.0f")), detail="leg_id", tooltip=[ alt.Tooltip("leg_id", title="Leg ID"), alt.Tooltip("leg_label", title=" "), alt.Tooltip("days_prior", title="Days Prior"), alt.Tooltip(measure, title=f"{measure_label} Bid Price", format="$,.2f"), ], **facet, ) ) return chart.properties(title=title)
# The summary accessor ``leg_bid_price_detail`` and the figure methods # ``fig_leg_bid_price_detail_rake`` and ``fig_leg_bid_price_history`` are defined # on ``passengersim.summaries.leg_callback_detail.SimTabLegCallbackDetail``; this # module no longer attaches them to the summary class as an import side effect.