-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnoiseutils.py
273 lines (225 loc) · 8.81 KB
/
noiseutils.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
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
import math
import numpy as np
import os
import scipy.stats
# ------------------------------------------------------------
# COMBINE DATA AND NOISE ESTIMATE INTO A SIGNAL-TO-NOISE CUBE
# ------------------------------------------------------------
def snr_cube(data,
noise,
specaxis=0):
"""
Return a signal-to-noise ratio cube from data + noise
estimates. Accepts single-value noise, noise spectrum, noise map
or noise cube. This is mostly here to handle dimensions. It will
treat 1-d noise as a spectrum, 2-d noise as a spatial map, and
otherwise directly divide the two.
"""
# We have a single noise estimate
if len(noise) == 1:
snr = data / noise
return snr
# The noise and data match dimensions
if data.ndim == noise.ndim:
snr = data / noise
return snr
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Noise has lower dimensionality than data - consider two cases.
# If the noise is 1d assume that we have a spectrum and divide
# along the spectral axis. If the noise is 2d assume that we have
# a map and divide perpendicular to the spectral axis.
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Case of a noise spectrum
if noise.ndim == 1:
snr = data.copy()
for i in np.arange(data.shape[specaxis]):
if specaxis == 0:
if snr.ndim == 2:
snr[i,:] = data[i,:]/noise[i]
elif snr.ndim == 3:
snr[i,:,:] = data[i,:,:]/noise[i]
elif specaxis == 1:
if snr.ndim == 1:
snr[:,i] = data[:,i]/noise[i]
elif snr.ndim == 3:
snr[:,i,:] = data[:,i,:]/noise[i]
elif specaxis == 2:
# ... only possible with three dimensions
snr[:,:,i] = data[:,i,:]/noise[i]
# Case of a noise map
if noise.ndim == 2:
pass
# We should not be here
return []
# ------------------------------------------------------------
# EXTRACT A SINGLE NOISE VALUE
# ------------------------------------------------------------
def noise(
data,
method="ROBUST"):
"""
Calculate a single noise estimate for a vector.
"""
# Use a robust estimator (sigma clipping + M.A.D.)
if method == "ROBUST":
sig_thresh = \
sig_n_outliers(len(data),
n_out=1.0,
pos_only=True)
return sigma_rob(data[valid],
iterations=1,
thresh=sig_thresh)
# Use the M.A.D. only.
if method == "MAD":
return mad(data[valid])
# Default to the standard deviation
return numpy.std(data[not_noise == False])
# ------------------------------------------------------------
# EXTRACT A NOISE MAP
# ------------------------------------------------------------
def noise_map(data, signal=None, blank=None, method="ROBUST"):
"""
Calculate a two-dimensional noise estimate for the cube, giving
options for region to avoid and use of robust statistics.
"""
# TBD - could add a default estimate and require # of channels for
# estimation.
# Initialize a default blanking mask
if blank==None:
blank = np.isfinite(data) == False
# Identify valid data to estimate the noise
if signal==None:
valid = (blank == False)
else:
valid = ((blank == False) * (signal == False))
# initialize the output
noise_map = np.zeros((data.shape[0],data.shape[1]))
# Use a robust estimator (sigma clipping + M.A.D.)
if method == "ROBUST":
# work out expected sigma threshold for one outlier
n_spec = data.shape[2]
sig_thresh = sig_n_outliers(n_spec,
n_out=1.0,
pos_only=True)
for i in np.arange(data.shape[0]):
for j in np.arange(data.shape[1]):
noise_map[i,j] = sigma_rob((data[i,j])[valid[i,j]],
iterations=1,
thresh=sig_thresh)
return noise_map
# Use the median absolute deviation
if method == "MAD":
for i in np.arange(data.shape[0]):
for j in np.arange(data.shape[1]):
noise_map[i,j] = \
mad((data[i,j])[valid[i,j]])
return noise_map
# Default to standard deviation
for i in np.arange(data.shape[0]):
for j in np.arange(data.shape[1]):
noise_map[i,j] = np.std((data[i,j])[valid[i,j]])
return noise_map
# ------------------------------------------------------------
# DERIVE A NOISE SPECTRUM
# ------------------------------------------------------------
def noise_spec(data, signal=None, blank=None, method="ROBUST"):
"""
Work out the noise along the third dimension, giving options for
region to avoid and use of robust statistics.
"""
# TBD - could add a default estimate and require # of channels for
# estimation.
# Initialize a default blanking mask
if blank==None:
blank = np.isfinite(data) == False
# Identify valid data to estimate the noise
if signal==None:
valid = (blank == False)
else:
valid = ((blank == False) * (signal == False))
# Initialize output
noise_spec = np.zeros((data.shape[2]))
# Estimate via outlier rejection
if method=="ROBUST":
# work out expected sigma threshold for one outlier
n_spec = data.shape[0]*data.shape[1]
sig_thresh = sig_n_outliers(n_spec,
n_out=1.0,
pos_only=True)
for i in range(data.shape[2]):
noise_spec[i] = sigma_rob((data[:,:,i])[valid[:,:,i]],
iterations=1,
thresh=sig_thresh)
return noise_spec
# Estimate via median absolute deviation
if method=="MAD":
for i in range(data.shape[2]):
noise_spec[i] = \
mad((data[:,:,i])[valid[:,:,i]])
return noise_spec
# Default to standard deviation
for i in range(data.shape[2]):
noise_spec[i] = np.std((data[:,:,i])[valid[:,:,i]])
return noise_spec
# ------------------------------------------------------------
# DERIVE A NOISE CUBE
# ------------------------------------------------------------
def noise_cube(data, signal=None, blank=None, method="ROBUST",
smooth_map=None, smooth_spec=None):
"""
Work out the pixel-by-pixel noise estimates, treating the sky and
spectral dimensions as separable.
"""
from scipy.ndimage import median_filter
# First work out and take out the 2-d structure
nmap = noise_map(data, signal=signal, blank=blank, method=method)
if smooth_map != None:
nmap = median_filter(nmap, size=(smooth_map,smooth_map))
ndata = snr_cube(data, nmap)
nspec = noise_spec(ndata, signal=signal, blank=blank, method=method)
if smooth_spec != None:
nspec = median_filter(nspec, size=smooth_spec)
noise_cube = data.copy()
for i in range(noise_cube.shape[2]):
noise_cube[:,:,i,0] = nmap * nspec[i]
return noise_cube
# ------------------------------------------------------------
# STASTICS HELPER PROCEDURES
# ------------------------------------------------------------
def mad(data, sigma=True):
"""
Return the median absolute deviation.
"""
med = np.median(data)
mad = np.median(np.abs(data - med))
if sigma==False:
return mad
else:
return mad*1.4826
def sigma_rob(data, iterations=1, thresh=3.0):
"""
Iterative m.a.d. based sigma with positive outlier rejection.
"""
noise = mad(data)
for i in range(iterations):
ind = (data <= thresh*noise).nonzero()
noise = mad(data[ind])
return noise
def sig_n_outliers(n_data, n_out=1.0, pos_only=True):
"""
Return the sigma needed to expect n (default 1) outliers given
n_data points.
"""
perc = float(n_out)/float(n_data)
if pos_only == False:
perc *= 2.0
return abs(scipy.stats.norm.ppf(perc))
# ------------------------------------------------------------
# TBD
# ------------------------------------------------------------
# Commentary: in theory the masked array class inside of numpy should
# expedite handling of blanked data (similarly the
# scipy.stats.nanmedian or nanstd functions). However, the masked
# array median operator seems to be either broken or infeasibly
# slow. This forces us into loops, which (shockingly) work out to be
# the fastest of the ways I have tried, but are still far from good.