C-Dash: Add bandwidth to iterative graphs
[csit.git] / csit.infra.dash / app / cdash / report / graphs.py
1 # Copyright (c) 2023 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
18 import plotly.graph_objects as go
19 import pandas as pd
20
21 from copy import deepcopy
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:dict, layout: dict,
77         normalize: bool) -> 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 data: pandas.DataFrame
87     :param sel: dict
88     :param layout: dict
89     :param normalize: bool
90     :returns: Tuple of graphs - throughput and latency.
91     :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
92     """
93
94     def get_y_values(data, y_data_max, param, norm_factor):
95         if "receive_rate" in param:
96             y_vals_raw = data[param].to_list()[0]
97         else:
98             y_vals_raw = data[param].to_list()
99         y_data = [(y * norm_factor) for y in y_vals_raw]
100         try:
101             y_data_max = max(max(y_data), y_data_max)
102         except TypeError:
103             y_data_max = 0
104         return y_data, y_data_max
105
106     fig_tput = None
107     fig_band = None
108     fig_lat = None
109
110     tput_traces = list()
111     y_tput_max = 0
112     y_units = set()
113
114     lat_traces = list()
115     y_lat_max = 0
116     x_lat = list()
117
118     band_traces = list()
119     y_band_max = 0
120     y_band_units = set()
121     x_band = list()
122
123     for idx, itm in enumerate(sel):
124
125         itm_data = select_iterative_data(data, itm)
126         if itm_data.empty:
127             continue
128
129         phy = itm["phy"].split("-")
130         topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
131         norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
132             if normalize else 1.0
133
134         if itm["area"] == "hoststack":
135             ttype = f"hoststack-{itm['testtype']}"
136         else:
137             ttype = itm["testtype"]
138
139         y_units.update(itm_data[C.UNIT[ttype]].unique().tolist())
140
141         y_data, y_tput_max = \
142             get_y_values(itm_data, y_tput_max, C.VALUE_ITER[ttype], norm_factor)
143
144         nr_of_samples = len(y_data)
145
146         customdata = list()
147         metadata = {
148             "csit release": itm["rls"],
149             "dut": itm["dut"],
150             "dut version": itm["dutver"],
151             "infra": itm["phy"],
152             "test": (
153                 f"{itm['area']}-{itm['framesize']}-{itm['core']}-"
154                 f"{itm['test']}-{itm['testtype']}"
155             )
156         }
157
158         if itm["testtype"] == "mrr":
159             metadata["csit-ref"] = (
160                 f"{itm_data['job'].to_list()[0]}/",
161                 f"{itm_data['build'].to_list()[0]}"
162             )
163             customdata = [{"metadata": metadata}, ] * nr_of_samples
164         else:
165             for _, row in itm_data.iterrows():
166                 metadata["csit-ref"] = f"{row['job']}/{row['build']}"
167                 customdata.append({"metadata": deepcopy(metadata)})
168         tput_kwargs = dict(
169             y=y_data,
170             name=(
171                 f"{idx + 1}. "
172                 f"({nr_of_samples:02d} "
173                 f"run{'s' if nr_of_samples > 1 else ''}) "
174                 f"{itm['id']}"
175             ),
176             hoverinfo=u"y+name",
177             boxpoints="all",
178             jitter=0.3,
179             marker=dict(color=get_color(idx)),
180             customdata=customdata
181         )
182         tput_traces.append(go.Box(**tput_kwargs))
183
184         if ttype in ("ndr", "pdr"):
185             y_band, y_band_max = get_y_values(
186                 itm_data,
187                 y_band_max,
188                 C.VALUE_ITER[f"{ttype}-bandwidth"],
189                 norm_factor
190             )
191             if not all(pd.isna(y_band)):
192                 y_band_units.update(
193                     itm_data[C.UNIT[f"{ttype}-bandwidth"]].unique().\
194                         dropna().tolist()
195                 )
196                 band_kwargs = dict(
197                     y=y_band,
198                     name=(
199                         f"{idx + 1}. "
200                         f"({nr_of_samples:02d} "
201                         f"run{'s' if nr_of_samples > 1 else ''}) "
202                         f"{itm['id']}"
203                     ),
204                     hoverinfo=u"y+name",
205                     boxpoints="all",
206                     jitter=0.3,
207                     marker=dict(color=get_color(idx)),
208                     customdata=customdata
209                 )
210                 x_band.append(idx + 1)
211                 band_traces.append(go.Box(**band_kwargs))
212
213         if ttype == "pdr":
214             y_lat, y_lat_max = get_y_values(
215                 itm_data,
216                 y_lat_max,
217                 C.VALUE_ITER["latency"],
218                 1 / norm_factor
219             )
220             if not all(pd.isna(y_lat)):
221                 customdata = list()
222                 for _, row in itm_data.iterrows():
223                     hdrh = get_hdrh_latencies(
224                         row,
225                         f"{metadata['infra']}-{metadata['test']}"
226                     )
227                     metadata["csit-ref"] = f"{row['job']}/{row['build']}"
228                     customdata.append({
229                         "metadata": deepcopy(metadata),
230                         "hdrh": hdrh
231                     })
232                 nr_of_samples = len(y_lat)
233                 lat_kwargs = dict(
234                     y=y_lat,
235                     name=(
236                         f"{idx + 1}. "
237                         f"({nr_of_samples:02d} "
238                         f"run{u's' if nr_of_samples > 1 else u''}) "
239                         f"{itm['id']}"
240                     ),
241                     hoverinfo="all",
242                     boxpoints="all",
243                     jitter=0.3,
244                     marker=dict(color=get_color(idx)),
245                     customdata=customdata
246                 )
247                 x_lat.append(idx + 1)
248                 lat_traces.append(go.Box(**lat_kwargs))
249
250     if tput_traces:
251         pl_tput = deepcopy(layout["plot-throughput"])
252         pl_tput["xaxis"]["tickvals"] = [i for i in range(len(sel))]
253         pl_tput["xaxis"]["ticktext"] = [str(i + 1) for i in range(len(sel))]
254         pl_tput["yaxis"]["title"] = f"Throughput [{'|'.join(sorted(y_units))}]"
255         if y_tput_max:
256             pl_tput["yaxis"]["range"] = [0, int(y_tput_max) + 2e6]
257         fig_tput = go.Figure(data=tput_traces, layout=pl_tput)
258
259     if band_traces:
260         pl_band = deepcopy(layout["plot-bandwidth"])
261         pl_band["xaxis"]["tickvals"] = [i for i in range(len(x_band))]
262         pl_band["xaxis"]["ticktext"] = x_band
263         pl_band["yaxis"]["title"] = \
264             f"Bandwidth [{'|'.join(sorted(y_band_units))}]"
265         if y_band_max:
266             pl_band["yaxis"]["range"] = [0, int(y_band_max) + 2e9]
267         fig_band = go.Figure(data=band_traces, layout=pl_band)
268
269     if lat_traces:
270         pl_lat = deepcopy(layout["plot-latency"])
271         pl_lat["xaxis"]["tickvals"] = [i for i in range(len(x_lat))]
272         pl_lat["xaxis"]["ticktext"] = x_lat
273         if y_lat_max:
274             pl_lat["yaxis"]["range"] = [0, int(y_lat_max) + 5]
275         fig_lat = go.Figure(data=lat_traces, layout=pl_lat)
276
277     return fig_tput, fig_band, fig_lat