C-Dash: Small changes in graphs processing
[csit.git] / csit.infra.dash / app / cdash / trending / 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 trending data.
15 """
16
17 import plotly.graph_objects as go
18 import pandas as pd
19
20 from ..utils.constants import Constants as C
21 from ..utils.utils import get_color, get_hdrh_latencies
22 from ..utils.anomalies import classify_anomalies
23
24
25 def select_trending_data(data: pd.DataFrame, itm: dict) -> pd.DataFrame:
26     """Select the data for graphs from the provided data frame.
27
28     :param data: Data frame with data for graphs.
29     :param itm: Item (in this case job name) which data will be selected from
30         the input data frame.
31     :type data: pandas.DataFrame
32     :type itm: dict
33     :returns: A data frame with selected data.
34     :rtype: pandas.DataFrame
35     """
36
37     phy = itm["phy"].split("-")
38     if len(phy) == 4:
39         topo, arch, nic, drv = phy
40         if drv == "dpdk":
41             drv = ""
42         else:
43             drv += "-"
44             drv = drv.replace("_", "-")
45     else:
46         return None
47
48     if itm["testtype"] in ("ndr", "pdr"):
49         test_type = "ndrpdr"
50     elif itm["testtype"] == "mrr":
51         test_type = "mrr"
52     elif itm["area"] == "hoststack":
53         test_type = "hoststack"
54     df = data.loc[(
55         (data["test_type"] == test_type) &
56         (data["passed"] == True)
57     )]
58     df = df[df.job.str.endswith(f"{topo}-{arch}")]
59     core = str() if itm["dut"] == "trex" else f"{itm['core']}"
60     ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
61     df = df[df.test_id.str.contains(
62         f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
63         regex=True
64     )].sort_values(by="start_time", ignore_index=True)
65
66     return df
67
68
69 def graph_trending(
70         data: pd.DataFrame,
71         sel: dict,
72         layout: dict,
73         normalize: bool
74     ) -> tuple:
75     """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
76     (result_latency_forward_pdr_50_avg).
77
78     :param data: Data frame with test results.
79     :param sel: Selected tests.
80     :param layout: Layout of plot.ly graph.
81     :param normalize: If True, the data is normalized to CPU frquency
82         Constants.NORM_FREQUENCY.
83     :type data: pandas.DataFrame
84     :type sel: dict
85     :type layout: dict
86     :type normalize: bool
87     :returns: Trending graph(s)
88     :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
89     """
90
91     if not sel:
92         return None, None
93
94
95     def _generate_trending_traces(
96             ttype: str,
97             name: str,
98             df: pd.DataFrame,
99             color: str,
100             norm_factor: float
101         ) -> list:
102         """Generate the trending traces for the trending graph.
103
104         :param ttype: Test type (MRR, NDR, PDR).
105         :param name: The test name to be displayed as the graph title.
106         :param df: Data frame with test data.
107         :param color: The color of the trace (samples and trend line).
108         :param norm_factor: The factor used for normalization of the results to
109             CPU frequency set to Constants.NORM_FREQUENCY.
110         :type ttype: str
111         :type name: str
112         :type df: pandas.DataFrame
113         :type color: str
114         :type norm_factor: float
115         :returns: Traces (samples, trending line, anomalies)
116         :rtype: list
117         """
118
119         df = df.dropna(subset=[C.VALUE[ttype], ])
120         if df.empty:
121             return list(), list()
122
123         x_axis = df["start_time"].tolist()
124         if ttype == "latency":
125             y_data = [(v / norm_factor) for v in df[C.VALUE[ttype]].tolist()]
126         else:
127             y_data = [(v * norm_factor) for v in df[C.VALUE[ttype]].tolist()]
128         units = df[C.UNIT[ttype]].unique().tolist()
129
130         anomalies, trend_avg, trend_stdev = classify_anomalies(
131             {k: v for k, v in zip(x_axis, y_data)}
132         )
133
134         hover = list()
135         customdata = list()
136         customdata_samples = list()
137         for idx, (_, row) in enumerate(df.iterrows()):
138             hover_itm = (
139                 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
140                 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
141                 f"<stdev>"
142                 f"<additional-info>"
143                 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
144                 f"csit-ref: {row['job']}/{row['build']}<br>"
145                 f"hosts: {', '.join(row['hosts'])}"
146             )
147             if ttype == "mrr":
148                 stdev = (
149                     f"stdev [{row['result_receive_rate_rate_unit']}]: "
150                     f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
151                 )
152             else:
153                 stdev = str()
154             if ttype in ("hoststack-cps", "hoststack-rps"):
155                 add_info = (
156                     f"bandwidth [{row[C.UNIT['hoststack-bps']]}]: "
157                     f"{row[C.VALUE['hoststack-bps']]:,.0f}<br>"
158                     f"latency [{row[C.UNIT['hoststack-lat']]}]: "
159                     f"{row[C.VALUE['hoststack-lat']]:,.0f}<br>"
160                 )
161             else:
162                 add_info = str()
163             hover_itm = hover_itm.replace(
164                 "<prop>", "latency" if ttype == "latency" else "average"
165             ).replace("<stdev>", stdev).replace("<additional-info>", add_info)
166             hover.append(hover_itm)
167             if ttype == "latency":
168                 customdata_samples.append(get_hdrh_latencies(row, name))
169                 customdata.append({"name": name})
170             else:
171                 customdata_samples.append(
172                     {"name": name, "show_telemetry": True}
173                 )
174                 customdata.append({"name": name})
175
176         hover_trend = list()
177         for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
178             hover_itm = (
179                 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
180                 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
181                 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
182                 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
183                 f"csit-ref: {row['job']}/{row['build']}<br>"
184                 f"hosts: {', '.join(row['hosts'])}"
185             )
186             if ttype == "latency":
187                 hover_itm = hover_itm.replace("[pps]", "[us]")
188             hover_trend.append(hover_itm)
189
190         traces = [
191             go.Scatter(  # Samples
192                 x=x_axis,
193                 y=y_data,
194                 name=name,
195                 mode="markers",
196                 marker={
197                     "size": 5,
198                     "color": color,
199                     "symbol": "circle",
200                 },
201                 text=hover,
202                 hoverinfo="text+name",
203                 showlegend=True,
204                 legendgroup=name,
205                 customdata=customdata_samples
206             ),
207             go.Scatter(  # Trend line
208                 x=x_axis,
209                 y=trend_avg,
210                 name=name,
211                 mode="lines",
212                 line={
213                     "shape": "linear",
214                     "width": 1,
215                     "color": color,
216                 },
217                 text=hover_trend,
218                 hoverinfo="text+name",
219                 showlegend=False,
220                 legendgroup=name,
221                 customdata=customdata
222             )
223         ]
224
225         if anomalies:
226             anomaly_x = list()
227             anomaly_y = list()
228             anomaly_color = list()
229             hover = list()
230             for idx, anomaly in enumerate(anomalies):
231                 if anomaly in ("regression", "progression"):
232                     anomaly_x.append(x_axis[idx])
233                     anomaly_y.append(trend_avg[idx])
234                     anomaly_color.append(C.ANOMALY_COLOR[anomaly])
235                     hover_itm = (
236                         f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
237                         f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
238                         f"classification: {anomaly}"
239                     )
240                     if ttype == "latency":
241                         hover_itm = hover_itm.replace("[pps]", "[us]")
242                     hover.append(hover_itm)
243             anomaly_color.extend([0.0, 0.5, 1.0])
244             traces.append(
245                 go.Scatter(
246                     x=anomaly_x,
247                     y=anomaly_y,
248                     mode="markers",
249                     text=hover,
250                     hoverinfo="text+name",
251                     showlegend=False,
252                     legendgroup=name,
253                     name=name,
254                     customdata=customdata,
255                     marker={
256                         "size": 15,
257                         "symbol": "circle-open",
258                         "color": anomaly_color,
259                         "colorscale": C.COLORSCALE_LAT \
260                             if ttype == "latency" else C.COLORSCALE_TPUT,
261                         "showscale": True,
262                         "line": {
263                             "width": 2
264                         },
265                         "colorbar": {
266                             "y": 0.5,
267                             "len": 0.8,
268                             "title": "Circles Marking Data Classification",
269                             "titleside": "right",
270                             "tickmode": "array",
271                             "tickvals": [0.167, 0.500, 0.833],
272                             "ticktext": C.TICK_TEXT_LAT \
273                                 if ttype == "latency" else C.TICK_TEXT_TPUT,
274                             "ticks": "",
275                             "ticklen": 0,
276                             "tickangle": -90,
277                             "thickness": 10
278                         }
279                     }
280                 )
281             )
282
283         return traces, units
284
285
286     fig_tput = None
287     fig_lat = None
288     y_units = set()
289     for idx, itm in enumerate(sel):
290         df = select_trending_data(data, itm)
291         if df is None or df.empty:
292             continue
293
294         if normalize:
295             phy = itm["phy"].split("-")
296             topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
297             norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
298                 if topo_arch else 1.0
299         else:
300             norm_factor = 1.0
301
302         if itm["area"] == "hoststack":
303             ttype = f"hoststack-{itm['testtype']}"
304         else:
305             ttype = itm["testtype"]
306
307         traces, units = _generate_trending_traces(
308             ttype,
309             itm["id"],
310             df,
311             get_color(idx),
312             norm_factor
313         )
314         if traces:
315             if not fig_tput:
316                 fig_tput = go.Figure()
317             fig_tput.add_traces(traces)
318
319         if itm["testtype"] == "pdr":
320             traces, _ = _generate_trending_traces(
321                 "latency",
322                 itm["id"],
323                 df,
324                 get_color(idx),
325                 norm_factor
326             )
327             if traces:
328                 if not fig_lat:
329                     fig_lat = go.Figure()
330                 fig_lat.add_traces(traces)
331
332         y_units.update(units)
333
334     if fig_tput:
335         fig_layout = layout.get("plot-trending-tput", dict())
336         fig_layout["yaxis"]["title"] = \
337             f"Throughput [{'|'.join(sorted(y_units))}]"
338         fig_tput.update_layout(fig_layout)
339     if fig_lat:
340         fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
341
342     return fig_tput, fig_lat
343
344
345 def graph_tm_trending(
346         data: pd.DataFrame,
347         layout: dict,
348         all_in_one: bool=False
349     ) -> list:
350     """Generates one trending graph per test, each graph includes all selected
351     metrics.
352
353     :param data: Data frame with telemetry data.
354     :param layout: Layout of plot.ly graph.
355     :param all_in_one: If True, all telemetry traces are placed in one graph,
356         otherwise they are split to separate graphs grouped by test ID.
357     :type data: pandas.DataFrame
358     :type layout: dict
359     :type all_in_one: bool
360     :returns: List of generated graphs together with test names.
361         list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
362     :rtype: list
363     """
364
365     if data.empty:
366         return list()
367
368     def _generate_traces(
369             data: pd.DataFrame,
370             test: str,
371             all_in_one: bool,
372             color_index: int
373         ) -> list:
374         """Generates a trending graph for given test with all metrics.
375
376         :param data: Data frame with telemetry data for the given test.
377         :param test: The name of the test.
378         :param all_in_one: If True, all telemetry traces are placed in one
379             graph, otherwise they are split to separate graphs grouped by
380             test ID.
381         :param color_index: The index of the test used if all_in_one is True.
382         :type data: pandas.DataFrame
383         :type test: str
384         :type all_in_one: bool
385         :type color_index: int
386         :returns: List of traces.
387         :rtype: list
388         """
389         traces = list()
390         metrics = data.tm_metric.unique().tolist()
391         for idx, metric in enumerate(metrics):
392             if "-pdr" in test and "='pdr'" not in metric:
393                 continue
394             if "-ndr" in test and "='ndr'" not in metric:
395                 continue
396
397             df = data.loc[(data["tm_metric"] == metric)]
398             x_axis = df["start_time"].tolist()
399             y_data = [float(itm) for itm in df["tm_value"].tolist()]
400             hover = list()
401             for i, (_, row) in enumerate(df.iterrows()):
402                 if row["test_type"] == "mrr":
403                     rate = (
404                         f"mrr avg [{row[C.UNIT['mrr']]}]: "
405                         f"{row[C.VALUE['mrr']]:,.0f}<br>"
406                         f"mrr stdev [{row[C.UNIT['mrr']]}]: "
407                         f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
408                     )
409                 elif row["test_type"] == "ndrpdr":
410                     if "-pdr" in test:
411                         rate = (
412                             f"pdr [{row[C.UNIT['pdr']]}]: "
413                             f"{row[C.VALUE['pdr']]:,.0f}<br>"
414                         )
415                     elif "-ndr" in test:
416                         rate = (
417                             f"ndr [{row[C.UNIT['ndr']]}]: "
418                             f"{row[C.VALUE['ndr']]:,.0f}<br>"
419                         )
420                     else:
421                         rate = str()
422                 else:
423                     rate = str()
424                 hover.append(
425                     f"date: "
426                     f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
427                     f"value: {y_data[i]:,.2f}<br>"
428                     f"{rate}"
429                     f"{row['dut_type']}-ref: {row['dut_version']}<br>"
430                     f"csit-ref: {row['job']}/{row['build']}<br>"
431                 )
432             if any(y_data):
433                 anomalies, trend_avg, trend_stdev = classify_anomalies(
434                     {k: v for k, v in zip(x_axis, y_data)}
435                 )
436                 hover_trend = list()
437                 for avg, stdev, (_, row) in \
438                         zip(trend_avg, trend_stdev, df.iterrows()):
439                     hover_trend.append(
440                         f"date: "
441                         f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
442                         f"trend: {avg:,.2f}<br>"
443                         f"stdev: {stdev:,.2f}<br>"
444                         f"{row['dut_type']}-ref: {row['dut_version']}<br>"
445                         f"csit-ref: {row['job']}/{row['build']}"
446                     )
447             else:
448                 anomalies = None
449             if all_in_one:
450                 color = get_color(color_index * len(metrics) + idx)
451                 metric_name = f"{test}<br>{metric}"
452             else:
453                 color = get_color(idx)
454                 metric_name = metric
455
456             traces.append(
457                 go.Scatter(  # Samples
458                     x=x_axis,
459                     y=y_data,
460                     name=metric_name,
461                     mode="markers",
462                     marker={
463                         "size": 5,
464                         "color": color,
465                         "symbol": "circle",
466                     },
467                     text=hover,
468                     hoverinfo="text+name",
469                     showlegend=True,
470                     legendgroup=metric_name
471                 )
472             )
473             if anomalies:
474                 traces.append(
475                     go.Scatter(  # Trend line
476                         x=x_axis,
477                         y=trend_avg,
478                         name=metric_name,
479                         mode="lines",
480                         line={
481                             "shape": "linear",
482                             "width": 1,
483                             "color": color,
484                         },
485                         text=hover_trend,
486                         hoverinfo="text+name",
487                         showlegend=False,
488                         legendgroup=metric_name
489                     )
490                 )
491
492                 anomaly_x = list()
493                 anomaly_y = list()
494                 anomaly_color = list()
495                 hover = list()
496                 for idx, anomaly in enumerate(anomalies):
497                     if anomaly in ("regression", "progression"):
498                         anomaly_x.append(x_axis[idx])
499                         anomaly_y.append(trend_avg[idx])
500                         anomaly_color.append(C.ANOMALY_COLOR[anomaly])
501                         hover_itm = (
502                             f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
503                             f"<br>trend: {trend_avg[idx]:,.2f}"
504                             f"<br>classification: {anomaly}"
505                         )
506                         hover.append(hover_itm)
507                 anomaly_color.extend([0.0, 0.5, 1.0])
508                 traces.append(
509                     go.Scatter(
510                         x=anomaly_x,
511                         y=anomaly_y,
512                         mode="markers",
513                         text=hover,
514                         hoverinfo="text+name",
515                         showlegend=False,
516                         legendgroup=metric_name,
517                         name=metric_name,
518                         marker={
519                             "size": 15,
520                             "symbol": "circle-open",
521                             "color": anomaly_color,
522                             "colorscale": C.COLORSCALE_TPUT,
523                             "showscale": True,
524                             "line": {
525                                 "width": 2
526                             },
527                             "colorbar": {
528                                 "y": 0.5,
529                                 "len": 0.8,
530                                 "title": "Circles Marking Data Classification",
531                                 "titleside": "right",
532                                 "tickmode": "array",
533                                 "tickvals": [0.167, 0.500, 0.833],
534                                 "ticktext": C.TICK_TEXT_TPUT,
535                                 "ticks": "",
536                                 "ticklen": 0,
537                                 "tickangle": -90,
538                                 "thickness": 10
539                             }
540                         }
541                     )
542                 )
543
544         unique_metrics = set()
545         for itm in metrics:
546             unique_metrics.add(itm.split("{", 1)[0])
547         return traces, unique_metrics
548
549     tm_trending_graphs = list()
550     graph_layout = layout.get("plot-trending-telemetry", dict())
551
552     if all_in_one:
553         all_traces = list()
554
555     all_metrics = set()
556     all_tests = list()
557     for idx, test in enumerate(data.test_name.unique()):
558         df = data.loc[(data["test_name"] == test)]
559         traces, metrics = _generate_traces(df, test, all_in_one, idx)
560         if traces:
561             all_metrics.update(metrics)
562             if all_in_one:
563                 all_traces.extend(traces)
564                 all_tests.append(test)
565             else:
566                 graph = go.Figure()
567                 graph.add_traces(traces)
568                 graph.update_layout(graph_layout)
569                 tm_trending_graphs.append((graph, [test, ], ))
570
571     if all_in_one:
572         graph = go.Figure()
573         graph.add_traces(all_traces)
574         graph.update_layout(graph_layout)
575         tm_trending_graphs.append((graph, all_tests, ))
576
577     return tm_trending_graphs, list(all_metrics)