added missing line to default binom_conf_interval for n=0 case
[p2pool.git] / p2pool / util / math.py
1 from __future__ import absolute_import, division
2
3 import __builtin__
4 import math
5 import random
6 import time
7
8 def median(x, use_float=True):
9     # there exist better algorithms...
10     y = sorted(x)
11     if not y:
12         raise ValueError('empty sequence!')
13     left = (len(y) - 1)//2
14     right = len(y)//2
15     sum = y[left] + y[right]
16     if use_float:
17         return sum/2
18     else:
19         return sum//2
20
21 def mean(x):
22     total = 0
23     count = 0
24     for y in x:
25         total += y
26         count += 1
27     return total/count
28
29 def shuffled(x):
30     x = list(x)
31     random.shuffle(x)
32     return x
33
34 def shift_left(n, m):
35     # python: :(
36     if m >= 0:
37         return n << m
38     return n >> -m
39
40 def clip(x, (low, high)):
41     if x < low:
42         return low
43     elif x > high:
44         return high
45     else:
46         return x
47
48 def nth(i, n=0):
49     i = iter(i)
50     for _ in xrange(n):
51         i.next()
52     return i.next()
53
54 def geometric(p):
55     if p <= 0 or p > 1:
56         raise ValueError('p must be in the interval (0.0, 1.0]')
57     if p == 1:
58         return 1
59     return int(math.log1p(-random.random()) / math.log1p(-p)) + 1
60
61 def add_dicts(*dicts):
62     res = {}
63     for d in 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)
67
68 def format(x):
69     prefixes = 'kMGTPEZY'
70     count = 0
71     while x >= 100000 and count < len(prefixes) - 2:
72         x = x//1000
73         count += 1
74     s = '' if count == 0 else prefixes[count - 1]
75     return '%i' % (x,) + s
76
77 def format_dt(dt):
78     for value, name in [(60*60*24, 'days'), (60*60, 'hours'), (60, 'minutes'), (1, 'seconds')]:
79         if dt > value:
80             break
81     return '%.01f %s' % (dt/value, name)
82
83 perfect_round = lambda x: int(x + random.random())
84
85 def erf(x):
86     # save the sign of x
87     sign = 1
88     if x < 0:
89         sign = -1
90     x = abs(x)
91     
92     # constants
93     a1 =  0.254829592
94     a2 = -0.284496736
95     a3 =  1.421413741
96     a4 = -1.453152027
97     a5 =  1.061405429
98     p  =  0.3275911
99     
100     # A&S formula 7.1.26
101     t = 1.0/(1.0 + p*x)
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)
104
105 def find_root(y_over_dy, start, steps=10, bounds=(None, None)):
106     guess = start
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]
111         if guess == prev:
112             break
113     return guess
114
115 def ierf(z):
116     return find_root(lambda x: (erf(x) - z)/(2*math.e**(-x**2)/math.sqrt(math.pi)), 0)
117
118 try:
119     from scipy import special
120 except ImportError:
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
124         if n == 0:
125             left = random.random()*(1 - conf)
126             return left, left + conf
127         # approximate - Wilson score interval
128         z = math.sqrt(2)*ierf(conf)
129         p = x/n
130         topa = p + z**2/2/n
131         topb = z * math.sqrt(p*(1-p)/n + z**2/4/n**2)
132         bottom = 1 + z**2/n
133         return (topa - topb)/bottom, (topa + topb)/bottom
134 else:
135     def binomial_conf_interval(x, n, conf=0.95):
136         assert 0 <= x <= n and 0 <= conf < 1
137         if n == 0:
138             left = random.random()*(1 - conf)
139             return left, left + conf
140         bl = float(special.betaln(x+1, n-x+1))
141         def f(left_a):
142             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)))
143             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)
144             bottom = (x - n*right)*left*(1-left) - (x - n*left)*right*(1-right)
145             return top/bottom
146         left_a = find_root(f, (1-conf)/2, bounds=(0, 1-conf))
147         return float(special.betaincinv(x+1, n-x+1, left_a)), float(special.betaincinv(x+1, n-x+1, left_a + conf))
148
149 minmax = lambda x: (min(x), max(x))
150
151 def format_binomial_conf(x, n, conf=0.95, f=lambda x: x):
152     if n == 0:
153         return '???'
154     left, right = minmax(map(f, binomial_conf_interval(x, n, conf)))
155     return '~%.1f%% (%.f-%.f%%)' % (100*f(x/n), math.floor(100*left), math.ceil(100*right))
156
157 def reversed(x):
158     try:
159         return __builtin__.reversed(x)
160     except TypeError:
161         return reversed(list(x))
162
163 class Object(object):
164     def __init__(self, **kwargs):
165         for k, v in kwargs.iteritems():
166             setattr(self, k, v)
167
168 def add_tuples(res, *tuples):
169     for t in tuples:
170         if len(t) != len(res):
171             raise ValueError('tuples must all be the same length')
172         res = tuple(a + b for a, b in zip(res, t))
173     return res
174
175 def flatten_linked_list(x):
176     while x is not None:
177         x, cur = x
178         yield cur
179
180 def weighted_choice(choices):
181     choices = list((item, weight) for item, weight in choices)
182     target = random.randrange(sum(weight for item, weight in choices))
183     for item, weight in choices:
184         if weight > target:
185             return item
186         target -= weight
187     raise AssertionError()
188
189 def natural_to_string(n, alphabet=None):
190     if n < 0:
191         raise TypeError('n must be a natural')
192     if alphabet is None:
193         s = '%x' % (n,)
194         if len(s) % 2:
195             s = '0' + s
196         return s.decode('hex')
197     else:
198         assert len(set(alphabet)) == len(alphabet)
199         res = []
200         while n:
201             n, x = divmod(n, len(alphabet))
202             res.append(alphabet[x])
203         res.reverse()
204         return ''.join(res)
205
206 def string_to_natural(s, alphabet=None):
207     if alphabet is None:
208         assert not s.startswith('\x00')
209         return int(s.encode('hex'), 16) if s else 0
210     else:
211         assert len(set(alphabet)) == len(alphabet)
212         assert not s.startswith(alphabet[0])
213         return sum(alphabet.index(char) * len(alphabet)**i for i, char in enumerate(reversed(s)))
214
215 class RateMonitor(object):
216     def __init__(self, max_lookback_time):
217         self.max_lookback_time = max_lookback_time
218         
219         self.datums = []
220         self.first_timestamp = None
221     
222     def _prune(self):
223         start_time = time.time() - self.max_lookback_time
224         for i, (ts, datum) in enumerate(self.datums):
225             if ts > start_time:
226                 self.datums[:] = self.datums[i:]
227                 return
228     
229     def get_datums_in_last(self, dt=None):
230         if dt is None:
231             dt = self.max_lookback_time
232         assert dt <= self.max_lookback_time
233         self._prune()
234         now = time.time()
235         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
236     
237     def add_datum(self, datum):
238         self._prune()
239         t = time.time()
240         self.datums.append((t, datum))
241         if self.first_timestamp is None:
242             self.first_timestamp = t
243
244 if __name__ == '__main__':
245     import random
246     a = 1
247     while True:
248         print a, format(a) + 'H/s'
249         a = a * random.randrange(2, 5)