CDash: Add comparison tables
[csit.git] / csit.infra.dash / app / cdash / utils / utils.py
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:
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 math import sqrt
21 from numpy import isnan
22 from dash import dcc
23 from datetime import datetime
24
25 from ..jumpavg import classify
26 from ..utils.constants import Constants as C
27 from ..utils.url_processing import url_encode
28
29
30 def classify_anomalies(data):
31     """Process the data and return anomalies and trending values.
32
33     Gather data into groups with average as trend value.
34     Decorate values within groups to be normal,
35     the first value of changed average as a regression, or a progression.
36
37     :param data: Full data set with unavailable samples replaced by nan.
38     :type data: OrderedDict
39     :returns: Classification and trend values
40     :rtype: 3-tuple, list of strings, list of floats and list of floats
41     """
42     # NaN means something went wrong.
43     # Use 0.0 to cause that being reported as a severe regression.
44     bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
45     # TODO: Make BitCountingGroupList a subclass of list again?
46     group_list = classify(bare_data).group_list
47     group_list.reverse()  # Just to use .pop() for FIFO.
48     classification = list()
49     avgs = list()
50     stdevs = list()
51     active_group = None
52     values_left = 0
53     avg = 0.0
54     stdv = 0.0
55     for sample in data.values():
56         if isnan(sample):
57             classification.append("outlier")
58             avgs.append(sample)
59             stdevs.append(sample)
60             continue
61         if values_left < 1 or active_group is None:
62             values_left = 0
63             while values_left < 1:  # Ignore empty groups (should not happen).
64                 active_group = group_list.pop()
65                 values_left = len(active_group.run_list)
66             avg = active_group.stats.avg
67             stdv = active_group.stats.stdev
68             classification.append(active_group.comment)
69             avgs.append(avg)
70             stdevs.append(stdv)
71             values_left -= 1
72             continue
73         classification.append("normal")
74         avgs.append(avg)
75         stdevs.append(stdv)
76         values_left -= 1
77     return classification, avgs, stdevs
78
79
80 def get_color(idx: int) -> str:
81     """Returns a color from the list defined in Constants.PLOT_COLORS defined by
82     its index.
83
84     :param idx: Index of the color.
85     :type idx: int
86     :returns: Color defined by hex code.
87     :trype: str
88     """
89     return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
90
91
92 def show_tooltip(tooltips:dict, id: str, title: str,
93         clipboard_id: str=None) -> list:
94     """Generate list of elements to display a text (e.g. a title) with a
95     tooltip and optionaly with Copy&Paste icon and the clipboard
96     functionality enabled.
97
98     :param tooltips: Dictionary with tooltips.
99     :param id: Tooltip ID.
100     :param title: A text for which the tooltip will be displayed.
101     :param clipboard_id: If defined, a Copy&Paste icon is displayed and the
102         clipboard functionality is enabled.
103     :type tooltips: dict
104     :type id: str
105     :type title: str
106     :type clipboard_id: str
107     :returns: List of elements to display a text with a tooltip and
108         optionaly with Copy&Paste icon.
109     :rtype: list
110     """
111
112     return [
113         dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
114             if clipboard_id else str(),
115         f"{title} ",
116         dbc.Badge(
117             id=id,
118             children="?",
119             pill=True,
120             color="white",
121             text_color="info",
122             class_name="border ms-1",
123         ),
124         dbc.Tooltip(
125             children=tooltips.get(id, str()),
126             target=id,
127             placement="auto"
128         )
129     ]
130
131
132 def label(key: str) -> str:
133     """Returns a label for input elements (dropdowns, ...).
134
135     If the label is not defined, the function returns the provided key.
136
137     :param key: The key to the label defined in Constants.LABELS.
138     :type key: str
139     :returns: Label.
140     :rtype: str
141     """
142     return C.LABELS.get(key, key)
143
144
145 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
146     """Synchronize a checklist with defined "options" with its "All" checklist.
147
148     :param options: List of options for the cheklist.
149     :param sel: List of selected options.
150     :param all: List of selected option from "All" checklist.
151     :param id: ID of a checklist to be used for synchronization.
152     :returns: Tuple of lists with otions for both checklists.
153     :rtype: tuple of lists
154     """
155     opts = {v["value"] for v in options}
156     if id =="all":
157         sel = list(opts) if all else list()
158     else:
159         all = ["all", ] if set(sel) == opts else list()
160     return sel, all
161
162
163 def list_tests(selection: dict) -> list:
164     """Transform list of tests to a list of dictionaries usable by checkboxes.
165
166     :param selection: List of tests to be displayed in "Selected tests" window.
167     :type selection: list
168     :returns: List of dictionaries with "label", "value" pairs for a checkbox.
169     :rtype: list
170     """
171     if selection:
172         return [{"label": v["id"], "value": v["id"]} for v in selection]
173     else:
174         return list()
175
176
177 def get_date(s_date: str) -> datetime:
178     """Transform string reprezentation of date to datetime.datetime data type.
179
180     :param s_date: String reprezentation of date.
181     :type s_date: str
182     :returns: Date as datetime.datetime.
183     :rtype: datetime.datetime
184     """
185     return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
186
187
188 def gen_new_url(url_components: dict, params: dict) -> str:
189     """Generate a new URL with encoded parameters.
190
191     :param url_components: Dictionary with URL elements. It should contain
192         "scheme", "netloc" and "path".
193     :param url_components: URL parameters to be encoded to the URL.
194     :type parsed_url: dict
195     :type params: dict
196     :returns Encoded URL with parameters.
197     :rtype: str
198     """
199
200     if url_components:
201         return url_encode(
202             {
203                 "scheme": url_components.get("scheme", ""),
204                 "netloc": url_components.get("netloc", ""),
205                 "path": url_components.get("path", ""),
206                 "params": params
207             }
208         )
209     else:
210         return str()
211
212
213 def get_duts(df: pd.DataFrame) -> list:
214     """Get the list of DUTs from the pre-processed information about jobs.
215
216     :param df: DataFrame with information about jobs.
217     :type df: pandas.DataFrame
218     :returns: Alphabeticaly sorted list of DUTs.
219     :rtype: list
220     """
221     return sorted(list(df["dut"].unique()))
222
223
224 def get_ttypes(df: pd.DataFrame, dut: str) -> list:
225     """Get the list of test types from the pre-processed information about
226     jobs.
227
228     :param df: DataFrame with information about jobs.
229     :param dut: The DUT for which the list of test types will be populated.
230     :type df: pandas.DataFrame
231     :type dut: str
232     :returns: Alphabeticaly sorted list of test types.
233     :rtype: list
234     """
235     return sorted(list(df.loc[(df["dut"] == dut)]["ttype"].unique()))
236
237
238 def get_cadences(df: pd.DataFrame, dut: str, ttype: str) -> list:
239     """Get the list of cadences from the pre-processed information about
240     jobs.
241
242     :param df: DataFrame with information about jobs.
243     :param dut: The DUT for which the list of cadences will be populated.
244     :param ttype: The test type for which the list of cadences will be
245         populated.
246     :type df: pandas.DataFrame
247     :type dut: str
248     :type ttype: str
249     :returns: Alphabeticaly sorted list of cadences.
250     :rtype: list
251     """
252     return sorted(list(df.loc[(
253         (df["dut"] == dut) &
254         (df["ttype"] == ttype)
255     )]["cadence"].unique()))
256
257
258 def get_test_beds(df: pd.DataFrame, dut: str, ttype: str, cadence: str) -> list:
259     """Get the list of test beds from the pre-processed information about
260     jobs.
261
262     :param df: DataFrame with information about jobs.
263     :param dut: The DUT for which the list of test beds will be populated.
264     :param ttype: The test type for which the list of test beds will be
265         populated.
266     :param cadence: The cadence for which the list of test beds will be
267         populated.
268     :type df: pandas.DataFrame
269     :type dut: str
270     :type ttype: str
271     :type cadence: str
272     :returns: Alphabeticaly sorted list of test beds.
273     :rtype: list
274     """
275     return sorted(list(df.loc[(
276         (df["dut"] == dut) &
277         (df["ttype"] == ttype) &
278         (df["cadence"] == cadence)
279     )]["tbed"].unique()))
280
281
282 def get_job(df: pd.DataFrame, dut, ttype, cadence, testbed):
283     """Get the name of a job defined by dut, ttype, cadence, test bed.
284     Input information comes from the control panel.
285
286     :param df: DataFrame with information about jobs.
287     :param dut: The DUT for which the job name will be created.
288     :param ttype: The test type for which the job name will be created.
289     :param cadence: The cadence for which the job name will be created.
290     :param testbed: The test bed for which the job name will be created.
291     :type df: pandas.DataFrame
292     :type dut: str
293     :type ttype: str
294     :type cadence: str
295     :type testbed: str
296     :returns: Job name.
297     :rtype: str
298     """
299     return df.loc[(
300         (df["dut"] == dut) &
301         (df["ttype"] == ttype) &
302         (df["cadence"] == cadence) &
303         (df["tbed"] == testbed)
304     )]["job"].item()
305
306
307 def generate_options(opts: list, sort: bool=True) -> list:
308     """Return list of options for radio items in control panel. The items in
309     the list are dictionaries with keys "label" and "value".
310
311     :params opts: List of options (str) to be used for the generated list.
312     :type opts: list
313     :returns: List of options (dict).
314     :rtype: list
315     """
316     if sort:
317         opts = sorted(opts)
318     return [{"label": i, "value": i} for i in opts]
319
320
321 def set_job_params(df: pd.DataFrame, job: str) -> dict:
322     """Create a dictionary with all options and values for (and from) the
323     given job.
324
325     :param df: DataFrame with information about jobs.
326     :params job: The name of job for and from which the dictionary will be
327         created.
328     :type df: pandas.DataFrame
329     :type job: str
330     :returns: Dictionary with all options and values for (and from) the
331         given job.
332     :rtype: dict
333     """
334
335     l_job = job.split("-")
336     return {
337         "job": job,
338         "dut": l_job[1],
339         "ttype": l_job[3],
340         "cadence": l_job[4],
341         "tbed": "-".join(l_job[-2:]),
342         "duts": generate_options(get_duts(df)),
343         "ttypes": generate_options(get_ttypes(df, l_job[1])),
344         "cadences": generate_options(get_cadences(df, l_job[1], l_job[3])),
345         "tbeds": generate_options(
346             get_test_beds(df, l_job[1], l_job[3], l_job[4]))
347     }
348
349
350 def get_list_group_items(
351         items: list,
352         type: str,
353         colorize: bool=True,
354         add_index: bool=False
355     ) -> list:
356     """Generate list of ListGroupItems with checkboxes with selected items.
357
358     :param items: List of items to be displayed in the ListGroup.
359     :param type: The type part of an element ID.
360     :param colorize: If True, the color of labels is set, otherwise the default
361         color is used.
362     :param add_index: Add index to the list items.
363     :type items: list
364     :type type: str
365     :type colorize: bool
366     :type add_index: bool
367     :returns: List of ListGroupItems with checkboxes with selected items.
368     :rtype: list
369     """
370
371     children = list()
372     for i, l in enumerate(items):
373         idx = f"{i + 1}. " if add_index else str()
374         label = f"{idx}{l['id']}" if isinstance(l, dict) else f"{idx}{l}"
375         children.append(
376             dbc.ListGroupItem(
377                 children=[
378                     dbc.Checkbox(
379                         id={"type": type, "index": i},
380                         label=label,
381                         value=False,
382                         label_class_name="m-0 p-0",
383                         label_style={
384                             "font-size": ".875em",
385                             "color": get_color(i) if colorize else "#55595c"
386                         },
387                         class_name="info"
388                     )
389                 ],
390                 class_name="p-0"
391             )
392         )
393
394     return children
395
396 def relative_change_stdev(mean1, mean2, std1, std2):
397     """Compute relative standard deviation of change of two values.
398
399     The "1" values are the base for comparison.
400     Results are returned as percentage (and percentual points for stdev).
401     Linearized theory is used, so results are wrong for relatively large stdev.
402
403     :param mean1: Mean of the first number.
404     :param mean2: Mean of the second number.
405     :param std1: Standard deviation estimate of the first number.
406     :param std2: Standard deviation estimate of the second number.
407     :type mean1: float
408     :type mean2: float
409     :type std1: float
410     :type std2: float
411     :returns: Relative change and its stdev.
412     :rtype: float
413     """
414     mean1, mean2 = float(mean1), float(mean2)
415     quotient = mean2 / mean1
416     first = std1 / mean1
417     second = std2 / mean2
418     std = quotient * sqrt(first * first + second * second)
419     return (quotient - 1) * 100, std * 100