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 """Function used by Dash applications.
18 import plotly.graph_objects as go
19 import dash_bootstrap_components as dbc
25 from numpy import isnan
27 from datetime import datetime
29 from ..jumpavg import classify
30 from ..utils.constants import Constants as C
31 from ..utils.url_processing import url_encode
34 def classify_anomalies(data):
35 """Process the data and return anomalies and trending values.
37 Gather data into groups with average as trend value.
38 Decorate values within groups to be normal,
39 the first value of changed average as a regression, or a progression.
41 :param data: Full data set with unavailable samples replaced by nan.
42 :type data: OrderedDict
43 :returns: Classification and trend values
44 :rtype: 3-tuple, list of strings, list of floats and list of floats
46 # NaN means something went wrong.
47 # Use 0.0 to cause that being reported as a severe regression.
48 bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
49 # TODO: Make BitCountingGroupList a subclass of list again?
50 group_list = classify(bare_data).group_list
51 group_list.reverse() # Just to use .pop() for FIFO.
52 classification = list()
59 for sample in data.values():
61 classification.append("outlier")
65 if values_left < 1 or active_group is None:
67 while values_left < 1: # Ignore empty groups (should not happen).
68 active_group = group_list.pop()
69 values_left = len(active_group.run_list)
70 avg = active_group.stats.avg
71 stdv = active_group.stats.stdev
72 classification.append(active_group.comment)
77 classification.append("normal")
81 return classification, avgs, stdevs
84 def get_color(idx: int) -> str:
85 """Returns a color from the list defined in Constants.PLOT_COLORS defined by
88 :param idx: Index of the color.
90 :returns: Color defined by hex code.
93 return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
96 def show_tooltip(tooltips:dict, id: str, title: str,
97 clipboard_id: str=None) -> list:
98 """Generate list of elements to display a text (e.g. a title) with a
99 tooltip and optionaly with Copy&Paste icon and the clipboard
100 functionality enabled.
102 :param tooltips: Dictionary with tooltips.
103 :param id: Tooltip ID.
104 :param title: A text for which the tooltip will be displayed.
105 :param clipboard_id: If defined, a Copy&Paste icon is displayed and the
106 clipboard functionality is enabled.
110 :type clipboard_id: str
111 :returns: List of elements to display a text with a tooltip and
112 optionaly with Copy&Paste icon.
117 dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
118 if clipboard_id else str(),
126 class_name="border ms-1",
129 children=tooltips.get(id, str()),
136 def label(key: str) -> str:
137 """Returns a label for input elements (dropdowns, ...).
139 If the label is not defined, the function returns the provided key.
141 :param key: The key to the label defined in Constants.LABELS.
146 return C.LABELS.get(key, key)
149 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
150 """Synchronize a checklist with defined "options" with its "All" checklist.
152 :param options: List of options for the cheklist.
153 :param sel: List of selected options.
154 :param all: List of selected option from "All" checklist.
155 :param id: ID of a checklist to be used for synchronization.
156 :returns: Tuple of lists with otions for both checklists.
157 :rtype: tuple of lists
159 opts = {v["value"] for v in options}
161 sel = list(opts) if all else list()
163 all = ["all", ] if set(sel) == opts else list()
167 def list_tests(selection: dict) -> list:
168 """Transform list of tests to a list of dictionaries usable by checkboxes.
170 :param selection: List of tests to be displayed in "Selected tests" window.
171 :type selection: list
172 :returns: List of dictionaries with "label", "value" pairs for a checkbox.
176 return [{"label": v["id"], "value": v["id"]} for v in selection]
181 def get_date(s_date: str) -> datetime:
182 """Transform string reprezentation of date to datetime.datetime data type.
184 :param s_date: String reprezentation of date.
186 :returns: Date as datetime.datetime.
187 :rtype: datetime.datetime
189 return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
192 def gen_new_url(url_components: dict, params: dict) -> str:
193 """Generate a new URL with encoded parameters.
195 :param url_components: Dictionary with URL elements. It should contain
196 "scheme", "netloc" and "path".
197 :param url_components: URL parameters to be encoded to the URL.
198 :type parsed_url: dict
200 :returns Encoded URL with parameters.
207 "scheme": url_components.get("scheme", ""),
208 "netloc": url_components.get("netloc", ""),
209 "path": url_components.get("path", ""),
217 def get_duts(df: pd.DataFrame) -> list:
218 """Get the list of DUTs from the pre-processed information about jobs.
220 :param df: DataFrame with information about jobs.
221 :type df: pandas.DataFrame
222 :returns: Alphabeticaly sorted list of DUTs.
225 return sorted(list(df["dut"].unique()))
228 def get_ttypes(df: pd.DataFrame, dut: str) -> list:
229 """Get the list of test types from the pre-processed information about
232 :param df: DataFrame with information about jobs.
233 :param dut: The DUT for which the list of test types will be populated.
234 :type df: pandas.DataFrame
236 :returns: Alphabeticaly sorted list of test types.
239 return sorted(list(df.loc[(df["dut"] == dut)]["ttype"].unique()))
242 def get_cadences(df: pd.DataFrame, dut: str, ttype: str) -> list:
243 """Get the list of cadences from the pre-processed information about
246 :param df: DataFrame with information about jobs.
247 :param dut: The DUT for which the list of cadences will be populated.
248 :param ttype: The test type for which the list of cadences will be
250 :type df: pandas.DataFrame
253 :returns: Alphabeticaly sorted list of cadences.
256 return sorted(list(df.loc[(
258 (df["ttype"] == ttype)
259 )]["cadence"].unique()))
262 def get_test_beds(df: pd.DataFrame, dut: str, ttype: str, cadence: str) -> list:
263 """Get the list of test beds from the pre-processed information about
266 :param df: DataFrame with information about jobs.
267 :param dut: The DUT for which the list of test beds will be populated.
268 :param ttype: The test type for which the list of test beds will be
270 :param cadence: The cadence for which the list of test beds will be
272 :type df: pandas.DataFrame
276 :returns: Alphabeticaly sorted list of test beds.
279 return sorted(list(df.loc[(
281 (df["ttype"] == ttype) &
282 (df["cadence"] == cadence)
283 )]["tbed"].unique()))
286 def get_job(df: pd.DataFrame, dut, ttype, cadence, testbed):
287 """Get the name of a job defined by dut, ttype, cadence, test bed.
288 Input information comes from the control panel.
290 :param df: DataFrame with information about jobs.
291 :param dut: The DUT for which the job name will be created.
292 :param ttype: The test type for which the job name will be created.
293 :param cadence: The cadence for which the job name will be created.
294 :param testbed: The test bed for which the job name will be created.
295 :type df: pandas.DataFrame
305 (df["ttype"] == ttype) &
306 (df["cadence"] == cadence) &
307 (df["tbed"] == testbed)
311 def generate_options(opts: list, sort: bool=True) -> list:
312 """Return list of options for radio items in control panel. The items in
313 the list are dictionaries with keys "label" and "value".
315 :params opts: List of options (str) to be used for the generated list.
317 :returns: List of options (dict).
322 return [{"label": i, "value": i} for i in opts]
325 def set_job_params(df: pd.DataFrame, job: str) -> dict:
326 """Create a dictionary with all options and values for (and from) the
329 :param df: DataFrame with information about jobs.
330 :params job: The name of job for and from which the dictionary will be
332 :type df: pandas.DataFrame
334 :returns: Dictionary with all options and values for (and from) the
339 l_job = job.split("-")
345 "tbed": "-".join(l_job[-2:]),
346 "duts": generate_options(get_duts(df)),
347 "ttypes": generate_options(get_ttypes(df, l_job[1])),
348 "cadences": generate_options(get_cadences(df, l_job[1], l_job[3])),
349 "tbeds": generate_options(
350 get_test_beds(df, l_job[1], l_job[3], l_job[4]))
354 def get_list_group_items(
358 add_index: bool=False
360 """Generate list of ListGroupItems with checkboxes with selected items.
362 :param items: List of items to be displayed in the ListGroup.
363 :param type: The type part of an element ID.
364 :param colorize: If True, the color of labels is set, otherwise the default
366 :param add_index: Add index to the list items.
370 :type add_index: bool
371 :returns: List of ListGroupItems with checkboxes with selected items.
376 for i, l in enumerate(items):
377 idx = f"{i + 1}. " if add_index else str()
378 label = f"{idx}{l['id']}" if isinstance(l, dict) else f"{idx}{l}"
383 id={"type": type, "index": i},
386 label_class_name="m-0 p-0",
388 "font-size": ".875em",
389 "color": get_color(i) if colorize else "#55595c"
401 def relative_change_stdev(mean1, mean2, std1, std2):
402 """Compute relative standard deviation of change of two values.
404 The "1" values are the base for comparison.
405 Results are returned as percentage (and percentual points for stdev).
406 Linearized theory is used, so results are wrong for relatively large stdev.
408 :param mean1: Mean of the first number.
409 :param mean2: Mean of the second number.
410 :param std1: Standard deviation estimate of the first number.
411 :param std2: Standard deviation estimate of the second number.
416 :returns: Relative change and its stdev.
419 mean1, mean2 = float(mean1), float(mean2)
420 quotient = mean2 / mean1
422 second = std2 / mean2
423 std = quotient * sqrt(first * first + second * second)
424 return (quotient - 1) * 100, std * 100
427 def get_hdrh_latencies(row: pd.Series, name: str) -> dict:
428 """Get the HDRH latencies from the test data.
430 :param row: A row fron the data frame with test data.
431 :param name: The test name to be displayed as the graph title.
432 :type row: pandas.Series
434 :returns: Dictionary with HDRH latencies.
438 latencies = {"name": name}
439 for key in C.LAT_HDRH:
441 latencies[key] = row[key]
448 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
449 """Generate HDR Latency histogram graphs.
451 :param data: HDRH data.
452 :param layout: Layout of plot.ly graph.
455 :returns: HDR latency Histogram.
456 :rtype: plotly.graph_objects.Figure
462 for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
464 decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
465 except (hdrh.codec.HdrLengthException, TypeError):
472 for item in decoded.get_recorded_iterator():
473 # The real value is "percentile".
474 # For 100%, we cut that down to "x_perc" to avoid
476 percentile = item.percentile_level_iterated_to
477 x_perc = min(percentile, C.PERCENTILE_MAX)
478 xaxis.append(previous_x)
479 yaxis.append(item.value_iterated_to)
481 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
482 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
483 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
484 f"Latency: {item.value_iterated_to}uSec"
486 next_x = 100.0 / (100.0 - x_perc)
488 yaxis.append(item.value_iterated_to)
490 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
491 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
492 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
493 f"Latency: {item.value_iterated_to}uSec"
496 prev_perc = percentile
502 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
504 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
505 showlegend=bool(idx % 2),
507 color=get_color(int(idx/2)),
509 width=1 if idx % 2 else 2
517 fig.add_traces(traces)
518 layout_hdrh = layout.get("plot-hdrh-latency", None)
520 fig.update_layout(layout_hdrh)