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.
14 """Function used by Dash applications.
17 import dash_bootstrap_components as dbc
19 from numpy import isnan
21 from datetime import datetime
23 from ..jumpavg import classify
24 from ..utils.constants import Constants as C
25 from ..utils.url_processing import url_encode
28 def classify_anomalies(data):
29 """Process the data and return anomalies and trending values.
31 Gather data into groups with average as trend value.
32 Decorate values within groups to be normal,
33 the first value of changed average as a regression, or a progression.
35 :param data: Full data set with unavailable samples replaced by nan.
36 :type data: OrderedDict
37 :returns: Classification and trend values
38 :rtype: 3-tuple, list of strings, list of floats and list of floats
40 # NaN means something went wrong.
41 # Use 0.0 to cause that being reported as a severe regression.
42 bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
43 # TODO: Make BitCountingGroupList a subclass of list again?
44 group_list = classify(bare_data).group_list
45 group_list.reverse() # Just to use .pop() for FIFO.
46 classification = list()
53 for sample in data.values():
55 classification.append("outlier")
59 if values_left < 1 or active_group is None:
61 while values_left < 1: # Ignore empty groups (should not happen).
62 active_group = group_list.pop()
63 values_left = len(active_group.run_list)
64 avg = active_group.stats.avg
65 stdv = active_group.stats.stdev
66 classification.append(active_group.comment)
71 classification.append("normal")
75 return classification, avgs, stdevs
78 def get_color(idx: int) -> str:
79 """Returns a color from the list defined in Constants.PLOT_COLORS defined by
82 :param idx: Index of the color.
84 :returns: Color defined by hex code.
87 return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
90 def show_tooltip(tooltips:dict, id: str, title: str,
91 clipboard_id: str=None) -> list:
92 """Generate list of elements to display a text (e.g. a title) with a
93 tooltip and optionaly with Copy&Paste icon and the clipboard
94 functionality enabled.
96 :param tooltips: Dictionary with tooltips.
97 :param id: Tooltip ID.
98 :param title: A text for which the tooltip will be displayed.
99 :param clipboard_id: If defined, a Copy&Paste icon is displayed and the
100 clipboard functionality is enabled.
104 :type clipboard_id: str
105 :returns: List of elements to display a text with a tooltip and
106 optionaly with Copy&Paste icon.
111 dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
112 if clipboard_id else str(),
120 class_name="border ms-1",
123 children=tooltips.get(id, str()),
130 def label(key: str) -> str:
131 """Returns a label for input elements (dropdowns, ...).
133 If the label is not defined, the function returns the provided key.
135 :param key: The key to the label defined in Constants.LABELS.
140 return C.LABELS.get(key, key)
143 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
144 """Synchronize a checklist with defined "options" with its "All" checklist.
146 :param options: List of options for the cheklist.
147 :param sel: List of selected options.
148 :param all: List of selected option from "All" checklist.
149 :param id: ID of a checklist to be used for synchronization.
150 :returns: Tuple of lists with otions for both checklists.
151 :rtype: tuple of lists
153 opts = {v["value"] for v in options}
155 sel = list(opts) if all else list()
157 all = ["all", ] if set(sel) == opts else list()
161 def list_tests(selection: dict) -> list:
162 """Transform list of tests to a list of dictionaries usable by checkboxes.
164 :param selection: List of tests to be displayed in "Selected tests" window.
165 :type selection: list
166 :returns: List of dictionaries with "label", "value" pairs for a checkbox.
170 return [{"label": v["id"], "value": v["id"]} for v in selection]
175 def get_date(s_date: str) -> datetime:
176 """Transform string reprezentation of date to datetime.datetime data type.
178 :param s_date: String reprezentation of date.
180 :returns: Date as datetime.datetime.
181 :rtype: datetime.datetime
183 return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
186 def gen_new_url(parsed_url: dict, params: dict) -> str:
187 """Generate a new URL with encoded parameters.
189 :param parsed_url: Dictionary with URL elements. It should contain "scheme",
191 :param params: URL parameters to be encoded to the URL.
192 :type parsed_url: dict
194 :returns Encoded URL with parameters.
201 "scheme": parsed_url.get("scheme", ""),
202 "netloc": parsed_url.get("netloc", ""),
203 "path": parsed_url.get("path", ""),