added per-miner graphs
[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 mult_dict = lambda c, x: dict((k, c*v) for k, v in x.iteritems())
69
70 def format(x):
71     prefixes = 'kMGTPEZY'
72     count = 0
73     while x >= 100000 and count < len(prefixes) - 2:
74         x = x//1000
75         count += 1
76     s = '' if count == 0 else prefixes[count - 1]
77     return '%i' % (x,) + s
78
79 def format_dt(dt):
80     for value, name in [(60*60*24, 'days'), (60*60, 'hours'), (60, 'minutes'), (1, 'seconds')]:
81         if dt > value:
82             break
83     return '%.01f %s' % (dt/value, name)
84
85 perfect_round = lambda x: int(x + random.random())
86
87 def erf(x):
88     # save the sign of x
89     sign = 1
90     if x < 0:
91         sign = -1
92     x = abs(x)
93     
94     # constants
95     a1 =  0.254829592
96     a2 = -0.284496736
97     a3 =  1.421413741
98     a4 = -1.453152027
99     a5 =  1.061405429
100     p  =  0.3275911
101     
102     # A&S formula 7.1.26
103     t = 1.0/(1.0 + p*x)
104     y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
105     return sign*y # erf(-x) = -erf(x)
106
107 def find_root(y_over_dy, start, steps=10, bounds=(None, None)):
108     guess = start
109     for i in xrange(steps):
110         prev, guess = guess, guess - y_over_dy(guess)
111         if bounds[0] is not None and guess < bounds[0]: guess = bounds[0]
112         if bounds[1] is not None and guess > bounds[1]: guess = bounds[1]
113         if guess == prev:
114             break
115     return guess
116
117 def ierf(z):
118     return find_root(lambda x: (erf(x) - z)/(2*math.e**(-x**2)/math.sqrt(math.pi)), 0)
119
120 try:
121     from scipy import special
122 except ImportError:
123     def binomial_conf_interval(x, n, conf=0.95):
124         assert 0 <= x <= n and 0 <= conf < 1
125         if n == 0:
126             left = random.random()*(1 - conf)
127             return left, left + conf
128         # approximate - Wilson score interval
129         z = math.sqrt(2)*ierf(conf)
130         p = x/n
131         topa = p + z**2/2/n
132         topb = z * math.sqrt(p*(1-p)/n + z**2/4/n**2)
133         bottom = 1 + z**2/n
134         return (topa - topb)/bottom, (topa + topb)/bottom
135 else:
136     def binomial_conf_interval(x, n, conf=0.95):
137         assert 0 <= x <= n and 0 <= conf < 1
138         if n == 0:
139             left = random.random()*(1 - conf)
140             return left, left + conf
141         bl = float(special.betaln(x+1, n-x+1))
142         def f(left_a):
143             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)))
144             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)
145             bottom = (x - n*right)*left*(1-left) - (x - n*left)*right*(1-right)
146             return top/bottom
147         left_a = find_root(f, (1-conf)/2, bounds=(0, 1-conf))
148         return float(special.betaincinv(x+1, n-x+1, left_a)), float(special.betaincinv(x+1, n-x+1, left_a + conf))
149
150 minmax = lambda x: (min(x), max(x))
151
152 def format_binomial_conf(x, n, conf=0.95, f=lambda x: x):
153     if n == 0:
154         return '???'
155     left, right = minmax(map(f, binomial_conf_interval(x, n, conf)))
156     return '~%.1f%% (%.f-%.f%%)' % (100*f(x/n), math.floor(100*left), math.ceil(100*right))
157
158 def reversed(x):
159     try:
160         return __builtin__.reversed(x)
161     except TypeError:
162         return reversed(list(x))
163
164 class Object(object):
165     def __init__(self, **kwargs):
166         for k, v in kwargs.iteritems():
167             setattr(self, k, v)
168
169 def add_tuples(res, *tuples):
170     for t in tuples:
171         if len(t) != len(res):
172             raise ValueError('tuples must all be the same length')
173         res = tuple(a + b for a, b in zip(res, t))
174     return res
175
176 def flatten_linked_list(x):
177     while x is not None:
178         x, cur = x
179         yield cur
180
181 def weighted_choice(choices):
182     choices = list((item, weight) for item, weight in choices)
183     target = random.randrange(sum(weight for item, weight in choices))
184     for item, weight in choices:
185         if weight > target:
186             return item
187         target -= weight
188     raise AssertionError()
189
190 def natural_to_string(n, alphabet=None):
191     if n < 0:
192         raise TypeError('n must be a natural')
193     if alphabet is None:
194         s = '%x' % (n,)
195         if len(s) % 2:
196             s = '0' + s
197         return s.decode('hex')
198     else:
199         assert len(set(alphabet)) == len(alphabet)
200         res = []
201         while n:
202             n, x = divmod(n, len(alphabet))
203             res.append(alphabet[x])
204         res.reverse()
205         return ''.join(res)
206
207 def string_to_natural(s, alphabet=None):
208     if alphabet is None:
209         assert not s.startswith('\x00')
210         return int(s.encode('hex'), 16) if s else 0
211     else:
212         assert len(set(alphabet)) == len(alphabet)
213         assert not s.startswith(alphabet[0])
214         return sum(alphabet.index(char) * len(alphabet)**i for i, char in enumerate(reversed(s)))
215
216 class RateMonitor(object):
217     def __init__(self, max_lookback_time):
218         self.max_lookback_time = max_lookback_time
219         
220         self.datums = []
221         self.first_timestamp = None
222     
223     def _prune(self):
224         start_time = time.time() - self.max_lookback_time
225         for i, (ts, datum) in enumerate(self.datums):
226             if ts > start_time:
227                 self.datums[:] = self.datums[i:]
228                 return
229     
230     def get_datums_in_last(self, dt=None):
231         if dt is None:
232             dt = self.max_lookback_time
233         assert dt <= self.max_lookback_time
234         self._prune()
235         now = time.time()
236         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
237     
238     def add_datum(self, datum):
239         self._prune()
240         t = time.time()
241         self.datums.append((t, datum))
242         if self.first_timestamp is None:
243             self.first_timestamp = t
244
245 if __name__ == '__main__':
246     import random
247     a = 1
248     while True:
249         print a, format(a) + 'H/s'
250         a = a * random.randrange(2, 5)