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 for idx, (_, row) in enumerate(df.iterrows()):
138 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
140 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
141 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
144 f"{d_type}-ref: {row['dut_version']}<br>"
145 f"csit-ref: {row['job']}/{row['build']}<br>"
146 f"hosts: {', '.join(row['hosts'])}"
150 f"stdev [{row['result_receive_rate_rate_unit']}]: "
151 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
155 if ttype in ("hoststack-cps", "hoststack-rps"):
157 f"bandwidth [{row[C.UNIT['hoststack-bps']]}]: "
158 f"{row[C.VALUE['hoststack-bps']]:,.0f}<br>"
159 f"latency [{row[C.UNIT['hoststack-lat']]}]: "
160 f"{row[C.VALUE['hoststack-lat']]:,.0f}<br>"
164 hover_itm = hover_itm.replace(
165 "<prop>", "latency" if ttype == "latency" else "average"
166 ).replace("<stdev>", stdev).replace("<additional-info>", add_info)
167 hover.append(hover_itm)
168 if ttype == "latency":
169 customdata_samples.append(get_hdrh_latencies(row, name))
170 customdata.append({"name": name})
172 customdata_samples.append(
173 {"name": name, "show_telemetry": True}
175 customdata.append({"name": name})
178 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
179 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
181 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
182 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
183 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
184 f"{d_type}-ref: {row['dut_version']}<br>"
185 f"csit-ref: {row['job']}/{row['build']}<br>"
186 f"hosts: {', '.join(row['hosts'])}"
188 if ttype == "latency":
189 hover_itm = hover_itm.replace("[pps]", "[us]")
190 hover_trend.append(hover_itm)
193 go.Scatter( # Samples
204 hoverinfo="text+name",
207 customdata=customdata_samples
209 go.Scatter( # Trend line
220 hoverinfo="text+name",
223 customdata=customdata
230 anomaly_color = list()
232 for idx, anomaly in enumerate(anomalies):
233 if anomaly in ("regression", "progression"):
234 anomaly_x.append(x_axis[idx])
235 anomaly_y.append(trend_avg[idx])
236 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
238 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
239 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
240 f"classification: {anomaly}"
242 if ttype == "latency":
243 hover_itm = hover_itm.replace("[pps]", "[us]")
244 hover.append(hover_itm)
245 anomaly_color.extend([0.0, 0.5, 1.0])
252 hoverinfo="text+name",
256 customdata=customdata,
259 "symbol": "circle-open",
260 "color": anomaly_color,
261 "colorscale": C.COLORSCALE_LAT \
262 if ttype == "latency" else C.COLORSCALE_TPUT,
270 "title": "Circles Marking Data Classification",
271 "titleside": "right",
273 "tickvals": [0.167, 0.500, 0.833],
274 "ticktext": C.TICK_TEXT_LAT \
275 if ttype == "latency" else C.TICK_TEXT_TPUT,
291 for idx, itm in enumerate(sel):
292 df = select_trending_data(data, itm)
293 if df is None or df.empty:
297 phy = itm["phy"].split("-")
298 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
299 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
300 if topo_arch else 1.0
304 if itm["area"] == "hoststack":
305 ttype = f"hoststack-{itm['testtype']}"
307 ttype = itm["testtype"]
309 traces, units = _generate_trending_traces(
318 fig_tput = go.Figure()
319 fig_tput.add_traces(traces)
321 if itm["testtype"] == "pdr":
322 traces, _ = _generate_trending_traces(
331 fig_lat = go.Figure()
332 fig_lat.add_traces(traces)
334 y_units.update(units)
337 fig_layout = layout.get("plot-trending-tput", dict())
338 fig_layout["yaxis"]["title"] = \
339 f"Throughput [{'|'.join(sorted(y_units))}]"
340 fig_tput.update_layout(fig_layout)
342 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
344 return fig_tput, fig_lat
347 def graph_tm_trending(data: pd.DataFrame, layout: dict) -> list:
348 """Generates one trending graph per test, each graph includes all selected
351 :param data: Data frame with telemetry data.
352 :param layout: Layout of plot.ly graph.
353 :type data: pandas.DataFrame
355 :returns: List of generated graphs together with test names.
356 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
366 """Generates a trending graph for given test with all metrics.
368 :param data: Data frame with telemetry data for the given test.
369 :param test: The name of the test.
370 :param layout: Layout of plot.ly graph.
371 :type data: pandas.DataFrame
374 :returns: A trending graph.
375 :rtype: plotly.graph_objects.Figure
379 for idx, metric in enumerate(data.tm_metric.unique()):
380 if "-pdr" in test and "='pdr'" not in metric:
382 if "-ndr" in test and "='ndr'" not in metric:
385 df = data.loc[(data["tm_metric"] == metric)]
386 x_axis = df["start_time"].tolist()
387 y_data = [float(itm) for itm in df["tm_value"].tolist()]
389 for i, (_, row) in enumerate(df.iterrows()):
390 if row["test_type"] == "mrr":
392 f"mrr avg [{row[C.UNIT['mrr']]}]: "
393 f"{row[C.VALUE['mrr']]:,.0f}<br>"
394 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
395 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
397 elif row["test_type"] == "ndrpdr":
400 f"pdr [{row[C.UNIT['pdr']]}]: "
401 f"{row[C.VALUE['pdr']]:,.0f}<br>"
405 f"ndr [{row[C.UNIT['ndr']]}]: "
406 f"{row[C.VALUE['ndr']]:,.0f}<br>"
414 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
415 f"value: {y_data[i]:,.0f}<br>"
417 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
418 f"csit-ref: {row['job']}/{row['build']}<br>"
421 anomalies, trend_avg, trend_stdev = classify_anomalies(
422 {k: v for k, v in zip(x_axis, y_data)}
425 for avg, stdev, (_, row) in \
426 zip(trend_avg, trend_stdev, df.iterrows()):
429 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
430 f"trend: {avg:,.0f}<br>"
431 f"stdev: {stdev:,.0f}<br>"
432 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
433 f"csit-ref: {row['job']}/{row['build']}"
437 color = get_color(idx)
439 go.Scatter( # Samples
450 hoverinfo="text+name",
457 go.Scatter( # Trend line
468 hoverinfo="text+name",
476 anomaly_color = list()
478 for idx, anomaly in enumerate(anomalies):
479 if anomaly in ("regression", "progression"):
480 anomaly_x.append(x_axis[idx])
481 anomaly_y.append(trend_avg[idx])
482 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
484 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
485 f"<br>trend: {trend_avg[idx]:,.0f}"
486 f"<br>classification: {anomaly}"
488 hover.append(hover_itm)
489 anomaly_color.extend([0.0, 0.5, 1.0])
496 hoverinfo="text+name",
502 "symbol": "circle-open",
503 "color": anomaly_color,
504 "colorscale": C.COLORSCALE_TPUT,
512 "title": "Circles Marking Data Classification",
513 "titleside": "right",
515 "tickvals": [0.167, 0.500, 0.833],
516 "ticktext": C.TICK_TEXT_TPUT,
528 graph.add_traces(traces)
529 graph.update_layout(layout.get("plot-trending-telemetry", dict()))
534 tm_trending_graphs = list()
537 return tm_trending_graphs
539 for test in data.test_name.unique():
540 df = data.loc[(data["test_name"] == test)]
541 graph = _generate_graph(df, test, layout)
543 tm_trending_graphs.append((graph, test, ))
545 return tm_trending_graphs