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["testtype"] == "soak":
55 elif itm["area"] == "hoststack":
56 test_type = "hoststack"
58 (data["test_type"] == test_type) &
59 (data["passed"] == True)
61 df = df[df.job.str.endswith(f"{topo}-{arch}")]
62 core = str() if itm["dut"] == "trex" else f"{itm['core']}"
63 ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
64 df = df[df.test_id.str.contains(
65 f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
67 )].sort_values(by="start_time", ignore_index=True)
78 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
79 (result_latency_forward_pdr_50_avg).
81 :param data: Data frame with test results.
82 :param sel: Selected tests.
83 :param layout: Layout of plot.ly graph.
84 :param normalize: If True, the data is normalized to CPU frquency
85 Constants.NORM_FREQUENCY.
86 :type data: pandas.DataFrame
90 :returns: Trending graph(s)
91 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
98 def _generate_trending_traces(
105 """Generate the trending traces for the trending graph.
107 :param ttype: Test type (MRR, NDR, PDR).
108 :param name: The test name to be displayed as the graph title.
109 :param df: Data frame with test data.
110 :param color: The color of the trace (samples and trend line).
111 :param nf: The factor used for normalization of the results to
112 CPU frequency set to Constants.NORM_FREQUENCY.
115 :type df: pandas.DataFrame
118 :returns: Traces (samples, trending line, anomalies)
122 df = df.dropna(subset=[C.VALUE[ttype], ])
124 return list(), list()
128 customdata_samples = list()
129 name_lst = name.split("-")
130 for _, row in df.iterrows():
131 h_tput, h_band, h_lat = str(), str(), str()
132 if ttype in ("mrr", "mrr-bandwidth"):
134 f"tput avg [{row['result_receive_rate_rate_unit']}]: "
135 f"{row['result_receive_rate_rate_avg'] * nf:,.0f}<br>"
136 f"tput stdev [{row['result_receive_rate_rate_unit']}]: "
137 f"{row['result_receive_rate_rate_stdev'] * nf:,.0f}<br>"
139 if pd.notna(row["result_receive_rate_bandwidth_avg"]):
142 f"[{row['result_receive_rate_bandwidth_unit']}]: "
143 f"{row['result_receive_rate_bandwidth_avg'] * nf:,.0f}"
146 f"[{row['result_receive_rate_bandwidth_unit']}]: "
147 f"{row['result_receive_rate_bandwidth_stdev']* nf:,.0f}"
150 elif ttype in ("ndr", "ndr-bandwidth"):
152 f"tput [{row['result_ndr_lower_rate_unit']}]: "
153 f"{row['result_ndr_lower_rate_value'] * nf:,.0f}<br>"
155 if pd.notna(row["result_ndr_lower_bandwidth_value"]):
157 f"bandwidth [{row['result_ndr_lower_bandwidth_unit']}]:"
158 f" {row['result_ndr_lower_bandwidth_value'] * nf:,.0f}"
161 elif ttype in ("pdr", "pdr-bandwidth", "latency"):
163 f"tput [{row['result_pdr_lower_rate_unit']}]: "
164 f"{row['result_pdr_lower_rate_value'] * nf:,.0f}<br>"
166 if pd.notna(row["result_pdr_lower_bandwidth_value"]):
168 f"bandwidth [{row['result_pdr_lower_bandwidth_unit']}]:"
169 f" {row['result_pdr_lower_bandwidth_value'] * nf:,.0f}"
172 if pd.notna(row["result_latency_forward_pdr_50_avg"]):
175 f"[{row['result_latency_forward_pdr_50_unit']}]: "
176 f"{row['result_latency_forward_pdr_50_avg'] / nf:,.0f}"
179 elif ttype in ("hoststack-cps", "hoststack-rps",
180 "hoststack-cps-bandwidth",
181 "hoststack-rps-bandwidth", "hoststack-latency"):
183 f"tput [{row['result_rate_unit']}]: "
184 f"{row['result_rate_value'] * nf:,.0f}<br>"
187 f"bandwidth [{row['result_bandwidth_unit']}]: "
188 f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
191 f"latency [{row['result_latency_unit']}]: "
192 f"{row['result_latency_value'] / nf:,.0f}<br>"
194 elif ttype in ("hoststack-bps", ):
196 f"bandwidth [{row['result_bandwidth_unit']}]: "
197 f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
199 elif ttype in ("soak", "soak-bandwidth"):
201 f"tput [{row['result_critical_rate_lower_rate_unit']}]: "
202 f"{row['result_critical_rate_lower_rate_value'] * nf:,.0f}"
205 if pd.notna(row["result_critical_rate_lower_bandwidth_value"]):
206 bv = row['result_critical_rate_lower_bandwidth_value']
209 f"[{row['result_critical_rate_lower_bandwidth_unit']}]:"
214 hosts = f"<br>hosts: {', '.join(row['hosts'])}"
215 except (KeyError, TypeError):
218 f"dut: {name_lst[0]}<br>"
219 f"infra: {'-'.join(name_lst[1:5])}<br>"
220 f"test: {'-'.join(name_lst[5:])}<br>"
221 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
222 f"{h_tput}{h_band}{h_lat}"
223 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
224 f"csit-ref: {row['job']}/{row['build']}"
227 hover.append(hover_itm)
228 if ttype == "latency":
229 customdata_samples.append(get_hdrh_latencies(row, name))
230 customdata.append({"name": name})
232 customdata_samples.append(
233 {"name": name, "show_telemetry": True}
235 customdata.append({"name": name})
237 x_axis = df["start_time"].tolist()
238 if "latency" in ttype:
239 y_data = [(v / nf) for v in df[C.VALUE[ttype]].tolist()]
241 y_data = [(v * nf) for v in df[C.VALUE[ttype]].tolist()]
242 units = df[C.UNIT[ttype]].unique().tolist()
245 anomalies, trend_avg, trend_stdev = classify_anomalies(
246 {k: v for k, v in zip(x_axis, y_data)}
248 except ValueError as err:
250 return list(), list()
253 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
255 hosts = f"<br>hosts: {', '.join(row['hosts'])}"
256 except (KeyError, TypeError):
259 f"dut: {name_lst[0]}<br>"
260 f"infra: {'-'.join(name_lst[1:5])}<br>"
261 f"test: {'-'.join(name_lst[5:])}<br>"
262 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
263 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
264 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
265 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
266 f"csit-ref: {row['job']}/{row['build']}"
269 if ttype == "latency":
270 hover_itm = hover_itm.replace("[pps]", "[us]")
271 hover_trend.append(hover_itm)
274 go.Scatter( # Samples
288 customdata=customdata_samples
290 go.Scatter( # Trend line
304 customdata=customdata
311 anomaly_color = list()
313 for idx, anomaly in enumerate(anomalies):
314 if anomaly in ("regression", "progression"):
315 anomaly_x.append(x_axis[idx])
316 anomaly_y.append(trend_avg[idx])
317 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
319 f"dut: {name_lst[0]}<br>"
320 f"infra: {'-'.join(name_lst[1:5])}<br>"
321 f"test: {'-'.join(name_lst[5:])}<br>"
322 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
323 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
324 f"classification: {anomaly}"
326 if ttype == "latency":
327 hover_itm = hover_itm.replace("[pps]", "[us]")
328 hover.append(hover_itm)
329 anomaly_color.extend([0.0, 0.5, 1.0])
340 customdata=customdata,
343 "symbol": "circle-open",
344 "color": anomaly_color,
345 "colorscale": C.COLORSCALE_LAT \
346 if ttype == "latency" else C.COLORSCALE_TPUT,
354 "title": "Circles Marking Data Classification",
355 "titleside": "right",
357 "tickvals": [0.167, 0.500, 0.833],
358 "ticktext": C.TICK_TEXT_LAT \
359 if ttype == "latency" else C.TICK_TEXT_TPUT,
376 for idx, itm in enumerate(sel):
377 df = select_trending_data(data, itm)
378 if df is None or df.empty:
382 phy = itm["phy"].split("-")
383 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
384 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY.get(topo_arch, 1.0)) \
385 if topo_arch else 1.0
389 if itm["area"] == "hoststack":
390 ttype = f"hoststack-{itm['testtype']}"
392 ttype = itm["testtype"]
394 traces, units = _generate_trending_traces(
403 fig_tput = go.Figure()
404 fig_tput.add_traces(traces)
406 if ttype in C.TESTS_WITH_BANDWIDTH:
407 traces, _ = _generate_trending_traces(
408 f"{ttype}-bandwidth",
416 fig_band = go.Figure()
417 fig_band.add_traces(traces)
419 if ttype in C.TESTS_WITH_LATENCY:
420 traces, _ = _generate_trending_traces(
421 "latency" if ttype == "pdr" else "hoststack-latency",
429 fig_lat = go.Figure()
430 fig_lat.add_traces(traces)
432 y_units.update(units)
435 fig_layout = layout.get("plot-trending-tput", dict())
436 fig_layout["yaxis"]["title"] = \
437 f"Throughput [{'|'.join(sorted(y_units))}]"
438 fig_tput.update_layout(fig_layout)
440 fig_band.update_layout(layout.get("plot-trending-bandwidth", dict()))
442 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
444 return fig_tput, fig_band, fig_lat
447 def graph_tm_trending(
450 all_in_one: bool=False
452 """Generates one trending graph per test, each graph includes all selected
455 :param data: Data frame with telemetry data.
456 :param layout: Layout of plot.ly graph.
457 :param all_in_one: If True, all telemetry traces are placed in one graph,
458 otherwise they are split to separate graphs grouped by test ID.
459 :type data: pandas.DataFrame
461 :type all_in_one: bool
462 :returns: List of generated graphs together with test names.
463 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
470 def _generate_traces(
476 """Generates a trending graph for given test with all metrics.
478 :param data: Data frame with telemetry data for the given test.
479 :param test: The name of the test.
480 :param all_in_one: If True, all telemetry traces are placed in one
481 graph, otherwise they are split to separate graphs grouped by
483 :param color_index: The index of the test used if all_in_one is True.
484 :type data: pandas.DataFrame
486 :type all_in_one: bool
487 :type color_index: int
488 :returns: List of traces.
492 metrics = data.tm_metric.unique().tolist()
493 for idx, metric in enumerate(metrics):
494 if "-pdr" in test and "='pdr'" not in metric:
496 if "-ndr" in test and "='ndr'" not in metric:
499 df = data.loc[(data["tm_metric"] == metric)]
500 x_axis = df["start_time"].tolist()
501 y_data = [float(itm) for itm in df["tm_value"].tolist()]
503 for i, (_, row) in enumerate(df.iterrows()):
504 if row["test_type"] == "mrr":
506 f"mrr avg [{row[C.UNIT['mrr']]}]: "
507 f"{row[C.VALUE['mrr']]:,.0f}<br>"
508 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
509 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
511 elif row["test_type"] == "ndrpdr":
514 f"pdr [{row[C.UNIT['pdr']]}]: "
515 f"{row[C.VALUE['pdr']]:,.0f}<br>"
519 f"ndr [{row[C.UNIT['ndr']]}]: "
520 f"{row[C.VALUE['ndr']]:,.0f}<br>"
528 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
529 f"value: {y_data[i]:,.2f}<br>"
531 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
532 f"csit-ref: {row['job']}/{row['build']}<br>"
535 anomalies, trend_avg, trend_stdev = classify_anomalies(
536 {k: v for k, v in zip(x_axis, y_data)}
539 for avg, stdev, (_, row) in \
540 zip(trend_avg, trend_stdev, df.iterrows()):
543 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
544 f"trend: {avg:,.2f}<br>"
545 f"stdev: {stdev:,.2f}<br>"
546 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
547 f"csit-ref: {row['job']}/{row['build']}"
552 color = get_color(color_index * len(metrics) + idx)
553 metric_name = f"{test}<br>{metric}"
555 color = get_color(idx)
559 go.Scatter( # Samples
570 hoverinfo="text+name",
572 legendgroup=metric_name
577 go.Scatter( # Trend line
588 hoverinfo="text+name",
590 legendgroup=metric_name
596 anomaly_color = list()
598 for idx, anomaly in enumerate(anomalies):
599 if anomaly in ("regression", "progression"):
600 anomaly_x.append(x_axis[idx])
601 anomaly_y.append(trend_avg[idx])
602 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
604 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
605 f"<br>trend: {trend_avg[idx]:,.2f}"
606 f"<br>classification: {anomaly}"
608 hover.append(hover_itm)
609 anomaly_color.extend([0.0, 0.5, 1.0])
616 hoverinfo="text+name",
618 legendgroup=metric_name,
622 "symbol": "circle-open",
623 "color": anomaly_color,
624 "colorscale": C.COLORSCALE_TPUT,
632 "title": "Circles Marking Data Classification",
633 "titleside": "right",
635 "tickvals": [0.167, 0.500, 0.833],
636 "ticktext": C.TICK_TEXT_TPUT,
646 unique_metrics = set()
648 unique_metrics.add(itm.split("{", 1)[0])
649 return traces, unique_metrics
651 tm_trending_graphs = list()
652 graph_layout = layout.get("plot-trending-telemetry", dict())
659 for idx, test in enumerate(data.test_name.unique()):
660 df = data.loc[(data["test_name"] == test)]
661 traces, metrics = _generate_traces(df, test, all_in_one, idx)
663 all_metrics.update(metrics)
665 all_traces.extend(traces)
666 all_tests.append(test)
669 graph.add_traces(traces)
670 graph.update_layout(graph_layout)
671 tm_trending_graphs.append((graph, [test, ], ))
675 graph.add_traces(all_traces)
676 graph.update_layout(graph_layout)
677 tm_trending_graphs.append((graph, all_tests, ))
679 return tm_trending_graphs, list(all_metrics)