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