1 # Copyright (c) 2022 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.
17 import plotly.graph_objects as go
23 from datetime import datetime
25 from ..utils.constants import Constants as C
26 from ..utils.utils import classify_anomalies, get_color
29 def _get_hdrh_latencies(row: pd.Series, name: str) -> dict:
30 """Get the HDRH latencies from the test data.
32 :param row: A row fron the data frame with test data.
33 :param name: The test name to be displayed as the graph title.
34 :type row: pandas.Series
36 :returns: Dictionary with HDRH latencies.
40 latencies = {"name": name}
41 for key in C.LAT_HDRH:
43 latencies[key] = row[key]
50 def select_trending_data(data: pd.DataFrame, itm:dict) -> pd.DataFrame:
51 """Select the data for graphs from the provided data frame.
53 :param data: Data frame with data for graphs.
54 :param itm: Item (in this case job name) which data will be selected from
56 :type data: pandas.DataFrame
58 :returns: A data frame with selected data.
59 :rtype: pandas.DataFrame
62 phy = itm["phy"].split("-")
64 topo, arch, nic, drv = phy
69 drv = drv.replace("_", "-")
73 core = str() if itm["dut"] == "trex" else f"{itm['core']}"
74 ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
75 dut_v100 = "none" if itm["dut"] == "trex" else itm["dut"]
81 (data["version"] == "1.0.0") &
82 (data["dut_type"].str.lower() == dut_v100)
85 (data["version"] == "1.0.1") &
86 (data["dut_type"].str.lower() == dut_v101)
89 (data["test_type"] == ttype) &
90 (data["passed"] == True)
92 df = df[df.job.str.endswith(f"{topo}-{arch}")]
93 df = df[df.test_id.str.contains(
94 f"^.*[.|-]{nic}.*{itm['framesize']}-{core}-{drv}{itm['test']}-{ttype}$",
96 )].sort_values(by="start_time", ignore_index=True)
101 def _generate_trending_traces(ttype: str, name: str, df: pd.DataFrame,
102 color: str, norm_factor: float) -> list:
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 CPU
110 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], ])
126 x_axis = df["start_time"].tolist()
127 if ttype == "pdr-lat":
128 y_data = [(itm / norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
130 y_data = [(itm * norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
132 anomalies, trend_avg, trend_stdev = classify_anomalies(
133 {k: v for k, v in zip(x_axis, y_data)}
138 for idx, (_, row) in enumerate(df.iterrows()):
139 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
141 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
142 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 hover_itm = hover_itm.replace(
156 "<prop>", "latency" if ttype == "pdr-lat" else "average"
157 ).replace("<stdev>", stdev)
158 hover.append(hover_itm)
159 if ttype == "pdr-lat":
160 customdata.append(_get_hdrh_latencies(row, name))
163 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
164 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
166 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
167 f"trend [pps]: {avg:,.0f}<br>"
168 f"stdev [pps]: {stdev:,.0f}<br>"
169 f"{d_type}-ref: {row['dut_version']}<br>"
170 f"csit-ref: {row['job']}/{row['build']}<br>"
171 f"hosts: {', '.join(row['hosts'])}"
173 if ttype == "pdr-lat":
174 hover_itm = hover_itm.replace("[pps]", "[us]")
175 hover_trend.append(hover_itm)
178 go.Scatter( # Samples
189 hoverinfo="text+name",
192 customdata=customdata
194 go.Scatter( # Trend line
205 hoverinfo="text+name",
214 anomaly_color = list()
216 for idx, anomaly in enumerate(anomalies):
217 if anomaly in ("regression", "progression"):
218 anomaly_x.append(x_axis[idx])
219 anomaly_y.append(trend_avg[idx])
220 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
222 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
223 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
224 f"classification: {anomaly}"
226 if ttype == "pdr-lat":
227 hover_itm = hover_itm.replace("[pps]", "[us]")
228 hover.append(hover_itm)
229 anomaly_color.extend([0.0, 0.5, 1.0])
236 hoverinfo="text+name",
242 "symbol": "circle-open",
243 "color": anomaly_color,
244 "colorscale": C.COLORSCALE_LAT \
245 if ttype == "pdr-lat" else C.COLORSCALE_TPUT,
253 "title": "Circles Marking Data Classification",
254 "titleside": "right",
256 "tickvals": [0.167, 0.500, 0.833],
257 "ticktext": C.TICK_TEXT_LAT \
258 if ttype == "pdr-lat" else C.TICK_TEXT_TPUT,
271 def graph_trending(data: pd.DataFrame, sel:dict, layout: dict,
272 normalize: bool) -> tuple:
273 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
274 (result_latency_forward_pdr_50_avg).
276 :param data: Data frame with test results.
277 :param sel: Selected tests.
278 :param layout: Layout of plot.ly graph.
279 :param normalize: If True, the data is normalized to CPU frquency
280 Constants.NORM_FREQUENCY.
281 :type data: pandas.DataFrame
284 :type normalize: bool
285 :returns: Trending graph(s)
286 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
294 for idx, itm in enumerate(sel):
296 df = select_trending_data(data, itm)
297 if df is None or df.empty:
300 name = "-".join((itm["dut"], itm["phy"], itm["framesize"], itm["core"],
301 itm["test"], itm["testtype"], ))
303 phy = itm["phy"].split("-")
304 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
305 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
306 if topo_arch else 1.0
309 traces = _generate_trending_traces(
310 itm["testtype"], name, df, get_color(idx), norm_factor
314 fig_tput = go.Figure()
315 fig_tput.add_traces(traces)
317 if itm["testtype"] == "pdr":
318 traces = _generate_trending_traces(
319 "pdr-lat", name, df, get_color(idx), norm_factor
323 fig_lat = go.Figure()
324 fig_lat.add_traces(traces)
327 fig_tput.update_layout(layout.get("plot-trending-tput", dict()))
329 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
331 return fig_tput, fig_lat
334 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
335 """Generate HDR Latency histogram graphs.
337 :param data: HDRH data.
338 :param layout: Layout of plot.ly graph.
341 :returns: HDR latency Histogram.
342 :rtype: plotly.graph_objects.Figure
348 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
350 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
351 except (hdrh.codec.HdrLengthException, TypeError) as err:
358 for item in decoded.get_recorded_iterator():
359 # The real value is "percentile".
360 # For 100%, we cut that down to "x_perc" to avoid
362 percentile = item.percentile_level_iterated_to
363 x_perc = min(percentile, C.PERCENTILE_MAX)
364 xaxis.append(previous_x)
365 yaxis.append(item.value_iterated_to)
367 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
368 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
369 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
370 f"Latency: {item.value_iterated_to}uSec"
372 next_x = 100.0 / (100.0 - x_perc)
374 yaxis.append(item.value_iterated_to)
376 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
377 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
378 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
379 f"Latency: {item.value_iterated_to}uSec"
382 prev_perc = percentile
388 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
390 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
391 showlegend=bool(idx % 2),
393 color=get_color(int(idx/2)),
395 width=1 if idx % 2 else 2
403 fig.add_traces(traces)
404 layout_hdrh = layout.get("plot-hdrh-latency", None)
406 fig.update_layout(layout_hdrh)