70fb02e1893c0c310f0fdd548dd51ccde1292fec
[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 dash_bootstrap_components as dbc
18
19 from numpy import isnan
20 from dash import dcc
21 from datetime import datetime
22
23 from ..jumpavg import classify
24 from ..utils.constants import Constants as C
25 from ..utils.url_processing import url_encode
26
27
28 def classify_anomalies(data):
29     """Process the data and return anomalies and trending values.
30
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.
34
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
39     """
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()
47     avgs = list()
48     stdevs = list()
49     active_group = None
50     values_left = 0
51     avg = 0.0
52     stdv = 0.0
53     for sample in data.values():
54         if isnan(sample):
55             classification.append("outlier")
56             avgs.append(sample)
57             stdevs.append(sample)
58             continue
59         if values_left < 1 or active_group is None:
60             values_left = 0
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)
67             avgs.append(avg)
68             stdevs.append(stdv)
69             values_left -= 1
70             continue
71         classification.append("normal")
72         avgs.append(avg)
73         stdevs.append(stdv)
74         values_left -= 1
75     return classification, avgs, stdevs
76
77
78 def get_color(idx: int) -> str:
79     """Returns a color from the list defined in Constants.PLOT_COLORS defined by
80     its index.
81
82     :param idx: Index of the color.
83     :type idex: int
84     :returns: Color defined by hex code.
85     :trype: str
86     """
87     return C.PLOT_COLORS[idx % len(C.PLOT_COLORS)]
88
89
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.
95
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.
101     :type tooltips: dict
102     :type id: str
103     :type title: str
104     :type clipboard_id: str
105     :returns: List of elements to display a text with a tooltip and
106         optionaly with Copy&Paste icon.
107     :rtype: list
108     """
109
110     return [
111         dcc.Clipboard(target_id=clipboard_id, title="Copy URL") \
112             if clipboard_id else str(),
113         f"{title} ",
114         dbc.Badge(
115             id=id,
116             children="?",
117             pill=True,
118             color="white",
119             text_color="info",
120             class_name="border ms-1",
121         ),
122         dbc.Tooltip(
123             children=tooltips.get(id, str()),
124             target=id,
125             placement="auto"
126         )
127     ]
128
129
130 def label(key: str) -> str:
131     """Returns a label for input elements (dropdowns, ...).
132
133     If the label is not defined, the function returns the provided key.
134
135     :param key: The key to the label defined in Constants.LABELS.
136     :type key: str
137     :returns: Label.
138     :rtype: str
139     """
140     return C.LABELS.get(key, key)
141
142
143 def sync_checklists(options: list, sel: list, all: list, id: str) -> tuple:
144     """Synchronize a checklist with defined "options" with its "All" checklist.
145
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
152     """
153     opts = {v["value"] for v in options}
154     if id =="all":
155         sel = list(opts) if all else list()
156     else:
157         all = ["all", ] if set(sel) == opts else list()
158     return sel, all
159
160
161 def list_tests(selection: dict) -> list:
162     """Transform list of tests to a list of dictionaries usable by checkboxes.
163
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.
167     :rtype: list
168     """
169     if selection:
170         return [{"label": v["id"], "value": v["id"]} for v in selection]
171     else:
172         return list()
173
174
175 def get_date(s_date: str) -> datetime:
176     """Transform string reprezentation of date to datetime.datetime data type.
177
178     :param s_date: String reprezentation of date.
179     :type s_date: str
180     :returns: Date as datetime.datetime.
181     :rtype: datetime.datetime
182     """
183     return datetime(int(s_date[0:4]), int(s_date[5:7]), int(s_date[8:10]))
184
185
186 def gen_new_url(parsed_url: dict, params: dict) -> str:
187     """Generate a new URL with encoded parameters.
188
189     :param parsed_url: Dictionary with URL elements. It should contain "scheme",
190         "netloc" and "path".
191     :param params: URL parameters to be encoded to the URL.
192     :type parsed_url: dict
193     :type params: dict
194     :returns Encoded URL with parameters.
195     :rtype: str
196     """
197
198     if parsed_url:
199         return url_encode(
200             {
201                 "scheme": parsed_url.get("scheme", ""),
202                 "netloc": parsed_url.get("netloc", ""),
203                 "path": parsed_url.get("path", ""),
204                 "params": params
205             }
206         )
207     else:
208         return str()