-
Notifications
You must be signed in to change notification settings - Fork 1
/
noise_filter.py
271 lines (200 loc) · 8.38 KB
/
noise_filter.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
import config as cf
import data_containers as dc
import pedestals as ped
import numpy as np
import numexpr as ne
import bottleneck as bn
from sklearn import linear_model
def define_ROI_ADC(thresh):
dc.mask = ne.evaluate( "where((data > thresh) | ~alive_chan, 0, 1)", global_dict={'data':dc.data, 'alive_chan':dc.alive_chan}).astype(bool)
def define_ROI(sig_thresh, iteration):
#ne.set_num_threads(4) #does not speed up things
""" Update the mask based on pedestal RMS """
for it in range(iteration):
ped.compute_pedestal_RMS()
dc.ped_rms = dc.ped_rms[:,:,:,None]
dc.ped_mean = dc.ped_mean[:,:,:,None]
dc.mask = ne.evaluate( "where((data > mean + sig_thresh*rms) | (~alive_chan), 0, 1)", global_dict={'data':dc.data, 'alive_chan':dc.alive_chan, 'rms':dc.ped_rms, 'mean':dc.ped_mean}).astype(bool)
dc.ped_rms = np.squeeze(dc.ped_rms, axis=3)
dc.ped_mean = np.squeeze(dc.ped_mean, axis=3)
def coherent_filter(groupings):
"""
1. Computes the mean along group of channels for non ROI points
2. Subtract mean to all points
"""
for group in groupings:
if( (cf.n_ChanPerCRP % group) > 0):
print(" Coherent Noise Filter in groups of ", group, " is not a possible ! ")
return
nslices = int(cf.n_ChanPerCRP / group)
dc.data = np.reshape(dc.data, (cf.n_CRPUsed, cf.n_View, nslices, group, cf.n_Sample))
dc.mask = np.reshape(dc.mask, (cf.n_CRPUsed, cf.n_View, nslices, group, cf.n_Sample))
"""sum data if mask is true"""
with np.errstate(divide='ignore', invalid='ignore'):
"""sum the data along the N channels (subscript l) if mask is true,
divide by nb of trues"""
mean = np.einsum('ijklm,ijklm->ijkm', dc.data, dc.mask)/dc.mask.sum(axis=3)
"""require at least 3 points to take into account the mean"""
mean[dc.mask.sum(axis=3) < 3] = 0.
"""Apply the correction to all data points"""
dc.data -= mean[:,:,:,None,:]
""" restore original data shape """
dc.data = np.reshape(dc.data, (cf.n_CRPUsed, cf.n_View, cf.n_ChanPerCRP, cf.n_Sample))
dc.mask = np.reshape(dc.mask, (cf.n_CRPUsed, cf.n_View, cf.n_ChanPerCRP, cf.n_Sample))
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def FFTLowPass(lowpass, freqlines) :
"""it's 5001 (n/2+1) points from 0Hz to 1./(2*sampling) = 1.25MHz (nyquist freq)"""
n = int(cf.n_Sample/2) + 1
rate = 1./cf.n_Sampling #in MHz
freq = np.linspace(0, rate/2., n)
"""define gaussian low pass filter"""
gauss_cut = np.where(freq < lowpass, 1., gaussian(freq, lowpass, 0.02))
"""go to frequency domain"""
fdata = np.fft.rfft(dc.data)
regr = linear_model.LinearRegression()
regi = linear_model.LinearRegression()
"""remove specific frequencies"""
# smooth the frequencies removed from prev and next freq. value (linear fit)
# still introduce artefacts - not recommended to use
for f in freqlines:
fbin = int(f * cf.n_Sample * cf.n_Sampling)
for icrp in range(cf.n_CRPUsed):
for iview in range(cf.n_View):
for ichan in range(cf.n_ChanPerCRP):
ptsx = []
ptsyr = []
ptsyi = []
for i in reversed(range(4)):
ptsx.append(fbin - 5 - i)
ptsyr.append(fdata[icrp, iview, ichan, fbin - 5 - i].real)
ptsyi.append(fdata[icrp, iview, ichan, fbin - 5 - i].imag)
for i in range(4):
ptsx.append(fbin + 5 + i)
ptsyr.append(fdata[icrp, iview, ichan, fbin + 5 + i].real)
ptsyi.append(fdata[icrp, iview, ichan, fbin + 5 + i].imag)
ptsx = np.asarray(ptsx).reshape(-1,1)
ptsyr = np.asarray(ptsyr)
ptsyi = np.asarray(ptsyi)
regr.fit(ptsx, ptsyr)
regi.fit(ptsx, ptsyi)
xtorm = np.asarray(range(fbin-4,fbin+5)).reshape(-1,1)
yvalr = regr.predict(xtorm)
yvali = regi.predict(xtorm)
for ib in range(9):
fdata[icrp,iview,ichan,fbin-4+ib] = complex(yvalr[ib], yvali[ib])
#gauss_cut[max(fbin-2,0):min(fbin+3,n)] = 0.2
#gauss_cut[max(fbin-1,0):min(fbin+2,n)] = 0.1
"""get power spectrum (before cut)"""
#ps = 10.*np.log10(np.abs(fdata)+1e-1)
"""Apply filter"""
fdata *= gauss_cut[None, None, None, :]
"""go back to time"""
dc.data = np.fft.irfft(fdata)
"""get power spectrum after cut"""
#ps = 10.*np.log10(np.abs(fdata)+1e-1)
#return ps
def FFT2D() :
for icrp in range(2):
for iview in range(2):
"""go to the 2D frequency domain"""
fft2D=np.fft.fft2(dc.data[icrp,iview,:,:])
'''x = np.linspace(0, 10000, 10000 )
y = np.linspace(0, 960, 960)
X, Y = np.meshgrid(x, y)'''
gmask = np.ones((960,10000))
"""Low Pass filter"""
for i in range(960):
gmask[i][400:9600]=0.
t=time.time()
"""Removing specific frequencies (different for each view and crp)"""
if icrp==0 and iview==0:
for i in range(5):
gmask[i][20:9980]=0
gmask[959-i][20:9980]=0
for i in range(13):
gmask[i][86:100]=0
gmask[i][9900:9913]=0
gmask[959-i][86:100]=0
gmask[959-i][9900:9913]=0
for i in range(40):
gmask[i][91:96]=0
gmask[i][9905:9909]=0
gmask[959-i][91:96]=0
gmask[959-i][9905:9909]=0
gmask[i][249:251]=0
gmask[i][9749:9751]=0
gmask[959-i][249:251]=0
gmask[959-i][9749:9751]=0
for i in range(100):
gmask[i][280:282]=0
gmask[i][9718:9721]=0
gmask[959-i][280:282]=0
gmask[959-i][9718:9721]=0
for i in range(40,920):
gmask[i][92:95]=0
gmask[i][9906:9908]=0
for i in range(3):
gmask[i][:]=0
gmask[959-i][:]=0
if icrp==0 and iview==1:
for i in range(5):
gmask[i][20:9980]=0
gmask[959-i][20:9980]=0
for i in range(30):
gmask[i][92:95]=0
gmask[i][9906:9908]=0
gmask[959-i][92:95]=0
gmask[959-i][9906:9908]=0
for i in range(2):
gmask[i][:]=0
gmask[959-i][:]=0
if icrp==1 and iview==0:
for i in range(5):
gmask[i][20:9980]=0
gmask[959-i][20:9980]=0
for i in range(30):
gmask[i][92:95]=0
gmask[i][9906:9908]=0
gmask[959-i][92:95]=0
gmask[959-i][9906:9908]=0
for i in range(2):
gmask[i][:]=0
gmask[959-i][:]=0
if icrp==1 and iview==1:
for i in range(5):
gmask[i][20:9980]=0
gmask[959-i][20:9980]=0
for i in range(30):
gmask[i][92:95]=0
gmask[i][9906:9908]=0
gmask[959-i][92:95]=0
gmask[959-i][9906:9908]=0
for i in range(2):
gmask[i][:]=0
gmask[959-i][:]=0
#gmask = np.where(gmask<0,0,gmask)
"""Apply the cuts"""
fft2D = fft2D * gmask
"""Go back in real space"""
filt = np.fft.ifft2(fft2D).real
dc.data[icrp,iview,:,:] = filt
print("Time to FFT2D: "+str(time.time()-t))
#return data #fft2D to see 2D frequency domain
def centered_median_filter(array, size):
""" pads the array such that the output is the centered sliding median"""
rsize = size - size // 2 - 1
array = np.pad(array, pad_width=((0, 0), (0, 0), (0, 0) , (0, rsize)),
mode='constant', constant_values=np.nan)
return bn.move_median(array, size, min_count=1, axis=-1)[:, :, :, rsize:]
def median_filter(window):
if(window < 0):
return
""" apply median filter on data to remove microphonic noise """
""" only on crp0 and crp1 to save some computing time"""
""" mask the data with nan where potential signal is (ROI)"""
med = centered_median_filter(np.where(dc.mask[0:2,:,:,:]==True, dc.data[0:2,:,:,:], np.nan), window)
""" in median computation, if everything is masked (all nan) nan is returnedso changed these cases to 0 """
med = np.nan_to_num(med, nan=0.)
""" apply correction to data points """
dc.data[0:2,:,:,:] -= med