1 from __future__ import absolute_import, division
8 def median(x, use_float=True):
9 # there exist better algorithms...
12 raise ValueError('empty sequence!')
13 left = (len(y) - 1)//2
15 sum = y[left] + y[right]
40 def clip(x, (low, high)):
56 raise ValueError('p must be in the interval (0.0, 1.0]')
59 return int(math.log1p(-random.random()) / math.log1p(-p)) + 1
61 def add_dicts(*dicts):
64 for k, v in d.iteritems():
65 res[k] = res.get(k, 0) + v
66 return dict((k, v) for k, v in res.iteritems() if v)
71 while x >= 100000 and count < len(prefixes) - 2:
74 s = '' if count == 0 else prefixes[count - 1]
75 return '%i' % (x,) + s
78 for value, name in [(60*60*24, 'days'), (60*60, 'hours'), (60, 'minutes'), (1, 'seconds')]:
81 return '%.01f %s' % (dt/value, name)
83 perfect_round = lambda x: int(x + random.random())
102 y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
103 return sign*y # erf(-x) = -erf(x)
105 def find_root(y_over_dy, start, steps=10, bounds=(None, None)):
107 for i in xrange(steps):
108 prev, guess = guess, guess - y_over_dy(guess)
109 if bounds[0] is not None and guess < bounds[0]: guess = bounds[0]
110 if bounds[1] is not None and guess > bounds[1]: guess = bounds[1]
116 return find_root(lambda x: (erf(x) - z)/(2*math.e**(-x**2)/math.sqrt(math.pi)), 0)
119 from scipy import special
121 print 'Install SciPy for more accurate confidence intervals!'
122 def binomial_conf_interval(x, n, conf=0.95):
123 assert 0 <= x <= n and 0 <= conf < 1
125 left = random.random()*(1 - conf)
126 # approximate - Wilson score interval
127 z = math.sqrt(2)*ierf(conf)
130 topb = z * math.sqrt(p*(1-p)/n + z**2/4/n**2)
132 return (topa - topb)/bottom, (topa + topb)/bottom
134 def binomial_conf_interval(x, n, conf=0.95):
135 assert 0 <= x <= n and 0 <= conf < 1
137 left = random.random()*(1 - conf)
138 return left, left + conf
139 bl = float(special.betaln(x+1, n-x+1))
141 left, right = max(1e-8, float(special.betaincinv(x+1, n-x+1, left_a))), min(1-1e-8, float(special.betaincinv(x+1, n-x+1, left_a + conf)))
142 top = math.exp(math.log(right)*(x+1) + math.log(1-right)*(n-x+1) + math.log(left) + math.log(1-left) - bl) - math.exp(math.log(left)*(x+1) + math.log(1-left)*(n-x+1) + math.log(right) + math.log(1-right) - bl)
143 bottom = (x - n*right)*left*(1-left) - (x - n*left)*right*(1-right)
145 left_a = find_root(f, (1-conf)/2, bounds=(0, 1-conf))
146 return float(special.betaincinv(x+1, n-x+1, left_a)), float(special.betaincinv(x+1, n-x+1, left_a + conf))
148 def binomial_conf_center_radius(x, n, conf=0.95):
149 assert 0 <= x <= n and 0 <= conf < 1
150 left, right = binomial_conf_interval(x, n, conf)
152 return (left+right)/2, (right-left)/2
154 return p, max(p - left, right - p)
156 minmax = lambda x: (min(x), max(x))
158 def format_binomial_conf(x, n, conf=0.95, f=lambda x: x):
161 left, right = minmax(map(f, binomial_conf_interval(x, n, conf)))
162 return '~%.1f%% (%.f-%.f%%)' % (100*f(x/n), math.floor(100*left), math.ceil(100*right))
166 return __builtin__.reversed(x)
168 return reversed(list(x))
170 class Object(object):
171 def __init__(self, **kwargs):
172 for k, v in kwargs.iteritems():
175 def add_tuples(res, *tuples):
177 if len(t) != len(res):
178 raise ValueError('tuples must all be the same length')
179 res = tuple(a + b for a, b in zip(res, t))
182 def flatten_linked_list(x):
187 def weighted_choice(choices):
188 choices = list((item, weight) for item, weight in choices)
189 target = random.randrange(sum(weight for item, weight in choices))
190 for item, weight in choices:
194 raise AssertionError()
196 def natural_to_string(n, alphabet=None):
198 raise TypeError('n must be a natural')
203 return s.decode('hex')
205 assert len(set(alphabet)) == len(alphabet)
208 n, x = divmod(n, len(alphabet))
209 res.append(alphabet[x])
213 def string_to_natural(s, alphabet=None):
215 assert not s.startswith('\x00')
216 return int(s.encode('hex'), 16) if s else 0
218 assert len(set(alphabet)) == len(alphabet)
219 assert not s.startswith(alphabet[0])
220 return sum(alphabet.index(char) * len(alphabet)**i for i, char in enumerate(reversed(s)))
222 class RateMonitor(object):
223 def __init__(self, max_lookback_time):
224 self.max_lookback_time = max_lookback_time
227 self.first_timestamp = None
230 start_time = time.time() - self.max_lookback_time
231 for i, (ts, datum) in enumerate(self.datums):
233 self.datums[:] = self.datums[i:]
236 def get_datums_in_last(self, dt=None):
238 dt = self.max_lookback_time
239 assert dt <= self.max_lookback_time
242 return [datum for ts, datum in self.datums if ts > now - dt], min(dt, now - self.first_timestamp) if self.first_timestamp is not None else 0
244 def add_datum(self, datum):
247 self.datums.append((t, datum))
248 if self.first_timestamp is None:
249 self.first_timestamp = t
251 if __name__ == '__main__':
255 print a, format(a) + 'H/s'
256 a = a * random.randrange(2, 5)