Python API#

DataCube#

class data_cube.DataCube(data: Any, time: str = 'date', keys: Sequence[str] = ('version_.*', 'model_.*'), values: Sequence[str] = ('time_.*', 'disc_.*'), ignored: Sequence[str] = (), recent: bool = False, formulas: Dict[str, Callable[[DataFrame], Any]] | None = None, fill_missing: Sequence[Tuple[str, Any]] | None = None, keep_last_date: bool = False)[source]#

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 data_cube.cube_py._cubepy.DataCube).

Parameters:
  • data – the raw data, a pandas.DataFrame, a list of dictionaries, a list of dataframes, a filename, a list of filenames or patterns (csv or zip files)

  • time – the time column

  • keys – the keys, can include regular expressions

  • values – the values, can include regular expressions

  • ignored – ignores some column, acts as negative regular expressions for the other two

  • recent – if more than one rows share the same keys, the cube only keeps the most recent one

  • formulas – columns to add, defined with formulas, a dictionary {name: f} where f receives a pandas.DataFrame and returns a series

  • fill_missing – a sequence of (column, value), defines values for the columns missing in some pieces of data

  • keep_last_date – overwrites all the times with the most recent one, it makes things easier for timeseries

load(verbose: int = 0) → DataCube[source]#

Loads and preprocesses the data. Returns self.

property cpp: DataCube#

Returns the C++ cube.

property data: DataFrame#

Returns the processed data (a copy converted into a dataframe).

property shape: Tuple[int, int]#

Returns the shape.

property columns: List[str]#

Returns the columns.

property time: str#

Returns the time column.

property keys_no_time: List[str]#

Returns the keys without the time.

property keys_time: List[str]#

Returns the time and the keys.

property values: List[str]#

Returns the values.

property ignored: List[str]#

Returns the ignored columns.

property ignored_keys: List[str]#

Returns the ignored keys.

property ignored_values: List[str]#

Returns the ignored values.

property dropped: List[str]#

Returns the unused columns (neither time, keys, values or ignored).

property keys_with_nans: List[str]#

Returns the keys with missing values.

property n_unique_for_key: Dict[str, int]#

Returns the number of distinct values for every key.

classmethod filter_column(filters: Sequence[str], columns: Sequence[str], can_be_empty: bool = False) → List[str][source]#

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.

clone(data: DataFrame | None = None, keys: Sequence[str] | None = None) → DataCube[source]#

Makes a copy of the dataframe. It copies the processed data not the original one.

make_view_def(name: str) → CubeViewDef | None[source]#

Returns a view definition.

Parameters:

name – name of a value

Returns:

a CubeViewDef or None if name does not make sense

view(view_def: str | CubeViewDef, return_view_def: bool = False, verbose: int = 0) → DataFrame | Tuple[DataFrame, CubeViewDef][source]#

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.

Parameters:
  • view_def – view definition

  • return_view_def – returns the view as well

  • verbose – verbosity level

Returns:

dataframe

describe() → DataFrame[source]#

Basic description of all variables.

cube_time(fill_other_dates: bool = False, threshold: float = 1.2) → DataCube[source]#

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.

sbs(configs: Dict[str, Dict[str, Any]], column_name: str = 'CONF') → Tuple[DataFrame, DataFrame, DataFrame][source]#

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.

Parameters:
  • configs – example dict(CFA=dict(exporter="E1", opt="O"), CFB=dict(exporter="E2", opt="O"))

  • column_name – column to add with the name of the configuration

Returns:

data, aggregated date, data with a row per model

to_excel(output: str, views: Sequence[str] | Dict[str, str | CubeViewDef], main: str | None = 'main', raw: str | None = 'raw', verbose: int = 0, csv: Sequence[str] | None = None, time_mask: bool = False, sbs: Dict[str, Dict[str, Any]] | None = None)[source]#

Creates an excel file with a list of views.

Parameters:
  • output – output file to create

  • views – sequence or dictionary of views to append

  • main – add a page with statistics on all variables

  • raw – add a page with the raw data

  • csv – views to dump as csv files (same name as outputs + view name)

  • verbose – verbosity

  • time_mask – color the background of the cells if one of the value for the last date is unexpected, assuming they should remain stale

  • 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"))

class data_cube.CubeViewDef(key_index: Sequence[str], values: Sequence[str], ignore_unique: bool = True, order: Sequence[str] | None = None, key_agg: Sequence[str] | None = None, agg_args: str | Sequence[Any] | Callable[[str], str] = ('sum',), agg_kwargs: Dict[str, Any] | None = None, agg_multi: Dict[str, Callable[[DataFrame], float]] | None = None, ignore_columns: Sequence[str] | None = None, keep_columns_in_index: Sequence[str] | None = None, dropna: bool = True, transpose: bool = False, f_highlight: Callable[[Any], HighLightKind] | None = None, name: str | None = None, no_index: bool = False, plots: bool = False, fix_aggregation_change: List[str] | None = None)[source]#

Defines how to compute a view.

Parameters:
  • key_index – keys to put in the row index

  • values – values to show

  • ignore_unique – ignore keys with a unique value

  • order – to reorder key in columns index

  • key_agg – aggregate according to these columns before creating the view

  • 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

  • agg_kwargs – not supported, kept for backward compatibility

  • agg_multi – aggregation over multiple columns, every function receives a pandas.DataFrame (the values of a group) and returns a float

  • ignore_columns – ignore the following columns if known to overload the view

  • keep_columns_in_index – keeps the columns even if there is only one unique value

  • dropna – drops rows with nan if not relevant

  • transpose – transpose

  • f_highlight – to highlights some values

  • name – name of the view, used mostly to debug

  • plots – adds plot to the Excel sheet

  • no_index – remove the index (but keeps the columns)

  • 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.

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.

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",
)
class HighLightKind(*values)[source]#

Codes to highlight values.

to_cpp(values: Sequence[str]) → ViewDef[source]#

Converts the definition into a C++ ViewDef.

Parameters:

values – values of the cube, used to resolve a callable agg_args

Returns:

ViewDef

class data_cube.CubePlot(df: DataFrame, kind: str = 'bar', orientation='col', split: bool = True, timeseries: str | None = None)[source]#

Creates a plot.

Parameters:
  • df – dataframe

  • kind – kind of graph to plot, bar, barh, line

  • split – draw a graph per line in the dataframe

  • timeseries – this assumes the time is one level of the columns, this argument indices the level name

It defines a graph. Usually bar or barh is used to compare experiments for every metric, a subplot by metric.

CubePlot(df, kind="barh", orientation="row", split=True)

line is usually used to plot timeseries showing the evolution of metrics over time.

CubePlot(
    df,
    kind="line",
    orientation="row",
    split=True,
    timeseries="time",
)
classmethod group_columns(columns: List[str], sep: str = '/', depth: int = 2) → List[List[str]][source]#

Groups columns to have nice display.

to_images(verbose: int = 0, merge: bool = True, title_suffix: str | None = None) → List[bytes][source]#

Converts data into plots and images.

Parameters:
  • verbose – verbosity

  • merge – returns all graphs in a single image (True) or an image for every graph (False)

  • title_suffix – suffix for the title of every graph

Returns:

list of binary images (format PNG)

Conversions#

data_cube.to_column(values: Any, size: int = -1) → Column[source]#

Converts a sequence of values (pandas Series, numpy array, list, scalar) into a Column.

Parameters:
  • values – values

  • size – expected size, a scalar is repeated size times

Returns:

column

data_cube.column_to_numpy(column: Column) → ndarray[source]#

Converts a Column into a numpy array. Integer columns with missing values become float arrays, string columns become object arrays where missing values are np.nan.

data_cube.dataframe_to_table(df: DataFrame) → Table[source]#

Converts a pandas.DataFrame into a Table.

data_cube.table_to_dataframe(table: Table) → DataFrame[source]#

Converts a Table into a pandas.DataFrame.

data_cube.frame_to_dataframe(frame: Frame) → DataFrame[source]#

Converts a Frame into a pandas.DataFrame.

Files#

data_cube._log_helper.enumerate_csv_files(data: DataFrame | List[str | Tuple[str, str, str, str]] | str | Tuple[str, str, str, str], verbose: int = 0, filtering: Callable[[str], bool] | None = None) → Iterator[DataFrame | str | Tuple[str, str, str, str]][source]#

Enumerates files considered for the aggregation. Only csv files are considered. If a zip file is given, the function digs into the zip files and loops over csv candidates.

Parameters:
  • data – dataframe with the raw data or a file or list of files

  • verbose – verbosity

  • filtering – function to filter in or out files in zip files, must return true to keep the file, false to skip it.

Returns:

a generator yielding tuples with the filename, date, full path and zip file

data can contains: * a dataframe * a string for a filename, zip or csv * a list of string * a tuple

data_cube._log_helper.open_table(data: str | Tuple[str, str, str, str] | DataFrame | Table) → Table[source]#

Opens a filename defined by function enumerate_csv_files() with the C++ CSV parser and adds a column RAWFILENAME.

Parameters:

data – a dataframe, a table, a filename, a tuple indicating the file is coming from a zip file

Returns:

a Table

data_cube._log_helper.open_dataframe(data: str | Tuple[str, str, str, str] | DataFrame) → DataFrame[source]#

Opens a filename defined by function data_cube._log_helper.enumerate_csv_files().

Parameters:

data – a dataframe, a filename, a tuple indicating the file is coming from a zip file

Returns:

a dataframe

data_cube._log_helper.filter_data(df: DataFrame, filter_in: str | None = None, filter_out: str | None = None, verbose: int = 0) → DataFrame[source]#

Argument filter follows the syntax <column1>:<fmt1>//<column2>:<fmt2>.

The format is the following:

  • a value or a set of values separated by ;

data_cube._log_helper.align_dataframe_with(df: DataFrame, baseline: DataFrame, fill_value: float = 0) → DataFrame | None[source]#

Modifies the first dataframe df to get the exact same number of columns and rows. They must share the same levels on both axes. Empty cells are filled with 0. We only keep the numerical columns. The function return None if the output is empty.

data_cube._excel_helper.apply_excel_style(filename_or_writer: Any, f_highlights: Dict[str, Callable[[Any], CubeViewDef.HighLightKind]] | None = None, time_mask_view: Dict[str, DataFrame] | None = None, verbose: int = 0)[source]#

Applies styles on all sheets in a file unless the sheet is too big.

Parameters:
  • filename_or_writer – filename, modified inplace

  • f_highlight – color function to apply, one per sheet

  • time_mask_view – if specified, it contains dataframe with the same shape and values in {-1, 0, +1} which indicates if a value is unexpectedly lower (-1) or higher (+1), it changes the color of the background then.

  • verbose – progress loop

C++ extension#

C++ implementation of DataCube.

class data_cube.cube_py._cubepy.Column(*args, **kwargs)#

Typed column, missing values are supported.

cast(self, type: data_cube.cube_py._cubepy.ColumnType) → data_cube.cube_py._cubepy.Column#

Casts the column into another type.

from_float64 = <nanobind.nb_func object>#
from_int64 = <nanobind.nb_func object>#
from_strings = <nanobind.nb_func object>#
from_timestamps = <nanobind.nb_func object>#
from_values = <nanobind.nb_func object>#
full = <nanobind.nb_func object>#
is_null(self, i: int) → bool#

Tells if a value is missing.

null_count(self) → int#

Returns the number of missing values.

take(self, rows: collections.abc.Sequence[int]) → data_cube.cube_py._cubepy.Column#

Returns a column with the selected rows.

to_float64(self) → numpy.ndarray[dtype=float64, shape=(*)]#

Returns the values as a float array, missing values are NaN.

to_int64(self) → numpy.ndarray[dtype=int64, shape=(*)]#

Returns the integer storage (int64 or datetime columns).

to_list(self) → list#

Returns the values as a list.

to_strings(self) → list#

Returns the values as strings, missing values are None.

property type#

Column type.

valid(self) → numpy.ndarray[dtype=uint8, shape=(*)]#

Returns the validity mask (1 for a valid value).

class data_cube.cube_py._cubepy.ColumnType(*values)#

Physical type of a column.

Int64 = 0#
Float64 = 1#
String = 2#
DateTime = 3#
class data_cube.cube_py._cubepy.DataCube(*args, **kwargs)#

Processes logs coming from experiments.

clone(self, data: data_cube.cube_py._cubepy.Table | None = None, keys: collections.abc.Sequence[str] | None = None) → data_cube.cube_py._cubepy.DataCube#

Makes a copy of the cube.

property columns#

(self) -> list[str]

cube_time(self, fill_other_dates: bool = False, threshold: float = 1.2) → data_cube.cube_py._cubepy.DataCube#

Detects changes on the last date.

property data#

Processed data (a copy).

describe(self) → data_cube.cube_py._cubepy.Frame#

Basic description of all variables.

property dropped#

(self) -> list[str]

filter_column = <nanobind.nb_func object>#
fix_aggregation_change(self, data: data_cube.cube_py._cubepy.Table, columns_to_fix: collections.abc.Sequence[str]) → data_cube.cube_py._cubepy.Table#
property ignored#

(self) -> list[str]

property ignored_keys#

(self) -> list[str]

property ignored_values#

(self) -> list[str]

property is_loaded#

(self) -> bool

property keep_last_date#

(self) -> bool

property keys_no_time#

(self) -> list[str]

property keys_time#

(self) -> list[str]

property keys_with_nans#

(self) -> list[str]

load(self, verbose: int = 0, log: collections.abc.Callable | None = None) → None#

Loads and preprocesses the data.

make_view_def(self, name: str) → data_cube.cube_py._cubepy.ViewDef#
property n_unique_for_key#

(self) -> dict[str, int]

property recent#

(self) -> bool

sbs(self, configs: collections.abc.Sequence[tuple[str, collections.abc.Sequence[tuple[str, None | int | float | str | data_cube.cube_py._cubepy.Timestamp]]]], column_name: str = 'CONF') → tuple[data_cube.cube_py._cubepy.Frame, data_cube.cube_py._cubepy.Frame, data_cube.cube_py._cubepy.Frame]#

Creates a side-by-side.

property shape#

(self) -> tuple[int, int]

property time#

(self) -> str

property values#

(self) -> list[str]

view(self, view_def: data_cube.cube_py._cubepy.ViewDef, verbose: int = 0, log: collections.abc.Callable | None = None) → data_cube.cube_py._cubepy.Frame#

Returns a pivot view.

class data_cube.cube_py._cubepy.Frame(*args, **kwargs)#

Result of a view, a two dimensional table with multi-level indices.

property column_names#

Names of the column index levels.

property columns#

Column index levels.

property data#

Data, one Column per column.

property index#

Row index levels.

property index_names#

Names of the row index levels.

property num_columns#

Number of columns.

property num_rows#

Number of rows.

reset_index(self) → data_cube.cube_py._cubepy.Frame#

Moves the row index into the columns.

sort_columns(self) → None#

Sorts the columns.

sort_index(self) → None#

Sorts the rows.

stack(self, level: str) → data_cube.cube_py._cubepy.Frame#

Moves a column level into the row index.

to_string(self, max_rows: int = 30) → str#

Text representation.

transpose(self) → data_cube.cube_py._cubepy.Frame#

Returns the transposed frame.

class data_cube.cube_py._cubepy.HighLightKind(*values)#

Codes to highlight values.

NONE = 0#
RED = 1#
GREEN = 2#
class data_cube.cube_py._cubepy.Table(*args, **kwargs)#

A list of named columns sharing the same number of rows.

add_column(self, name: str, column: data_cube.cube_py._cubepy.Column) → None#

Adds or replaces a column.

column(self, name: str) → data_cube.cube_py._cubepy.Column#

Returns a copy of a column.

concat = <nanobind.nb_func object>#
drop_column(self, name: str) → None#

Removes a column.

from_records = <nanobind.nb_func object>#
has_column(self, name: str) → bool#

Tells if a column exists.

property names#

Column names.

property num_columns#

Number of columns.

property num_rows#

Number of rows.

select(self, names: collections.abc.Sequence[str]) → data_cube.cube_py._cubepy.Table#

Returns a subset of columns.

take(self, rows: collections.abc.Sequence[int]) → data_cube.cube_py._cubepy.Table#

Returns a subset of rows.

to_string(self, max_rows: int = 20) → str#

Text representation.

class data_cube.cube_py._cubepy.Timestamp(*args, **kwargs)#

Naive timestamp, nanoseconds since 1970-01-01 00:00:00.

property ns#

Nanoseconds since the epoch.

class data_cube.cube_py._cubepy.ViewDef(*args, **kwargs)#

Defines how to compute a view.

property agg#

(self) -> str

property agg_by_column#

(self) -> dict[str, str]

property agg_multi_names#

Names of the aggregations over multiple columns.

property dropna#

(self) -> bool

property fix_aggregation_change#

(self) -> list[str]

property ignore_columns#

(self) -> list[str]

property ignore_unique#

(self) -> bool

property keep_columns_in_index#

(self) -> list[str]

property key_agg#

(self) -> list[str]

property key_index#

(self) -> list[str]

property name#

(self) -> str

property no_index#

(self) -> bool

property order#

(self) -> list[str]

property plots#

(self) -> bool

set_agg_multi(self, aggs: collections.abc.Sequence[tuple[str, collections.abc.Callable]]) → None#

Sets the aggregations over multiple columns, every function receives a Table and returns a float.

property transpose#

(self) -> bool

property values#

(self) -> list[str]