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