Source code for data_cube.data_cube

"""
Python API of :class:`DataCube`, the computation is done in C++,
inputs and outputs are :class:`pandas.DataFrame`.
"""

import enum
import io
import warnings
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pandas
from pandas.api.types import is_datetime64_any_dtype
from ._convert import (
    dataframe_to_table,
    frame_to_dataframe,
    records_to_table,
    table_to_dataframe,
    to_column,
    to_value,
)
from ._helper import string_sig
from ._log_helper import align_dataframe_with, enumerate_csv_files, open_table
from .cube_py import _cubepy
from .cube_py._cubepy import Table


[docs] class CubeViewDef: """ Defines how to compute a view. :param key_index: keys to put in the row index :param values: values to show :param ignore_unique: ignore keys with a unique value :param order: to reorder key in columns index :param key_agg: aggregate according to these columns before creating the view :param agg_args: aggregation applied to every value, it can be a string (``"sum"``, ``"mean"``, ``"median"``, ``"min"``, ``"max"``, ``"count"``, ``"first"``, ``"last"``, ``"std"``, ``"var"``, ``"nunique"``, ``"size"``), a tuple containing a string or a dictionary ``{column: aggregation}``, it can be also a callable to return a different aggregation method depending on the column name :param agg_kwargs: not supported, kept for backward compatibility :param agg_multi: aggregation over multiple columns, every function receives a :class:`pandas.DataFrame` (the values of a group) and returns a float :param ignore_columns: ignore the following columns if known to overload the view :param keep_columns_in_index: keeps the columns even if there is only one unique value :param dropna: drops rows with nan if not relevant :param transpose: transpose :param f_highlight: to highlights some values :param name: name of the view, used mostly to debug :param plots: adds plot to the Excel sheet :param no_index: remove the index (but keeps the columns) :param fix_aggregation_change: a column among the keys which changes aggregation value for different dates Some examples of views. First example is an aggregated view for many metrics. .. code-block:: python cube = DataCube(...) CubeViewDef( key_index=cube.filter_column(fs, cube.keys_time), values=cube.filter_column( ["TIME_ITER", "speedup", "time_latency.*", "onnx_n_nodes"], cube.values, ), ignore_unique=True, key_agg=["model_name", "task", "model_task", "suite"], agg_args=lambda column_name: "sum" if column_name.startswith("n_") else "mean", agg_multi={"speedup_weighted": mean_weight, "speedup_geo": mean_geo}, name="agg-all", plots=True, ) Next one focuses on a couple of metrics. .. code-block:: python cube = DataCube(...) CubeViewDef( key_index=cube.filter_column(fs, cube.keys_time), values=cube.filter_column(["speedup"], cube.values), ignore_unique=True, keep_columns_in_index=["suite"], name="speedup", ) """
[docs] class HighLightKind(enum.IntEnum): "Codes to highlight values." NONE = 0 RED = 1 GREEN = 2
def __init__( self, key_index: Sequence[str], values: Sequence[str], ignore_unique: bool = True, order: Optional[Sequence[str]] = None, key_agg: Optional[Sequence[str]] = None, agg_args: Union[str, Sequence[Any], Callable[[str], str]] = ("sum",), agg_kwargs: Optional[Dict[str, Any]] = None, agg_multi: Optional[Dict[str, Callable[[pandas.DataFrame], float]]] = None, ignore_columns: Optional[Sequence[str]] = None, keep_columns_in_index: Optional[Sequence[str]] = None, dropna: bool = True, transpose: bool = False, f_highlight: Optional[Callable[[Any], "CubeViewDef.HighLightKind"]] = None, name: Optional[str] = None, no_index: bool = False, plots: bool = False, fix_aggregation_change: Optional[List[str]] = None, ): self.key_index = key_index self.values = values self.ignore_unique = ignore_unique self.order = order self.key_agg = key_agg self.agg_args = agg_args self.agg_kwargs = agg_kwargs self.agg_multi = agg_multi self.dropna = dropna self.ignore_columns = ignore_columns self.keep_columns_in_index = keep_columns_in_index self.f_highlight = f_highlight self.transpose = transpose self.name = name self.no_index = no_index self.plots = plots self.fix_aggregation_change = fix_aggregation_change def __repr__(self) -> str: "usual" return string_sig(self) # type: ignore[arg-type]
[docs] def to_cpp(self, values: Sequence[str]) -> _cubepy.ViewDef: """ Converts the definition into a C++ :class:`ViewDef`. :param values: values of the cube, used to resolve a callable *agg_args* :return: :class:`ViewDef` """ if self.agg_kwargs: raise NotImplementedError(f"agg_kwargs={self.agg_kwargs!r} is not supported.") vd = _cubepy.ViewDef() vd.key_index = list(self.key_index) vd.values = list(self.values) vd.ignore_unique = bool(self.ignore_unique) vd.order = list(self.order or []) vd.key_agg = list(self.key_agg or []) vd.ignore_columns = list(self.ignore_columns or []) vd.keep_columns_in_index = list(self.keep_columns_in_index or []) vd.dropna = bool(self.dropna) vd.transpose = bool(self.transpose) vd.name = self.name or "" vd.no_index = bool(self.no_index) vd.plots = bool(self.plots) vd.fix_aggregation_change = list(self.fix_aggregation_change or []) agg = self.agg_args if callable(agg): selected = DataCube.filter_column(self.values, values) vd.agg_by_column = {c: self._check_agg(agg(c)) for c in selected} elif isinstance(agg, str): vd.agg = self._check_agg(agg) elif isinstance(agg, dict): vd.agg_by_column = {k: self._check_agg(v) for k, v in agg.items()} else: agg = tuple(agg) if len(agg) != 1: raise NotImplementedError(f"agg_args={self.agg_args!r} is not supported.") if isinstance(agg[0], dict): vd.agg_by_column = {k: self._check_agg(v) for k, v in agg[0].items()} else: vd.agg = self._check_agg(agg[0]) if self.agg_multi: vd.set_agg_multi( [ (name, lambda table, f=f: float(f(table_to_dataframe(table)))) for name, f in self.agg_multi.items() ] ) return vd
@classmethod def _check_agg(cls, agg: Any) -> str: if not isinstance(agg, str): raise NotImplementedError( f"Only aggregations defined by their names are supported, not {agg!r}." ) return agg
[docs] class DataCube: """ Processes logs coming from experiments. A cube is basically a database with certain columns playing specific roles. * time: only one column, it is not mandatory but it is recommended to have one * keys: they are somehow coordinates, they cannot be aggregated, they are not numbers, more like categories, `(time, *keys)` identifies an element of the database in an unique way, there cannot be more than one row sharing the same key and time values * values: they are not necessary numerical, but if they are, they can be aggregated Every other column is kept but not used. More columns can be added by using formulas. The computation happens in C++ (see :class:`data_cube.cube_py._cubepy.DataCube`). :param data: the raw data, a :class:`pandas.DataFrame`, a list of dictionaries, a list of dataframes, a filename, a list of filenames or patterns (csv or zip files) :param time: the time column :param keys: the keys, can include regular expressions :param values: the values, can include regular expressions :param ignored: ignores some column, acts as negative regular expressions for the other two :param recent: if more than one rows share the same keys, the cube only keeps the most recent one :param formulas: columns to add, defined with formulas, a dictionary ``{name: f}`` where ``f`` receives a :class:`pandas.DataFrame` and returns a series :param fill_missing: a sequence of ``(column, value)``, defines values for the columns missing in some pieces of data :param keep_last_date: overwrites all the times with the most recent one, it makes things easier for timeseries """ def __init__( self, data: Any, time: str = "date", keys: Sequence[str] = ("version_.*", "model_.*"), values: Sequence[str] = ("time_.*", "disc_.*"), ignored: Sequence[str] = (), recent: bool = False, formulas: Optional[Dict[str, Callable[[pandas.DataFrame], Any]]] = None, fill_missing: Optional[Sequence[Tuple[str, Any]]] = None, keep_last_date: bool = False, ): self._data = data self._time = time self._keys = keys self._values = values self._ignored = ignored self.recent = recent self._formulas = formulas self.fill_missing = fill_missing self.keep_last_date = keep_last_date self._cube: Optional[_cubepy.DataCube] = None self._data_cache: Optional[pandas.DataFrame] = None @classmethod def _from_cpp(cls, cube: _cubepy.DataCube) -> "DataCube": res = cls(None, time=cube.time, keys=cube.keys_no_time, values=cube.values) res._cube = cube return res def _tables(self, verbose: int = 0) -> List[Table]: data = self._data if isinstance(data, Table): return [data] if isinstance(data, pandas.DataFrame): if verbose: print(f"[DataCube.load] load from dataframe, shape={data.shape}") return [dataframe_to_table(data)] if isinstance(data, list) and data and all(isinstance(r, dict) for r in data): if verbose: print(f"[DataCube.load] load from list of dicts, n={len(data)}") return [records_to_table(data)] if isinstance(data, list) and data and all(isinstance(r, Table) for r in data): return list(data) if isinstance(data, list) and data and all(isinstance(r, pandas.DataFrame) for r in data): if verbose: print(f"[DataCube.load] load from list of DataFrame, n={len(data)}") return [dataframe_to_table(r) for r in data] if isinstance(data, (list, str, tuple)): if verbose: print("[DataCube.load] load from list of files") tables = [open_table(item) for item in enumerate_csv_files(data, verbose=verbose)] assert tables, f"No file was found in {data!r}" return tables raise NotImplementedError(f"Not implemented with the provided data (type={type(data)})") def _cpp_formulas(self) -> List[Tuple[str, Callable[[Table], Any]]]: if not self._formulas: return [] if not isinstance(self._formulas, dict): raise TypeError( f"formulas must be a dictionary {{name: callable}}, got {type(self._formulas)}" ) def _wrap(f): assert callable(f), f"formula={f!r} is not supported." def _call(table): df = table_to_dataframe(table) res = f(df) if isinstance(res, pandas.Series): res = res.to_numpy() return to_column(res, table.num_rows) return _call return [(k, _wrap(f)) for k, f in self._formulas.items()]
[docs] def load(self, verbose: int = 0) -> "DataCube": """Loads and preprocesses the data. Returns self.""" tables = self._tables(verbose=verbose) fill_missing = [(k, to_value(v)) for k, v in (self.fill_missing or [])] self._cube = _cubepy.DataCube( tables, time=self._time, keys=list(self._keys), values=list(self._values), ignored=list(self._ignored), recent=bool(self.recent), formulas=self._cpp_formulas(), fill_missing=fill_missing, keep_last_date=bool(self.keep_last_date), ) self._cube.load(verbose=verbose) self._data_cache = None return self
@property def cpp(self) -> _cubepy.DataCube: "Returns the C++ cube." assert self._cube is not None, "Method load was not called" return self._cube @property def data(self) -> pandas.DataFrame: "Returns the processed data (a copy converted into a dataframe)." if self._data_cache is None: self._data_cache = table_to_dataframe(self.cpp.data) return self._data_cache @property def shape(self) -> Tuple[int, int]: "Returns the shape." return tuple(self.cpp.shape) # type: ignore[return-value] @property def columns(self) -> List[str]: "Returns the columns." return list(self.cpp.columns) @property def time(self) -> str: "Returns the time column." return self.cpp.time @property def keys_no_time(self) -> List[str]: "Returns the keys without the time." return list(self.cpp.keys_no_time) @property def keys_time(self) -> List[str]: "Returns the time and the keys." return list(self.cpp.keys_time) @property def values(self) -> List[str]: "Returns the values." return list(self.cpp.values) @property def ignored(self) -> List[str]: "Returns the ignored columns." return list(self.cpp.ignored) @property def ignored_keys(self) -> List[str]: "Returns the ignored keys." return list(self.cpp.ignored_keys) @property def ignored_values(self) -> List[str]: "Returns the ignored values." return list(self.cpp.ignored_values) @property def dropped(self) -> List[str]: "Returns the unused columns (neither time, keys, values or ignored)." return list(self.cpp.dropped) @property def keys_with_nans(self) -> List[str]: "Returns the keys with missing values." return list(self.cpp.keys_with_nans) @property def n_unique_for_key(self) -> Dict[str, int]: "Returns the number of distinct values for every key." return dict(self.cpp.n_unique_for_key)
[docs] @classmethod def filter_column( cls, filters: Sequence[str], columns: Sequence[str], can_be_empty: bool = False ) -> List[str]: """ Selects the columns matching filters. A filter is a regular expression if it contains one of ``"^.*+{}``, otherwise it must be equal to a column name. """ return _cubepy.DataCube.filter_column(list(filters), list(columns), can_be_empty)
_filter_column = filter_column def __str__(self) -> str: "usual" return str(self.data) if self._cube is not None else str(self._data)
[docs] def clone( self, data: Optional[pandas.DataFrame] = None, keys: Optional[Sequence[str]] = None ) -> "DataCube": """ Makes a copy of the dataframe. It copies the processed data not the original one. """ cube = self.__class__( dataframe_to_table(data) if data is not None else self.cpp.data, time=self.time, keys=keys or self.keys_no_time, values=self.values, ) cube.load() return cube
[docs] def make_view_def(self, name: str) -> Optional[CubeViewDef]: """ Returns a view definition. :param name: name of a value :return: a CubeViewDef or None if name does not make sense """ vd = self.cpp.make_view_def(name) return CubeViewDef(key_index=list(vd.key_index), values=list(vd.values), name=vd.name)
[docs] def view( self, view_def: Union[str, CubeViewDef], return_view_def: bool = False, verbose: int = 0 ) -> Union[pandas.DataFrame, Tuple[pandas.DataFrame, CubeViewDef]]: """ Returns a dataframe, a pivot view. `key_index` determines the index, the other key columns determines the columns. If `ignore_unique` is True, every columns with a unique value is removed. :param view_def: view definition :param return_view_def: returns the view as well :param verbose: verbosity level :return: dataframe """ if isinstance(view_def, str): view_def_ = self.make_view_def(view_def) assert view_def_ is not None, f"Unable to create a view from {view_def!r}" view_def = view_def_ assert isinstance( view_def, CubeViewDef ), f"view_def should be a CubeViewDef, got {type(view_def)}: {view_def!r} instead" frame = self.cpp.view(view_def.to_cpp(self.values), verbose=verbose) piv = frame_to_dataframe(frame) return (piv, view_def) if return_view_def else piv
[docs] def describe(self) -> pandas.DataFrame: """Basic description of all variables.""" return frame_to_dataframe(self.cpp.describe())
[docs] def cube_time(self, fill_other_dates: bool = False, threshold: float = 1.2) -> "DataCube": """ Aggregates the data over time to detect changes on the last value. If *fill_other_dates* is True, all dates are kept, but values are filled with 0. *threshold* determines the bandwidth within the values are expected, should be a factor of the standard deviation. """ return DataCube._from_cpp( self.cpp.cube_time(fill_other_dates=fill_other_dates, threshold=threshold) )
[docs] def sbs( self, configs: Dict[str, Dict[str, Any]], column_name: str = "CONF" ) -> Tuple[pandas.DataFrame, pandas.DataFrame, pandas.DataFrame]: """ Creates a side-by-side for two configurations. Every configuration a dictionary column:value which filters in the rows to keep in order to compute the side by side. Every configuration is given a name (the key in configs), it is added in column column_name. :param configs: example ``dict(CFA=dict(exporter="E1", opt="O"), CFB=dict(exporter="E2", opt="O"))`` :param column_name: column to add with the name of the configuration :return: data, aggregated date, data with a row per model """ cpp_configs = [ (name, [(k, to_value(v)) for k, v in conf.items()]) for name, conf in configs.items() ] raw, agg, col = self.cpp.sbs(cpp_configs, column_name) return frame_to_dataframe(raw), frame_to_dataframe(agg), frame_to_dataframe(col)
[docs] def to_excel( self, output: str, views: Union[Sequence[str], Dict[str, Union[str, CubeViewDef]]], main: Optional[str] = "main", raw: Optional[str] = "raw", verbose: int = 0, csv: Optional[Sequence[str]] = None, time_mask: bool = False, sbs: Optional[Dict[str, Dict[str, Any]]] = None, ): """ Creates an excel file with a list of views. :param output: output file to create :param views: sequence or dictionary of views to append :param main: add a page with statistics on all variables :param raw: add a page with the raw data :param csv: views to dump as csv files (same name as outputs + view name) :param verbose: verbosity :param time_mask: color the background of the cells if one of the value for the last date is unexpected, assuming they should remain stale :param sbs: configurations to compare side-by-side, this adds two tabs, one gathering raw data about the two configurations, the other one is aggregated by metrics, example: ``=dict(CFA=dict(exporter="E1", opt="O"), CFB=dict(exporter="E2", opt="O"))`` """ from ._excel_helper import apply_excel_style from .cube_plot import CubePlot if verbose: print(f"[DataCube.to_excel] create Excel file {output}, shape={self.shape}") time_mask &= len(self.data[self.time].unique()) > 2 cube_time = self.cube_time(fill_other_dates=True) if time_mask else None views = {k: k for k in views} if not isinstance(views, dict) else views f_highlights = {} plots = [] with pandas.ExcelWriter(output, engine="openpyxl") as writer: if main: assert main not in views, f"{main!r} is duplicated in views {sorted(views)}" df = self.describe().sort_index() if verbose: print(f"[DataCube.to_excel] add sheet {main!r} with shape {df.shape}") df.to_excel(writer, sheet_name=main, freeze_panes=(1, 1)) time_mask_view: Dict[str, pandas.DataFrame] = {} df = None for name, view in views.items(): if view is None: continue df, tview = self.view(view, return_view_def=True, verbose=max(verbose - 1, 0)) if cube_time is not None: cube_mask = cube_time.view(view) assert isinstance(cube_mask, pandas.DataFrame) # type checking assert isinstance(df, pandas.DataFrame) # type checking aligned = align_dataframe_with(cube_mask, df) if aligned is not None: assert aligned.shape == df.shape, ( f"Shape mismatch between the view {df.shape} and the mask " f"{aligned.shape}" ) time_mask_view[name] = aligned if verbose: print( f"[DataCube.to_excel] compute mask for view {name!r} " f"with shape {aligned.shape}" ) if tview is None: continue assert isinstance(df, pandas.DataFrame) # type checking memory = df.memory_usage(deep=True).sum() if verbose: print( f"[DataCube.to_excel] add sheet {name!r} with shape " f"{df.shape} ({memory} bytes), index={df.index.names}, " f"columns={df.columns.names}" ) if self.time in df.columns.names: # Let's convert the time into str fr = df.columns.to_frame() if is_datetime64_any_dtype(fr[self.time]): dt = fr[self.time] has_time = (dt != dt.dt.normalize()).any() # type: ignore[missing-attribute] sdt = dt.apply( lambda t, has_time=has_time: t.strftime( "%Y-%m-%dT%H-%M-%S" if has_time else "%Y-%m-%d" ) ) fr[self.time] = sdt df.columns = pandas.MultiIndex.from_frame(fr) if csv and name in csv: name_csv = f"{output}.{name}.csv" if verbose: print(f"[DataCube.to_excel] saving sheet {name!r} in {name_csv!r}") df.reset_index(drop=False).to_csv(f"{output}.{name}.csv", index=False) if memory > 2**22: msg = ( f"[DataCube.to_excel] skipping {name!r}, " f"too big for excel with {memory} bytes" ) if verbose: print(msg) else: warnings.warn(msg, category=RuntimeWarning, stacklevel=0) else: df.to_excel( writer, sheet_name=name, freeze_panes=(df.columns.nlevels + 1, df.index.nlevels), ) f_highlights[name] = tview.f_highlight if tview.plots: plots.append( CubePlot( df, kind="line", orientation="row", split=True, timeseries=self.time, ) if self.time in df.columns.names else CubePlot(df, kind="barh", orientation="row", split=True) ) if raw: assert raw not in views, f"{raw!r} is duplicated in views {sorted(views)}" data = self.data if csv and "raw" in csv: data.reset_index(drop=False).to_csv(f"{output}.raw.csv", index=False) memory = data.memory_usage(deep=True).sum() if memory > 2**22: msg = ( f"[DataCube.to_excel] skipping 'raw', " f"too big for excel with {memory} bytes" ) if verbose: print(msg) else: warnings.warn(msg, category=RuntimeWarning, stacklevel=0) else: if verbose: print(f"[DataCube.to_excel] add sheet 'raw' with shape {self.shape}") data.to_excel(writer, sheet_name=raw, freeze_panes=(1, 1), index=True) if sbs: if verbose: for k, v in sbs.items(): print(f"[DataCube.to_excel] sbs {k}: {v}") name = "∧".join(sbs) sbs_raw, sbs_agg, sbs_col = self.sbs(sbs) if verbose: print(f"[DataCube.to_excel] add sheet {name!r} with shape {sbs_raw.shape}") print( f"[DataCube.to_excel] add sheet '{name}-AGG' " f"with shape {sbs_agg.shape}" ) sbs_raw = sbs_raw.reset_index(drop=False) sbs_raw.to_excel( writer, sheet_name=name, freeze_panes=(sbs_raw.columns.nlevels + 1, sbs_raw.index.nlevels), ) sbs_agg.to_excel( writer, sheet_name=f"{name}-AGG", freeze_panes=(sbs_agg.columns.nlevels + 1, sbs_agg.index.nlevels), ) sbs_col.to_excel( writer, sheet_name=f"{name}-COL", freeze_panes=(sbs_col.columns.nlevels + 1, sbs_col.index.nlevels), ) if plots: from openpyxl.drawing.image import Image # type: ignore if verbose: print(f"[DataCube.to_excel] plots {len(plots)} plots") sheet = writer.book.create_sheet("plots") pos = 0 times = self.data[self.time].dropna() mini, maxi = times.min(), times.max() title_suffix = (str(mini) if mini == maxi else f"{mini}-{maxi}").replace( " 00:00:00", "" ) for plot in plots: imgs = plot.to_images(verbose=verbose, merge=True, title_suffix=title_suffix) for img in imgs: y = (pos // 2) * 16 + 1 loc = f"A{y}" if pos % 2 == 0 else f"M{y}" sheet.add_image(Image(io.BytesIO(img)), loc) if verbose: no = f"{output}.png" print(f"[DataCube.to_excel] dump graphs into {no!r}") with open(no, "wb") as f: f.write(img) pos += 1 if verbose: print(f"[DataCube.to_excel] applies style to {output!r}") apply_excel_style( writer, f_highlights, time_mask_view=time_mask_view, verbose=verbose # type: ignore[arg-type] ) if verbose: print(f"[DataCube.to_excel] done with {len(views)} views")