CSIT-1110: Prepare for migrating the new detection
[csit.git] / resources / tools / presentation / new / jumpavg / AvgStdevMetadataFactory.py
1 # Copyright (c) 2018 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 """Module holding AvgStdevMetadataFactory class."""
15
16 import math
17
18 from AvgStdevMetadata import AvgStdevMetadata
19
20
21 class AvgStdevMetadataFactory(object):
22     """Class factory which creates avg,stdev metadata from data."""
23
24     @staticmethod
25     def from_data(values):
26         """Return new metadata object fitting the values.
27
28         :param values: Run values to be processed.
29         :type values: Iterable of float or of AvgStdevMetadata
30         :returns: The metadata matching the values.
31         :rtype: AvgStdevMetadata
32         """
33         sum_0 = 0
34         sum_1 = 0.0
35         sum_2 = 0.0
36         for value in values:
37             if isinstance(value, AvgStdevMetadata):
38                 sum_0 += value.size
39                 sum_1 += value.avg * value.size
40                 sum_2 += value.stdev * value.stdev * value.size
41                 sum_2 += value.avg * value.avg * value.size
42             else:  # The value is assumed to be float.
43                 sum_0 += 1
44                 sum_1 += value
45                 sum_2 += value * value
46         if sum_0 < 1:
47             return AvgStdevMetadata()
48         avg = sum_1 / sum_0
49         stdev = math.sqrt(sum_2 / sum_0 - avg * avg)
50         ret_obj = AvgStdevMetadata(size=sum_0, avg=avg, stdev=stdev)
51         return ret_obj