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 start: datetime, end: datetime, 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 start: The date (and time) when the selected data starts.
109 :param end: The date (and time) when the selected data ends.
110 :param color: The color of the trace (samples and trend line).
111 :param norm_factor: The factor used for normalization of the results to CPU
112 frequency set to Constants.NORM_FREQUENCY.
115 :type df: pandas.DataFrame
116 :type start: datetime.datetime
117 :type end: datetime.datetime
119 :type norm_factor: float
120 :returns: Traces (samples, trending line, anomalies)
124 df = df.dropna(subset=[C.VALUE[ttype], ])
127 df = df.loc[((df["start_time"] >= start) & (df["start_time"] <= end))]
131 x_axis = df["start_time"].tolist()
132 if ttype == "pdr-lat":
133 y_data = [(itm / norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
135 y_data = [(itm * norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
137 anomalies, trend_avg, trend_stdev = classify_anomalies(
138 {k: v for k, v in zip(x_axis, y_data)}
143 for idx, (_, row) in enumerate(df.iterrows()):
144 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
146 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
147 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
149 f"{d_type}-ref: {row['dut_version']}<br>"
150 f"csit-ref: {row['job']}/{row['build']}<br>"
151 f"hosts: {', '.join(row['hosts'])}"
155 f"stdev [{row['result_receive_rate_rate_unit']}]: "
156 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
160 hover_itm = hover_itm.replace(
161 "<prop>", "latency" if ttype == "pdr-lat" else "average"
162 ).replace("<stdev>", stdev)
163 hover.append(hover_itm)
164 if ttype == "pdr-lat":
165 customdata.append(_get_hdrh_latencies(row, name))
168 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
169 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
171 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
172 f"trend [pps]: {avg:,.0f}<br>"
173 f"stdev [pps]: {stdev:,.0f}<br>"
174 f"{d_type}-ref: {row['dut_version']}<br>"
175 f"csit-ref: {row['job']}/{row['build']}<br>"
176 f"hosts: {', '.join(row['hosts'])}"
178 if ttype == "pdr-lat":
179 hover_itm = hover_itm.replace("[pps]", "[us]")
180 hover_trend.append(hover_itm)
183 go.Scatter( # Samples
194 hoverinfo="text+name",
197 customdata=customdata
199 go.Scatter( # Trend line
210 hoverinfo="text+name",
219 anomaly_color = list()
221 for idx, anomaly in enumerate(anomalies):
222 if anomaly in ("regression", "progression"):
223 anomaly_x.append(x_axis[idx])
224 anomaly_y.append(trend_avg[idx])
225 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
227 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
228 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
229 f"classification: {anomaly}"
231 if ttype == "pdr-lat":
232 hover_itm = hover_itm.replace("[pps]", "[us]")
233 hover.append(hover_itm)
234 anomaly_color.extend([0.0, 0.5, 1.0])
241 hoverinfo="text+name",
247 "symbol": "circle-open",
248 "color": anomaly_color,
249 "colorscale": C.COLORSCALE_LAT \
250 if ttype == "pdr-lat" else C.COLORSCALE_TPUT,
258 "title": "Circles Marking Data Classification",
259 "titleside": "right",
261 "tickvals": [0.167, 0.500, 0.833],
262 "ticktext": C.TICK_TEXT_LAT \
263 if ttype == "pdr-lat" else C.TICK_TEXT_TPUT,
276 def graph_trending(data: pd.DataFrame, sel:dict, layout: dict,
277 start: datetime, end: datetime, normalize: bool) -> tuple:
278 """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
279 (result_latency_forward_pdr_50_avg).
281 :param data: Data frame with test results.
282 :param sel: Selected tests.
283 :param layout: Layout of plot.ly graph.
284 :param start: The date (and time) when the selected data starts.
285 :param end: The date (and time) when the selected data ends.
286 :param normalize: If True, the data is normalized to CPU frquency
287 Constants.NORM_FREQUENCY.
288 :type data: pandas.DataFrame
291 :type start: datetime.datetime
292 :type end: datetype.datetype
293 :type normalize: bool
294 :returns: Trending graph(s)
295 :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
303 for idx, itm in enumerate(sel):
305 df = select_trending_data(data, itm)
306 if df is None or df.empty:
309 name = "-".join((itm["dut"], itm["phy"], itm["framesize"], itm["core"],
310 itm["test"], itm["testtype"], ))
312 phy = itm["phy"].split("-")
313 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
314 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
315 if topo_arch else 1.0
318 traces = _generate_trending_traces(
319 itm["testtype"], name, df, start, end, get_color(idx), norm_factor
323 fig_tput = go.Figure()
324 fig_tput.add_traces(traces)
326 if itm["testtype"] == "pdr":
327 traces = _generate_trending_traces(
328 "pdr-lat", name, df, start, end, get_color(idx), norm_factor
332 fig_lat = go.Figure()
333 fig_lat.add_traces(traces)
336 fig_tput.update_layout(layout.get("plot-trending-tput", dict()))
338 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
340 return fig_tput, fig_lat
343 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
344 """Generate HDR Latency histogram graphs.
346 :param data: HDRH data.
347 :param layout: Layout of plot.ly graph.
350 :returns: HDR latency Histogram.
351 :rtype: plotly.graph_objects.Figure
357 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
359 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
360 except (hdrh.codec.HdrLengthException, TypeError) as err:
367 for item in decoded.get_recorded_iterator():
368 # The real value is "percentile".
369 # For 100%, we cut that down to "x_perc" to avoid
371 percentile = item.percentile_level_iterated_to
372 x_perc = min(percentile, C.PERCENTILE_MAX)
373 xaxis.append(previous_x)
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"
381 next_x = 100.0 / (100.0 - x_perc)
383 yaxis.append(item.value_iterated_to)
385 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
386 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
387 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
388 f"Latency: {item.value_iterated_to}uSec"
391 prev_perc = percentile
397 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
399 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
400 showlegend=bool(idx % 2),
402 color=get_color(int(idx/2)),
404 width=1 if idx % 2 else 2
412 fig.add_traces(traces)
413 layout_hdrh = layout.get("plot-hdrh-latency", None)
415 fig.update_layout(layout_hdrh)