This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
stats.py
436 lines (340 loc) · 13.1 KB
/
stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from __future__ import print_function
from math import log, sqrt
from time import mktime
import random
import sqlparse
from pycalendar.datetime import DateTime
from pycalendar.duration import Duration as PyDuration
from pycalendar.icalendar.property import Property
from pycalendar.timezone import Timezone
from zope.interface import Interface, implements
from twisted.python.util import FancyEqMixin
NANO = 1000000000.0
def mean(samples):
return sum(samples) / len(samples)
def median(samples):
return sorted(samples)[len(samples) / 2]
def residuals(samples, from_):
return [from_ - s for s in samples]
def stddev(samples):
m = mean(samples)
variance = sum([datum ** 2 for datum in residuals(samples, m)]) / len(samples)
return variance ** 0.5
def mad(samples):
"""
Return the median absolute deviation of the given data set.
"""
med = median(samples)
res = map(abs, residuals(samples, med))
return median(res)
class _Statistic(object):
commands = ['summarize']
def __init__(self, name):
self.name = name
def __eq__(self, other):
if isinstance(other, _Statistic):
return self.name == other.name
return NotImplemented
def __hash__(self):
return hash((self.__class__, self.name))
def __repr__(self):
return '<Stat %r>' % (self.name,)
def squash(self, samples, mode=None):
"""
Normalize the sample data into float values (one per sample)
in seconds (I hope time is the only thing you measure).
"""
return samples
def summarize(self, data):
return ''.join([
self.name, ' mean ', str(mean(data)), '\n',
self.name, ' median ', str(median(data)), '\n',
self.name, ' stddev ', str(stddev(data)), '\n',
self.name, ' median absolute deviation ', str(mad(data)), '\n',
self.name, ' sum ', str(sum(data)), '\n'])
def write(self, basename, data):
fObj = file(basename % (self.name,), 'w')
fObj.write('\n'.join(map(str, data)) + '\n')
fObj.close()
class Duration(_Statistic):
pass
class SQLDuration(_Statistic):
commands = ['summarize', 'statements', 'transcript']
def _is_literal(self, token):
if token.ttype in sqlparse.tokens.Literal:
return True
if token.ttype == sqlparse.tokens.Keyword and token.value in (u'True', u'False'):
return True
return False
def _substitute(self, expression, replacement):
try:
expression.tokens
except AttributeError:
return
for i, token in enumerate(expression.tokens):
if self._is_literal(token):
expression.tokens[i] = replacement
elif token.is_whitespace():
expression.tokens[i] = sqlparse.sql.Token('Whitespace', ' ')
else:
self._substitute(token, replacement)
def normalize(self, sql):
(statement,) = sqlparse.parse(sql)
# Replace any literal values with placeholders
qmark = sqlparse.sql.Token('Operator', '?')
self._substitute(statement, qmark)
return sqlparse.format(unicode(statement).encode('ascii'))
def squash(self, samples, mode="duration"):
"""
Summarize the execution of a number of SQL statements.
@param mode: C{"duration"} to squash the durations into the
result. C{"count"} to squash the count of statements
executed into the result.
"""
results = []
for data in samples:
if mode == "duration":
value = sum([interval for (_ignore_sql, interval) in data]) / NANO
else:
value = len(data)
results.append(value)
return results
def summarize(self, samples):
times = []
statements = {}
for data in samples:
total = 0
for (sql, interval) in data:
sql = self.normalize(sql)
statements[sql] = statements.get(sql, 0) + 1
total += interval
times.append(total / NANO * 1000)
return ''.join([
'%d: %s\n' % (count, statement)
for (statement, count)
in statements.iteritems()]) + _Statistic.summarize(self, times)
def statements(self, samples):
statements = {}
for data in samples:
for (sql, interval) in data:
sql = self.normalize(sql)
statements.setdefault(sql, []).append(interval)
byTime = []
for statement, times in statements.iteritems():
byTime.append((sum(times), len(times), statement))
byTime.sort()
byTime.reverse()
if byTime:
header = '%10s %10s %10s %s'
row = '%10.5f %10.5f %10d %s'
print(header % ('TOTAL MS', 'PERCALL MS', 'NCALLS', 'STATEMENT'))
for (time, count, statement) in byTime:
time = time / NANO * 1000
print(row % (time, time / count, count, statement))
def transcript(self, samples):
statements = []
data = samples[len(samples) / 2]
for (sql, _ignore_interval) in data:
statements.append(self.normalize(sql))
return '\n'.join(statements) + '\n'
class Bytes(_Statistic):
def squash(self, samples):
return [sum(bytes) for bytes in samples]
def summarize(self, samples):
return _Statistic.summarize(self, self.squash(samples))
def quantize(data):
"""
Given some continuous data, quantize it into appropriately sized
discrete buckets (eg, as would be suitable for constructing a
histogram of the values).
"""
# buckets = {}
return []
class IPopulation(Interface):
def sample(): # @NoSelf
pass
class UniformDiscreteDistribution(object, FancyEqMixin):
"""
"""
implements(IPopulation)
compareAttributes = ['_values']
def __init__(self, values, randomize=True):
self._values = values
self._randomize = randomize
self._refill()
def _refill(self):
self._remaining = self._values[:]
if self._randomize:
random.shuffle(self._remaining)
def sample(self):
if not self._remaining:
self._refill()
return self._remaining.pop()
class LogNormalDistribution(object, FancyEqMixin):
"""
"""
implements(IPopulation)
compareAttributes = ['_mu', '_sigma', '_maximum']
def __init__(self, mu=None, sigma=None, mean=None, mode=None, median=None, maximum=None):
if mu is not None and sigma is not None:
scale = 1.0
elif not (mu is None and sigma is None):
raise ValueError("mu and sigma must both be defined or both not defined")
elif mode is None:
raise ValueError("When mu and sigma are not defined, mode must be defined")
elif median is not None:
scale = mode
median /= float(mode)
mode = 1.0
mu = log(median)
sigma = sqrt(log(median) - log(mode))
elif mean is not None:
scale = mode
mean /= float(mode)
mode = 1.0
mu = log(mean) + log(mode) / 2.0
sigma = sqrt(log(mean) - log(mode) / 2.0)
else:
raise ValueError("When using mode one of median or mean must be defined")
self._mode = mode
self._median = median
self._mu = mu
self._sigma = sigma
self._scale = scale
self._maximum = maximum
def sample(self):
result = self._scale * random.lognormvariate(self._mu, self._sigma)
if self._maximum is not None and result > self._maximum:
for _ignore in range(10):
result = self._scale * random.lognormvariate(self._mu, self._sigma)
if result <= self._maximum:
break
else:
raise ValueError("Unable to generate LogNormalDistribution sample within required range")
return result
class FixedDistribution(object, FancyEqMixin):
"""
"""
implements(IPopulation)
compareAttributes = ['_value']
def __init__(self, value):
self._value = value
def sample(self):
return self._value
class NearFutureDistribution(object, FancyEqMixin):
compareAttributes = ['_offset']
def __init__(self):
self._offset = LogNormalDistribution(7, 0.8)
def sample(self):
now = DateTime.getNowUTC()
now.offsetSeconds(int(self._offset.sample()))
return now
class NormalDistribution(object, FancyEqMixin):
compareAttributes = ['_mu', '_sigma']
def __init__(self, mu, sigma):
self._mu = mu
self._sigma = sigma
def sample(self):
# Only return positive values or zero
v = random.normalvariate(self._mu, self._sigma)
while v < 0:
v = random.normalvariate(self._mu, self._sigma)
return v
class UniformIntegerDistribution(object, FancyEqMixin):
compareAttributes = ['_min', '_max']
def __init__(self, min, max):
self._min = min
self._max = max
def sample(self):
return int(random.uniform(self._min, self._max))
NUM_WEEKDAYS = 7
class WorkDistribution(object, FancyEqMixin):
compareAttributes = ["_daysOfWeek", "_beginHour", "_endHour"]
_weekdayNames = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
def __init__(self, daysOfWeek=["mon", "tue", "wed", "thu", "fri"], beginHour=8, endHour=17, tzname="UTC"):
self._daysOfWeek = [self._weekdayNames.index(day) for day in daysOfWeek]
self._beginHour = beginHour
self._endHour = endHour
self._tzname = tzname
self._helperDistribution = NormalDistribution(
# Mean 6 workdays in the future
60 * 60 * 8 * 6,
# Standard deviation of 4 workdays
60 * 60 * 8 * 4)
self.now = DateTime.getNow
def astimestamp(self, dt):
return mktime(dt.timetuple())
def _findWorkAfter(self, when):
"""
Return a two-tuple of the start and end of work hours following
C{when}. If C{when} falls within work hours, then the start time will
be equal to when.
"""
# Find a workday that follows the timestamp
weekday = when.getDayOfWeek()
for i in range(NUM_WEEKDAYS):
day = when + PyDuration(days=i)
if (weekday + i) % NUM_WEEKDAYS in self._daysOfWeek:
# Joy, a day on which work might occur. Find the first hour on
# this day when work may start.
day.setHHMMSS(self._beginHour, 0, 0)
begin = day
end = begin.duplicate()
end.setHHMMSS(self._endHour, 0, 0)
if end > when:
return begin, end
def sample(self):
offset = PyDuration(seconds=int(self._helperDistribution.sample()))
beginning = self.now(Timezone(tzid=self._tzname))
while offset:
start, end = self._findWorkAfter(beginning)
if end - start > offset:
result = start + offset
result.setMinutes(result.getMinutes() // 15 * 15)
result.setSeconds(0)
return result
offset.setDuration(offset.getTotalSeconds() - (end - start).getTotalSeconds())
beginning = end
class RecurrenceDistribution(object, FancyEqMixin):
compareAttributes = ["_allowRecurrence", "_weights"]
_model_rrules = {
"none": None,
"daily": "RRULE:FREQ=DAILY",
"weekly": "RRULE:FREQ=WEEKLY",
"monthly": "RRULE:FREQ=MONTHLY",
"yearly": "RRULE:FREQ=YEARLY",
"dailylimit": "RRULE:FREQ=DAILY;COUNT=14",
"weeklylimit": "RRULE:FREQ=WEEKLY;COUNT=4",
"workdays": "RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"
}
def __init__(self, allowRecurrence, weights={}):
self._allowRecurrence = allowRecurrence
self._rrules = []
if self._allowRecurrence:
for rrule, count in sorted(weights.items(), key=lambda x: x[0]):
for _ignore in range(count):
self._rrules.append(self._model_rrules[rrule])
self._helperDistribution = UniformIntegerDistribution(0, len(self._rrules) - 1)
def sample(self):
if self._allowRecurrence:
index = self._helperDistribution.sample()
rrule = self._rrules[index]
if rrule:
prop = Property.parseText(rrule)
return prop
return None