-
Notifications
You must be signed in to change notification settings - Fork 6
/
statutils.py
59 lines (50 loc) · 1.55 KB
/
statutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import sys
import numpy
from scipy.interpolate import interp1d
def bootstrap(vec, func, n_bootstraps):
results = list()
for i in xrange(n_bootstraps):
vec_bs = numpy.random.choice(vec, replace=True)
results.append(func(vec_bs))
return results
def inverse_quantile(x, y):
'''Calculates the location of each member of y in x
:param x:
:param y:
:return:
>>> inverse_quantile([1,2,3], 2.5).tolist()
0.75
>>> inverse_quantile([1,2,3], [2.5]).tolist()
[0.75]
>>> inverse_quantile([1,1,1], [0.99, 1, 1.01]).tolist()
[0.0, 0.5, 1.0]
>>> inverse_quantile([1], [0.5, 1.0, 1.5]).tolist()
[0.0, 0.5, 1.0]
>>> inverse_quantile([1, 2, 3], [[0.5, 1.0], [1.5, 2.5]]).tolist()
[[0.0, 0.0], [0.25, 0.75]]
'''
x = numpy.sort(x)
if not isinstance(y, numpy.ndarray):
y = numpy.array(y)
assert len(x.shape) == 1
if x[0] == x[-1]:
inv_q_y = numpy.ones_like(y) * float('nan')
if len(y.shape) == 0:
if inv_q_y == x[0]:
inv_q_y = 0.5
else:
inv_q_y[y == x[0]] = 0.5
else:
quantiles = numpy.linspace(0.0, 1.0, num=len(x), endpoint=True)
interp_func = interp1d(x, quantiles, bounds_error=False)
inv_q_y = interp_func(y)
if len(y.shape) == 0:
if y < x[0]:
inv_q_y = 0.0
elif y > x[-1]:
inv_q_y = 1.0
else:
inv_q_y[y < x[0]] = 0.0
inv_q_y[y > x[-1]] = 1.0
assert numpy.all(numpy.logical_not(numpy.isnan(y)))
return numpy.array(inv_q_y)