UTI: code clean-up
[csit.git] / resources / tools / dash / app / pal / utils / utils.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """Function used by Dash applications.
15 """
16
17 import pandas as pd
18 import dash_bootstrap_components as dbc
19
20 from numpy import isnan
21 from dash import dcc
22 from datetime import datetime
23
24 from ..jumpavg import classify
25 from ..utils.constants import Constants as C
26 from ..utils.url_processing import url_encode
27
28
29 def classify_anomalies(data):
30     """Process the data and return anomalies and trending values.
31
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.
35
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
40     """
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()
48     avgs = list()
49     stdevs = list()
50     active_group = None
51     values_left = 0
52     avg = 0.0
53     stdv = 0.0
54     for sample in data.values():
55         if isnan(sample):
56             classification.append("outlier")
57             avgs.append(sample)
58             stdevs.append(sample)
59             continue
60         if values_left < 1 or active_group is None:
61             values_left = 0
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)
68             avgs.append(avg)
69             stdevs.append(stdv)
70             values_left -= 1
71             continue
72         classification.append("normal")
73         avgs.append(avg)
74         stdevs.append(stdv)
75         values_left -= 1
76     return classification, avgs, stdevs
77
78
79 def get_color(idx: int) -> str:
80     """Returns a color from the list defined in Constants.PLOT_COLORS defined by
81     its index.
82
83     :param idx: Index of the color.
84     :type idx: int
85     :returns: Color defined by hex code.
86     :trype: str
87     """
88     return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
89
90
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.
96
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.
102     :type tooltips: dict
103     :type id: str
104     :type title: str
105     :type clipboard_id: str
106     :returns: List of elements to display a text with a tooltip and
107         optionaly with Copy&Paste icon.
108     :rtype: list
109     """
110
111     return [
112         dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
113             if clipboard_id else str(),
114         f"{title} ",
115         dbc.Badge(
116             id=id,
117             children="?",
118             pill=True,
119             color="white",
120             text_color="info",
121             class_name="border ms-1",
122         ),
123         dbc.Tooltip(
124             children=tooltips.get(id, str()),
125             target=id,
126             placement="auto"
127         )
128     ]
129
130
131 def label(key: str) -> str:
132     """Returns a label for input elements (dropdowns, ...).
133
134     If the label is not defined, the function returns the provided key.
135
136     :param key: The key to the label defined in Constants.LABELS.
137     :type key: str
138     :returns: Label.
139     :rtype: str
140     """
141     return C.LABELS.get(key, key)
142
143
144 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
145     """Synchronize a checklist with defined "options" with its "All" checklist.
146
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
153     """
154     opts = {v["value"] for v in options}
155     if id =="all":
156         sel = list(opts) if all else list()
157     else:
158         all = ["all", ] if set(sel) == opts else list()
159     return sel, all
160
161
162 def list_tests(selection: dict) -> list:
163     """Transform list of tests to a list of dictionaries usable by checkboxes.
164
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.
168     :rtype: list
169     """
170     if selection:
171         return [{"label": v["id"], "value": v["id"]} for v in selection]
172     else:
173         return list()
174
175
176 def get_date(s_date: str) -> datetime:
177     """Transform string reprezentation of date to datetime.datetime data type.
178
179     :param s_date: String reprezentation of date.
180     :type s_date: str
181     :returns: Date as datetime.datetime.
182     :rtype: datetime.datetime
183     """
184     return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
185
186
187 def gen_new_url(url_components: dict, params: dict) -> str:
188     """Generate a new URL with encoded parameters.
189
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
194     :type params: dict
195     :returns Encoded URL with parameters.
196     :rtype: str
197     """
198
199     if url_components:
200         return url_encode(
201             {
202                 "scheme": url_components.get("scheme", ""),
203                 "netloc": url_components.get("netloc", ""),
204                 "path": url_components.get("path", ""),
205                 "params": params
206             }
207         )
208     else:
209         return str()
210
211
212 def get_duts(df: pd.DataFrame) -> list:
213     """Get the list of DUTs from the pre-processed information about jobs.
214
215     :param df: DataFrame with information about jobs.
216     :type df: pandas.DataFrame
217     :returns: Alphabeticaly sorted list of DUTs.
218     :rtype: list
219     """
220     return sorted(list(df["dut"].unique()))
221
222
223 def get_ttypes(df: pd.DataFrame, dut: str) -> list:
224     """Get the list of test types from the pre-processed information about
225     jobs.
226
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
230     :type dut: str
231     :returns: Alphabeticaly sorted list of test types.
232     :rtype: list
233     """
234     return sorted(list(df.loc[(df["dut"] == dut)]["ttype"].unique()))
235
236
237 def get_cadences(df: pd.DataFrame, dut: str, ttype: str) -> list:
238     """Get the list of cadences from the pre-processed information about
239     jobs.
240
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
244         populated.
245     :type df: pandas.DataFrame
246     :type dut: str
247     :type ttype: str
248     :returns: Alphabeticaly sorted list of cadences.
249     :rtype: list
250     """
251     return sorted(list(df.loc[(
252         (df["dut"] == dut) &
253         (df["ttype"] == ttype)
254     )]["cadence"].unique()))
255
256
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
259     jobs.
260
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
264         populated.
265     :param cadence: The cadence for which the list of test beds will be
266         populated.
267     :type df: pandas.DataFrame
268     :type dut: str
269     :type ttype: str
270     :type cadence: str
271     :returns: Alphabeticaly sorted list of test beds.
272     :rtype: list
273     """
274     return sorted(list(df.loc[(
275         (df["dut"] == dut) &
276         (df["ttype"] == ttype) &
277         (df["cadence"] == cadence)
278     )]["tbed"].unique()))
279
280
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.
284
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
291     :type dut: str
292     :type ttype: str
293     :type cadence: str
294     :type testbed: str
295     :returns: Job name.
296     :rtype: str
297     """
298     return df.loc[(
299         (df["dut"] == dut) &
300         (df["ttype"] == ttype) &
301         (df["cadence"] == cadence) &
302         (df["tbed"] == testbed)
303     )]["job"].item()
304
305
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".
309
310     :params opts: List of options (str) to be used for the generated list.
311     :type opts: list
312     :returns: List of options (dict).
313     :rtype: list
314     """
315     return [{"label": i, "value": i} for i in opts]
316
317
318 def set_job_params(df: pd.DataFrame, job: str) -> dict:
319     """Create a dictionary with all options and values for (and from) the
320     given job.
321
322     :param df: DataFrame with information about jobs.
323     :params job: The name of job for and from which the dictionary will be
324         created.
325     :type df: pandas.DataFrame
326     :type job: str
327     :returns: Dictionary with all options and values for (and from) the
328         given job.
329     :rtype: dict
330     """
331
332     l_job = job.split("-")
333     return {
334         "job": job,
335         "dut": l_job[1],
336         "ttype": l_job[3],
337         "cadence": l_job[4],
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]))
344     }