forked from grzeimann/VIRUS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
309 lines (231 loc) · 8.64 KB
/
utils.py
File metadata and controls
309 lines (231 loc) · 8.64 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 18:12:13 2016
@author: gregz
"""
import numpy as np
from numpy import ma
from bspline import Bspline
import sys
def median_absolute_deviation(a, axis=None):
"""Compute the median absolute deviation.
Returns the median absolute deviation (MAD) of the array elements.
The MAD is defined as ``median(abs(a - median(a)))``.
Parameters
----------
a : array-like
Input array or object that can be converted to an array.
axis : tuple, optional
Axis along which the medians are computed. The default (axis=None)
is to compute the median along a flattened version of the array.
Returns
-------
median_absolute_deviation : ndarray
A new array holding the result. If the input contains
integers, or floats of smaller precision than 64, then the output
data-type is float64. Otherwise, the output data-type is the same
as that of the input.
Examples
--------
This will generate random variates from a Gaussian distribution and return
the median absolute deviation for that distribution::
>>> from utils import median_absolute_deviation
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> mad = median_absolute_deviation(randvar)
See Also
--------
numpy.median
Note
--------
Copy of the astropy function with the "axis" argument added appropriately.
"""
# Check if the array has a mask and if so use np.ma.median
# See https://github.com/numpy/numpy/issues/7330 why using np.ma.median
# for normal arrays should not be done (summary: np.ma.median always
# returns an masked array even if the result should be scalar). (#4658)
if isinstance(a, np.ma.MaskedArray):
func = np.ma.median
else:
func = np.median
a = np.asanyarray(a)
a_median = func(a, axis=axis)
# re-broadcast the output median array to subtract it
if axis is not None:
for i in axis:
a_median = np.expand_dims(a_median, axis=i)
# calculated the median average deviation
return func(np.abs(a - a_median), axis=axis)
def biweight_location(a, c=6.0, M=None, axis=None):
"""Compute the biweight location for an array.
Returns the biweight location for the array elements.
The biweight is a robust statistic for determining the central
location of a distribution.
The biweight location is given by the following equation
.. math::
C_{bl}= M+\\frac{\Sigma_{\|u_i\|<1} (x_i-M)(1-u_i^2)^2}
{\Sigma_{\|u_i\|<1} (1-u_i^2)^2}
where M is the sample mean or if run iterative the initial guess,
and u_i is given by
.. math::
u_{i} = \\frac{(x_i-M)}{cMAD}
where MAD is the median absolute deviation.
For more details, see Beers, Flynn, and Gebhardt, 1990, AJ, 100, 32B
Parameters
----------
a : array-like
Input array or object that can be converted to an array.
c : float, optional
Tuning constant for the biweight estimator. Default value is 6.0.
M : float, optional
Initial guess for the biweight location.
axis : tuple, optional
tuple of the integer axis values ot calculate over. Should be sorted.
Returns
-------
biweight_location : float
Returns the biweight location for the array elements.
Examples
--------
This will generate random variates from a Gaussian distribution and return
the biweight location of the distribution::
>>> from utils import biweight_location
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> cbl = biweight_location(randvar)
See Also
--------
median_absolute_deviation, biweight_midvariance
Note
--------
Copy of the astropy function with the "axis" argument added appropriately.
"""
a = np.array(a, copy=False)
if M is None:
if axis is None:
M = np.median(a)
else:
M = np.median(a, axis=axis)
N = M*1.
# set up the difference
if axis is not None:
for i in axis:
N = np.expand_dims(N, axis=i)
d = a - N
# set up the weighting
if axis is not None:
MAD = median_absolute_deviation(a, axis=axis)
for i in axis:
MAD = np.expand_dims(MAD, axis=i)
else:
MAD = median_absolute_deviation(a)
u = d / c / MAD
# now remove the outlier points
mask = ((np.abs(u) < 1) * (np.isfinite(u))).astype(np.int)
u = (1 - u ** 2) ** 2
return M + (d * u * mask).sum(axis=axis) / (u * mask).sum(axis=axis)
def biweight_midvariance(a, c=9.0, M=None, axis=None):
"""Compute the biweight midvariance for an array.
Returns the biweight midvariance for the array elements.
The biweight midvariance is a robust statistic for determining
the midvariance (i.e. the standard deviation) of a distribution.
The biweight location is given by the following equation
.. math::
C_{bl}= (n')^{1/2} \\frac{[\Sigma_{|u_i|<1} (x_i-M)^2(1-u_i^2)^4]^{0.5}}
{|\Sigma_{|u_i|<1} (1-u_i^2)(1-5u_i^2)|}
where :math:`u_i` is given by
.. math::
u_{i} = \\frac{(x_i-M)}{cMAD}
where MAD is the median absolute deviation.
:math:`n'` is the number of data for which :math:`|u_i| < 1` holds, while the
summations are over all i up to n:
.. math::
n' = \Sigma_{|u_i|<1}^n 1
This is slightly different than given in the reference below, but
results in a value closer to the true midvariance.
The midvariance parameter c is typically 9.0.
For more details, see Beers, Flynn, and Gebhardt, 1990, AJ, 100, 32B
Parameters
----------
a : array-like
Input array or object that can be converted to an array.
c : float
Tuning constant for the biweight estimator. Default value is 9.0.
M : float, optional
Initial guess for the biweight location.
axis : tuple, optional
tuple of the integer axis values ot calculate over. Should be sorted.
Returns
-------
biweight_midvariance : float
Returns the biweight midvariance for the array elements.
Examples
--------
This will generate random variates from a Gaussian distribution and return
the biweight midvariance of the distribution::
>>> from utils import biweight_midvariance
>>> from numpy.random import randn
>>> randvar = randn(10000)
>>> scl = biweight_midvariance(randvar)
See Also
--------
median_absolute_deviation, biweight_location
Note
--------
Copy of the astropy function with the "axis" argument added appropriately.
"""
a = np.array(a, copy=False)
if M is None:
if axis is None:
M = np.median(a)
else:
M = np.median(a, axis=axis)
N = M*1.
# set up the difference
if axis is not None:
for i in axis:
N = np.expand_dims(N, axis=i)
# set up the difference
d = a - N
# set up the weighting
if axis is not None:
MAD = median_absolute_deviation(a, axis=axis)
for i in axis:
MAD = np.expand_dims(MAD, axis=i)
else:
MAD = median_absolute_deviation(a)
# set up the weighting
u = d / c / MAD
# now remove the outlier points
mask = (np.abs(u) < 1).astype(np.int)
u = u ** 2
n = mask.sum(axis=axis)
return n ** 0.5 * ((d*mask)**2 * (1 - u * mask) ** 4).sum(axis=axis) ** 0.5\
/ np.abs(((1 - u * mask) * (1 - 5 * u * mask)).sum(axis=axis))
def is_outlier(points, thresh=3.5):
"""
Returns a boolean array with True if points are outliers and False
otherwise.
Parameters:
-----------
points : An numobservations by numdimensions array of observations
thresh : The modified z-score to use as a threshold. Observations with
a modified z-score (based on the median absolute deviation) greater
than this value will be classified as outliers.
Returns:
--------
mask : A numobservations-length boolean array.
References:
----------
Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and
Handle Outliers", The ASQC Basic References in Quality Control:
Statistical Techniques, Edward F. Mykytka, Ph.D., Editor.
"""
if len(points.shape) == 1:
points = points[:,None]
median = np.median(points, axis=0)
diff = np.sum((points - median)**2, axis=-1)
diff = np.sqrt(diff)
med_abs_deviation = np.median(diff)
modified_z_score = 0.6745 * diff / med_abs_deviation
return modified_z_score > thresh