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.
18 import dash_bootstrap_components as dbc
20 from numpy import isnan
22 from datetime import datetime
24 from ..jumpavg import classify
25 from ..utils.constants import Constants as C
26 from ..utils.url_processing import url_encode
29 def classify_anomalies(data):
30 """Process the data and return anomalies and trending values.
32 Gather data into groups with average as trend value.
33 Decorate values within groups to be normal,
34 the first value of changed average as a regression, or a progression.
36 :param data: Full data set with unavailable samples replaced by nan.
37 :type data: OrderedDict
38 :returns: Classification and trend values
39 :rtype: 3-tuple, list of strings, list of floats and list of floats
41 # NaN means something went wrong.
42 # Use 0.0 to cause that being reported as a severe regression.
43 bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
44 # TODO: Make BitCountingGroupList a subclass of list again?
45 group_list = classify(bare_data).group_list
46 group_list.reverse() # Just to use .pop() for FIFO.
47 classification = list()
54 for sample in data.values():
56 classification.append("outlier")
60 if values_left < 1 or active_group is None:
62 while values_left < 1: # Ignore empty groups (should not happen).
63 active_group = group_list.pop()
64 values_left = len(active_group.run_list)
65 avg = active_group.stats.avg
66 stdv = active_group.stats.stdev
67 classification.append(active_group.comment)
72 classification.append("normal")
76 return classification, avgs, stdevs
79 def get_color(idx: int) -> str:
80 """Returns a color from the list defined in Constants.PLOT_COLORS defined by
83 :param idx: Index of the color.
85 :returns: Color defined by hex code.
88 return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
91 def show_tooltip(tooltips:dict, id: str, title: str,
92 clipboard_id: str=None) -> list:
93 """Generate list of elements to display a text (e.g. a title) with a
94 tooltip and optionaly with Copy&Paste icon and the clipboard
95 functionality enabled.
97 :param tooltips: Dictionary with tooltips.
98 :param id: Tooltip ID.
99 :param title: A text for which the tooltip will be displayed.
100 :param clipboard_id: If defined, a Copy&Paste icon is displayed and the
101 clipboard functionality is enabled.
105 :type clipboard_id: str
106 :returns: List of elements to display a text with a tooltip and
107 optionaly with Copy&Paste icon.
112 dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
113 if clipboard_id else str(),
121 class_name="border ms-1",
124 children=tooltips.get(id, str()),
131 def label(key: str) -> str:
132 """Returns a label for input elements (dropdowns, ...).
134 If the label is not defined, the function returns the provided key.
136 :param key: The key to the label defined in Constants.LABELS.
141 return C.LABELS.get(key, key)
144 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
145 """Synchronize a checklist with defined "options" with its "All" checklist.
147 :param options: List of options for the cheklist.
148 :param sel: List of selected options.
149 :param all: List of selected option from "All" checklist.
150 :param id: ID of a checklist to be used for synchronization.
151 :returns: Tuple of lists with otions for both checklists.
152 :rtype: tuple of lists
154 opts = {v["value"] for v in options}
156 sel = list(opts) if all else list()
158 all = ["all", ] if set(sel) == opts else list()
162 def list_tests(selection: dict) -> list:
163 """Transform list of tests to a list of dictionaries usable by checkboxes.
165 :param selection: List of tests to be displayed in "Selected tests" window.
166 :type selection: list
167 :returns: List of dictionaries with "label", "value" pairs for a checkbox.
171 return [{"label": v["id"], "value": v["id"]} for v in selection]
176 def get_date(s_date: str) -> datetime:
177 """Transform string reprezentation of date to datetime.datetime data type.
179 :param s_date: String reprezentation of date.
181 :returns: Date as datetime.datetime.
182 :rtype: datetime.datetime
184 return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
187 def gen_new_url(url_components: dict, params: dict) -> str:
188 """Generate a new URL with encoded parameters.
190 :param url_components: Dictionary with URL elements. It should contain
191 "scheme", "netloc" and "path".
192 :param url_components: URL parameters to be encoded to the URL.
193 :type parsed_url: dict
195 :returns Encoded URL with parameters.
202 "scheme": url_components.get("scheme", ""),
203 "netloc": url_components.get("netloc", ""),
204 "path": url_components.get("path", ""),
212 def get_duts(df: pd.DataFrame) -> list:
213 """Get the list of DUTs from the pre-processed information about jobs.
215 :param df: DataFrame with information about jobs.
216 :type df: pandas.DataFrame
217 :returns: Alphabeticaly sorted list of DUTs.
220 return sorted(list(df["dut"].unique()))
223 def get_ttypes(df: pd.DataFrame, dut: str) -> list:
224 """Get the list of test types from the pre-processed information about
227 :param df: DataFrame with information about jobs.
228 :param dut: The DUT for which the list of test types will be populated.
229 :type df: pandas.DataFrame
231 :returns: Alphabeticaly sorted list of test types.
234 return sorted(list(df.loc[(df["dut"] == dut)]["ttype"].unique()))
237 def get_cadences(df: pd.DataFrame, dut: str, ttype: str) -> list:
238 """Get the list of cadences from the pre-processed information about
241 :param df: DataFrame with information about jobs.
242 :param dut: The DUT for which the list of cadences will be populated.
243 :param ttype: The test type for which the list of cadences will be
245 :type df: pandas.DataFrame
248 :returns: Alphabeticaly sorted list of cadences.
251 return sorted(list(df.loc[(
253 (df["ttype"] == ttype)
254 )]["cadence"].unique()))
257 def get_test_beds(df: pd.DataFrame, dut: str, ttype: str, cadence: str) -> list:
258 """Get the list of test beds from the pre-processed information about
261 :param df: DataFrame with information about jobs.
262 :param dut: The DUT for which the list of test beds will be populated.
263 :param ttype: The test type for which the list of test beds will be
265 :param cadence: The cadence for which the list of test beds will be
267 :type df: pandas.DataFrame
271 :returns: Alphabeticaly sorted list of test beds.
274 return sorted(list(df.loc[(
276 (df["ttype"] == ttype) &
277 (df["cadence"] == cadence)
278 )]["tbed"].unique()))
281 def get_job(df: pd.DataFrame, dut, ttype, cadence, testbed):
282 """Get the name of a job defined by dut, ttype, cadence, test bed.
283 Input information comes from the control panel.
285 :param df: DataFrame with information about jobs.
286 :param dut: The DUT for which the job name will be created.
287 :param ttype: The test type for which the job name will be created.
288 :param cadence: The cadence for which the job name will be created.
289 :param testbed: The test bed for which the job name will be created.
290 :type df: pandas.DataFrame
300 (df["ttype"] == ttype) &
301 (df["cadence"] == cadence) &
302 (df["tbed"] == testbed)
306 def generate_options(opts: list) -> list:
307 """Return list of options for radio items in control panel. The items in
308 the list are dictionaries with keys "label" and "value".
310 :params opts: List of options (str) to be used for the generated list.
312 :returns: List of options (dict).
315 return [{"label": i, "value": i} for i in opts]
318 def set_job_params(df: pd.DataFrame, job: str) -> dict:
319 """Create a dictionary with all options and values for (and from) the
322 :param df: DataFrame with information about jobs.
323 :params job: The name of job for and from which the dictionary will be
325 :type df: pandas.DataFrame
327 :returns: Dictionary with all options and values for (and from) the
332 l_job = job.split("-")
338 "tbed": "-".join(l_job[-2:]),
339 "duts": generate_options(get_duts(df)),
340 "ttypes": generate_options(get_ttypes(df, l_job[1])),
341 "cadences": generate_options(get_cadences(df, l_job[1], l_job[3])),
342 "tbeds": generate_options(
343 get_test_beds(df, l_job[1], l_job[3], l_job[4]))