Completed
Pull Request — master (#59)
by
unknown
01:05
created

Metadata.__bool__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 2
rs 10
1
from __future__ import division
2
from __future__ import print_function
3
4
import statistics
5
from bisect import bisect_left
6
from bisect import bisect_right
7
import operator
8
9
from .utils import cached_property
10
from .utils import funcname
11
from .utils import get_cprofile_functions
12
13
14
class Stats(object):
15
    fields = (
16
        "min", "max", "mean", "stddev", "rounds", "median", "iqr", "q1", "q3", "iqr_outliers", "stddev_outliers",
17
        "outliers", "ld15iqr", "hd15iqr"
18
    )
19
20
    def __init__(self):
21
        self.data = []
22
23
    def __bool__(self):
24
        return bool(self.data)
25
26
    def __nonzero__(self):
27
        return bool(self.data)
28
29
    def as_dict(self):
30
        return dict(
31
            (field, getattr(self, field))
32
            for field in self.fields
33
        )
34
35
    def update(self, duration):
36
        self.data.append(duration)
37
38
    @cached_property
39
    def sorted_data(self):
40
        return sorted(self.data)
41
42
    @cached_property
43
    def total(self):
44
        return sum(self.data)
45
46
    @cached_property
47
    def min(self):
48
        return min(self.data)
49
50
    @cached_property
51
    def max(self):
52
        return max(self.data)
53
54
    @cached_property
55
    def mean(self):
56
        return statistics.mean(self.data)
57
58
    @cached_property
59
    def stddev(self):
60
        if len(self.data) > 1:
61
            return statistics.stdev(self.data)
62
        else:
63
            return 0
64
65
    @property
66
    def stddev_outliers(self):
67
        """
68
        Count of StdDev outliers: what's beyond (Mean - StdDev, Mean - StdDev)
69
        """
70
        count = 0
71
        q0 = self.mean - self.stddev
72
        q4 = self.mean + self.stddev
73
        for val in self.data:
74
            if val < q0 or val > q4:
75
                count += 1
76
        return count
77
78
    @cached_property
79
    def rounds(self):
80
        return len(self.data)
81
82
    @cached_property
83
    def median(self):
84
        return statistics.median(self.data)
85
86
    @cached_property
87
    def ld15iqr(self):
88
        """
89
        Tukey-style Lowest Datum within 1.5 IQR under Q1.
90
        """
91
        if len(self.data) == 1:
92
            return self.data[0]
93
        else:
94
            return self.sorted_data[bisect_left(self.sorted_data, self.q1 - 1.5 * self.iqr)]
95
96
    @cached_property
97
    def hd15iqr(self):
98
        """
99
        Tukey-style Highest Datum within 1.5 IQR over Q3.
100
        """
101
        if len(self.data) == 1:
102
            return self.data[0]
103
        else:
104
            pos = bisect_right(self.sorted_data, self.q3 + 1.5 * self.iqr)
105
            if pos == len(self.data):
106
                return self.sorted_data[-1]
107
            else:
108
                return self.sorted_data[pos]
109
110
    @cached_property
111
    def q1(self):
112
        rounds = self.rounds
113
        data = self.sorted_data
114
115
        # See: https://en.wikipedia.org/wiki/Quartile#Computing_methods
116 View Code Duplication
        if rounds == 1:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
117
            return data[0]
118
        elif rounds % 2:  # Method 3
119
            n, q = rounds // 4, rounds % 4
120
            if q == 1:
121
                return 0.25 * data[n - 1] + 0.75 * data[n]
122
            else:
123
                return 0.75 * data[n] + 0.25 * data[n + 1]
124
        else:  # Method 2
125
            return statistics.median(data[:rounds // 2])
126
127
    @cached_property
128
    def q3(self):
129
        rounds = self.rounds
130
        data = self.sorted_data
131
132
        # See: https://en.wikipedia.org/wiki/Quartile#Computing_methods
133 View Code Duplication
        if rounds == 1:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
134
            return data[0]
135
        elif rounds % 2:  # Method 3
136
            n, q = rounds // 4, rounds % 4
137
            if q == 1:
138
                return 0.75 * data[3 * n] + 0.25 * data[3 * n + 1]
139
            else:
140
                return 0.25 * data[3 * n + 1] + 0.75 * data[3 * n + 2]
141
        else:  # Method 2
142
            return statistics.median(data[rounds // 2:])
143
144
    @cached_property
145
    def iqr(self):
146
        return self.q3 - self.q1
147
148
    @property
149
    def iqr_outliers(self):
150
        """
151
        Count of Tukey outliers: what's beyond (Q1 - 1.5IQR, Q3 + 1.5IQR)
152
        """
153
        count = 0
154
        q0 = self.q1 - 1.5 * self.iqr
155
        q4 = self.q3 + 1.5 * self.iqr
156
        for val in self.data:
157
            if val < q0 or val > q4:
158
                count += 1
159
        return count
160
161
    @cached_property
162
    def outliers(self):
163
        return "%s;%s" % (self.stddev_outliers, self.iqr_outliers)
164
165
166
class Metadata(object):
167
    def __init__(self, fixture, iterations, options):
168
        self.name = fixture.name
169
        self.fullname = fixture.fullname
170
        self.group = fixture.group
171
        self.param = fixture.param
172
        self.params = fixture.params
173
        self.cprofile_stats = fixture.cprofile_stats
174
175
        self.iterations = iterations
176
        self.stats = Stats()
177
        self.options = options
178
        self.fixture = fixture
179
180
    def __bool__(self):
181
        return bool(self.stats)
182
183
    def __nonzero__(self):
184
        return bool(self.stats)
185
186
    def get(self, key, default=None):
187
        try:
188
            return getattr(self.stats, key)
189
        except AttributeError:
190
            return getattr(self, key, default)
191
192
    def __getitem__(self, key):
193
        try:
194
            return getattr(self.stats, key)
195
        except AttributeError:
196
            return getattr(self, key)
197
198
    @property
199
    def has_error(self):
200
        return self.fixture.has_error
201
202
    def as_dict(self, include_data=True, flat=False, stats=True, cprofile=None):
203
        result = {
204
            "group": self.group,
205
            "name": self.name,
206
            "fullname": self.fullname,
207
            "params": self.params,
208
            "param": self.param,
209
            "options": dict(
210
                (k, funcname(v) if callable(v) else v) for k, v in self.options.items()
211
            )
212
        }
213
        if self.cprofile_stats:
214
            cprofile_list = result["cprofile"] = []
215
            cprofile_functions = get_cprofile_functions(self.cprofile_stats)
216
            stats_columns = ["cumtime", "tottime","ncalls", "ncalls_recursion",
217
                             "tottime_per", "cumtime_per", "function_name"]
218
            # move column first
219
            if cprofile is not None:
220
                stats_columns.remove(cprofile)
221
                stats_columns.insert(0, cprofile)
222
            for column in stats_columns:
223
                cprofile_functions.sort(key=operator.itemgetter(column), reverse=True)
224
                for cprofile_function in cprofile_functions[:25]:
225
                    if cprofile_function not in cprofile_list:
226
                        cprofile_list.append(cprofile_function)
227
                # if we want only one column or we already have all available functions
228
                if cprofile is None or len(cprofile_functions) == len(cprofile_list):
229
                    break
230
        if stats:
231
            stats = self.stats.as_dict()
232
            if include_data:
233
                stats["data"] = self.stats.data
234
            stats["iterations"] = self.iterations
235
            if flat:
236
                result.update(stats)
237
            else:
238
                result["stats"] = stats
239
        return result
240
241
    def update(self, duration):
242
        self.stats.update(duration / self.iterations)
243