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
29 def _get_color(idx: int) -> str:
32 return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
35 def _get_hdrh_latencies(row: pd.Series, name: str) -> dict:
39 latencies = {"name": name}
40 for key in C.LAT_HDRH:
42 latencies[key] = row[key]
49 def select_trending_data(data: pd.DataFrame, itm:dict) -> pd.DataFrame:
53 phy = itm["phy"].split("-")
55 topo, arch, nic, drv = phy
60 drv = drv.replace("_", "-")
64 core = str() if itm["dut"] == "trex" else f"{itm['core']}"
65 ttype = "ndrpdr" if itm["testtype"] in ("ndr", "pdr") else itm["testtype"]
66 dut_v100 = "none" if itm["dut"] == "trex" else itm["dut"]
72 (data["version"] == "1.0.0") &
73 (data["dut_type"].str.lower() == dut_v100)
76 (data["version"] == "1.0.1") &
77 (data["dut_type"].str.lower() == dut_v101)
80 (data["test_type"] == ttype) &
81 (data["passed"] == True)
83 df = df[df.job.str.endswith(f"{topo}-{arch}")]
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)
92 def _generate_trending_traces(ttype: str, name: str, df: pd.DataFrame,
93 start: datetime, end: datetime, color: str, norm_factor: float) -> list:
97 df = df.dropna(subset=[C.VALUE[ttype], ])
100 df = df.loc[((df["start_time"] >= start) & (df["start_time"] <= end))]
104 x_axis = df["start_time"].tolist()
105 if ttype == "pdr-lat":
106 y_data = [(itm / norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
108 y_data = [(itm * norm_factor) for itm in df[C.VALUE[ttype]].tolist()]
110 anomalies, trend_avg, trend_stdev = classify_anomalies(
111 {k: v for k, v in zip(x_axis, y_data)}
116 for idx, (_, row) in enumerate(df.iterrows()):
117 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
119 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
120 f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
122 f"{d_type}-ref: {row['dut_version']}<br>"
123 f"csit-ref: {row['job']}/{row['build']}<br>"
124 f"hosts: {', '.join(row['hosts'])}"
128 f"stdev [{row['result_receive_rate_rate_unit']}]: "
129 f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
133 hover_itm = hover_itm.replace(
134 "<prop>", "latency" if ttype == "pdr-lat" else "average"
135 ).replace("<stdev>", stdev)
136 hover.append(hover_itm)
137 if ttype == "pdr-lat":
138 customdata.append(_get_hdrh_latencies(row, name))
141 for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
142 d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
144 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
145 f"trend [pps]: {avg:,.0f}<br>"
146 f"stdev [pps]: {stdev:,.0f}<br>"
147 f"{d_type}-ref: {row['dut_version']}<br>"
148 f"csit-ref: {row['job']}/{row['build']}<br>"
149 f"hosts: {', '.join(row['hosts'])}"
151 if ttype == "pdr-lat":
152 hover_itm = hover_itm.replace("[pps]", "[us]")
153 hover_trend.append(hover_itm)
156 go.Scatter( # Samples
167 hoverinfo="text+name",
170 customdata=customdata
172 go.Scatter( # Trend line
183 hoverinfo="text+name",
192 anomaly_color = list()
194 for idx, anomaly in enumerate(anomalies):
195 if anomaly in ("regression", "progression"):
196 anomaly_x.append(x_axis[idx])
197 anomaly_y.append(trend_avg[idx])
198 anomaly_color.append(C.ANOMALY_COLOR[anomaly])
200 f"date: {x_axis[idx].strftime('%Y-%m-%d %H:%M:%S')}<br>"
201 f"trend [pps]: {trend_avg[idx]:,.0f}<br>"
202 f"classification: {anomaly}"
204 if ttype == "pdr-lat":
205 hover_itm = hover_itm.replace("[pps]", "[us]")
206 hover.append(hover_itm)
207 anomaly_color.extend([0.0, 0.5, 1.0])
214 hoverinfo="text+name",
220 "symbol": "circle-open",
221 "color": anomaly_color,
222 "colorscale": C.COLORSCALE_LAT \
223 if ttype == "pdr-lat" else C.COLORSCALE_TPUT,
231 "title": "Circles Marking Data Classification",
232 "titleside": "right",
234 "tickvals": [0.167, 0.500, 0.833],
235 "ticktext": C.TICK_TEXT_LAT \
236 if ttype == "pdr-lat" else C.TICK_TEXT_TPUT,
249 def graph_trending(data: pd.DataFrame, sel:dict, layout: dict,
250 start: datetime, end: datetime, normalize: bool) -> tuple:
259 for idx, itm in enumerate(sel):
261 df = select_trending_data(data, itm)
262 if df is None or df.empty:
265 name = "-".join((itm["dut"], itm["phy"], itm["framesize"], itm["core"],
266 itm["test"], itm["testtype"], ))
268 phy = itm["phy"].split("-")
269 topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
270 norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
271 if topo_arch else 1.0
274 traces = _generate_trending_traces(
275 itm["testtype"], name, df, start, end, _get_color(idx), norm_factor
279 fig_tput = go.Figure()
280 fig_tput.add_traces(traces)
282 if itm["testtype"] == "pdr":
283 traces = _generate_trending_traces(
284 "pdr-lat", name, df, start, end, _get_color(idx), norm_factor
288 fig_lat = go.Figure()
289 fig_lat.add_traces(traces)
292 fig_tput.update_layout(layout.get("plot-trending-tput", dict()))
294 fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
296 return fig_tput, fig_lat
299 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
306 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
308 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
309 except (hdrh.codec.HdrLengthException, TypeError) as err:
316 for item in decoded.get_recorded_iterator():
317 # The real value is "percentile".
318 # For 100%, we cut that down to "x_perc" to avoid
320 percentile = item.percentile_level_iterated_to
321 x_perc = min(percentile, C.PERCENTILE_MAX)
322 xaxis.append(previous_x)
323 yaxis.append(item.value_iterated_to)
325 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
326 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
327 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
328 f"Latency: {item.value_iterated_to}uSec"
330 next_x = 100.0 / (100.0 - x_perc)
332 yaxis.append(item.value_iterated_to)
334 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
335 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
336 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
337 f"Latency: {item.value_iterated_to}uSec"
340 prev_perc = percentile
346 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
348 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
349 showlegend=bool(idx % 2),
351 color=_get_color(int(idx/2)),
353 width=1 if idx % 2 else 2
361 fig.add_traces(traces)
362 layout_hdrh = layout.get("plot-hdrh-latency", None)
364 fig.update_layout(layout_hdrh)