"""
.. _l-plot-data-cube-sbs:

Side by side comparison of two configurations
=============================================

:meth:`data_cube.DataCube.sbs` compares two (or more) configurations,
each one defined by a set of key values. For every pair of configurations
and every metric, it counts how many times a metric is missing in one
configuration or both, how many times one is lower, equal or greater than
the other, and it sums the metric over the rows where both are available.

Data
++++

Two exporters are benchmarked over three models and two days.
Some runs failed (empty values), and one run uses another optimization
level, it is excluded by the configurations.
"""

import io
import textwrap
import pandas
import matplotlib.pyplot as plt
from data_cube import DataCube

pandas.set_option("display.width", 250)
pandas.set_option("display.max_columns", 30)

df = pandas.read_csv(io.StringIO(textwrap.dedent("""
    date,model_name,exporter,opt,time_latency,accuracy
    2025/01/01,phi3,export,O2,0.10,0.99
    2025/01/01,phi3,dynamo,O2,0.12,0.99
    2025/01/01,phi4,export,O2,0.20,0.98
    2025/01/01,phi4,dynamo,O2,,
    2025/01/01,llama,export,O2,0.31,0.97
    2025/01/01,llama,dynamo,O2,0.29,0.97
    2025/01/02,phi3,export,O2,0.09,0.99
    2025/01/02,phi3,dynamo,O2,0.11,0.99
    2025/01/02,phi4,export,O2,0.21,0.98
    2025/01/02,phi4,dynamo,O2,0.19,0.98
    2025/01/02,llama,export,O2,,
    2025/01/02,llama,dynamo,O2,0.28,0.96
    2025/01/02,llama,dynamo,O0,0.40,0.96
    """)))

cube = DataCube(
    df, time="date", keys=["model_name", "exporter", "opt"], values=["time_.*", "accuracy"]
).load()
print(cube.describe())

# %%
# Side by side
# ++++++++++++
#
# Every configuration has a name and a dictionary ``{key: value}`` selecting
# the rows it contains. All configurations must use the same keys.

configs = dict(EXPORT=dict(exporter="export", opt="O2"), DYNAMO=dict(exporter="dynamo", opt="O2"))
sbs, sbs_agg, sbs_col = cube.sbs(configs)

# %%
# The first dataframe has one row per metric, model and date.
# The column level ``CONF`` contains the configuration names followed by
# the comparison columns:
#
# * ``∅EXPORT∧∅DYNAMO``: both values are missing,
# * ``∅EXPORT∧DYNAMO``, ``EXPORT∧∅DYNAMO``: only one value is missing,
# * ``EXPORT∧DYNAMO``: both values are available,
# * ``EXPORT<DYNAMO``, ``EXPORT==DYNAMO``, ``EXPORT>DYNAMO``: comparison,
# * ``EXPORT*(EXPORT∧DYNAMO)``, ``DYNAMO*(EXPORT∧DYNAMO)``: the value
#   when both are available, 0 otherwise.

print(sbs.columns.tolist())
print(sbs.loc["time_latency"])

# %%
# The second dataframe aggregates over the models for every date.
# The metrics are averaged, the comparison columns are summed.
# Summing the last two columns gives the total latency of both exporters
# over the models where both succeeded, a fair comparison.

print(sbs_agg)

# %%
# The third dataframe moves the metrics into the columns,
# one row per model and date.

print(sbs_col.index.names, sbs_col.columns.names)
print(sbs_col["time_latency"][["EXPORT", "DYNAMO"]])

# %%
# Excel
# +++++
#
# :meth:`data_cube.DataCube.to_excel` adds the side by side in dedicated
# sheets with ``sbs=configs``.
#
# .. code-block:: python
#
#     cube.to_excel("report.xlsx", views=["time_latency"], sbs=configs)
#
# Plot
# ++++
#
# Latency of both exporters for every model and date.

latency = sbs.loc["time_latency"][["EXPORT", "DYNAMO"]].droplevel("exporter", axis=1)
ax = latency.plot.bar(title="time_latency, EXPORT vs DYNAMO")
ax.set_ylabel("seconds")
plt.tight_layout()
