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

Add a variable computed with a formula
======================================

The logs rarely contain every metric needed to compare experiments.
Argument ``formulas`` of :class:`data_cube.DataCube` adds new columns
when the data is loaded. Every formula is a function receiving a
:class:`pandas.DataFrame` (the data loaded so far) and returning a series.
The new columns are values: they can be shown in views and aggregated
like any other value.

Data
++++

Every row is one model exported with one exporter on one day.
The latency of the exported model and the latency of the original model
(the baseline) are measured, as well as the peak memory.
One export failed (no latency) and one exported model is slower than the baseline.
"""

import io
import textwrap
import numpy as np
import pandas
import matplotlib.pyplot as plt
from data_cube import DataCube, CubeViewDef

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,time_latency,time_baseline,mem_peak
    2025/01/01,phi3,export,0.10,0.15,1200
    2025/01/01,phi3,dynamo,0.12,0.15,1100
    2025/01/01,phi4,export,0.20,0.26,2300
    2025/01/01,phi4,dynamo,,0.26,
    2025/01/01,llama,export,0.31,0.35,4100
    2025/01/01,llama,dynamo,0.29,0.35,3900
    2025/01/02,phi3,export,0.09,0.15,1210
    2025/01/02,phi3,dynamo,0.11,0.15,1090
    2025/01/02,phi4,export,0.21,0.26,2280
    2025/01/02,phi4,dynamo,0.19,0.26,2250
    2025/01/02,llama,export,0.38,0.35,4150
    2025/01/02,llama,dynamo,0.28,0.35,3870
    """)))

# %%
# Formulas
# ++++++++
#
# Three variables are added:
#
# * ``speedup``: the baseline latency divided by the latency,
# * ``speedup_increase``: the relative gain in percent, it reuses ``speedup``,
#   formulas are applied in the order of the dictionary and every formula
#   sees the columns added by the previous ones,
# * ``faster``: 1 if the exported model is faster than the baseline,
#   0 if it is not, missing if the export failed.


def faster(data: pandas.DataFrame) -> pandas.Series:
    res = (data["time_latency"] < data["time_baseline"]).astype(float)
    res[data["time_latency"].isna()] = np.nan
    return res


cube = DataCube(
    df,
    time="date",
    keys=["model_name", "exporter"],
    values=["time_.*", "mem_.*"],
    formulas={
        "speedup": lambda d: d["time_baseline"] / d["time_latency"],
        "speedup_increase": lambda d: (d["speedup"] - 1) * 100,
        "faster": faster,
    },
).load()

print(cube.values)
print(cube.data[["date", "model_name", "exporter", "speedup", "speedup_increase", "faster"]])

# %%
# The new variables are described like the others.

print(cube.describe())

# %%
# A view on a formula
# +++++++++++++++++++
#
# The models are the rows, the exporters and dates are the columns.

view = cube.view(CubeViewDef(key_index=["model_name"], values=["speedup_increase"]))
print(view)

# %%
# Aggregation
# +++++++++++
#
# The speedup is averaged over the models and ``faster`` is summed:
# it counts the models faster than the baseline.

agg = cube.view(
    CubeViewDef(
        key_index=["exporter"],
        values=["speedup", "faster"],
        key_agg=["model_name"],
        agg_args=lambda name: "sum" if name == "faster" else "mean",
    )
)
print(agg)

# %%
# Plot
# ++++

ts = cube.view(CubeViewDef(key_index=["model_name", "exporter"], values=["speedup"]))
ax = ts.T.droplevel(0).plot(title="speedup over time", marker="o")
ax.set_ylabel("baseline / latency")
plt.tight_layout()
