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:
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.
18 import plotly.graph_objects as go
21 from ..utils.constants import Constants as C
22 from ..utils.utils import get_color, get_hdrh_latencies
23 from ..utils.anomalies import classify_anomalies
26 def select_trending_data(data: pd.DataFrame, itm: dict) -> pd.DataFrame:
27 """Select the data for graphs from the provided data frame.
29 :param data: Data frame with data for graphs.
30 :param itm: Item (in this case job name) which data will be selected from
32 :type data: pandas.DataFrame
34 :returns: A data frame with selected data.
35 :rtype: pandas.DataFrame
38 phy = itm["phy"].split("-")
40 topo, arch, nic, drv = phy
45 drv = drv.replace("_", "-")
49 if itm["testtype"] in ("ndr", "pdr"):
51 elif itm["testtype"] == "mrr":
53 elif itm["area"] == "hoststack":
54 test_type = "hoststack"
56 (data["test_type"] == test_type) &
57 (data["passed"] == True)
59 df = df[df.job.str.endswith(f"{topo}-{arch}")]
60 core = str() if itm["dut"] == "trex" else f"{itm['core']}"
61 ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
62 df = df[df.test_id.str.contains(
63 f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
65 )].sort_values(by="start_time", ignore_index=True)
76 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
77 (result_latency_forward_pdr_50_avg).
79 :param data: Data frame with test results.
80 :param sel: Selected tests.
81 :param layout: Layout of plot.ly graph.
82 :param normalize: If True, the data is normalized to CPU frquency
83 Constants.NORM_FREQUENCY.
84 :type data: pandas.DataFrame
88 :returns: Trending graph(s)
89 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
96 def _generate_trending_traces(
103 """Generate the trending traces for the trending graph.
105 :param ttype: Test type (MRR, NDR, PDR).
106 :param name: The test name to be displayed as the graph title.
107 :param df: Data frame with test data.
108 :param color: The color of the trace (samples and trend line).
109 :param nf: The factor used for normalization of the results to
110 CPU frequency set to Constants.NORM_FREQUENCY.
113 :type df: pandas.DataFrame
116 :returns: Traces (samples, trending line, anomalies)
120 df = df.dropna(subset=[C.VALUE[ttype], ])
122 return list(), list()
126 customdata_samples = list()
127 name_lst = name.split("-")
128 for _, row in df.iterrows():
129 h_tput, h_band, h_lat = str(), str(), str()
130 if ttype in ("mrr", "mrr-bandwidth"):
132 f"tput avg [{row['result_receive_rate_rate_unit']}]: "
133 f"{row['result_receive_rate_rate_avg'] * nf:,.0f}<br>"
134 f"tput stdev [{row['result_receive_rate_rate_unit']}]: "
135 f"{row['result_receive_rate_rate_stdev'] * nf:,.0f}<br>"
137 if pd.notna(row["result_receive_rate_bandwidth_avg"]):
140 f"[{row['result_receive_rate_bandwidth_unit']}]: "
141 f"{row['result_receive_rate_bandwidth_avg'] * nf:,.0f}"
144 f"[{row['result_receive_rate_bandwidth_unit']}]: "
145 f"{row['result_receive_rate_bandwidth_stdev']* nf:,.0f}"
148 elif ttype in ("ndr", "ndr-bandwidth"):
150 f"tput [{row['result_ndr_lower_rate_unit']}]: "
151 f"{row['result_ndr_lower_rate_value'] * nf:,.0f}<br>"
153 if pd.notna(row["result_ndr_lower_bandwidth_value"]):
155 f"bandwidth [{row['result_ndr_lower_bandwidth_unit']}]:"
156 f" {row['result_ndr_lower_bandwidth_value'] * nf:,.0f}"
159 elif ttype in ("pdr", "pdr-bandwidth", "latency"):
161 f"tput [{row['result_pdr_lower_rate_unit']}]: "
162 f"{row['result_pdr_lower_rate_value'] * nf:,.0f}<br>"
164 if pd.notna(row["result_pdr_lower_bandwidth_value"]):
166 f"bandwidth [{row['result_pdr_lower_bandwidth_unit']}]:"
167 f" {row['result_pdr_lower_bandwidth_value'] * nf:,.0f}"
170 if pd.notna(row["result_latency_forward_pdr_50_avg"]):
173 f"[{row['result_latency_forward_pdr_50_unit']}]: "
174 f"{row['result_latency_forward_pdr_50_avg'] / nf:,.0f}"
177 elif ttype in ("hoststack-cps", "hoststack-rps",
178 "hoststack-cps-bandwidth",
179 "hoststack-rps-bandwidth", "hoststack-latency"):
181 f"tput [{row['result_rate_unit']}]: "
182 f"{row['result_rate_value'] * nf:,.0f}<br>"
185 f"bandwidth [{row['result_bandwidth_unit']}]: "
186 f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
189 f"latency [{row['result_latency_unit']}]: "
190 f"{row['result_latency_value'] / nf:,.0f}<br>"
192 elif ttype in ("hoststack-bps", ):
194 f"bandwidth [{row['result_bandwidth_unit']}]: "
195 f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
198 f"dut: {name_lst[0]}<br>"
199 f"infra: {'-'.join(name_lst[1:5])}<br>"
200 f"test: {'-'.join(name_lst[5:])}<br>"
201 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
202 f"{h_tput}{h_band}{h_lat}"
203 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
204 f"csit-ref: {row['job']}/{row['build']}<br>"
205 f"hosts: {', '.join(row['hosts'])}"
207 hover.append(hover_itm)
208 if ttype == "latency":
209 customdata_samples.append(get_hdrh_latencies(row, name))
210 customdata.append({"name": name})
212 customdata_samples.append(
213 {"name": name, "show_telemetry": True}
215 customdata.append({"name": name})
217 x_axis = df["start_time"].tolist()
218 if "latency" in ttype:
219 y_data = [(v / nf) for v in df[C.VALUE[ttype]].tolist()]
221 y_data = [(v * nf) for v in df[C.VALUE[ttype]].tolist()]
222 units = df[C.UNIT[ttype]].unique().tolist()
225 anomalies, trend_avg, trend_stdev = classify_anomalies(
226 {k: v for k, v in zip(x_axis, y_data)}
228 except ValueError as err:
230 return list(), list()
233 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
235 f"dut: {name_lst[0]}<br>"
236 f"infra: {'-'.join(name_lst[1:5])}<br>"
237 f"test: {'-'.join(name_lst[5:])}<br>"
238 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
239 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
240 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
241 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
242 f"csit-ref: {row['job']}/{row['build']}<br>"
243 f"hosts: {', '.join(row['hosts'])}"
245 if ttype == "latency":
246 hover_itm = hover_itm.replace("[pps]", "[us]")
247 hover_trend.append(hover_itm)
250 go.Scatter( # Samples
264 customdata=customdata_samples
266 go.Scatter( # Trend line
280 customdata=customdata
287 anomaly_color = list()
289 for idx, anomaly in enumerate(anomalies):
290 if anomaly in ("regression", "progression"):
291 anomaly_x.append(x_axis[idx])
292 anomaly_y.append(trend_avg[idx])
293 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
295 f"dut: {name_lst[0]}<br>"
296 f"infra: {'-'.join(name_lst[1:5])}<br>"
297 f"test: {'-'.join(name_lst[5:])}<br>"
298 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
299 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
300 f"classification: {anomaly}"
302 if ttype == "latency":
303 hover_itm = hover_itm.replace("[pps]", "[us]")
304 hover.append(hover_itm)
305 anomaly_color.extend([0.0, 0.5, 1.0])
316 customdata=customdata,
319 "symbol": "circle-open",
320 "color": anomaly_color,
321 "colorscale": C.COLORSCALE_LAT \
322 if ttype == "latency" else C.COLORSCALE_TPUT,
330 "title": "Circles Marking Data Classification",
331 "titleside": "right",
333 "tickvals": [0.167, 0.500, 0.833],
334 "ticktext": C.TICK_TEXT_LAT \
335 if ttype == "latency" else C.TICK_TEXT_TPUT,
352 for idx, itm in enumerate(sel):
353 df = select_trending_data(data, itm)
354 if df is None or df.empty:
358 phy = itm["phy"].split("-")
359 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
360 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY.get(topo_arch, 1.0)) \
361 if topo_arch else 1.0
365 if itm["area"] == "hoststack":
366 ttype = f"hoststack-{itm['testtype']}"
368 ttype = itm["testtype"]
370 traces, units = _generate_trending_traces(
379 fig_tput = go.Figure()
380 fig_tput.add_traces(traces)
382 if ttype in ("ndr", "pdr", "mrr", "hoststack-cps", "hoststack-rps"):
383 traces, _ = _generate_trending_traces(
384 f"{ttype}-bandwidth",
392 fig_band = go.Figure()
393 fig_band.add_traces(traces)
395 if ttype in ("pdr", "hoststack-cps", "hoststack-rps"):
396 traces, _ = _generate_trending_traces(
397 "latency" if ttype == "pdr" else "hoststack-latency",
405 fig_lat = go.Figure()
406 fig_lat.add_traces(traces)
408 y_units.update(units)
411 fig_layout = layout.get("plot-trending-tput", dict())
412 fig_layout["yaxis"]["title"] = \
413 f"Throughput [{'|'.join(sorted(y_units))}]"
414 fig_tput.update_layout(fig_layout)
416 fig_band.update_layout(layout.get("plot-trending-bandwidth", dict()))
418 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
420 return fig_tput, fig_band, fig_lat
423 def graph_tm_trending(
426 all_in_one: bool=False
428 """Generates one trending graph per test, each graph includes all selected
431 :param data: Data frame with telemetry data.
432 :param layout: Layout of plot.ly graph.
433 :param all_in_one: If True, all telemetry traces are placed in one graph,
434 otherwise they are split to separate graphs grouped by test ID.
435 :type data: pandas.DataFrame
437 :type all_in_one: bool
438 :returns: List of generated graphs together with test names.
439 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
446 def _generate_traces(
452 """Generates a trending graph for given test with all metrics.
454 :param data: Data frame with telemetry data for the given test.
455 :param test: The name of the test.
456 :param all_in_one: If True, all telemetry traces are placed in one
457 graph, otherwise they are split to separate graphs grouped by
459 :param color_index: The index of the test used if all_in_one is True.
460 :type data: pandas.DataFrame
462 :type all_in_one: bool
463 :type color_index: int
464 :returns: List of traces.
468 metrics = data.tm_metric.unique().tolist()
469 for idx, metric in enumerate(metrics):
470 if "-pdr" in test and "='pdr'" not in metric:
472 if "-ndr" in test and "='ndr'" not in metric:
475 df = data.loc[(data["tm_metric"] == metric)]
476 x_axis = df["start_time"].tolist()
477 y_data = [float(itm) for itm in df["tm_value"].tolist()]
479 for i, (_, row) in enumerate(df.iterrows()):
480 if row["test_type"] == "mrr":
482 f"mrr avg [{row[C.UNIT['mrr']]}]: "
483 f"{row[C.VALUE['mrr']]:,.0f}<br>"
484 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
485 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
487 elif row["test_type"] == "ndrpdr":
490 f"pdr [{row[C.UNIT['pdr']]}]: "
491 f"{row[C.VALUE['pdr']]:,.0f}<br>"
495 f"ndr [{row[C.UNIT['ndr']]}]: "
496 f"{row[C.VALUE['ndr']]:,.0f}<br>"
504 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
505 f"value: {y_data[i]:,.2f}<br>"
507 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
508 f"csit-ref: {row['job']}/{row['build']}<br>"
511 anomalies, trend_avg, trend_stdev = classify_anomalies(
512 {k: v for k, v in zip(x_axis, y_data)}
515 for avg, stdev, (_, row) in \
516 zip(trend_avg, trend_stdev, df.iterrows()):
519 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
520 f"trend: {avg:,.2f}<br>"
521 f"stdev: {stdev:,.2f}<br>"
522 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
523 f"csit-ref: {row['job']}/{row['build']}"
528 color = get_color(color_index * len(metrics) + idx)
529 metric_name = f"{test}<br>{metric}"
531 color = get_color(idx)
535 go.Scatter( # Samples
546 hoverinfo="text+name",
548 legendgroup=metric_name
553 go.Scatter( # Trend line
564 hoverinfo="text+name",
566 legendgroup=metric_name
572 anomaly_color = list()
574 for idx, anomaly in enumerate(anomalies):
575 if anomaly in ("regression", "progression"):
576 anomaly_x.append(x_axis[idx])
577 anomaly_y.append(trend_avg[idx])
578 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
580 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
581 f"<br>trend: {trend_avg[idx]:,.2f}"
582 f"<br>classification: {anomaly}"
584 hover.append(hover_itm)
585 anomaly_color.extend([0.0, 0.5, 1.0])
592 hoverinfo="text+name",
594 legendgroup=metric_name,
598 "symbol": "circle-open",
599 "color": anomaly_color,
600 "colorscale": C.COLORSCALE_TPUT,
608 "title": "Circles Marking Data Classification",
609 "titleside": "right",
611 "tickvals": [0.167, 0.500, 0.833],
612 "ticktext": C.TICK_TEXT_TPUT,
622 unique_metrics = set()
624 unique_metrics.add(itm.split("{", 1)[0])
625 return traces, unique_metrics
627 tm_trending_graphs = list()
628 graph_layout = layout.get("plot-trending-telemetry", dict())
635 for idx, test in enumerate(data.test_name.unique()):
636 df = data.loc[(data["test_name"] == test)]
637 traces, metrics = _generate_traces(df, test, all_in_one, idx)
639 all_metrics.update(metrics)
641 all_traces.extend(traces)
642 all_tests.append(test)
645 graph.add_traces(traces)
646 graph.update_layout(graph_layout)
647 tm_trending_graphs.append((graph, [test, ], ))
651 graph.add_traces(all_traces)
652 graph.update_layout(graph_layout)
653 tm_trending_graphs.append((graph, all_tests, ))
655 return tm_trending_graphs, list(all_metrics)