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)):
48 add_to_range = lambda x, (low, high): (min(low, x), max(high, x))
58 raise ValueError('p must be in the interval (0.0, 1.0]')
61 return int(math.log1p(-random.random()) / math.log1p(-p)) + 1
63 def add_dicts_ext(add_func=lambda a, b: a+b, zero=0):
64 def add_dicts(*dicts):
67 for k, v in d.iteritems():
68 res[k] = add_func(res.get(k, zero), v)
69 return dict((k, v) for k, v in res.iteritems() if v != zero)
71 add_dicts = add_dicts_ext()
73 mult_dict = lambda c, x: dict((k, c*v) for k, v in x.iteritems())
78 while x >= 100000 and count < len(prefixes) - 2:
81 s = '' if count == 0 else prefixes[count - 1]
82 return '%i' % (x,) + s
86 (365.2425*60*60*24, 'years'),
94 return '%.01f %s' % (dt/value, name)
96 perfect_round = lambda x: int(x + random.random())
115 y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
116 return sign*y # erf(-x) = -erf(x)
118 def find_root(y_over_dy, start, steps=10, bounds=(None, None)):
120 for i in xrange(steps):
121 prev, guess = guess, guess - y_over_dy(guess)
122 if bounds[0] is not None and guess < bounds[0]: guess = bounds[0]
123 if bounds[1] is not None and guess > bounds[1]: guess = bounds[1]
129 return find_root(lambda x: (erf(x) - z)/(2*math.e**(-x**2)/math.sqrt(math.pi)), 0)
131 def binomial_conf_interval(x, n, conf=0.95):
132 assert 0 <= x <= n and 0 <= conf < 1
134 left = random.random()*(1 - conf)
135 return left, left + conf
136 # approximate - Wilson score interval
137 z = math.sqrt(2)*ierf(conf)
140 topb = z * math.sqrt(p*(1-p)/n + z**2/4/n**2)
142 return [clip(x, (0, 1)) for x in add_to_range(x/n, [(topa - topb)/bottom, (topa + topb)/bottom])]
144 minmax = lambda x: (min(x), max(x))
146 def format_binomial_conf(x, n, conf=0.95, f=lambda x: x):
149 left, right = minmax(map(f, binomial_conf_interval(x, n, conf)))
150 return '~%.1f%% (%.f-%.f%%)' % (100*f(x/n), math.floor(100*left), math.ceil(100*right))
154 return __builtin__.reversed(x)
156 return reversed(list(x))
158 class Object(object):
159 def __init__(self, **kwargs):
160 for k, v in kwargs.iteritems():
163 def add_tuples(res, *tuples):
165 if len(t) != len(res):
166 raise ValueError('tuples must all be the same length')
167 res = tuple(a + b for a, b in zip(res, t))
170 def flatten_linked_list(x):
175 def weighted_choice(choices):
176 choices = list((item, weight) for item, weight in choices)
177 target = random.randrange(sum(weight for item, weight in choices))
178 for item, weight in choices:
182 raise AssertionError()
184 def natural_to_string(n, alphabet=None):
186 raise TypeError('n must be a natural')
188 s = ('%x' % (n,)).lstrip('0')
191 return s.decode('hex')
193 assert len(set(alphabet)) == len(alphabet)
196 n, x = divmod(n, len(alphabet))
197 res.append(alphabet[x])
201 def string_to_natural(s, alphabet=None):
203 assert not s.startswith('\x00')
204 return int(s.encode('hex'), 16) if s else 0
206 assert len(set(alphabet)) == len(alphabet)
207 assert not s.startswith(alphabet[0])
208 return sum(alphabet.index(char) * len(alphabet)**i for i, char in enumerate(reversed(s)))
210 class RateMonitor(object):
211 def __init__(self, max_lookback_time):
212 self.max_lookback_time = max_lookback_time
215 self.first_timestamp = None
218 start_time = time.time() - self.max_lookback_time
219 for i, (ts, datum) in enumerate(self.datums):
221 self.datums[:] = self.datums[i:]
224 def get_datums_in_last(self, dt=None):
226 dt = self.max_lookback_time
227 assert dt <= self.max_lookback_time
230 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
232 def add_datum(self, datum):
235 if self.first_timestamp is None:
236 self.first_timestamp = t
238 self.datums.append((t, datum))
240 def merge_dicts(*dicts):
242 for d in dicts: res.update(d)