63c9c1aaa44336a9ae59d3942bb96d4e29db54f5
[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 """
15 """
16
17 from numpy import isnan
18
19 from ..jumpavg import classify
20
21
22 def classify_anomalies(data):
23     """Process the data and return anomalies and trending values.
24
25     Gather data into groups with average as trend value.
26     Decorate values within groups to be normal,
27     the first value of changed average as a regression, or a progression.
28
29     :param data: Full data set with unavailable samples replaced by nan.
30     :type data: OrderedDict
31     :returns: Classification and trend values
32     :rtype: 3-tuple, list of strings, list of floats and list of floats
33     """
34     # NaN means something went wrong.
35     # Use 0.0 to cause that being reported as a severe regression.
36     bare_data = [0.0 if isnan(sample) else sample for sample in data.values()]
37     # TODO: Make BitCountingGroupList a subclass of list again?
38     group_list = classify(bare_data).group_list
39     group_list.reverse()  # Just to use .pop() for FIFO.
40     classification = list()
41     avgs = list()
42     stdevs = list()
43     active_group = None
44     values_left = 0
45     avg = 0.0
46     stdv = 0.0
47     for sample in data.values():
48         if isnan(sample):
49             classification.append("outlier")
50             avgs.append(sample)
51             stdevs.append(sample)
52             continue
53         if values_left < 1 or active_group is None:
54             values_left = 0
55             while values_left < 1:  # Ignore empty groups (should not happen).
56                 active_group = group_list.pop()
57                 values_left = len(active_group.run_list)
58             avg = active_group.stats.avg
59             stdv = active_group.stats.stdev
60             classification.append(active_group.comment)
61             avgs.append(avg)
62             stdevs.append(stdv)
63             values_left -= 1
64             continue
65         classification.append("normal")
66         avgs.append(avg)
67         stdevs.append(stdv)
68         values_left -= 1
69     return classification, avgs, stdevs