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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Implementation of graphs for trending data.
17 import plotly.graph_objects as go
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
25 def select_trending_data(data: pd.DataFrame, itm: dict) -> pd.DataFrame:
26 """Select the data for graphs from the provided data frame.
28 :param data: Data frame with data for graphs.
29 :param itm: Item (in this case job name) which data will be selected from
31 :type data: pandas.DataFrame
33 :returns: A data frame with selected data.
34 :rtype: pandas.DataFrame
37 phy = itm["phy"].split("-")
39 topo, arch, nic, drv = phy
44 drv = drv.replace("_", "-")
48 if itm["testtype"] in ("ndr", "pdr"):
50 elif itm["testtype"] == "mrr":
52 elif itm["area"] == "hoststack":
53 test_type = "hoststack"
55 (data["test_type"] == test_type) &
56 (data["passed"] == True)
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}$",
64 )].sort_values(by="start_time", ignore_index=True)
75 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
76 (result_latency_forward_pdr_50_avg).
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
87 :returns: Trending graph(s)
88 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
95 def _generate_trending_traces(
102 """Generate the trending traces for the trending graph.
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.
112 :type df: pandas.DataFrame
114 :type norm_factor: float
115 :returns: Traces (samples, trending line, anomalies)
119 df = df.dropna(subset=[C.VALUE[ttype], ])
121 return list(), list()
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()]
127 y_data = [(v * norm_factor) for v in df[C.VALUE[ttype]].tolist()]
128 units = df[C.UNIT[ttype]].unique().tolist()
130 anomalies, trend_avg, trend_stdev = classify_anomalies(
131 {k: v for k, v in zip(x_axis, y_data)}
136 customdata_samples = list()
137 name_lst = name.split("-")
138 for idx, (_, row) in enumerate(df.iterrows()):
140 f"dut: {name_lst[0]}<br>"
141 f"infra: {'-'.join(name_lst[1:5])}<br>"
142 f"test: {'-'.join(name_lst[5:])}<br>"
143 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
144 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
147 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
148 f"csit-ref: {row['job']}/{row['build']}<br>"
149 f"hosts: {', '.join(row['hosts'])}"
153 f"stdev [{row['result_receive_rate_rate_unit']}]: "
154 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
158 if ttype in ("hoststack-cps", "hoststack-rps"):
160 f"bandwidth [{row[C.UNIT['hoststack-bps']]}]: "
161 f"{row[C.VALUE['hoststack-bps']]:,.0f}<br>"
162 f"latency [{row[C.UNIT['hoststack-latency']]}]: "
163 f"{row[C.VALUE['hoststack-latency']]:,.0f}<br>"
165 elif ttype in ("ndr", "pdr"): # Add mrr
166 test_type = f"{ttype}-bandwidth"
168 f"bandwidth [{row[C.UNIT[test_type]]}]: "
169 f"{row[C.VALUE[test_type]]:,.0f}<br>"
173 hover_itm = hover_itm.replace(
174 "<prop>", "latency" if ttype == "latency" else "average"
175 ).replace("<stdev>", stdev).replace("<additional-info>", add_info)
176 hover.append(hover_itm)
177 if ttype == "latency":
178 customdata_samples.append(get_hdrh_latencies(row, name))
179 customdata.append({"name": name})
181 customdata_samples.append(
182 {"name": name, "show_telemetry": True}
184 customdata.append({"name": name})
187 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
189 f"dut: {name_lst[0]}<br>"
190 f"infra: {'-'.join(name_lst[1:5])}<br>"
191 f"test: {'-'.join(name_lst[5:])}<br>"
192 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
193 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
194 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
195 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
196 f"csit-ref: {row['job']}/{row['build']}<br>"
197 f"hosts: {', '.join(row['hosts'])}"
199 if ttype == "latency":
200 hover_itm = hover_itm.replace("[pps]", "[us]")
201 hover_trend.append(hover_itm)
204 go.Scatter( # Samples
218 customdata=customdata_samples
220 go.Scatter( # Trend line
234 customdata=customdata
241 anomaly_color = list()
243 for idx, anomaly in enumerate(anomalies):
244 if anomaly in ("regression", "progression"):
245 anomaly_x.append(x_axis[idx])
246 anomaly_y.append(trend_avg[idx])
247 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
249 f"dut: {name_lst[0]}<br>"
250 f"infra: {'-'.join(name_lst[1:5])}<br>"
251 f"test: {'-'.join(name_lst[5:])}<br>"
252 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
253 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
254 f"classification: {anomaly}"
256 if ttype == "latency":
257 hover_itm = hover_itm.replace("[pps]", "[us]")
258 hover.append(hover_itm)
259 anomaly_color.extend([0.0, 0.5, 1.0])
270 customdata=customdata,
273 "symbol": "circle-open",
274 "color": anomaly_color,
275 "colorscale": C.COLORSCALE_LAT \
276 if ttype == "latency" else C.COLORSCALE_TPUT,
284 "title": "Circles Marking Data Classification",
285 "titleside": "right",
287 "tickvals": [0.167, 0.500, 0.833],
288 "ticktext": C.TICK_TEXT_LAT \
289 if ttype == "latency" else C.TICK_TEXT_TPUT,
306 for idx, itm in enumerate(sel):
307 df = select_trending_data(data, itm)
308 if df is None or df.empty:
312 phy = itm["phy"].split("-")
313 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
314 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
315 if topo_arch else 1.0
319 if itm["area"] == "hoststack":
320 ttype = f"hoststack-{itm['testtype']}"
322 ttype = itm["testtype"]
324 traces, units = _generate_trending_traces(
333 fig_tput = go.Figure()
334 fig_tput.add_traces(traces)
336 if ttype in ("ndr", "pdr"): # Add mrr
337 traces, _ = _generate_trending_traces(
338 f"{ttype}-bandwidth",
346 fig_band = go.Figure()
347 fig_band.add_traces(traces)
349 if itm["testtype"] == "pdr":
350 traces, _ = _generate_trending_traces(
359 fig_lat = go.Figure()
360 fig_lat.add_traces(traces)
362 y_units.update(units)
365 fig_layout = layout.get("plot-trending-tput", dict())
366 fig_layout["yaxis"]["title"] = \
367 f"Throughput [{'|'.join(sorted(y_units))}]"
368 fig_tput.update_layout(fig_layout)
370 fig_band.update_layout(layout.get("plot-trending-bandwidth", dict()))
372 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
374 return fig_tput, fig_band, fig_lat
377 def graph_tm_trending(
380 all_in_one: bool=False
382 """Generates one trending graph per test, each graph includes all selected
385 :param data: Data frame with telemetry data.
386 :param layout: Layout of plot.ly graph.
387 :param all_in_one: If True, all telemetry traces are placed in one graph,
388 otherwise they are split to separate graphs grouped by test ID.
389 :type data: pandas.DataFrame
391 :type all_in_one: bool
392 :returns: List of generated graphs together with test names.
393 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
400 def _generate_traces(
406 """Generates a trending graph for given test with all metrics.
408 :param data: Data frame with telemetry data for the given test.
409 :param test: The name of the test.
410 :param all_in_one: If True, all telemetry traces are placed in one
411 graph, otherwise they are split to separate graphs grouped by
413 :param color_index: The index of the test used if all_in_one is True.
414 :type data: pandas.DataFrame
416 :type all_in_one: bool
417 :type color_index: int
418 :returns: List of traces.
422 metrics = data.tm_metric.unique().tolist()
423 for idx, metric in enumerate(metrics):
424 if "-pdr" in test and "='pdr'" not in metric:
426 if "-ndr" in test and "='ndr'" not in metric:
429 df = data.loc[(data["tm_metric"] == metric)]
430 x_axis = df["start_time"].tolist()
431 y_data = [float(itm) for itm in df["tm_value"].tolist()]
433 for i, (_, row) in enumerate(df.iterrows()):
434 if row["test_type"] == "mrr":
436 f"mrr avg [{row[C.UNIT['mrr']]}]: "
437 f"{row[C.VALUE['mrr']]:,.0f}<br>"
438 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
439 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
441 elif row["test_type"] == "ndrpdr":
444 f"pdr [{row[C.UNIT['pdr']]}]: "
445 f"{row[C.VALUE['pdr']]:,.0f}<br>"
449 f"ndr [{row[C.UNIT['ndr']]}]: "
450 f"{row[C.VALUE['ndr']]:,.0f}<br>"
458 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
459 f"value: {y_data[i]:,.2f}<br>"
461 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
462 f"csit-ref: {row['job']}/{row['build']}<br>"
465 anomalies, trend_avg, trend_stdev = classify_anomalies(
466 {k: v for k, v in zip(x_axis, y_data)}
469 for avg, stdev, (_, row) in \
470 zip(trend_avg, trend_stdev, df.iterrows()):
473 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
474 f"trend: {avg:,.2f}<br>"
475 f"stdev: {stdev:,.2f}<br>"
476 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
477 f"csit-ref: {row['job']}/{row['build']}"
482 color = get_color(color_index * len(metrics) + idx)
483 metric_name = f"{test}<br>{metric}"
485 color = get_color(idx)
489 go.Scatter( # Samples
500 hoverinfo="text+name",
502 legendgroup=metric_name
507 go.Scatter( # Trend line
518 hoverinfo="text+name",
520 legendgroup=metric_name
526 anomaly_color = list()
528 for idx, anomaly in enumerate(anomalies):
529 if anomaly in ("regression", "progression"):
530 anomaly_x.append(x_axis[idx])
531 anomaly_y.append(trend_avg[idx])
532 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
534 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
535 f"<br>trend: {trend_avg[idx]:,.2f}"
536 f"<br>classification: {anomaly}"
538 hover.append(hover_itm)
539 anomaly_color.extend([0.0, 0.5, 1.0])
546 hoverinfo="text+name",
548 legendgroup=metric_name,
552 "symbol": "circle-open",
553 "color": anomaly_color,
554 "colorscale": C.COLORSCALE_TPUT,
562 "title": "Circles Marking Data Classification",
563 "titleside": "right",
565 "tickvals": [0.167, 0.500, 0.833],
566 "ticktext": C.TICK_TEXT_TPUT,
576 unique_metrics = set()
578 unique_metrics.add(itm.split("{", 1)[0])
579 return traces, unique_metrics
581 tm_trending_graphs = list()
582 graph_layout = layout.get("plot-trending-telemetry", dict())
589 for idx, test in enumerate(data.test_name.unique()):
590 df = data.loc[(data["test_name"] == test)]
591 traces, metrics = _generate_traces(df, test, all_in_one, idx)
593 all_metrics.update(metrics)
595 all_traces.extend(traces)
596 all_tests.append(test)
599 graph.add_traces(traces)
600 graph.update_layout(graph_layout)
601 tm_trending_graphs.append((graph, [test, ], ))
605 graph.add_traces(all_traces)
606 graph.update_layout(graph_layout)
607 tm_trending_graphs.append((graph, all_tests, ))
609 return tm_trending_graphs, list(all_metrics)