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], ])
144 return list(), list()
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()]
151 units = df[C.UNIT[ttype]].unique().tolist()
153 anomalies, trend_avg, trend_stdev = classify_anomalies(
154 {k: v for k, v in zip(x_axis, y_data)}
159 customdata_samples = list()
160 for idx, (_, row) in enumerate(df.iterrows()):
161 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
163 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
164 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
167 f"{d_type}-ref: {row['dut_version']}<br>"
168 f"csit-ref: {row['job']}/{row['build']}<br>"
169 f"hosts: {', '.join(row['hosts'])}"
173 f"stdev [{row['result_receive_rate_rate_unit']}]: "
174 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
178 if ttype in ("hoststack-cps", "hoststack-rps"):
180 f"bandwidth [{row[C.UNIT['hoststack-bps']]}]: "
181 f"{row[C.VALUE['hoststack-bps']]:,.0f}<br>"
182 f"latency [{row[C.UNIT['hoststack-lat']]}]: "
183 f"{row[C.VALUE['hoststack-lat']]:,.0f}<br>"
187 hover_itm = hover_itm.replace(
188 "<prop>", "latency" if ttype == "pdr-lat" else "average"
189 ).replace("<stdev>", stdev).replace("<additional-info>", add_info)
190 hover.append(hover_itm)
191 if ttype == "pdr-lat":
192 customdata_samples.append(_get_hdrh_latencies(row, name))
193 customdata.append({"name": name})
195 customdata_samples.append(
196 {"name": name, "show_telemetry": True}
198 customdata.append({"name": name})
201 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
202 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
204 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
205 f"trend [{row[C.UNIT[ttype]]}]: {avg:,.0f}<br>"
206 f"stdev [{row[C.UNIT[ttype]]}]: {stdev:,.0f}<br>"
207 f"{d_type}-ref: {row['dut_version']}<br>"
208 f"csit-ref: {row['job']}/{row['build']}<br>"
209 f"hosts: {', '.join(row['hosts'])}"
211 if ttype == "pdr-lat":
212 hover_itm = hover_itm.replace("[pps]", "[us]")
213 hover_trend.append(hover_itm)
216 go.Scatter( # Samples
227 hoverinfo="text+name",
230 customdata=customdata_samples
232 go.Scatter( # Trend line
243 hoverinfo="text+name",
246 customdata=customdata
253 anomaly_color = list()
255 for idx, anomaly in enumerate(anomalies):
256 if anomaly in ("regression", "progression"):
257 anomaly_x.append(x_axis[idx])
258 anomaly_y.append(trend_avg[idx])
259 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
261 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
262 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
263 f"classification: {anomaly}"
265 if ttype == "pdr-lat":
266 hover_itm = hover_itm.replace("[pps]", "[us]")
267 hover.append(hover_itm)
268 anomaly_color.extend([0.0, 0.5, 1.0])
275 hoverinfo="text+name",
279 customdata=customdata,
282 "symbol": "circle-open",
283 "color": anomaly_color,
284 "colorscale": C.COLORSCALE_LAT \
285 if ttype == "pdr-lat" else C.COLORSCALE_TPUT,
293 "title": "Circles Marking Data Classification",
294 "titleside": "right",
296 "tickvals": [0.167, 0.500, 0.833],
297 "ticktext": C.TICK_TEXT_LAT \
298 if ttype == "pdr-lat" else C.TICK_TEXT_TPUT,
314 for idx, itm in enumerate(sel):
315 df = select_trending_data(data, itm)
316 if df is None or df.empty:
320 phy = itm["phy"].split("-")
321 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
322 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
323 if topo_arch else 1.0
327 if itm["area"] == "hoststack":
328 ttype = f"hoststack-{itm['testtype']}"
330 ttype = itm["testtype"]
332 traces, units = _generate_trending_traces(
341 fig_tput = go.Figure()
342 fig_tput.add_traces(traces)
344 if itm["testtype"] == "pdr":
345 traces, _ = _generate_trending_traces(
354 fig_lat = go.Figure()
355 fig_lat.add_traces(traces)
357 y_units.update(units)
360 fig_layout = layout.get("plot-trending-tput", dict())
361 fig_layout["yaxis"]["title"] = \
362 f"Throughput [{'|'.join(sorted(y_units))}]"
363 fig_tput.update_layout(fig_layout)
365 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
367 return fig_tput, fig_lat
370 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
371 """Generate HDR Latency histogram graphs.
373 :param data: HDRH data.
374 :param layout: Layout of plot.ly graph.
377 :returns: HDR latency Histogram.
378 :rtype: plotly.graph_objects.Figure
384 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
386 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
387 except (hdrh.codec.HdrLengthException, TypeError):
394 for item in decoded.get_recorded_iterator():
395 # The real value is "percentile".
396 # For 100%, we cut that down to "x_perc" to avoid
398 percentile = item.percentile_level_iterated_to
399 x_perc = min(percentile, C.PERCENTILE_MAX)
400 xaxis.append(previous_x)
401 yaxis.append(item.value_iterated_to)
403 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
404 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
405 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
406 f"Latency: {item.value_iterated_to}uSec"
408 next_x = 100.0 / (100.0 - x_perc)
410 yaxis.append(item.value_iterated_to)
412 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
413 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
414 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
415 f"Latency: {item.value_iterated_to}uSec"
418 prev_perc = percentile
424 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
426 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
427 showlegend=bool(idx % 2),
429 color=get_color(int(idx/2)),
431 width=1 if idx % 2 else 2
439 fig.add_traces(traces)
440 layout_hdrh = layout.get("plot-hdrh-latency", None)
442 fig.update_layout(layout_hdrh)
447 def graph_tm_trending(data: pd.DataFrame, layout: dict) -> list:
448 """Generates one trending graph per test, each graph includes all selected
451 :param data: Data frame with telemetry data.
452 :param layout: Layout of plot.ly graph.
453 :type data: pandas.DataFrame
455 :returns: List of generated graphs together with test names.
456 list(tuple(plotly.graph_objects.Figure(), str()), tuple(...), ...)
466 """Generates a trending graph for given test with all metrics.
468 :param data: Data frame with telemetry data for the given test.
469 :param test: The name of the test.
470 :param layout: Layout of plot.ly graph.
471 :type data: pandas.DataFrame
474 :returns: A trending graph.
475 :rtype: plotly.graph_objects.Figure
479 for idx, metric in enumerate(data.tm_metric.unique()):
480 if "-pdr" in test and "='pdr'" not in metric:
482 if "-ndr" in test and "='ndr'" not in metric:
485 df = data.loc[(data["tm_metric"] == metric)]
486 x_axis = df["start_time"].tolist()
487 y_data = [float(itm) for itm in df["tm_value"].tolist()]
489 for i, (_, row) in enumerate(df.iterrows()):
490 if row["test_type"] == "mrr":
492 f"mrr avg [{row[C.UNIT['mrr']]}]: "
493 f"{row[C.VALUE['mrr']]:,.0f}<br>"
494 f"mrr stdev [{row[C.UNIT['mrr']]}]: "
495 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
497 elif row["test_type"] == "ndrpdr":
500 f"pdr [{row[C.UNIT['pdr']]}]: "
501 f"{row[C.VALUE['pdr']]:,.0f}<br>"
505 f"ndr [{row[C.UNIT['ndr']]}]: "
506 f"{row[C.VALUE['ndr']]:,.0f}<br>"
514 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
515 f"value: {y_data[i]:,.0f}<br>"
517 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
518 f"csit-ref: {row['job']}/{row['build']}<br>"
521 anomalies, trend_avg, trend_stdev = classify_anomalies(
522 {k: v for k, v in zip(x_axis, y_data)}
525 for avg, stdev, (_, row) in \
526 zip(trend_avg, trend_stdev, df.iterrows()):
529 f"{row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
530 f"trend: {avg:,.0f}<br>"
531 f"stdev: {stdev:,.0f}<br>"
532 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
533 f"csit-ref: {row['job']}/{row['build']}"
537 color = get_color(idx)
539 go.Scatter( # Samples
550 hoverinfo="text+name",
557 go.Scatter( # Trend line
568 hoverinfo="text+name",
576 anomaly_color = list()
578 for idx, anomaly in enumerate(anomalies):
579 if anomaly in ("regression", "progression"):
580 anomaly_x.append(x_axis[idx])
581 anomaly_y.append(trend_avg[idx])
582 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
584 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}"
585 f"<br>trend: {trend_avg[idx]:,.0f}"
586 f"<br>classification: {anomaly}"
588 hover.append(hover_itm)
589 anomaly_color.extend([0.0, 0.5, 1.0])
596 hoverinfo="text+name",
602 "symbol": "circle-open",
603 "color": anomaly_color,
604 "colorscale": C.COLORSCALE_TPUT,
612 "title": "Circles Marking Data Classification",
613 "titleside": "right",
615 "tickvals": [0.167, 0.500, 0.833],
616 "ticktext": C.TICK_TEXT_TPUT,
628 graph.add_traces(traces)
629 graph.update_layout(layout.get("plot-trending-telemetry", dict()))
634 tm_trending_graphs = list()
637 return tm_trending_graphs
639 for test in data.test_name.unique():
640 df = data.loc[(data["test_name"] == test)]
641 graph = _generate_graph(df, test, layout)
643 tm_trending_graphs.append((graph, test, ))
645 return tm_trending_graphs