C-Dash: Fix anomaly detection for the news
[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 """Functions used by Dash applications.
15 """
16
17 import pandas as pd
18 import plotly.graph_objects as go
19 import dash_bootstrap_components as dbc
20
21 import hdrh.histogram
22 import hdrh.codec
23
24 from math import sqrt
25 from dash import dcc
26 from datetime import datetime
27
28 from ..utils.constants import Constants as C
29 from ..utils.url_processing import url_encode
30
31
32 def get_color(idx: int) -> str:
33     """Returns a color from the list defined in Constants.PLOT_COLORS defined by
34     its index.
35
36     :param idx: Index of the color.
37     :type idx: int
38     :returns: Color defined by hex code.
39     :trype: str
40     """
41     return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
42
43
44 def show_tooltip(tooltips:dict, id: str, title: str,
45         clipboard_id: str=None) -> list:
46     """Generate list of elements to display a text (e.g. a title) with a
47     tooltip and optionaly with Copy&Paste icon and the clipboard
48     functionality enabled.
49
50     :param tooltips: Dictionary with tooltips.
51     :param id: Tooltip ID.
52     :param title: A text for which the tooltip will be displayed.
53     :param clipboard_id: If defined, a Copy&Paste icon is displayed and the
54         clipboard functionality is enabled.
55     :type tooltips: dict
56     :type id: str
57     :type title: str
58     :type clipboard_id: str
59     :returns: List of elements to display a text with a tooltip and
60         optionaly with Copy&Paste icon.
61     :rtype: list
62     """
63
64     return [
65         dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
66             if clipboard_id else str(),
67         f"{title} ",
68         dbc.Badge(
69             id=id,
70             children="?",
71             pill=True,
72             color="white",
73             text_color="info",
74             class_name="border ms-1",
75         ),
76         dbc.Tooltip(
77             children=tooltips.get(id, str()),
78             target=id,
79             placement="auto"
80         )
81     ]
82
83
84 def label(key: str) -> str:
85     """Returns a label for input elements (dropdowns, ...).
86
87     If the label is not defined, the function returns the provided key.
88
89     :param key: The key to the label defined in Constants.LABELS.
90     :type key: str
91     :returns: Label.
92     :rtype: str
93     """
94     return C.LABELS.get(key, key)
95
96
97 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
98     """Synchronize a checklist with defined "options" with its "All" checklist.
99
100     :param options: List of options for the cheklist.
101     :param sel: List of selected options.
102     :param all: List of selected option from "All" checklist.
103     :param id: ID of a checklist to be used for synchronization.
104     :returns: Tuple of lists with otions for both checklists.
105     :rtype: tuple of lists
106     """
107     opts = {v["value"] for v in options}
108     if id =="all":
109         sel = list(opts) if all else list()
110     else:
111         all = ["all", ] if set(sel) == opts else list()
112     return sel, all
113
114
115 def list_tests(selection: dict) -> list:
116     """Transform list of tests to a list of dictionaries usable by checkboxes.
117
118     :param selection: List of tests to be displayed in "Selected tests" window.
119     :type selection: list
120     :returns: List of dictionaries with "label", "value" pairs for a checkbox.
121     :rtype: list
122     """
123     if selection:
124         return [{"label": v["id"], "value": v["id"]} for v in selection]
125     else:
126         return list()
127
128
129 def get_date(s_date: str) -> datetime:
130     """Transform string reprezentation of date to datetime.datetime data type.
131
132     :param s_date: String reprezentation of date.
133     :type s_date: str
134     :returns: Date as datetime.datetime.
135     :rtype: datetime.datetime
136     """
137     return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
138
139
140 def gen_new_url(url_components: dict, params: dict) -> str:
141     """Generate a new URL with encoded parameters.
142
143     :param url_components: Dictionary with URL elements. It should contain
144         "scheme", "netloc" and "path".
145     :param url_components: URL parameters to be encoded to the URL.
146     :type parsed_url: dict
147     :type params: dict
148     :returns Encoded URL with parameters.
149     :rtype: str
150     """
151
152     if url_components:
153         return url_encode(
154             {
155                 "scheme": url_components.get("scheme", ""),
156                 "netloc": url_components.get("netloc", ""),
157                 "path": url_components.get("path", ""),
158                 "params": params
159             }
160         )
161     else:
162         return str()
163
164
165 def get_duts(df: pd.DataFrame) -> list:
166     """Get the list of DUTs from the pre-processed information about jobs.
167
168     :param df: DataFrame with information about jobs.
169     :type df: pandas.DataFrame
170     :returns: Alphabeticaly sorted list of DUTs.
171     :rtype: list
172     """
173     return sorted(list(df["dut"].unique()))
174
175
176 def get_ttypes(df: pd.DataFrame, dut: str) -> list:
177     """Get the list of test types from the pre-processed information about
178     jobs.
179
180     :param df: DataFrame with information about jobs.
181     :param dut: The DUT for which the list of test types will be populated.
182     :type df: pandas.DataFrame
183     :type dut: str
184     :returns: Alphabeticaly sorted list of test types.
185     :rtype: list
186     """
187     return sorted(list(df.loc[(df["dut"] == dut)]["ttype"].unique()))
188
189
190 def get_cadences(df: pd.DataFrame, dut: str, ttype: str) -> list:
191     """Get the list of cadences from the pre-processed information about
192     jobs.
193
194     :param df: DataFrame with information about jobs.
195     :param dut: The DUT for which the list of cadences will be populated.
196     :param ttype: The test type for which the list of cadences will be
197         populated.
198     :type df: pandas.DataFrame
199     :type dut: str
200     :type ttype: str
201     :returns: Alphabeticaly sorted list of cadences.
202     :rtype: list
203     """
204     return sorted(list(df.loc[(
205         (df["dut"] == dut) &
206         (df["ttype"] == ttype)
207     )]["cadence"].unique()))
208
209
210 def get_test_beds(df: pd.DataFrame, dut: str, ttype: str, cadence: str) -> list:
211     """Get the list of test beds from the pre-processed information about
212     jobs.
213
214     :param df: DataFrame with information about jobs.
215     :param dut: The DUT for which the list of test beds will be populated.
216     :param ttype: The test type for which the list of test beds will be
217         populated.
218     :param cadence: The cadence for which the list of test beds will be
219         populated.
220     :type df: pandas.DataFrame
221     :type dut: str
222     :type ttype: str
223     :type cadence: str
224     :returns: Alphabeticaly sorted list of test beds.
225     :rtype: list
226     """
227     return sorted(list(df.loc[(
228         (df["dut"] == dut) &
229         (df["ttype"] == ttype) &
230         (df["cadence"] == cadence)
231     )]["tbed"].unique()))
232
233
234 def get_job(df: pd.DataFrame, dut, ttype, cadence, testbed):
235     """Get the name of a job defined by dut, ttype, cadence, test bed.
236     Input information comes from the control panel.
237
238     :param df: DataFrame with information about jobs.
239     :param dut: The DUT for which the job name will be created.
240     :param ttype: The test type for which the job name will be created.
241     :param cadence: The cadence for which the job name will be created.
242     :param testbed: The test bed for which the job name will be created.
243     :type df: pandas.DataFrame
244     :type dut: str
245     :type ttype: str
246     :type cadence: str
247     :type testbed: str
248     :returns: Job name.
249     :rtype: str
250     """
251     return df.loc[(
252         (df["dut"] == dut) &
253         (df["ttype"] == ttype) &
254         (df["cadence"] == cadence) &
255         (df["tbed"] == testbed)
256     )]["job"].item()
257
258
259 def generate_options(opts: list, sort: bool=True) -> list:
260     """Return list of options for radio items in control panel. The items in
261     the list are dictionaries with keys "label" and "value".
262
263     :params opts: List of options (str) to be used for the generated list.
264     :type opts: list
265     :returns: List of options (dict).
266     :rtype: list
267     """
268     if sort:
269         opts = sorted(opts)
270     return [{"label": i, "value": i} for i in opts]
271
272
273 def set_job_params(df: pd.DataFrame, job: str) -> dict:
274     """Create a dictionary with all options and values for (and from) the
275     given job.
276
277     :param df: DataFrame with information about jobs.
278     :params job: The name of job for and from which the dictionary will be
279         created.
280     :type df: pandas.DataFrame
281     :type job: str
282     :returns: Dictionary with all options and values for (and from) the
283         given job.
284     :rtype: dict
285     """
286
287     l_job = job.split("-")
288     return {
289         "job": job,
290         "dut": l_job[1],
291         "ttype": l_job[3],
292         "cadence": l_job[4],
293         "tbed": "-".join(l_job[-2:]),
294         "duts": generate_options(get_duts(df)),
295         "ttypes": generate_options(get_ttypes(df, l_job[1])),
296         "cadences": generate_options(get_cadences(df, l_job[1], l_job[3])),
297         "tbeds": generate_options(
298             get_test_beds(df, l_job[1], l_job[3], l_job[4]))
299     }
300
301
302 def get_list_group_items(
303         items: list,
304         type: str,
305         colorize: bool=True,
306         add_index: bool=False
307     ) -> list:
308     """Generate list of ListGroupItems with checkboxes with selected items.
309
310     :param items: List of items to be displayed in the ListGroup.
311     :param type: The type part of an element ID.
312     :param colorize: If True, the color of labels is set, otherwise the default
313         color is used.
314     :param add_index: Add index to the list items.
315     :type items: list
316     :type type: str
317     :type colorize: bool
318     :type add_index: bool
319     :returns: List of ListGroupItems with checkboxes with selected items.
320     :rtype: list
321     """
322
323     children = list()
324     for i, l in enumerate(items):
325         idx = f"{i + 1}. " if add_index else str()
326         label = f"{idx}{l['id']}" if isinstance(l, dict) else f"{idx}{l}"
327         children.append(
328             dbc.ListGroupItem(
329                 children=[
330                     dbc.Checkbox(
331                         id={"type": type, "index": i},
332                         label=label,
333                         value=False,
334                         label_class_name="m-0 p-0",
335                         label_style={
336                             "font-size": ".875em",
337                             "color": get_color(i) if colorize else "#55595c"
338                         },
339                         class_name="info"
340                     )
341                 ],
342                 class_name="p-0"
343             )
344         )
345
346     return children
347
348
349 def relative_change_stdev(mean1, mean2, std1, std2):
350     """Compute relative standard deviation of change of two values.
351
352     The "1" values are the base for comparison.
353     Results are returned as percentage (and percentual points for stdev).
354     Linearized theory is used, so results are wrong for relatively large stdev.
355
356     :param mean1: Mean of the first number.
357     :param mean2: Mean of the second number.
358     :param std1: Standard deviation estimate of the first number.
359     :param std2: Standard deviation estimate of the second number.
360     :type mean1: float
361     :type mean2: float
362     :type std1: float
363     :type std2: float
364     :returns: Relative change and its stdev.
365     :rtype: float
366     """
367     mean1, mean2 = float(mean1), float(mean2)
368     quotient = mean2 / mean1
369     first = std1 / mean1
370     second = std2 / mean2
371     std = quotient * sqrt(first * first + second * second)
372     return (quotient - 1) * 100, std * 100
373
374
375 def get_hdrh_latencies(row: pd.Series, name: str) -> dict:
376     """Get the HDRH latencies from the test data.
377
378     :param row: A row fron the data frame with test data.
379     :param name: The test name to be displayed as the graph title.
380     :type row: pandas.Series
381     :type name: str
382     :returns: Dictionary with HDRH latencies.
383     :rtype: dict
384     """
385
386     latencies = {"name": name}
387     for key in C.LAT_HDRH:
388         try:
389             latencies[key] = row[key]
390         except KeyError:
391             return None
392
393     return latencies
394
395
396 def graph_hdrh_latency(data: dict, layout: dict) -> go.Figure:
397     """Generate HDR Latency histogram graphs.
398
399     :param data: HDRH data.
400     :param layout: Layout of plot.ly graph.
401     :type data: dict
402     :type layout: dict
403     :returns: HDR latency Histogram.
404     :rtype: plotly.graph_objects.Figure
405     """
406
407     fig = None
408
409     traces = list()
410     for idx, (lat_name, lat_hdrh) in enumerate(data.items()):
411         try:
412             decoded = hdrh.histogram.HdrHistogram.decode(lat_hdrh)
413         except (hdrh.codec.HdrLengthException, TypeError):
414             continue
415         previous_x = 0.0
416         prev_perc = 0.0
417         xaxis = list()
418         yaxis = list()
419         hovertext = list()
420         for item in decoded.get_recorded_iterator():
421             # The real value is "percentile".
422             # For 100%, we cut that down to "x_perc" to avoid
423             # infinity.
424             percentile = item.percentile_level_iterated_to
425             x_perc = min(percentile, C.PERCENTILE_MAX)
426             xaxis.append(previous_x)
427             yaxis.append(item.value_iterated_to)
428             hovertext.append(
429                 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
430                 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
431                 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
432                 f"Latency: {item.value_iterated_to}uSec"
433             )
434             next_x = 100.0 / (100.0 - x_perc)
435             xaxis.append(next_x)
436             yaxis.append(item.value_iterated_to)
437             hovertext.append(
438                 f"<b>{C.GRAPH_LAT_HDRH_DESC[lat_name]}</b><br>"
439                 f"Direction: {('W-E', 'E-W')[idx % 2]}<br>"
440                 f"Percentile: {prev_perc:.5f}-{percentile:.5f}%<br>"
441                 f"Latency: {item.value_iterated_to}uSec"
442             )
443             previous_x = next_x
444             prev_perc = percentile
445
446         traces.append(
447             go.Scatter(
448                 x=xaxis,
449                 y=yaxis,
450                 name=C.GRAPH_LAT_HDRH_DESC[lat_name],
451                 mode="lines",
452                 legendgroup=C.GRAPH_LAT_HDRH_DESC[lat_name],
453                 showlegend=bool(idx % 2),
454                 line=dict(
455                     color=get_color(int(idx/2)),
456                     dash="solid",
457                     width=1 if idx % 2 else 2
458                 ),
459                 hovertext=hovertext,
460                 hoverinfo="text"
461             )
462         )
463     if traces:
464         fig = go.Figure()
465         fig.add_traces(traces)
466         layout_hdrh = layout.get("plot-hdrh-latency", None)
467         if lat_hdrh:
468             fig.update_layout(layout_hdrh)
469
470     return fig