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.
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 norm_factor: The factor used for normalization of the results to
110 CPU frequency set to Constants.NORM_FREQUENCY.
113 :type df: pandas.DataFrame
115 :type norm_factor: float
116 :returns: Traces (samples, trending line, anomalies)
120 df = df.dropna(subset=[C.VALUE[ttype], ])
122 return list(), list()
124 x_axis = df["start_time"].tolist()
125 if ttype == "latency":
126 y_data = [(v / norm_factor) for v in df[C.VALUE[ttype]].tolist()]
128 y_data = [(v * norm_factor) for v in df[C.VALUE[ttype]].tolist()]
129 units = df[C.UNIT[ttype]].unique().tolist()
132 anomalies, trend_avg, trend_stdev = classify_anomalies(
133 {k: v for k, v in zip(x_axis, y_data)}
135 except ValueError as err:
137 return list(), list()
141 customdata_samples = list()
142 name_lst = name.split("-")
143 for idx, (_, row) in enumerate(df.iterrows()):
144 h_tput, h_band, h_lat = str(), str(), str()
145 if ttype in ("mrr", "mrr-bandwidth"):
147 f"tput avg [{row['result_receive_rate_rate_unit']}]: "
148 f"{row['result_receive_rate_rate_avg']:,.0f}<br>"
149 f"tput stdev [{row['result_receive_rate_rate_unit']}]: "
150 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
152 if pd.notna(row["result_receive_rate_bandwidth_avg"]):
155 f"[{row['result_receive_rate_bandwidth_unit']}]: "
156 f"{row['result_receive_rate_bandwidth_avg']:,.0f}<br>"
158 f"[{row['result_receive_rate_bandwidth_unit']}]: "
159 f"{row['result_receive_rate_bandwidth_stdev']:,.0f}<br>"
161 elif ttype in ("ndr", "ndr-bandwidth"):
163 f"tput [{row['result_ndr_lower_rate_unit']}]: "
164 f"{row['result_ndr_lower_rate_value']:,.0f}<br>"
166 if pd.notna(row["result_ndr_lower_bandwidth_value"]):
168 f"bandwidth [{row['result_ndr_lower_bandwidth_unit']}]:"
169 f" {row['result_ndr_lower_bandwidth_value']:,.0f}<br>"
171 elif ttype in ("pdr", "pdr-bandwidth", "latency"):
173 f"tput [{row['result_pdr_lower_rate_unit']}]: "
174 f"{row['result_pdr_lower_rate_value']:,.0f}<br>"
176 if pd.notna(row["result_pdr_lower_bandwidth_value"]):
178 f"bandwidth [{row['result_pdr_lower_bandwidth_unit']}]:"
179 f" {row['result_pdr_lower_bandwidth_value']:,.0f}<br>"
181 if pd.notna(row["result_latency_forward_pdr_50_avg"]):
184 f"[{row['result_latency_forward_pdr_50_unit']}]: "
185 f"{row['result_latency_forward_pdr_50_avg']:,.0f}<br>"
187 elif ttype in ("hoststack-cps", "hoststack-rps",
188 "hoststack-cps-bandwidth",
189 "hoststack-rps-bandwidth", "hoststack-latency"):
191 f"tput [{row['result_rate_unit']}]: "
192 f"{row['result_rate_value']:,.0f}<br>"
195 f"bandwidth [{row['result_bandwidth_unit']}]: "
196 f"{row['result_bandwidth_value']:,.0f}<br>"
199 f"latency [{row['result_latency_unit']}]: "
200 f"{row['result_latency_value']:,.0f}<br>"
202 elif ttype in ("hoststack-bps", ):
204 f"bandwidth [{row['result_bandwidth_unit']}]: "
205 f"{row['result_bandwidth_value']:,.0f}<br>"
208 f"dut: {name_lst[0]}<br>"
209 f"infra: {'-'.join(name_lst[1:5])}<br>"
210 f"test: {'-'.join(name_lst[5:])}<br>"
211 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
212 f"{h_tput}{h_band}{h_lat}"
213 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
214 f"csit-ref: {row['job']}/{row['build']}<br>"
215 f"hosts: {', '.join(row['hosts'])}"
217 hover.append(hover_itm)
218 if ttype == "latency":
219 customdata_samples.append(get_hdrh_latencies(row, name))
220 customdata.append({"name": name})
222 customdata_samples.append(
223 {"name": name, "show_telemetry": True}
225 customdata.append({"name": name})
228 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
230 f"dut: {name_lst[0]}<br>"
231 f"infra: {'-'.join(name_lst[1:5])}<br>"
232 f"test: {'-'.join(name_lst[5:])}<br>"
233 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
234 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
235 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
236 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
237 f"csit-ref: {row['job']}/{row['build']}<br>"
238 f"hosts: {', '.join(row['hosts'])}"
240 if ttype == "latency":
241 hover_itm = hover_itm.replace("[pps]", "[us]")
242 hover_trend.append(hover_itm)
245 go.Scatter( # Samples
259 customdata=customdata_samples
261 go.Scatter( # Trend line
275 customdata=customdata
282 anomaly_color = list()
284 for idx, anomaly in enumerate(anomalies):
285 if anomaly in ("regression", "progression"):
286 anomaly_x.append(x_axis[idx])
287 anomaly_y.append(trend_avg[idx])
288 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
290 f"dut: {name_lst[0]}<br>"
291 f"infra: {'-'.join(name_lst[1:5])}<br>"
292 f"test: {'-'.join(name_lst[5:])}<br>"
293 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
294 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
295 f"classification: {anomaly}"
297 if ttype == "latency":
298 hover_itm = hover_itm.replace("[pps]", "[us]")
299 hover.append(hover_itm)
300 anomaly_color.extend([0.0, 0.5, 1.0])
311 customdata=customdata,
314 "symbol": "circle-open",
315 "color": anomaly_color,
316 "colorscale": C.COLORSCALE_LAT \
317 if ttype == "latency" else C.COLORSCALE_TPUT,
325 "title": "Circles Marking Data Classification",
326 "titleside": "right",
328 "tickvals": [0.167, 0.500, 0.833],
329 "ticktext": C.TICK_TEXT_LAT \
330 if ttype == "latency" else C.TICK_TEXT_TPUT,
347 for idx, itm in enumerate(sel):
348 df = select_trending_data(data, itm)
349 if df is None or df.empty:
353 phy = itm["phy"].split("-")
354 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
355 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
356 if topo_arch else 1.0
360 if itm["area"] == "hoststack":
361 ttype = f"hoststack-{itm['testtype']}"
363 ttype = itm["testtype"]
365 traces, units = _generate_trending_traces(
374 fig_tput = go.Figure()
375 fig_tput.add_traces(traces)
377 if ttype in ("ndr", "pdr", "mrr", "hoststack-cps", "hoststack-rps"):
378 traces, _ = _generate_trending_traces(
379 f"{ttype}-bandwidth",
387 fig_band = go.Figure()
388 fig_band.add_traces(traces)
390 if ttype in ("pdr", "hoststack-cps", "hoststack-rps"):
391 traces, _ = _generate_trending_traces(
392 "latency" if ttype == "pdr" else "hoststack-latency",
400 fig_lat = go.Figure()
401 fig_lat.add_traces(traces)
403 y_units.update(units)
406 fig_layout = layout.get("plot-trending-tput", dict())
407 fig_layout["yaxis"]["title"] = \
408 f"Throughput [{'|'.join(sorted(y_units))}]"
409 fig_tput.update_layout(fig_layout)
411 fig_band.update_layout(layout.get("plot-trending-bandwidth", dict()))
413 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
415 return fig_tput, fig_band, fig_lat
418 def graph_tm_trending(
421 all_in_one: bool=False
423 """Generates one trending graph per test, each graph includes all selected
426 :param data: Data frame with telemetry data.
427 :param layout: Layout of plot.ly graph.
428 :param all_in_one: If True, all telemetry traces are placed in one graph,
429 otherwise they are split to separate graphs grouped by test ID.
430 :type data: pandas.DataFrame
432 :type all_in_one: bool
433 :returns: List of generated graphs together with test names.
434 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
441 def _generate_traces(
447 """Generates a trending graph for given test with all metrics.
449 :param data: Data frame with telemetry data for the given test.
450 :param test: The name of the test.
451 :param all_in_one: If True, all telemetry traces are placed in one
452 graph, otherwise they are split to separate graphs grouped by
454 :param color_index: The index of the test used if all_in_one is True.
455 :type data: pandas.DataFrame
457 :type all_in_one: bool
458 :type color_index: int
459 :returns: List of traces.
463 metrics = data.tm_metric.unique().tolist()
464 for idx, metric in enumerate(metrics):
465 if "-pdr" in test and "='pdr'" not in metric:
467 if "-ndr" in test and "='ndr'" not in metric:
470 df = data.loc[(data["tm_metric"] == metric)]
471 x_axis = df["start_time"].tolist()
472 y_data = [float(itm) for itm in df["tm_value"].tolist()]
474 for i, (_, row) in enumerate(df.iterrows()):
475 if row["test_type"] == "mrr":
477 f"mrr avg [{row[C.UNIT['mrr']]}]: "
478 f"{row[C.VALUE['mrr']]:,.0f}<br>"
479 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
480 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
482 elif row["test_type"] == "ndrpdr":
485 f"pdr [{row[C.UNIT['pdr']]}]: "
486 f"{row[C.VALUE['pdr']]:,.0f}<br>"
490 f"ndr [{row[C.UNIT['ndr']]}]: "
491 f"{row[C.VALUE['ndr']]:,.0f}<br>"
499 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
500 f"value: {y_data[i]:,.2f}<br>"
502 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
503 f"csit-ref: {row['job']}/{row['build']}<br>"
506 anomalies, trend_avg, trend_stdev = classify_anomalies(
507 {k: v for k, v in zip(x_axis, y_data)}
510 for avg, stdev, (_, row) in \
511 zip(trend_avg, trend_stdev, df.iterrows()):
514 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
515 f"trend: {avg:,.2f}<br>"
516 f"stdev: {stdev:,.2f}<br>"
517 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
518 f"csit-ref: {row['job']}/{row['build']}"
523 color = get_color(color_index * len(metrics) + idx)
524 metric_name = f"{test}<br>{metric}"
526 color = get_color(idx)
530 go.Scatter( # Samples
541 hoverinfo="text+name",
543 legendgroup=metric_name
548 go.Scatter( # Trend line
559 hoverinfo="text+name",
561 legendgroup=metric_name
567 anomaly_color = list()
569 for idx, anomaly in enumerate(anomalies):
570 if anomaly in ("regression", "progression"):
571 anomaly_x.append(x_axis[idx])
572 anomaly_y.append(trend_avg[idx])
573 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
575 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
576 f"<br>trend: {trend_avg[idx]:,.2f}"
577 f"<br>classification: {anomaly}"
579 hover.append(hover_itm)
580 anomaly_color.extend([0.0, 0.5, 1.0])
587 hoverinfo="text+name",
589 legendgroup=metric_name,
593 "symbol": "circle-open",
594 "color": anomaly_color,
595 "colorscale": C.COLORSCALE_TPUT,
603 "title": "Circles Marking Data Classification",
604 "titleside": "right",
606 "tickvals": [0.167, 0.500, 0.833],
607 "ticktext": C.TICK_TEXT_TPUT,
617 unique_metrics = set()
619 unique_metrics.add(itm.split("{", 1)[0])
620 return traces, unique_metrics
622 tm_trending_graphs = list()
623 graph_layout = layout.get("plot-trending-telemetry", dict())
630 for idx, test in enumerate(data.test_name.unique()):
631 df = data.loc[(data["test_name"] == test)]
632 traces, metrics = _generate_traces(df, test, all_in_one, idx)
634 all_metrics.update(metrics)
636 all_traces.extend(traces)
637 all_tests.append(test)
640 graph.add_traces(traces)
641 graph.update_layout(graph_layout)
642 tm_trending_graphs.append((graph, [test, ], ))
646 graph.add_traces(all_traces)
647 graph.update_layout(graph_layout)
648 tm_trending_graphs.append((graph, all_tests, ))
650 return tm_trending_graphs, list(all_metrics)