C-Dash: Add detailed views to comparison tables
[csit.git] / csit.infra.dash / app / cdash / report / graphs.py
1 # Copyright (c) 2024 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Implementation of graphs for iterative data.
15 """
16
17 import plotly.graph_objects as go
18 import pandas as pd
19
20 from copy import deepcopy
21 from numpy import percentile
22
23 from ..utils.constants import Constants as C
24 from ..utils.utils import get_color, get_hdrh_latencies
25
26
27 def select_iterative_data(data: pd.DataFrame, itm:dict) -> pd.DataFrame:
28     """Select the data for graphs and tables from the provided data frame.
29
30     :param data: Data frame with data for graphs and tables.
31     :param itm: Item (in this case job name) which data will be selected from
32         the input data frame.
33     :type data: pandas.DataFrame
34     :type itm: str
35     :returns: A data frame with selected data.
36     :rtype: pandas.DataFrame
37     """
38
39     phy = itm["phy"].split("-")
40     if len(phy) == 4:
41         topo, arch, nic, drv = phy
42         if drv == "dpdk":
43             drv = ""
44         else:
45             drv += "-"
46             drv = drv.replace("_", "-")
47     else:
48         return None
49
50     if itm["testtype"] in ("ndr", "pdr"):
51         test_type = "ndrpdr"
52     elif itm["testtype"] == "mrr":
53         test_type = "mrr"
54     elif itm["area"] == "hoststack":
55         test_type = "hoststack"
56     df = data.loc[(
57         (data["release"] == itm["rls"]) &
58         (data["test_type"] == test_type) &
59         (data["passed"] == True)
60     )]
61
62     core = str() if itm["dut"] == "trex" else f"{itm['core']}"
63     ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
64     regex_test = \
65         f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$"
66     df = df[
67         (df.job.str.endswith(f"{topo}-{arch}")) &
68         (df.dut_version.str.contains(itm["dutver"].replace(".r", "-r").\
69             replace("rls", "release"))) &
70         (df.test_id.str.contains(regex_test, regex=True))
71     ]
72
73     return df
74
75
76 def graph_iterative(data: pd.DataFrame, sel: list, layout: dict,
77         normalize: bool=False, remove_outliers: bool=False) -> tuple:
78     """Generate the statistical box graph with iterative data (MRR, NDR and PDR,
79     for PDR also Latencies).
80
81     :param data: Data frame with iterative data.
82     :param sel: Selected tests.
83     :param layout: Layout of plot.ly graph.
84     :param normalize: If True, the data is normalized to CPU frequency
85         Constants.NORM_FREQUENCY.
86     :param remove_outliers: If True the outliers are removed before
87         generating the table.
88     :type data: pandas.DataFrame
89     :type sel: list
90     :type layout: dict
91     :type normalize: bool
92     :type remove_outliers: bool
93     :returns: Tuple of graphs - throughput and latency.
94     :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
95     """
96
97     def get_y_values(data, y_data_max, param, norm_factor, release=str(),
98                      remove_outliers=False):
99         if param == "result_receive_rate_rate_values":
100             if release == "rls2402":
101                 y_vals_raw = data["result_receive_rate_rate_avg"].to_list()
102             else:
103                 y_vals_raw = data[param].to_list()[0]
104         else:
105             y_vals_raw = data[param].to_list()
106         y_data = [(y * norm_factor) for y in y_vals_raw]
107
108         if remove_outliers:
109             try:
110                 q1 = percentile(y_data, 25, method=C.COMP_PERCENTILE_METHOD)
111                 q3 = percentile(y_data, 75, method=C.COMP_PERCENTILE_METHOD)
112                 irq = q3 - q1
113                 lif = q1 - C.COMP_OUTLIER_TYPE * irq
114                 uif = q3 + C.COMP_OUTLIER_TYPE * irq
115                 y_data = [i for i in y_data if i >= lif and i <= uif]
116             except TypeError:
117                 pass
118         try:
119             y_data_max = max(max(y_data), y_data_max)
120         except TypeError:
121             y_data_max = 0
122         return y_data, y_data_max
123
124     fig_tput = None
125     fig_band = None
126     fig_lat = None
127
128     tput_traces = list()
129     y_tput_max = 0
130     y_units = set()
131
132     lat_traces = list()
133     y_lat_max = 0
134     x_lat = list()
135
136     band_traces = list()
137     y_band_max = 0
138     y_band_units = set()
139     x_band = list()
140
141     for idx, itm in enumerate(sel):
142
143         itm_data = select_iterative_data(data, itm)
144         if itm_data.empty:
145             continue
146
147         phy = itm["phy"].split("-")
148         topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
149         norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
150             if normalize else 1.0
151
152         if itm["area"] == "hoststack":
153             ttype = f"hoststack-{itm['testtype']}"
154         else:
155             ttype = itm["testtype"]
156
157         y_units.update(itm_data[C.UNIT[ttype]].unique().tolist())
158
159         y_data, y_tput_max = get_y_values(
160             itm_data,
161             y_tput_max,
162             C.VALUE_ITER[ttype],
163             norm_factor,
164             itm["rls"],
165             remove_outliers
166         )
167
168         nr_of_samples = len(y_data)
169
170         customdata = list()
171         metadata = {
172             "csit release": itm["rls"],
173             "dut": itm["dut"],
174             "dut version": itm["dutver"],
175             "infra": itm["phy"],
176             "test": (
177                 f"{itm['area']}-{itm['framesize']}-{itm['core']}-"
178                 f"{itm['test']}-{itm['testtype']}"
179             )
180         }
181
182         if itm["testtype"] == "mrr" and itm["rls"] in ("rls2306", "rls2310"):
183             trial_run = "trial"
184             metadata["csit-ref"] = (
185                 f"{itm_data['job'].to_list()[0]}/",
186                 f"{itm_data['build'].to_list()[0]}"
187             )
188             customdata = [{"metadata": metadata}, ] * nr_of_samples
189         else:
190             trial_run = "run"
191             for _, row in itm_data.iterrows():
192                 metadata["csit-ref"] = f"{row['job']}/{row['build']}"
193                 customdata.append({"metadata": deepcopy(metadata)})
194         tput_kwargs = dict(
195             y=y_data,
196             name=(
197                 f"{idx + 1}. "
198                 f"({nr_of_samples:02d} "
199                 f"{trial_run}{'s' if nr_of_samples > 1 else ''}) "
200                 f"{itm['id']}"
201             ),
202             hoverinfo=u"y+name",
203             boxpoints="all",
204             jitter=0.3,
205             marker=dict(color=get_color(idx)),
206             customdata=customdata
207         )
208         tput_traces.append(go.Box(**tput_kwargs))
209
210         if ttype in ("ndr", "pdr", "mrr"):
211             y_band, y_band_max = get_y_values(
212                 itm_data,
213                 y_band_max,
214                 C.VALUE_ITER[f"{ttype}-bandwidth"],
215                 norm_factor,
216                 remove_outliers=remove_outliers
217             )
218             if not all(pd.isna(y_band)):
219                 y_band_units.update(
220                     itm_data[C.UNIT[f"{ttype}-bandwidth"]].unique().\
221                         dropna().tolist()
222                 )
223                 band_kwargs = dict(
224                     y=y_band,
225                     name=(
226                         f"{idx + 1}. "
227                         f"({nr_of_samples:02d} "
228                         f"run{'s' if nr_of_samples > 1 else ''}) "
229                         f"{itm['id']}"
230                     ),
231                     hoverinfo=u"y+name",
232                     boxpoints="all",
233                     jitter=0.3,
234                     marker=dict(color=get_color(idx)),
235                     customdata=customdata
236                 )
237                 x_band.append(idx + 1)
238                 band_traces.append(go.Box(**band_kwargs))
239
240         if ttype == "pdr":
241             y_lat, y_lat_max = get_y_values(
242                 itm_data,
243                 y_lat_max,
244                 C.VALUE_ITER["latency"],
245                 1 / norm_factor,
246                 remove_outliers=remove_outliers
247             )
248             if not all(pd.isna(y_lat)):
249                 customdata = list()
250                 for _, row in itm_data.iterrows():
251                     hdrh = get_hdrh_latencies(
252                         row,
253                         f"{metadata['infra']}-{metadata['test']}"
254                     )
255                     metadata["csit-ref"] = f"{row['job']}/{row['build']}"
256                     customdata.append({
257                         "metadata": deepcopy(metadata),
258                         "hdrh": hdrh
259                     })
260                 nr_of_samples = len(y_lat)
261                 lat_kwargs = dict(
262                     y=y_lat,
263                     name=(
264                         f"{idx + 1}. "
265                         f"({nr_of_samples:02d} "
266                         f"run{u's' if nr_of_samples > 1 else u''}) "
267                         f"{itm['id']}"
268                     ),
269                     hoverinfo="all",
270                     boxpoints="all",
271                     jitter=0.3,
272                     marker=dict(color=get_color(idx)),
273                     customdata=customdata
274                 )
275                 x_lat.append(idx + 1)
276                 lat_traces.append(go.Box(**lat_kwargs))
277
278     if tput_traces:
279         pl_tput = deepcopy(layout["plot-throughput"])
280         pl_tput["xaxis"]["tickvals"] = [i for i in range(len(sel))]
281         pl_tput["xaxis"]["ticktext"] = [str(i + 1) for i in range(len(sel))]
282         pl_tput["yaxis"]["title"] = f"Throughput [{'|'.join(sorted(y_units))}]"
283         if y_tput_max:
284             pl_tput["yaxis"]["range"] = [0, int(y_tput_max) + 2e6]
285         fig_tput = go.Figure(data=tput_traces, layout=pl_tput)
286
287     if band_traces:
288         pl_band = deepcopy(layout["plot-bandwidth"])
289         pl_band["xaxis"]["tickvals"] = [i for i in range(len(x_band))]
290         pl_band["xaxis"]["ticktext"] = x_band
291         pl_band["yaxis"]["title"] = \
292             f"Bandwidth [{'|'.join(sorted(y_band_units))}]"
293         if y_band_max:
294             pl_band["yaxis"]["range"] = [0, int(y_band_max) + 2e9]
295         fig_band = go.Figure(data=band_traces, layout=pl_band)
296
297     if lat_traces:
298         pl_lat = deepcopy(layout["plot-latency"])
299         pl_lat["xaxis"]["tickvals"] = [i for i in range(len(x_lat))]
300         pl_lat["xaxis"]["ticktext"] = x_lat
301         if y_lat_max:
302             pl_lat["yaxis"]["range"] = [0, int(y_lat_max) + 5]
303         fig_lat = go.Figure(data=lat_traces, layout=pl_lat)
304
305     return fig_tput, fig_band, fig_lat