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
23 from ..utils.constants import Constants as C
24 from ..utils.utils import classify_anomalies, get_color
27 def _get_hdrh_latencies(row: pd.Series, name: str) -> dict:
28 """Get the HDRH latencies from the test data.
30 :param row: A row fron the data frame with test data.
31 :param name: The test name to be displayed as the graph title.
32 :type row: pandas.Series
34 :returns: Dictionary with HDRH latencies.
38 latencies = {"name": name}
39 for key in C.LAT_HDRH:
41 latencies[key] = row[key]
48 def select_trending_data(data: pd.DataFrame, itm: dict) -> pd.DataFrame:
49 """Select the data for graphs from the provided data frame.
51 :param data: Data frame with data for graphs.
52 :param itm: Item (in this case job name) which data will be selected from
54 :type data: pandas.DataFrame
56 :returns: A data frame with selected data.
57 :rtype: pandas.DataFrame
60 phy = itm["phy"].split("-")
62 topo, arch, nic, drv = phy
67 drv = drv.replace("_", "-")
71 if itm["testtype"] in ("ndr", "pdr"):
73 elif itm["testtype"] == "mrr":
75 elif itm["area"] == "hoststack":
76 test_type = "hoststack"
78 (data["test_type"] == test_type) &
79 (data["passed"] == True)
81 df = df[df.job.str.endswith(f"{topo}-{arch}")]
82 core = str() if itm["dut"] == "trex" else f"{itm['core']}"
83 ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
84 df = df[df.test_id.str.contains(
85 f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
87 )].sort_values(by="start_time", ignore_index=True)
98 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
99 (result_latency_forward_pdr_50_avg).
101 :param data: Data frame with test results.
102 :param sel: Selected tests.
103 :param layout: Layout of plot.ly graph.
104 :param normalize: If True, the data is normalized to CPU frquency
105 Constants.NORM_FREQUENCY.
106 :type data: pandas.DataFrame
109 :type normalize: bool
110 :returns: Trending graph(s)
111 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
118 def _generate_trending_traces(
125 """Generate the trending traces for the trending graph.
127 :param ttype: Test type (MRR, NDR, PDR).
128 :param name: The test name to be displayed as the graph title.
129 :param df: Data frame with test data.
130 :param color: The color of the trace (samples and trend line).
131 :param norm_factor: The factor used for normalization of the results to
132 CPU frequency set to Constants.NORM_FREQUENCY.
135 :type df: pandas.DataFrame
137 :type norm_factor: float
138 :returns: Traces (samples, trending line, anomalies)
142 df = df.dropna(subset=[C.VALUE[ttype], ])
146 x_axis = df["start_time"].tolist()
147 if ttype == "pdr-lat":
148 y_data = [(v / norm_factor) for v in df[C.VALUE[ttype]].tolist()]
150 y_data = [(v * norm_factor) for v in df[C.VALUE[ttype]].tolist()]
152 anomalies, trend_avg, trend_stdev = classify_anomalies(
153 {k: v for k, v in zip(x_axis, y_data)}
158 customdata_samples = list()
159 for idx, (_, row) in enumerate(df.iterrows()):
160 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
162 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
163 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
165 f"{d_type}-ref: {row['dut_version']}<br>"
166 f"csit-ref: {row['job']}/{row['build']}<br>"
167 f"hosts: {', '.join(row['hosts'])}"
171 f"stdev [{row['result_receive_rate_rate_unit']}]: "
172 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
176 hover_itm = hover_itm.replace(
177 "<prop>", "latency" if ttype == "pdr-lat" else "average"
178 ).replace("<stdev>", stdev)
179 hover.append(hover_itm)
180 if ttype == "pdr-lat":
181 customdata_samples.append(_get_hdrh_latencies(row, name))
182 customdata.append({"name": name})
184 customdata_samples.append(
185 {"name": name, "show_telemetry": True}
187 customdata.append({"name": name})
190 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
191 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
193 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
194 f"trend [pps]: {avg:,.0f}<br>"
195 f"stdev [pps]: {stdev:,.0f}<br>"
196 f"{d_type}-ref: {row['dut_version']}<br>"
197 f"csit-ref: {row['job']}/{row['build']}<br>"
198 f"hosts: {', '.join(row['hosts'])}"
200 if ttype == "pdr-lat":
201 hover_itm = hover_itm.replace("[pps]", "[us]")
202 hover_trend.append(hover_itm)
205 go.Scatter( # Samples
216 hoverinfo="text+name",
219 customdata=customdata_samples
221 go.Scatter( # Trend line
232 hoverinfo="text+name",
235 customdata=customdata
242 anomaly_color = list()
244 for idx, anomaly in enumerate(anomalies):
245 if anomaly in ("regression", "progression"):
246 anomaly_x.append(x_axis[idx])
247 anomaly_y.append(trend_avg[idx])
248 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
250 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
251 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
252 f"classification: {anomaly}"
254 if ttype == "pdr-lat":
255 hover_itm = hover_itm.replace("[pps]", "[us]")
256 hover.append(hover_itm)
257 anomaly_color.extend([0.0, 0.5, 1.0])
264 hoverinfo="text+name",
268 customdata=customdata,
271 "symbol": "circle-open",
272 "color": anomaly_color,
273 "colorscale": C.COLORSCALE_LAT \
274 if ttype == "pdr-lat" else C.COLORSCALE_TPUT,
282 "title": "Circles Marking Data Classification",
283 "titleside": "right",
285 "tickvals": [0.167, 0.500, 0.833],
286 "ticktext": C.TICK_TEXT_LAT \
287 if ttype == "pdr-lat" else C.TICK_TEXT_TPUT,
302 for idx, itm in enumerate(sel):
303 df = select_trending_data(data, itm)
304 if df is None or df.empty:
308 phy = itm["phy"].split("-")
309 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
310 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
311 if topo_arch else 1.0
314 traces = _generate_trending_traces(itm["testtype"], itm["id"], df,
315 get_color(idx), norm_factor)
318 fig_tput = go.Figure()
319 fig_tput.add_traces(traces)
321 if itm["testtype"] == "pdr":
322 traces = _generate_trending_traces("pdr-lat", itm["id"], df,
323 get_color(idx), norm_factor)
326 fig_lat = go.Figure()
327 fig_lat.add_traces(traces)
330 fig_tput.update_layout(layout.get("plot-trending-tput", dict()))
332 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
334 return fig_tput, fig_lat
337 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
338 """Generate HDR Latency histogram graphs.
340 :param data: HDRH data.
341 :param layout: Layout of plot.ly graph.
344 :returns: HDR latency Histogram.
345 :rtype: plotly.graph_objects.Figure
351 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
353 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
354 except (hdrh.codec.HdrLengthException, TypeError):
361 for item in decoded.get_recorded_iterator():
362 # The real value is "percentile".
363 # For 100%, we cut that down to "x_perc" to avoid
365 percentile = item.percentile_level_iterated_to
366 x_perc = min(percentile, C.PERCENTILE_MAX)
367 xaxis.append(previous_x)
368 yaxis.append(item.value_iterated_to)
370 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
371 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
372 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
373 f"Latency: {item.value_iterated_to}uSec"
375 next_x = 100.0 / (100.0 - x_perc)
377 yaxis.append(item.value_iterated_to)
379 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
380 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
381 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
382 f"Latency: {item.value_iterated_to}uSec"
385 prev_perc = percentile
391 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
393 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
394 showlegend=bool(idx % 2),
396 color=get_color(int(idx/2)),
398 width=1 if idx % 2 else 2
406 fig.add_traces(traces)
407 layout_hdrh = layout.get("plot-hdrh-latency", None)
409 fig.update_layout(layout_hdrh)
414 def graph_tm_trending(data: pd.DataFrame, layout: dict) -> list:
415 """Generates one trending graph per test, each graph includes all selected
418 :param data: Data frame with telemetry data.
419 :param layout: Layout of plot.ly graph.
420 :type data: pandas.DataFrame
422 :returns: List of generated graphs together with test names.
423 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
433 """Generates a trending graph for given test with all metrics.
435 :param data: Data frame with telemetry data for the given test.
436 :param test: The name of the test.
437 :param layout: Layout of plot.ly graph.
438 :type data: pandas.DataFrame
441 :returns: A trending graph.
442 :rtype: plotly.graph_objects.Figure
446 for idx, metric in enumerate(data.tm_metric.unique()):
447 if "-pdr" in test and "='pdr'" not in metric:
449 if "-ndr" in test and "='ndr'" not in metric:
452 df = data.loc[(data["tm_metric"] == metric)]
453 x_axis = df["start_time"].tolist()
454 y_data = [float(itm) for itm in df["tm_value"].tolist()]
456 for i, (_, row) in enumerate(df.iterrows()):
459 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
460 f"value: {y_data[i]:,.0f}<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:,.0f}<br>"
475 f"stdev: {stdev:,.0f}<br>"
476 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
477 f"csit-ref: {row['job']}/{row['build']}"
481 color = get_color(idx)
483 go.Scatter( # Samples
494 hoverinfo="text+name",
501 go.Scatter( # Trend line
512 hoverinfo="text+name",
520 anomaly_color = list()
522 for idx, anomaly in enumerate(anomalies):
523 if anomaly in ("regression", "progression"):
524 anomaly_x.append(x_axis[idx])
525 anomaly_y.append(trend_avg[idx])
526 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
528 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
529 f"<br>trend: {trend_avg[idx]:,.0f}"
530 f"<br>classification: {anomaly}"
532 hover.append(hover_itm)
533 anomaly_color.extend([0.0, 0.5, 1.0])
540 hoverinfo="text+name",
546 "symbol": "circle-open",
547 "color": anomaly_color,
548 "colorscale": C.COLORSCALE_TPUT,
556 "title": "Circles Marking Data Classification",
557 "titleside": "right",
559 "tickvals": [0.167, 0.500, 0.833],
560 "ticktext": C.TICK_TEXT_TPUT,
572 graph.add_traces(traces)
573 graph.update_layout(layout.get("plot-trending-telemetry", dict()))
578 tm_trending_graphs = list()
581 return tm_trending_graphs
583 for test in data.test_name.unique():
584 df = data.loc[(data["test_name"] == test)]
585 graph = _generate_graph(df, test, layout)
587 tm_trending_graphs.append((graph, test, ))
589 return tm_trending_graphs