from __future__ import annotations
from typing import TYPE_CHECKING
import pandas as pd
from passengersim.reporting import report_figure
from .generic import GenericSimulationTables, SimulationTableItem
from .tools import aggregate_by_summing_dataframe
if TYPE_CHECKING:
import altair as alt
from passengersim import Simulation
_GROUP_TITLES = {"booking_class": "Booking Class", "brand": "Brand"}
"""Title suffixes for fare class mix figures aggregated above the fare class level."""
def _group_fare_class_mix(df: pd.DataFrame, group_by: str | None = "") -> tuple[pd.DataFrame, str]:
"""Aggregate fare class mix data to the requested grouping level.
Parameters
----------
df : pd.DataFrame
Long-format data with a ``carrier`` column, an ``avg_sold`` column,
and a column named for the grouping level.
group_by : {"", "fare_class", "booking_class", "brand"} or None
The grouping level. An empty string or None leaves fare classes
unaggregated.
Returns
-------
df : pd.DataFrame
The grouped data, with ``carrier``, the grouping column, and ``avg_sold``.
group_key : str
The name of the grouping column.
Raises
------
ValueError
If `group_by` is not a recognized grouping level.
"""
if group_by in ("", None, "fare_class"):
return df, "fare_class"
if group_by not in _GROUP_TITLES:
raise ValueError("Invalid value for group_by")
# observed=True keeps categorical inputs from producing empty cartesian rows.
grouped = df.groupby(["carrier", group_by], observed=True).agg(avg_sold=("avg_sold", "sum")).reset_index()
return grouped, group_by
def _fig_fare_class_mix(
df: pd.DataFrame,
label_threshold: float = 0.06,
title: str | None = None,
group_by: str | None = "",
) -> alt.Chart:
"""Draw a stacked bar chart of average sales by carrier and grouping level.
The input is grouped with :func:`_group_fare_class_mix`, so callers may pass
either fare-class-level data or data already aggregated to `group_by`.
"""
import altair as alt
df, group_key = _group_fare_class_mix(df, group_by)
if title and group_key in _GROUP_TITLES:
title = f"{title} - by {_GROUP_TITLES[group_key]}"
label_threshold_value = df.groupby("carrier", observed=False).avg_sold.sum().max() * label_threshold
chart = alt.Chart(df, **({"title": title} if title else {})).transform_calculate(
halfsold="datum.avg_sold / 2.0",
)
bars = chart.mark_bar().encode(
x=alt.X("carrier:N", title="Carrier"),
y=alt.Y("avg_sold:Q", title="Seats").stack("zero"),
color=group_key,
tooltip=[
"carrier",
group_key,
alt.Tooltip("avg_sold", format=".2f"),
],
)
text = chart.mark_text(dx=0, dy=3, color="white", baseline="top").encode(
x=alt.X("carrier:N", title="Carrier"),
y=alt.Y("avg_sold:Q", title="Seats").stack("zero"),
text=alt.Text("avg_sold:Q", format=".2f"),
opacity=alt.condition(
f"datum.avg_sold < {label_threshold_value:.3f}",
alt.value(0),
alt.value(1),
),
# Labels must stack in the same order as the bars, which are colored by group_key.
order=alt.Order(f"{group_key}:N", sort="descending"),
tooltip=[
"carrier",
group_key,
alt.Tooltip("avg_sold", format=".2f"),
],
)
return (
(bars + text)
.properties(
width=400,
height=300,
)
.configure_axis(
labelFontSize=12,
titleFontSize=12,
)
.configure_legend(
titleFontSize=12,
labelFontSize=15,
)
)
[docs]
class SimTabFareClassMix(GenericSimulationTables):
"""Container for summary tables and figures extracted from a Simulation.
This class is a subclass of GenericSimulationTables, which is defined in
the generic module. It lists the items that are available in the
SimulationTables class, and provides type hints and (optionally, but
ideally) documentation for the data that is stored in each item.
"""
fare_class_mix: pd.DataFrame = SimulationTableItem(
aggregation_func=aggregate_by_summing_dataframe("fare_class_mix"),
extraction_func=extract_fare_class_mix,
doc="Fare class mix data.",
)
[docs]
@report_figure
def fig_fare_class_mix(
self,
*,
raw_df: bool = False,
also_df: bool = False,
label_threshold: float = 0.06,
title: str | None = "Fare Class Mix",
group_by: str | None = "",
) -> alt.Chart | pd.DataFrame | tuple[alt.Chart, pd.DataFrame]:
"""
Plot the fare class mix data.
Parameters
----------
raw_df : bool, optional
If True, return the raw dataframe instead of the figure.
also_df : bool, optional
If True, return the dataframe as well as the figure.
label_threshold : float, optional
The threshold for displaying labels on the bars. Default is 0.06.
title : str or None, optional
The figure title. When grouping by booking class or brand, the
grouping level is appended. None omits the title.
group_by : {"", "fare_class", "booking_class", "brand"} or None, optional
The level at which to aggregate average sales. The default (empty
string or None) shows each fare class. Any dataframe returned
through `raw_df` or `also_df` is aggregated to this same level.
Returns
-------
alt.Chart or pd.DataFrame or tuple[alt.Chart, pd.DataFrame]
The fare class mix figure or dataframe.
Raises
------
ValueError
If `group_by` is not a recognized grouping level.
"""
if self.fare_class_mix is not None and self.n_total_samples > 0:
df = self.fare_class_mix / self.n_total_samples
df = df.rename(columns={"sold": "avg_sold"})
df = df.reset_index()[["carrier", "fare_class", "booking_class", "brand", "avg_sold"]]
else:
return None
# Group here so any returned dataframe matches what the figure shows.
df, _ = _group_fare_class_mix(df, group_by)
if raw_df:
return df
fig = _fig_fare_class_mix(df, label_threshold=label_threshold, title=title, group_by=group_by)
if also_df:
return fig, df
return fig