-
Notifications
You must be signed in to change notification settings - Fork 2
/
clipped_histogram.py
86 lines (64 loc) · 1.78 KB
/
clipped_histogram.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""Calculates mean and standard deviation of clipped distribution.
Examples
--------
>>> import clipped_histogram
>>> clipped_histogram.test()
References
----------
http://www.roe.ac.uk/~rsc/wsa/Epy_Wsa/wsatools.Statistics-pysrc.html#clippedHistogram
"""
# THIRD-PARTY
import numpy as np
def clippedHistogram(xx, clip=0, Niter=10, imean=0.0, isd=0.0):
"""
Parameters
----------
xx : array
Input array.
clip : float, optional
Clipping sigma.
Niter : int
Number of iterations.
imean, isd : float
Initial mean and sigma to use at the start of clipping.
Returns
-------
mean, sd : float
Clipped mean and sigma.
"""
xx = np.array(xx)
if xx.size < 2:
return 0.0, 0.0
if clip == 0.0:
mean = xx.mean()
sd = xx.std()
else:
not_test = True
it = 0
if imean == 0.0 and isd == 0.0:
mean = xx.mean()
sd = xx.std()
else:
mean, sd = imean, isd
while not_test and it < Niter:
meanold, sdold = mean, sd
minV = mean - clip * sd
maxV = mean + clip * sd
xx_mask = xx[(xx >= minV) & (xx <= maxV)]
mean = xx_mask.mean()
sd = xx_mask.std()
if mean == meanold and sd == sdold:
not_test = False
it += 1
return mean, sd
def test():
import matplotlib.pyplot as plt
xx = np.random.normal(0, 0.1, 1000)
mean, sd = clippedHistogram(xx, clip=3.0)
print 'Orig mean, sig =', xx.mean(), xx.std()
print 'Clipped mean, sig =', mean, sd
plt.hist(xx.ravel())
plt.axvline(mean, color='r', ls='-')
plt.axvline(sd, color='r', ls='--')
plt.axvline(-sd, color='r', ls='--')
plt.draw()