##// END OF EJS Templates
Operando clean Rayleigh con crossSpectra
joabAM -
r1392:e987b2f0c1da
parent child
Show More
@@ -1,712 +1,727
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Distributed under the terms of the BSD 3-clause license.
4 # Distributed under the terms of the BSD 3-clause license.
5 """Classes to plot Spectra data
5 """Classes to plot Spectra data
6
6
7 """
7 """
8
8
9 import os
9 import os
10 import numpy
10 import numpy
11
11
12 from schainpy.model.graphics.jroplot_base import Plot, plt, log
12 from schainpy.model.graphics.jroplot_base import Plot, plt, log
13
13
14
14
15 class SpectraPlot(Plot):
15 class SpectraPlot(Plot):
16 '''
16 '''
17 Plot for Spectra data
17 Plot for Spectra data
18 '''
18 '''
19
19
20 CODE = 'spc'
20 CODE = 'spc'
21 colormap = 'jet'
21 colormap = 'jet'
22 plot_type = 'pcolor'
22 plot_type = 'pcolor'
23 buffering = False
23 buffering = False
24 channelList = []
24 channelList = []
25
25
26 def setup(self):
26 def setup(self):
27 self.nplots = len(self.data.channels)
27 self.nplots = len(self.data.channels)
28 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
28 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
29 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
29 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
30 self.height = 2.6 * self.nrows
30 self.height = 2.6 * self.nrows
31
31
32 self.cb_label = 'dB'
32 self.cb_label = 'dB'
33 if self.showprofile:
33 if self.showprofile:
34 self.width = 4 * self.ncols
34 self.width = 4 * self.ncols
35 else:
35 else:
36 self.width = 3.5 * self.ncols
36 self.width = 3.5 * self.ncols
37 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.08})
37 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.08})
38 self.ylabel = 'Range [km]'
38 self.ylabel = 'Range [km]'
39
39
40 def update(self, dataOut):
40 def update(self, dataOut):
41 if self.channelList == None:
41 if self.channelList == None:
42 self.channelList = dataOut.channelList
42 self.channelList = dataOut.channelList
43 data = {}
43 data = {}
44 meta = {}
44 meta = {}
45 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
45 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
46 data['spc'] = spc
46 data['spc'] = spc
47 data['rti'] = dataOut.getPower()
47 data['rti'] = dataOut.getPower()
48 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
48 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
49 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
49 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
50 if self.CODE == 'spc_moments':
50 if self.CODE == 'spc_moments':
51 data['moments'] = dataOut.moments
51 data['moments'] = dataOut.moments
52
52
53 return data, meta
53 return data, meta
54
54
55 def plot(self):
55 def plot(self):
56 if self.xaxis == "frequency":
56 if self.xaxis == "frequency":
57 x = self.data.xrange[0]
57 x = self.data.xrange[0]
58 self.xlabel = "Frequency (kHz)"
58 self.xlabel = "Frequency (kHz)"
59 elif self.xaxis == "time":
59 elif self.xaxis == "time":
60 x = self.data.xrange[1]
60 x = self.data.xrange[1]
61 self.xlabel = "Time (ms)"
61 self.xlabel = "Time (ms)"
62 else:
62 else:
63 x = self.data.xrange[2]
63 x = self.data.xrange[2]
64 self.xlabel = "Velocity (m/s)"
64 self.xlabel = "Velocity (m/s)"
65
65
66 if self.CODE == 'spc_moments':
66 if self.CODE == 'spc_moments':
67 x = self.data.xrange[2]
67 x = self.data.xrange[2]
68 self.xlabel = "Velocity (m/s)"
68 self.xlabel = "Velocity (m/s)"
69
69
70 self.titles = []
70 self.titles = []
71
71
72 y = self.data.yrange
72 y = self.data.yrange
73 self.y = y
73 self.y = y
74
74
75 data = self.data[-1]
75 data = self.data[-1]
76 z = data['spc']
76 z = data['spc']
77
77
78 for n, ax in enumerate(self.axes):
78 for n, ax in enumerate(self.axes):
79 noise = data['noise'][n]
79 noise = data['noise'][n]
80 if self.CODE == 'spc_moments':
80 if self.CODE == 'spc_moments':
81 mean = data['moments'][n, 1]
81 mean = data['moments'][n, 1]
82 if ax.firsttime:
82 if ax.firsttime:
83 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
83 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
84 self.xmin = self.xmin if self.xmin else -self.xmax
84 self.xmin = self.xmin if self.xmin else -self.xmax
85 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
85 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
86 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
86 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
87 ax.plt = ax.pcolormesh(x, y, z[n].T,
87 ax.plt = ax.pcolormesh(x, y, z[n].T,
88 vmin=self.zmin,
88 vmin=self.zmin,
89 vmax=self.zmax,
89 vmax=self.zmax,
90 cmap=plt.get_cmap(self.colormap)
90 cmap=plt.get_cmap(self.colormap)
91 )
91 )
92
92
93 if self.showprofile:
93 if self.showprofile:
94 ax.plt_profile = self.pf_axes[n].plot(
94 ax.plt_profile = self.pf_axes[n].plot(
95 data['rti'][n], y)[0]
95 data['rti'][n], y)[0]
96 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
96 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
97 color="k", linestyle="dashed", lw=1)[0]
97 color="k", linestyle="dashed", lw=1)[0]
98 if self.CODE == 'spc_moments':
98 if self.CODE == 'spc_moments':
99 ax.plt_mean = ax.plot(mean, y, color='k')[0]
99 ax.plt_mean = ax.plot(mean, y, color='k')[0]
100 else:
100 else:
101 ax.plt.set_array(z[n].T.ravel())
101 ax.plt.set_array(z[n].T.ravel())
102 if self.showprofile:
102 if self.showprofile:
103 ax.plt_profile.set_data(data['rti'][n], y)
103 ax.plt_profile.set_data(data['rti'][n], y)
104 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
104 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
105 if self.CODE == 'spc_moments':
105 if self.CODE == 'spc_moments':
106 ax.plt_mean.set_data(mean, y)
106 ax.plt_mean.set_data(mean, y)
107 self.titles.append('CH {}: {:3.2f}dB'.format(self.channelList[n], noise))
107 self.titles.append('CH {}: {:3.2f}dB'.format(self.channelList[n], noise))
108
108
109
109
110 class CrossSpectraPlot(Plot):
110 class CrossSpectraPlot(Plot):
111
111
112 CODE = 'cspc'
112 CODE = 'cspc'
113 colormap = 'jet'
113 colormap = 'jet'
114 plot_type = 'pcolor'
114 plot_type = 'pcolor'
115 zmin_coh = None
115 zmin_coh = None
116 zmax_coh = None
116 zmax_coh = None
117 zmin_phase = None
117 zmin_phase = None
118 zmax_phase = None
118 zmax_phase = None
119 realChannels = None
120 crossPairs = None
119
121
120 def setup(self):
122 def setup(self):
121
123
122 self.ncols = 4
124 self.ncols = 4
123 self.nplots = len(self.data.pairs) * 2
125 self.nplots = len(self.data.pairs) * 2
124 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
126 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
125 self.width = 3.1 * self.ncols
127 self.width = 3.1 * self.ncols
126 self.height = 2.6 * self.nrows
128 self.height = 2.6 * self.nrows
127 self.ylabel = 'Range [km]'
129 self.ylabel = 'Range [km]'
128 self.showprofile = False
130 self.showprofile = False
129 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
131 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
130
132
131 def update(self, dataOut):
133 def update(self, dataOut):
132
134
133 data = {}
135 data = {}
134 meta = {}
136 meta = {}
135
137
136 spc = dataOut.data_spc
138 spc = dataOut.data_spc
137 cspc = dataOut.data_cspc
139 cspc = dataOut.data_cspc
138 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
140 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
139 meta['pairs'] = dataOut.pairsList
141 rawPairs = list(combinations(list(range(dataOut.nChannels)), 2))
142 #print(rawPairs)
143 meta['pairs'] = rawPairs
144
145 if self.crossPairs == None:
146 self.crossPairs = dataOut.pairsList
140
147
141 tmp = []
148 tmp = []
142
149
143 for n, pair in enumerate(meta['pairs']):
150 for n, pair in enumerate(meta['pairs']):
151
144 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
152 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
145 coh = numpy.abs(out)
153 coh = numpy.abs(out)
146 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
154 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
147 tmp.append(coh)
155 tmp.append(coh)
148 tmp.append(phase)
156 tmp.append(phase)
149
157
150 data['cspc'] = numpy.array(tmp)
158 data['cspc'] = numpy.array(tmp)
151
159
152 return data, meta
160 return data, meta
153
161
154 def plot(self):
162 def plot(self):
155
163
156 if self.xaxis == "frequency":
164 if self.xaxis == "frequency":
157 x = self.data.xrange[0]
165 x = self.data.xrange[0]
158 self.xlabel = "Frequency (kHz)"
166 self.xlabel = "Frequency (kHz)"
159 elif self.xaxis == "time":
167 elif self.xaxis == "time":
160 x = self.data.xrange[1]
168 x = self.data.xrange[1]
161 self.xlabel = "Time (ms)"
169 self.xlabel = "Time (ms)"
162 else:
170 else:
163 x = self.data.xrange[2]
171 x = self.data.xrange[2]
164 self.xlabel = "Velocity (m/s)"
172 self.xlabel = "Velocity (m/s)"
165
173
166 self.titles = []
174 self.titles = []
167
175
168 y = self.data.yrange
176 y = self.data.yrange
169 self.y = y
177 self.y = y
170
178
171 data = self.data[-1]
179 data = self.data[-1]
172 cspc = data['cspc']
180 cspc = data['cspc']
173
181 #print(self.crossPairs)
174 for n in range(len(self.data.pairs)):
182 for n in range(len(self.data.pairs)):
175 pair = self.data.pairs[n]
183 #pair = self.data.pairs[n]
184 pair = self.crossPairs[n]
185
176 coh = cspc[n*2]
186 coh = cspc[n*2]
177 phase = cspc[n*2+1]
187 phase = cspc[n*2+1]
178 ax = self.axes[2 * n]
188 ax = self.axes[2 * n]
189
179 if ax.firsttime:
190 if ax.firsttime:
180 ax.plt = ax.pcolormesh(x, y, coh.T,
191 ax.plt = ax.pcolormesh(x, y, coh.T,
181 vmin=0,
192 vmin=0,
182 vmax=1,
193 vmax=1,
183 cmap=plt.get_cmap(self.colormap_coh)
194 cmap=plt.get_cmap(self.colormap_coh)
184 )
195 )
185 else:
196 else:
186 ax.plt.set_array(coh.T.ravel())
197 ax.plt.set_array(coh.T.ravel())
187 self.titles.append(
198 self.titles.append(
188 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
199 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
189
200
190 ax = self.axes[2 * n + 1]
201 ax = self.axes[2 * n + 1]
191 if ax.firsttime:
202 if ax.firsttime:
192 ax.plt = ax.pcolormesh(x, y, phase.T,
203 ax.plt = ax.pcolormesh(x, y, phase.T,
193 vmin=-180,
204 vmin=-180,
194 vmax=180,
205 vmax=180,
195 cmap=plt.get_cmap(self.colormap_phase)
206 cmap=plt.get_cmap(self.colormap_phase)
196 )
207 )
197 else:
208 else:
198 ax.plt.set_array(phase.T.ravel())
209 ax.plt.set_array(phase.T.ravel())
199 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
210 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
200
211
201
212
202 class RTIPlot(Plot):
213 class RTIPlot(Plot):
203 '''
214 '''
204 Plot for RTI data
215 Plot for RTI data
205 '''
216 '''
206
217
207 CODE = 'rti'
218 CODE = 'rti'
208 colormap = 'jet'
219 colormap = 'jet'
209 plot_type = 'pcolorbuffer'
220 plot_type = 'pcolorbuffer'
210 titles = None
221 titles = None
211 channelList = []
222 channelList = []
212
223
213 def setup(self):
224 def setup(self):
214 self.xaxis = 'time'
225 self.xaxis = 'time'
215 self.ncols = 1
226 self.ncols = 1
216 print("dataChannels ",self.data.channels)
227 print("dataChannels ",self.data.channels)
217 self.nrows = len(self.data.channels)
228 self.nrows = len(self.data.channels)
218 self.nplots = len(self.data.channels)
229 self.nplots = len(self.data.channels)
219 self.ylabel = 'Range [km]'
230 self.ylabel = 'Range [km]'
220 self.xlabel = 'Time'
231 self.xlabel = 'Time'
221 self.cb_label = 'dB'
232 self.cb_label = 'dB'
222 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95})
233 self.plots_adjust.update({'hspace':0.8, 'left': 0.1, 'bottom': 0.08, 'right':0.95})
223 self.titles = ['{} Channel {}'.format(
234 self.titles = ['{} Channel {}'.format(
224 self.CODE.upper(), x) for x in range(self.nplots)]
235 self.CODE.upper(), x) for x in range(self.nplots)]
225 print("SETUP")
236 print("SETUP")
226 def update(self, dataOut):
237 def update(self, dataOut):
227 if len(self.channelList) == 0:
238 if len(self.channelList) == 0:
228 self.channelList = dataOut.channelList
239 self.channelList = dataOut.channelList
229 data = {}
240 data = {}
230 meta = {}
241 meta = {}
231 data['rti'] = dataOut.getPower()
242 data['rti'] = dataOut.getPower()
232 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
243 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
233
244
234 return data, meta
245 return data, meta
235
246
236 def plot(self):
247 def plot(self):
237 self.x = self.data.times
248 self.x = self.data.times
238 self.y = self.data.yrange
249 self.y = self.data.yrange
239 self.z = self.data[self.CODE]
250 self.z = self.data[self.CODE]
240 self.z = numpy.ma.masked_invalid(self.z)
251 self.z = numpy.ma.masked_invalid(self.z)
241 if self.channelList != None:
252 try:
242 self.titles = ['{} Channel {}'.format(
253 if self.channelList != None:
243 self.CODE.upper(), x) for x in self.channelList]
254 self.titles = ['{} Channel {}'.format(
244
255 self.CODE.upper(), x) for x in self.channelList]
256 except:
257 if self.channelList.any() != None:
258 self.titles = ['{} Channel {}'.format(
259 self.CODE.upper(), x) for x in self.channelList]
245 if self.decimation is None:
260 if self.decimation is None:
246 x, y, z = self.fill_gaps(self.x, self.y, self.z)
261 x, y, z = self.fill_gaps(self.x, self.y, self.z)
247 else:
262 else:
248 x, y, z = self.fill_gaps(*self.decimate())
263 x, y, z = self.fill_gaps(*self.decimate())
249
264
250 for n, ax in enumerate(self.axes):
265 for n, ax in enumerate(self.axes):
251 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
266 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
252 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
267 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
253 data = self.data[-1]
268 data = self.data[-1]
254 if ax.firsttime:
269 if ax.firsttime:
255 ax.plt = ax.pcolormesh(x, y, z[n].T,
270 ax.plt = ax.pcolormesh(x, y, z[n].T,
256 vmin=self.zmin,
271 vmin=self.zmin,
257 vmax=self.zmax,
272 vmax=self.zmax,
258 cmap=plt.get_cmap(self.colormap)
273 cmap=plt.get_cmap(self.colormap)
259 )
274 )
260 if self.showprofile:
275 if self.showprofile:
261 ax.plot_profile = self.pf_axes[n].plot(
276 ax.plot_profile = self.pf_axes[n].plot(
262 data['rti'][n], self.y)[0]
277 data['rti'][n], self.y)[0]
263 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
278 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
264 color="k", linestyle="dashed", lw=1)[0]
279 color="k", linestyle="dashed", lw=1)[0]
265 else:
280 else:
266 ax.collections.remove(ax.collections[0])
281 ax.collections.remove(ax.collections[0])
267 ax.plt = ax.pcolormesh(x, y, z[n].T,
282 ax.plt = ax.pcolormesh(x, y, z[n].T,
268 vmin=self.zmin,
283 vmin=self.zmin,
269 vmax=self.zmax,
284 vmax=self.zmax,
270 cmap=plt.get_cmap(self.colormap)
285 cmap=plt.get_cmap(self.colormap)
271 )
286 )
272 if self.showprofile:
287 if self.showprofile:
273 ax.plot_profile.set_data(data['rti'][n], self.y)
288 ax.plot_profile.set_data(data['rti'][n], self.y)
274 ax.plot_noise.set_data(numpy.repeat(
289 ax.plot_noise.set_data(numpy.repeat(
275 data['noise'][n], len(self.y)), self.y)
290 data['noise'][n], len(self.y)), self.y)
276
291
277
292
278 class CoherencePlot(RTIPlot):
293 class CoherencePlot(RTIPlot):
279 '''
294 '''
280 Plot for Coherence data
295 Plot for Coherence data
281 '''
296 '''
282
297
283 CODE = 'coh'
298 CODE = 'coh'
284
299
285 def setup(self):
300 def setup(self):
286 self.xaxis = 'time'
301 self.xaxis = 'time'
287 self.ncols = 1
302 self.ncols = 1
288 self.nrows = len(self.data.pairs)
303 self.nrows = len(self.data.pairs)
289 self.nplots = len(self.data.pairs)
304 self.nplots = len(self.data.pairs)
290 self.ylabel = 'Range [km]'
305 self.ylabel = 'Range [km]'
291 self.xlabel = 'Time'
306 self.xlabel = 'Time'
292 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
307 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
293 if self.CODE == 'coh':
308 if self.CODE == 'coh':
294 self.cb_label = ''
309 self.cb_label = ''
295 self.titles = [
310 self.titles = [
296 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
311 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
297 else:
312 else:
298 self.cb_label = 'Degrees'
313 self.cb_label = 'Degrees'
299 self.titles = [
314 self.titles = [
300 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
315 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
301
316
302 def update(self, dataOut):
317 def update(self, dataOut):
303
318
304 data = {}
319 data = {}
305 meta = {}
320 meta = {}
306 data['coh'] = dataOut.getCoherence()
321 data['coh'] = dataOut.getCoherence()
307 meta['pairs'] = dataOut.pairsList
322 meta['pairs'] = dataOut.pairsList
308
323
309 return data, meta
324 return data, meta
310
325
311 class PhasePlot(CoherencePlot):
326 class PhasePlot(CoherencePlot):
312 '''
327 '''
313 Plot for Phase map data
328 Plot for Phase map data
314 '''
329 '''
315
330
316 CODE = 'phase'
331 CODE = 'phase'
317 colormap = 'seismic'
332 colormap = 'seismic'
318
333
319 def update(self, dataOut):
334 def update(self, dataOut):
320
335
321 data = {}
336 data = {}
322 meta = {}
337 meta = {}
323 data['phase'] = dataOut.getCoherence(phase=True)
338 data['phase'] = dataOut.getCoherence(phase=True)
324 meta['pairs'] = dataOut.pairsList
339 meta['pairs'] = dataOut.pairsList
325
340
326 return data, meta
341 return data, meta
327
342
328 class NoisePlot(Plot):
343 class NoisePlot(Plot):
329 '''
344 '''
330 Plot for noise
345 Plot for noise
331 '''
346 '''
332
347
333 CODE = 'noise'
348 CODE = 'noise'
334 plot_type = 'scatterbuffer'
349 plot_type = 'scatterbuffer'
335
350
336 def setup(self):
351 def setup(self):
337 self.xaxis = 'time'
352 self.xaxis = 'time'
338 self.ncols = 1
353 self.ncols = 1
339 self.nrows = 1
354 self.nrows = 1
340 self.nplots = 1
355 self.nplots = 1
341 self.ylabel = 'Intensity [dB]'
356 self.ylabel = 'Intensity [dB]'
342 self.xlabel = 'Time'
357 self.xlabel = 'Time'
343 self.titles = ['Noise']
358 self.titles = ['Noise']
344 self.colorbar = False
359 self.colorbar = False
345 self.plots_adjust.update({'right': 0.85 })
360 self.plots_adjust.update({'right': 0.85 })
346
361
347 def update(self, dataOut):
362 def update(self, dataOut):
348
363
349 data = {}
364 data = {}
350 meta = {}
365 meta = {}
351 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor).reshape(dataOut.nChannels, 1)
366 data['noise'] = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor).reshape(dataOut.nChannels, 1)
352 meta['yrange'] = numpy.array([])
367 meta['yrange'] = numpy.array([])
353
368
354 return data, meta
369 return data, meta
355
370
356 def plot(self):
371 def plot(self):
357
372
358 x = self.data.times
373 x = self.data.times
359 xmin = self.data.min_time
374 xmin = self.data.min_time
360 xmax = xmin + self.xrange * 60 * 60
375 xmax = xmin + self.xrange * 60 * 60
361 Y = self.data['noise']
376 Y = self.data['noise']
362
377
363 if self.axes[0].firsttime:
378 if self.axes[0].firsttime:
364 self.ymin = numpy.nanmin(Y) - 5
379 self.ymin = numpy.nanmin(Y) - 5
365 self.ymax = numpy.nanmax(Y) + 5
380 self.ymax = numpy.nanmax(Y) + 5
366 for ch in self.data.channels:
381 for ch in self.data.channels:
367 y = Y[ch]
382 y = Y[ch]
368 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
383 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
369 plt.legend(bbox_to_anchor=(1.18, 1.0))
384 plt.legend(bbox_to_anchor=(1.18, 1.0))
370 else:
385 else:
371 for ch in self.data.channels:
386 for ch in self.data.channels:
372 y = Y[ch]
387 y = Y[ch]
373 self.axes[0].lines[ch].set_data(x, y)
388 self.axes[0].lines[ch].set_data(x, y)
374
389
375
390
376 class PowerProfilePlot(Plot):
391 class PowerProfilePlot(Plot):
377
392
378 CODE = 'pow_profile'
393 CODE = 'pow_profile'
379 plot_type = 'scatter'
394 plot_type = 'scatter'
380
395
381 def setup(self):
396 def setup(self):
382
397
383 self.ncols = 1
398 self.ncols = 1
384 self.nrows = 1
399 self.nrows = 1
385 self.nplots = 1
400 self.nplots = 1
386 self.height = 4
401 self.height = 4
387 self.width = 3
402 self.width = 3
388 self.ylabel = 'Range [km]'
403 self.ylabel = 'Range [km]'
389 self.xlabel = 'Intensity [dB]'
404 self.xlabel = 'Intensity [dB]'
390 self.titles = ['Power Profile']
405 self.titles = ['Power Profile']
391 self.colorbar = False
406 self.colorbar = False
392
407
393 def update(self, dataOut):
408 def update(self, dataOut):
394
409
395 data = {}
410 data = {}
396 meta = {}
411 meta = {}
397 data[self.CODE] = dataOut.getPower()
412 data[self.CODE] = dataOut.getPower()
398
413
399 return data, meta
414 return data, meta
400
415
401 def plot(self):
416 def plot(self):
402
417
403 y = self.data.yrange
418 y = self.data.yrange
404 self.y = y
419 self.y = y
405
420
406 x = self.data[-1][self.CODE]
421 x = self.data[-1][self.CODE]
407
422
408 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
423 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
409 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
424 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
410
425
411 if self.axes[0].firsttime:
426 if self.axes[0].firsttime:
412 for ch in self.data.channels:
427 for ch in self.data.channels:
413 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
428 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
414 plt.legend()
429 plt.legend()
415 else:
430 else:
416 for ch in self.data.channels:
431 for ch in self.data.channels:
417 self.axes[0].lines[ch].set_data(x[ch], y)
432 self.axes[0].lines[ch].set_data(x[ch], y)
418
433
419
434
420 class SpectraCutPlot(Plot):
435 class SpectraCutPlot(Plot):
421
436
422 CODE = 'spc_cut'
437 CODE = 'spc_cut'
423 plot_type = 'scatter'
438 plot_type = 'scatter'
424 buffering = False
439 buffering = False
425
440
426 def setup(self):
441 def setup(self):
427
442
428 self.nplots = len(self.data.channels)
443 self.nplots = len(self.data.channels)
429 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
444 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
430 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
445 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
431 self.width = 3.4 * self.ncols + 1.5
446 self.width = 3.4 * self.ncols + 1.5
432 self.height = 3 * self.nrows
447 self.height = 3 * self.nrows
433 self.ylabel = 'Power [dB]'
448 self.ylabel = 'Power [dB]'
434 self.colorbar = False
449 self.colorbar = False
435 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.75, 'bottom':0.08})
450 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.75, 'bottom':0.08})
436
451
437 def update(self, dataOut):
452 def update(self, dataOut):
438
453
439 data = {}
454 data = {}
440 meta = {}
455 meta = {}
441 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
456 spc = 10*numpy.log10(dataOut.data_spc/dataOut.normFactor)
442 data['spc'] = spc
457 data['spc'] = spc
443 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
458 meta['xrange'] = (dataOut.getFreqRange(1)/1000., dataOut.getAcfRange(1), dataOut.getVelRange(1))
444
459
445 return data, meta
460 return data, meta
446
461
447 def plot(self):
462 def plot(self):
448 if self.xaxis == "frequency":
463 if self.xaxis == "frequency":
449 x = self.data.xrange[0][1:]
464 x = self.data.xrange[0][1:]
450 self.xlabel = "Frequency (kHz)"
465 self.xlabel = "Frequency (kHz)"
451 elif self.xaxis == "time":
466 elif self.xaxis == "time":
452 x = self.data.xrange[1]
467 x = self.data.xrange[1]
453 self.xlabel = "Time (ms)"
468 self.xlabel = "Time (ms)"
454 else:
469 else:
455 x = self.data.xrange[2]
470 x = self.data.xrange[2]
456 self.xlabel = "Velocity (m/s)"
471 self.xlabel = "Velocity (m/s)"
457
472
458 self.titles = []
473 self.titles = []
459
474
460 y = self.data.yrange
475 y = self.data.yrange
461 z = self.data[-1]['spc']
476 z = self.data[-1]['spc']
462
477
463 if self.height_index:
478 if self.height_index:
464 index = numpy.array(self.height_index)
479 index = numpy.array(self.height_index)
465 else:
480 else:
466 index = numpy.arange(0, len(y), int((len(y))/9))
481 index = numpy.arange(0, len(y), int((len(y))/9))
467
482
468 for n, ax in enumerate(self.axes):
483 for n, ax in enumerate(self.axes):
469 if ax.firsttime:
484 if ax.firsttime:
470 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
485 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
471 self.xmin = self.xmin if self.xmin else -self.xmax
486 self.xmin = self.xmin if self.xmin else -self.xmax
472 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
487 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
473 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
488 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
474 ax.plt = ax.plot(x, z[n, :, index].T)
489 ax.plt = ax.plot(x, z[n, :, index].T)
475 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
490 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
476 self.figures[0].legend(ax.plt, labels, loc='center right')
491 self.figures[0].legend(ax.plt, labels, loc='center right')
477 else:
492 else:
478 for i, line in enumerate(ax.plt):
493 for i, line in enumerate(ax.plt):
479 line.set_data(x, z[n, :, index[i]])
494 line.set_data(x, z[n, :, index[i]])
480 self.titles.append('CH {}'.format(n))
495 self.titles.append('CH {}'.format(n))
481
496
482
497
483 class BeaconPhase(Plot):
498 class BeaconPhase(Plot):
484
499
485 __isConfig = None
500 __isConfig = None
486 __nsubplots = None
501 __nsubplots = None
487
502
488 PREFIX = 'beacon_phase'
503 PREFIX = 'beacon_phase'
489
504
490 def __init__(self):
505 def __init__(self):
491 Plot.__init__(self)
506 Plot.__init__(self)
492 self.timerange = 24*60*60
507 self.timerange = 24*60*60
493 self.isConfig = False
508 self.isConfig = False
494 self.__nsubplots = 1
509 self.__nsubplots = 1
495 self.counter_imagwr = 0
510 self.counter_imagwr = 0
496 self.WIDTH = 800
511 self.WIDTH = 800
497 self.HEIGHT = 400
512 self.HEIGHT = 400
498 self.WIDTHPROF = 120
513 self.WIDTHPROF = 120
499 self.HEIGHTPROF = 0
514 self.HEIGHTPROF = 0
500 self.xdata = None
515 self.xdata = None
501 self.ydata = None
516 self.ydata = None
502
517
503 self.PLOT_CODE = BEACON_CODE
518 self.PLOT_CODE = BEACON_CODE
504
519
505 self.FTP_WEI = None
520 self.FTP_WEI = None
506 self.EXP_CODE = None
521 self.EXP_CODE = None
507 self.SUB_EXP_CODE = None
522 self.SUB_EXP_CODE = None
508 self.PLOT_POS = None
523 self.PLOT_POS = None
509
524
510 self.filename_phase = None
525 self.filename_phase = None
511
526
512 self.figfile = None
527 self.figfile = None
513
528
514 self.xmin = None
529 self.xmin = None
515 self.xmax = None
530 self.xmax = None
516
531
517 def getSubplots(self):
532 def getSubplots(self):
518
533
519 ncol = 1
534 ncol = 1
520 nrow = 1
535 nrow = 1
521
536
522 return nrow, ncol
537 return nrow, ncol
523
538
524 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
539 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
525
540
526 self.__showprofile = showprofile
541 self.__showprofile = showprofile
527 self.nplots = nplots
542 self.nplots = nplots
528
543
529 ncolspan = 7
544 ncolspan = 7
530 colspan = 6
545 colspan = 6
531 self.__nsubplots = 2
546 self.__nsubplots = 2
532
547
533 self.createFigure(id = id,
548 self.createFigure(id = id,
534 wintitle = wintitle,
549 wintitle = wintitle,
535 widthplot = self.WIDTH+self.WIDTHPROF,
550 widthplot = self.WIDTH+self.WIDTHPROF,
536 heightplot = self.HEIGHT+self.HEIGHTPROF,
551 heightplot = self.HEIGHT+self.HEIGHTPROF,
537 show=show)
552 show=show)
538
553
539 nrow, ncol = self.getSubplots()
554 nrow, ncol = self.getSubplots()
540
555
541 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
556 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
542
557
543 def save_phase(self, filename_phase):
558 def save_phase(self, filename_phase):
544 f = open(filename_phase,'w+')
559 f = open(filename_phase,'w+')
545 f.write('\n\n')
560 f.write('\n\n')
546 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
561 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
547 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
562 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
548 f.close()
563 f.close()
549
564
550 def save_data(self, filename_phase, data, data_datetime):
565 def save_data(self, filename_phase, data, data_datetime):
551 f=open(filename_phase,'a')
566 f=open(filename_phase,'a')
552 timetuple_data = data_datetime.timetuple()
567 timetuple_data = data_datetime.timetuple()
553 day = str(timetuple_data.tm_mday)
568 day = str(timetuple_data.tm_mday)
554 month = str(timetuple_data.tm_mon)
569 month = str(timetuple_data.tm_mon)
555 year = str(timetuple_data.tm_year)
570 year = str(timetuple_data.tm_year)
556 hour = str(timetuple_data.tm_hour)
571 hour = str(timetuple_data.tm_hour)
557 minute = str(timetuple_data.tm_min)
572 minute = str(timetuple_data.tm_min)
558 second = str(timetuple_data.tm_sec)
573 second = str(timetuple_data.tm_sec)
559 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
574 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
560 f.close()
575 f.close()
561
576
562 def plot(self):
577 def plot(self):
563 log.warning('TODO: Not yet implemented...')
578 log.warning('TODO: Not yet implemented...')
564
579
565 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
580 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
566 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
581 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
567 timerange=None,
582 timerange=None,
568 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
583 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
569 server=None, folder=None, username=None, password=None,
584 server=None, folder=None, username=None, password=None,
570 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
585 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
571
586
572 if dataOut.flagNoData:
587 if dataOut.flagNoData:
573 return dataOut
588 return dataOut
574
589
575 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
590 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
576 return
591 return
577
592
578 if pairsList == None:
593 if pairsList == None:
579 pairsIndexList = dataOut.pairsIndexList[:10]
594 pairsIndexList = dataOut.pairsIndexList[:10]
580 else:
595 else:
581 pairsIndexList = []
596 pairsIndexList = []
582 for pair in pairsList:
597 for pair in pairsList:
583 if pair not in dataOut.pairsList:
598 if pair not in dataOut.pairsList:
584 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
599 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
585 pairsIndexList.append(dataOut.pairsList.index(pair))
600 pairsIndexList.append(dataOut.pairsList.index(pair))
586
601
587 if pairsIndexList == []:
602 if pairsIndexList == []:
588 return
603 return
589
604
590 # if len(pairsIndexList) > 4:
605 # if len(pairsIndexList) > 4:
591 # pairsIndexList = pairsIndexList[0:4]
606 # pairsIndexList = pairsIndexList[0:4]
592
607
593 hmin_index = None
608 hmin_index = None
594 hmax_index = None
609 hmax_index = None
595
610
596 if hmin != None and hmax != None:
611 if hmin != None and hmax != None:
597 indexes = numpy.arange(dataOut.nHeights)
612 indexes = numpy.arange(dataOut.nHeights)
598 hmin_list = indexes[dataOut.heightList >= hmin]
613 hmin_list = indexes[dataOut.heightList >= hmin]
599 hmax_list = indexes[dataOut.heightList <= hmax]
614 hmax_list = indexes[dataOut.heightList <= hmax]
600
615
601 if hmin_list.any():
616 if hmin_list.any():
602 hmin_index = hmin_list[0]
617 hmin_index = hmin_list[0]
603
618
604 if hmax_list.any():
619 if hmax_list.any():
605 hmax_index = hmax_list[-1]+1
620 hmax_index = hmax_list[-1]+1
606
621
607 x = dataOut.getTimeRange()
622 x = dataOut.getTimeRange()
608
623
609 thisDatetime = dataOut.datatime
624 thisDatetime = dataOut.datatime
610
625
611 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
626 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
612 xlabel = "Local Time"
627 xlabel = "Local Time"
613 ylabel = "Phase (degrees)"
628 ylabel = "Phase (degrees)"
614
629
615 update_figfile = False
630 update_figfile = False
616
631
617 nplots = len(pairsIndexList)
632 nplots = len(pairsIndexList)
618 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
633 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
619 phase_beacon = numpy.zeros(len(pairsIndexList))
634 phase_beacon = numpy.zeros(len(pairsIndexList))
620 for i in range(nplots):
635 for i in range(nplots):
621 pair = dataOut.pairsList[pairsIndexList[i]]
636 pair = dataOut.pairsList[pairsIndexList[i]]
622 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
637 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
623 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
638 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
624 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
639 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
625 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
640 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
626 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
641 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
627
642
628 if dataOut.beacon_heiIndexList:
643 if dataOut.beacon_heiIndexList:
629 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
644 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
630 else:
645 else:
631 phase_beacon[i] = numpy.average(phase)
646 phase_beacon[i] = numpy.average(phase)
632
647
633 if not self.isConfig:
648 if not self.isConfig:
634
649
635 nplots = len(pairsIndexList)
650 nplots = len(pairsIndexList)
636
651
637 self.setup(id=id,
652 self.setup(id=id,
638 nplots=nplots,
653 nplots=nplots,
639 wintitle=wintitle,
654 wintitle=wintitle,
640 showprofile=showprofile,
655 showprofile=showprofile,
641 show=show)
656 show=show)
642
657
643 if timerange != None:
658 if timerange != None:
644 self.timerange = timerange
659 self.timerange = timerange
645
660
646 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
661 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
647
662
648 if ymin == None: ymin = 0
663 if ymin == None: ymin = 0
649 if ymax == None: ymax = 360
664 if ymax == None: ymax = 360
650
665
651 self.FTP_WEI = ftp_wei
666 self.FTP_WEI = ftp_wei
652 self.EXP_CODE = exp_code
667 self.EXP_CODE = exp_code
653 self.SUB_EXP_CODE = sub_exp_code
668 self.SUB_EXP_CODE = sub_exp_code
654 self.PLOT_POS = plot_pos
669 self.PLOT_POS = plot_pos
655
670
656 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
671 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
657 self.isConfig = True
672 self.isConfig = True
658 self.figfile = figfile
673 self.figfile = figfile
659 self.xdata = numpy.array([])
674 self.xdata = numpy.array([])
660 self.ydata = numpy.array([])
675 self.ydata = numpy.array([])
661
676
662 update_figfile = True
677 update_figfile = True
663
678
664 #open file beacon phase
679 #open file beacon phase
665 path = '%s%03d' %(self.PREFIX, self.id)
680 path = '%s%03d' %(self.PREFIX, self.id)
666 beacon_file = os.path.join(path,'%s.txt'%self.name)
681 beacon_file = os.path.join(path,'%s.txt'%self.name)
667 self.filename_phase = os.path.join(figpath,beacon_file)
682 self.filename_phase = os.path.join(figpath,beacon_file)
668 #self.save_phase(self.filename_phase)
683 #self.save_phase(self.filename_phase)
669
684
670
685
671 #store data beacon phase
686 #store data beacon phase
672 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
687 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
673
688
674 self.setWinTitle(title)
689 self.setWinTitle(title)
675
690
676
691
677 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
692 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
678
693
679 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
694 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
680
695
681 axes = self.axesList[0]
696 axes = self.axesList[0]
682
697
683 self.xdata = numpy.hstack((self.xdata, x[0:1]))
698 self.xdata = numpy.hstack((self.xdata, x[0:1]))
684
699
685 if len(self.ydata)==0:
700 if len(self.ydata)==0:
686 self.ydata = phase_beacon.reshape(-1,1)
701 self.ydata = phase_beacon.reshape(-1,1)
687 else:
702 else:
688 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
703 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
689
704
690
705
691 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
706 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
692 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
707 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
693 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
708 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
694 XAxisAsTime=True, grid='both'
709 XAxisAsTime=True, grid='both'
695 )
710 )
696
711
697 self.draw()
712 self.draw()
698
713
699 if dataOut.ltctime >= self.xmax:
714 if dataOut.ltctime >= self.xmax:
700 self.counter_imagwr = wr_period
715 self.counter_imagwr = wr_period
701 self.isConfig = False
716 self.isConfig = False
702 update_figfile = True
717 update_figfile = True
703
718
704 self.save(figpath=figpath,
719 self.save(figpath=figpath,
705 figfile=figfile,
720 figfile=figfile,
706 save=save,
721 save=save,
707 ftp=ftp,
722 ftp=ftp,
708 wr_period=wr_period,
723 wr_period=wr_period,
709 thisDatetime=thisDatetime,
724 thisDatetime=thisDatetime,
710 update_figfile=update_figfile)
725 update_figfile=update_figfile)
711
726
712 return dataOut
727 return dataOut
@@ -1,1411 +1,1439
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
1 # Copyright (c) 2012-2020 Jicamarca Radio Observatory
2 # All rights reserved.
2 # All rights reserved.
3 #
3 #
4 # Distributed under the terms of the BSD 3-clause license.
4 # Distributed under the terms of the BSD 3-clause license.
5 """Spectra processing Unit and operations
5 """Spectra processing Unit and operations
6
6
7 Here you will find the processing unit `SpectraProc` and several operations
7 Here you will find the processing unit `SpectraProc` and several operations
8 to work with Spectra data type
8 to work with Spectra data type
9 """
9 """
10
10
11 import time
11 import time
12 import itertools
12 import itertools
13
13
14 import numpy
14 import numpy
15 import math
15 import math
16
16
17 from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation
17 from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation
18 from schainpy.model.data.jrodata import Spectra
18 from schainpy.model.data.jrodata import Spectra
19 from schainpy.model.data.jrodata import hildebrand_sekhon
19 from schainpy.model.data.jrodata import hildebrand_sekhon
20 from schainpy.utils import log
20 from schainpy.utils import log
21
21
22 from scipy.optimize import curve_fit
22 from scipy.optimize import curve_fit
23
23
24
24
25 class SpectraProc(ProcessingUnit):
25 class SpectraProc(ProcessingUnit):
26
26
27 def __init__(self):
27 def __init__(self):
28
28
29 ProcessingUnit.__init__(self)
29 ProcessingUnit.__init__(self)
30
30
31 self.buffer = None
31 self.buffer = None
32 self.firstdatatime = None
32 self.firstdatatime = None
33 self.profIndex = 0
33 self.profIndex = 0
34 self.dataOut = Spectra()
34 self.dataOut = Spectra()
35 self.id_min = None
35 self.id_min = None
36 self.id_max = None
36 self.id_max = None
37 self.setupReq = False #Agregar a todas las unidades de proc
37 self.setupReq = False #Agregar a todas las unidades de proc
38
38
39 def __updateSpecFromVoltage(self):
39 def __updateSpecFromVoltage(self):
40
40
41 self.dataOut.timeZone = self.dataIn.timeZone
41 self.dataOut.timeZone = self.dataIn.timeZone
42 self.dataOut.dstFlag = self.dataIn.dstFlag
42 self.dataOut.dstFlag = self.dataIn.dstFlag
43 self.dataOut.errorCount = self.dataIn.errorCount
43 self.dataOut.errorCount = self.dataIn.errorCount
44 self.dataOut.useLocalTime = self.dataIn.useLocalTime
44 self.dataOut.useLocalTime = self.dataIn.useLocalTime
45 try:
45 try:
46 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
46 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
47 except:
47 except:
48 pass
48 pass
49 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
49 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
50 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
50 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
51 self.dataOut.channelList = self.dataIn.channelList
51 self.dataOut.channelList = self.dataIn.channelList
52 self.dataOut.heightList = self.dataIn.heightList
52 self.dataOut.heightList = self.dataIn.heightList
53 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
53 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
54 self.dataOut.nProfiles = self.dataOut.nFFTPoints
54 self.dataOut.nProfiles = self.dataOut.nFFTPoints
55 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
55 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
56 self.dataOut.utctime = self.firstdatatime
56 self.dataOut.utctime = self.firstdatatime
57 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
57 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
58 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
58 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
59 self.dataOut.flagShiftFFT = False
59 self.dataOut.flagShiftFFT = False
60 self.dataOut.nCohInt = self.dataIn.nCohInt
60 self.dataOut.nCohInt = self.dataIn.nCohInt
61 self.dataOut.nIncohInt = 1
61 self.dataOut.nIncohInt = 1
62 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
62 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
63 self.dataOut.frequency = self.dataIn.frequency
63 self.dataOut.frequency = self.dataIn.frequency
64 self.dataOut.realtime = self.dataIn.realtime
64 self.dataOut.realtime = self.dataIn.realtime
65 self.dataOut.azimuth = self.dataIn.azimuth
65 self.dataOut.azimuth = self.dataIn.azimuth
66 self.dataOut.zenith = self.dataIn.zenith
66 self.dataOut.zenith = self.dataIn.zenith
67 self.dataOut.codeList = self.dataIn.codeList
67 self.dataOut.codeList = self.dataIn.codeList
68 self.dataOut.azimuthList = self.dataIn.azimuthList
68 self.dataOut.azimuthList = self.dataIn.azimuthList
69 self.dataOut.elevationList = self.dataIn.elevationList
69 self.dataOut.elevationList = self.dataIn.elevationList
70
70
71 def __getFft(self):
71 def __getFft(self):
72 """
72 """
73 Convierte valores de Voltaje a Spectra
73 Convierte valores de Voltaje a Spectra
74
74
75 Affected:
75 Affected:
76 self.dataOut.data_spc
76 self.dataOut.data_spc
77 self.dataOut.data_cspc
77 self.dataOut.data_cspc
78 self.dataOut.data_dc
78 self.dataOut.data_dc
79 self.dataOut.heightList
79 self.dataOut.heightList
80 self.profIndex
80 self.profIndex
81 self.buffer
81 self.buffer
82 self.dataOut.flagNoData
82 self.dataOut.flagNoData
83 """
83 """
84 fft_volt = numpy.fft.fft(
84 fft_volt = numpy.fft.fft(
85 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
85 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
86 fft_volt = fft_volt.astype(numpy.dtype('complex'))
86 fft_volt = fft_volt.astype(numpy.dtype('complex'))
87 dc = fft_volt[:, 0, :]
87 dc = fft_volt[:, 0, :]
88
88
89 # calculo de self-spectra
89 # calculo de self-spectra
90 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
90 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
91 spc = fft_volt * numpy.conjugate(fft_volt)
91 spc = fft_volt * numpy.conjugate(fft_volt)
92 spc = spc.real
92 spc = spc.real
93
93
94 blocksize = 0
94 blocksize = 0
95 blocksize += dc.size
95 blocksize += dc.size
96 blocksize += spc.size
96 blocksize += spc.size
97
97
98 cspc = None
98 cspc = None
99 pairIndex = 0
99 pairIndex = 0
100 if self.dataOut.pairsList != None:
100 if self.dataOut.pairsList != None:
101 # calculo de cross-spectra
101 # calculo de cross-spectra
102 cspc = numpy.zeros(
102 cspc = numpy.zeros(
103 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
103 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
104 for pair in self.dataOut.pairsList:
104 for pair in self.dataOut.pairsList:
105 if pair[0] not in self.dataOut.channelList:
105 if pair[0] not in self.dataOut.channelList:
106 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
106 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
107 str(pair), str(self.dataOut.channelList)))
107 str(pair), str(self.dataOut.channelList)))
108 if pair[1] not in self.dataOut.channelList:
108 if pair[1] not in self.dataOut.channelList:
109 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
109 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
110 str(pair), str(self.dataOut.channelList)))
110 str(pair), str(self.dataOut.channelList)))
111
111
112 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
112 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
113 numpy.conjugate(fft_volt[pair[1], :, :])
113 numpy.conjugate(fft_volt[pair[1], :, :])
114 pairIndex += 1
114 pairIndex += 1
115 blocksize += cspc.size
115 blocksize += cspc.size
116
116
117 self.dataOut.data_spc = spc
117 self.dataOut.data_spc = spc
118 self.dataOut.data_cspc = cspc
118 self.dataOut.data_cspc = cspc
119 self.dataOut.data_dc = dc
119 self.dataOut.data_dc = dc
120 self.dataOut.blockSize = blocksize
120 self.dataOut.blockSize = blocksize
121 self.dataOut.flagShiftFFT = False
121 self.dataOut.flagShiftFFT = False
122
122
123 def run(self, nProfiles=None, nFFTPoints=None, pairsList=None, ippFactor=None, shift_fft=False):
123 def run(self, nProfiles=None, nFFTPoints=None, pairsList=None, ippFactor=None, shift_fft=False):
124
124
125 if self.dataIn.type == "Spectra":
125 if self.dataIn.type == "Spectra":
126 self.dataOut.copy(self.dataIn)
126 self.dataOut.copy(self.dataIn)
127 if shift_fft:
127 if shift_fft:
128 #desplaza a la derecha en el eje 2 determinadas posiciones
128 #desplaza a la derecha en el eje 2 determinadas posiciones
129 shift = int(self.dataOut.nFFTPoints/2)
129 shift = int(self.dataOut.nFFTPoints/2)
130 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
130 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
131
131
132 if self.dataOut.data_cspc is not None:
132 if self.dataOut.data_cspc is not None:
133 #desplaza a la derecha en el eje 2 determinadas posiciones
133 #desplaza a la derecha en el eje 2 determinadas posiciones
134 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
134 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
135 if pairsList:
135 if pairsList:
136 self.__selectPairs(pairsList)
136 self.__selectPairs(pairsList)
137
137
138 elif self.dataIn.type == "Voltage":
138 elif self.dataIn.type == "Voltage":
139
139
140 self.dataOut.flagNoData = True
140 self.dataOut.flagNoData = True
141
141
142 if nFFTPoints == None:
142 if nFFTPoints == None:
143 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
143 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
144
144
145 if nProfiles == None:
145 if nProfiles == None:
146 nProfiles = nFFTPoints
146 nProfiles = nFFTPoints
147
147
148 if ippFactor == None:
148 if ippFactor == None:
149 self.dataOut.ippFactor = 1
149 self.dataOut.ippFactor = 1
150
150
151 self.dataOut.nFFTPoints = nFFTPoints
151 self.dataOut.nFFTPoints = nFFTPoints
152
152
153 if self.buffer is None:
153 if self.buffer is None:
154 self.buffer = numpy.zeros((self.dataIn.nChannels,
154 self.buffer = numpy.zeros((self.dataIn.nChannels,
155 nProfiles,
155 nProfiles,
156 self.dataIn.nHeights),
156 self.dataIn.nHeights),
157 dtype='complex')
157 dtype='complex')
158
158
159 if self.dataIn.flagDataAsBlock:
159 if self.dataIn.flagDataAsBlock:
160 nVoltProfiles = self.dataIn.data.shape[1]
160 nVoltProfiles = self.dataIn.data.shape[1]
161
161
162 if nVoltProfiles == nProfiles:
162 if nVoltProfiles == nProfiles:
163 self.buffer = self.dataIn.data.copy()
163 self.buffer = self.dataIn.data.copy()
164 self.profIndex = nVoltProfiles
164 self.profIndex = nVoltProfiles
165
165
166 elif nVoltProfiles < nProfiles:
166 elif nVoltProfiles < nProfiles:
167
167
168 if self.profIndex == 0:
168 if self.profIndex == 0:
169 self.id_min = 0
169 self.id_min = 0
170 self.id_max = nVoltProfiles
170 self.id_max = nVoltProfiles
171
171
172 self.buffer[:, self.id_min:self.id_max,
172 self.buffer[:, self.id_min:self.id_max,
173 :] = self.dataIn.data
173 :] = self.dataIn.data
174 self.profIndex += nVoltProfiles
174 self.profIndex += nVoltProfiles
175 self.id_min += nVoltProfiles
175 self.id_min += nVoltProfiles
176 self.id_max += nVoltProfiles
176 self.id_max += nVoltProfiles
177 else:
177 else:
178 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
178 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
179 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
179 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
180 self.dataOut.flagNoData = True
180 self.dataOut.flagNoData = True
181 else:
181 else:
182 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
182 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
183 self.profIndex += 1
183 self.profIndex += 1
184
184
185 if self.firstdatatime == None:
185 if self.firstdatatime == None:
186 self.firstdatatime = self.dataIn.utctime
186 self.firstdatatime = self.dataIn.utctime
187
187
188 if self.profIndex == nProfiles:
188 if self.profIndex == nProfiles:
189 self.__updateSpecFromVoltage()
189 self.__updateSpecFromVoltage()
190 if pairsList == None:
190 if pairsList == None:
191 self.dataOut.pairsList = [pair for pair in itertools.combinations(self.dataOut.channelList, 2)]
191 self.dataOut.pairsList = [pair for pair in itertools.combinations(self.dataOut.channelList, 2)]
192 else:
192 else:
193 self.dataOut.pairsList = pairsList
193 self.dataOut.pairsList = pairsList
194 self.__getFft()
194 self.__getFft()
195 self.dataOut.flagNoData = False
195 self.dataOut.flagNoData = False
196 self.firstdatatime = None
196 self.firstdatatime = None
197 self.profIndex = 0
197 self.profIndex = 0
198 else:
198 else:
199 raise ValueError("The type of input object '%s' is not valid".format(
199 raise ValueError("The type of input object '%s' is not valid".format(
200 self.dataIn.type))
200 self.dataIn.type))
201
201
202 def __selectPairs(self, pairsList):
202 def __selectPairs(self, pairsList):
203
203
204 if not pairsList:
204 if not pairsList:
205 return
205 return
206
206
207 pairs = []
207 pairs = []
208 pairsIndex = []
208 pairsIndex = []
209
209
210 for pair in pairsList:
210 for pair in pairsList:
211 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
211 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
212 continue
212 continue
213 pairs.append(pair)
213 pairs.append(pair)
214 pairsIndex.append(pairs.index(pair))
214 pairsIndex.append(pairs.index(pair))
215
215
216 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
216 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
217 self.dataOut.pairsList = pairs
217 self.dataOut.pairsList = pairs
218
218
219 return
219 return
220
220
221 def selectFFTs(self, minFFT, maxFFT ):
221 def selectFFTs(self, minFFT, maxFFT ):
222 """
222 """
223 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
223 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
224 minFFT<= FFT <= maxFFT
224 minFFT<= FFT <= maxFFT
225 """
225 """
226
226
227 if (minFFT > maxFFT):
227 if (minFFT > maxFFT):
228 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
228 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
229
229
230 if (minFFT < self.dataOut.getFreqRange()[0]):
230 if (minFFT < self.dataOut.getFreqRange()[0]):
231 minFFT = self.dataOut.getFreqRange()[0]
231 minFFT = self.dataOut.getFreqRange()[0]
232
232
233 if (maxFFT > self.dataOut.getFreqRange()[-1]):
233 if (maxFFT > self.dataOut.getFreqRange()[-1]):
234 maxFFT = self.dataOut.getFreqRange()[-1]
234 maxFFT = self.dataOut.getFreqRange()[-1]
235
235
236 minIndex = 0
236 minIndex = 0
237 maxIndex = 0
237 maxIndex = 0
238 FFTs = self.dataOut.getFreqRange()
238 FFTs = self.dataOut.getFreqRange()
239
239
240 inda = numpy.where(FFTs >= minFFT)
240 inda = numpy.where(FFTs >= minFFT)
241 indb = numpy.where(FFTs <= maxFFT)
241 indb = numpy.where(FFTs <= maxFFT)
242
242
243 try:
243 try:
244 minIndex = inda[0][0]
244 minIndex = inda[0][0]
245 except:
245 except:
246 minIndex = 0
246 minIndex = 0
247
247
248 try:
248 try:
249 maxIndex = indb[0][-1]
249 maxIndex = indb[0][-1]
250 except:
250 except:
251 maxIndex = len(FFTs)
251 maxIndex = len(FFTs)
252
252
253 self.selectFFTsByIndex(minIndex, maxIndex)
253 self.selectFFTsByIndex(minIndex, maxIndex)
254
254
255 return 1
255 return 1
256
256
257 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
257 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
258 newheis = numpy.where(
258 newheis = numpy.where(
259 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
259 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
260
260
261 if hei_ref != None:
261 if hei_ref != None:
262 newheis = numpy.where(self.dataOut.heightList > hei_ref)
262 newheis = numpy.where(self.dataOut.heightList > hei_ref)
263
263
264 minIndex = min(newheis[0])
264 minIndex = min(newheis[0])
265 maxIndex = max(newheis[0])
265 maxIndex = max(newheis[0])
266 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
266 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
267 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
267 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
268
268
269 # determina indices
269 # determina indices
270 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
270 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
271 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
271 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
272 avg_dB = 10 * \
272 avg_dB = 10 * \
273 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
273 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
274 beacon_dB = numpy.sort(avg_dB)[-nheis:]
274 beacon_dB = numpy.sort(avg_dB)[-nheis:]
275 beacon_heiIndexList = []
275 beacon_heiIndexList = []
276 for val in avg_dB.tolist():
276 for val in avg_dB.tolist():
277 if val >= beacon_dB[0]:
277 if val >= beacon_dB[0]:
278 beacon_heiIndexList.append(avg_dB.tolist().index(val))
278 beacon_heiIndexList.append(avg_dB.tolist().index(val))
279
279
280 #data_spc = data_spc[:,:,beacon_heiIndexList]
280 #data_spc = data_spc[:,:,beacon_heiIndexList]
281 data_cspc = None
281 data_cspc = None
282 if self.dataOut.data_cspc is not None:
282 if self.dataOut.data_cspc is not None:
283 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
283 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
284 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
284 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
285
285
286 data_dc = None
286 data_dc = None
287 if self.dataOut.data_dc is not None:
287 if self.dataOut.data_dc is not None:
288 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
288 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
289 #data_dc = data_dc[:,beacon_heiIndexList]
289 #data_dc = data_dc[:,beacon_heiIndexList]
290
290
291 self.dataOut.data_spc = data_spc
291 self.dataOut.data_spc = data_spc
292 self.dataOut.data_cspc = data_cspc
292 self.dataOut.data_cspc = data_cspc
293 self.dataOut.data_dc = data_dc
293 self.dataOut.data_dc = data_dc
294 self.dataOut.heightList = heightList
294 self.dataOut.heightList = heightList
295 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
295 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
296
296
297 return 1
297 return 1
298
298
299 def selectFFTsByIndex(self, minIndex, maxIndex):
299 def selectFFTsByIndex(self, minIndex, maxIndex):
300 """
300 """
301
301
302 """
302 """
303
303
304 if (minIndex < 0) or (minIndex > maxIndex):
304 if (minIndex < 0) or (minIndex > maxIndex):
305 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
305 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
306
306
307 if (maxIndex >= self.dataOut.nProfiles):
307 if (maxIndex >= self.dataOut.nProfiles):
308 maxIndex = self.dataOut.nProfiles-1
308 maxIndex = self.dataOut.nProfiles-1
309
309
310 #Spectra
310 #Spectra
311 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
311 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
312
312
313 data_cspc = None
313 data_cspc = None
314 if self.dataOut.data_cspc is not None:
314 if self.dataOut.data_cspc is not None:
315 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
315 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
316
316
317 data_dc = None
317 data_dc = None
318 if self.dataOut.data_dc is not None:
318 if self.dataOut.data_dc is not None:
319 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
319 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
320
320
321 self.dataOut.data_spc = data_spc
321 self.dataOut.data_spc = data_spc
322 self.dataOut.data_cspc = data_cspc
322 self.dataOut.data_cspc = data_cspc
323 self.dataOut.data_dc = data_dc
323 self.dataOut.data_dc = data_dc
324
324
325 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
325 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
326 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
326 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
327 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
327 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
328
328
329 return 1
329 return 1
330
330
331 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
331 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
332 # validacion de rango
332 # validacion de rango
333 if minHei == None:
333 if minHei == None:
334 minHei = self.dataOut.heightList[0]
334 minHei = self.dataOut.heightList[0]
335
335
336 if maxHei == None:
336 if maxHei == None:
337 maxHei = self.dataOut.heightList[-1]
337 maxHei = self.dataOut.heightList[-1]
338
338
339 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
339 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
340 print('minHei: %.2f is out of the heights range' % (minHei))
340 print('minHei: %.2f is out of the heights range' % (minHei))
341 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
341 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
342 minHei = self.dataOut.heightList[0]
342 minHei = self.dataOut.heightList[0]
343
343
344 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
344 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
345 print('maxHei: %.2f is out of the heights range' % (maxHei))
345 print('maxHei: %.2f is out of the heights range' % (maxHei))
346 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
346 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
347 maxHei = self.dataOut.heightList[-1]
347 maxHei = self.dataOut.heightList[-1]
348
348
349 # validacion de velocidades
349 # validacion de velocidades
350 velrange = self.dataOut.getVelRange(1)
350 velrange = self.dataOut.getVelRange(1)
351
351
352 if minVel == None:
352 if minVel == None:
353 minVel = velrange[0]
353 minVel = velrange[0]
354
354
355 if maxVel == None:
355 if maxVel == None:
356 maxVel = velrange[-1]
356 maxVel = velrange[-1]
357
357
358 if (minVel < velrange[0]) or (minVel > maxVel):
358 if (minVel < velrange[0]) or (minVel > maxVel):
359 print('minVel: %.2f is out of the velocity range' % (minVel))
359 print('minVel: %.2f is out of the velocity range' % (minVel))
360 print('minVel is setting to %.2f' % (velrange[0]))
360 print('minVel is setting to %.2f' % (velrange[0]))
361 minVel = velrange[0]
361 minVel = velrange[0]
362
362
363 if (maxVel > velrange[-1]) or (maxVel < minVel):
363 if (maxVel > velrange[-1]) or (maxVel < minVel):
364 print('maxVel: %.2f is out of the velocity range' % (maxVel))
364 print('maxVel: %.2f is out of the velocity range' % (maxVel))
365 print('maxVel is setting to %.2f' % (velrange[-1]))
365 print('maxVel is setting to %.2f' % (velrange[-1]))
366 maxVel = velrange[-1]
366 maxVel = velrange[-1]
367
367
368 # seleccion de indices para rango
368 # seleccion de indices para rango
369 minIndex = 0
369 minIndex = 0
370 maxIndex = 0
370 maxIndex = 0
371 heights = self.dataOut.heightList
371 heights = self.dataOut.heightList
372
372
373 inda = numpy.where(heights >= minHei)
373 inda = numpy.where(heights >= minHei)
374 indb = numpy.where(heights <= maxHei)
374 indb = numpy.where(heights <= maxHei)
375
375
376 try:
376 try:
377 minIndex = inda[0][0]
377 minIndex = inda[0][0]
378 except:
378 except:
379 minIndex = 0
379 minIndex = 0
380
380
381 try:
381 try:
382 maxIndex = indb[0][-1]
382 maxIndex = indb[0][-1]
383 except:
383 except:
384 maxIndex = len(heights)
384 maxIndex = len(heights)
385
385
386 if (minIndex < 0) or (minIndex > maxIndex):
386 if (minIndex < 0) or (minIndex > maxIndex):
387 raise ValueError("some value in (%d,%d) is not valid" % (
387 raise ValueError("some value in (%d,%d) is not valid" % (
388 minIndex, maxIndex))
388 minIndex, maxIndex))
389
389
390 if (maxIndex >= self.dataOut.nHeights):
390 if (maxIndex >= self.dataOut.nHeights):
391 maxIndex = self.dataOut.nHeights - 1
391 maxIndex = self.dataOut.nHeights - 1
392
392
393 # seleccion de indices para velocidades
393 # seleccion de indices para velocidades
394 indminvel = numpy.where(velrange >= minVel)
394 indminvel = numpy.where(velrange >= minVel)
395 indmaxvel = numpy.where(velrange <= maxVel)
395 indmaxvel = numpy.where(velrange <= maxVel)
396 try:
396 try:
397 minIndexVel = indminvel[0][0]
397 minIndexVel = indminvel[0][0]
398 except:
398 except:
399 minIndexVel = 0
399 minIndexVel = 0
400
400
401 try:
401 try:
402 maxIndexVel = indmaxvel[0][-1]
402 maxIndexVel = indmaxvel[0][-1]
403 except:
403 except:
404 maxIndexVel = len(velrange)
404 maxIndexVel = len(velrange)
405
405
406 # seleccion del espectro
406 # seleccion del espectro
407 data_spc = self.dataOut.data_spc[:,
407 data_spc = self.dataOut.data_spc[:,
408 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
408 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
409 # estimacion de ruido
409 # estimacion de ruido
410 noise = numpy.zeros(self.dataOut.nChannels)
410 noise = numpy.zeros(self.dataOut.nChannels)
411
411
412 for channel in range(self.dataOut.nChannels):
412 for channel in range(self.dataOut.nChannels):
413 daux = data_spc[channel, :, :]
413 daux = data_spc[channel, :, :]
414 sortdata = numpy.sort(daux, axis=None)
414 sortdata = numpy.sort(daux, axis=None)
415 noise[channel] = hildebrand_sekhon(sortdata, self.dataOut.nIncohInt)
415 noise[channel] = hildebrand_sekhon(sortdata, self.dataOut.nIncohInt)
416
416
417 self.dataOut.noise_estimation = noise.copy()
417 self.dataOut.noise_estimation = noise.copy()
418
418
419 return 1
419 return 1
420
420
421 class removeDC(Operation):
421 class removeDC(Operation):
422
422
423 def run(self, dataOut, mode=2):
423 def run(self, dataOut, mode=2):
424 self.dataOut = dataOut
424 self.dataOut = dataOut
425 jspectra = self.dataOut.data_spc
425 jspectra = self.dataOut.data_spc
426 jcspectra = self.dataOut.data_cspc
426 jcspectra = self.dataOut.data_cspc
427
427
428 num_chan = jspectra.shape[0]
428 num_chan = jspectra.shape[0]
429 num_hei = jspectra.shape[2]
429 num_hei = jspectra.shape[2]
430
430
431 if jcspectra is not None:
431 if jcspectra is not None:
432 jcspectraExist = True
432 jcspectraExist = True
433 num_pairs = jcspectra.shape[0]
433 num_pairs = jcspectra.shape[0]
434 else:
434 else:
435 jcspectraExist = False
435 jcspectraExist = False
436
436
437 freq_dc = int(jspectra.shape[1] / 2)
437 freq_dc = int(jspectra.shape[1] / 2)
438 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
438 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
439 ind_vel = ind_vel.astype(int)
439 ind_vel = ind_vel.astype(int)
440
440
441 if ind_vel[0] < 0:
441 if ind_vel[0] < 0:
442 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
442 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
443
443
444 if mode == 1:
444 if mode == 1:
445 jspectra[:, freq_dc, :] = (
445 jspectra[:, freq_dc, :] = (
446 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
446 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
447
447
448 if jcspectraExist:
448 if jcspectraExist:
449 jcspectra[:, freq_dc, :] = (
449 jcspectra[:, freq_dc, :] = (
450 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
450 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
451
451
452 if mode == 2:
452 if mode == 2:
453
453
454 vel = numpy.array([-2, -1, 1, 2])
454 vel = numpy.array([-2, -1, 1, 2])
455 xx = numpy.zeros([4, 4])
455 xx = numpy.zeros([4, 4])
456
456
457 for fil in range(4):
457 for fil in range(4):
458 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
458 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
459
459
460 xx_inv = numpy.linalg.inv(xx)
460 xx_inv = numpy.linalg.inv(xx)
461 xx_aux = xx_inv[0, :]
461 xx_aux = xx_inv[0, :]
462
462
463 for ich in range(num_chan):
463 for ich in range(num_chan):
464 yy = jspectra[ich, ind_vel, :]
464 yy = jspectra[ich, ind_vel, :]
465 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
465 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
466
466
467 junkid = jspectra[ich, freq_dc, :] <= 0
467 junkid = jspectra[ich, freq_dc, :] <= 0
468 cjunkid = sum(junkid)
468 cjunkid = sum(junkid)
469
469
470 if cjunkid.any():
470 if cjunkid.any():
471 jspectra[ich, freq_dc, junkid.nonzero()] = (
471 jspectra[ich, freq_dc, junkid.nonzero()] = (
472 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
472 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
473
473
474 if jcspectraExist:
474 if jcspectraExist:
475 for ip in range(num_pairs):
475 for ip in range(num_pairs):
476 yy = jcspectra[ip, ind_vel, :]
476 yy = jcspectra[ip, ind_vel, :]
477 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
477 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
478
478
479 self.dataOut.data_spc = jspectra
479 self.dataOut.data_spc = jspectra
480 self.dataOut.data_cspc = jcspectra
480 self.dataOut.data_cspc = jcspectra
481
481
482 return self.dataOut
482 return self.dataOut
483
483
484 # import matplotlib.pyplot as plt
484 # import matplotlib.pyplot as plt
485
485
486 def fit_func( x, a0, a1, a2): #, a3, a4, a5):
486 def fit_func( x, a0, a1, a2): #, a3, a4, a5):
487 z = (x - a1) / a2
487 z = (x - a1) / a2
488 y = a0 * numpy.exp(-z**2 / a2) #+ a3 + a4 * x + a5 * x**2
488 y = a0 * numpy.exp(-z**2 / a2) #+ a3 + a4 * x + a5 * x**2
489 return y
489 return y
490
491
490 class CleanRayleigh(Operation):
492 class CleanRayleigh(Operation):
491
493
492 def __init__(self):
494 def __init__(self):
493
495
494 Operation.__init__(self)
496 Operation.__init__(self)
495 self.i=0
497 self.i=0
496 self.isConfig = False
498 self.isConfig = False
497 self.__dataReady = False
499 self.__dataReady = False
498 self.__profIndex = 0
500 self.__profIndex = 0
499 self.byTime = False
501 self.byTime = False
500 self.byProfiles = False
502 self.byProfiles = False
501
503
502 self.bloques = None
504 self.bloques = None
503 self.bloque0 = None
505 self.bloque0 = None
504
506
505 self.index = 0
507 self.index = 0
506
508
507 self.buffer = 0
509 self.buffer = 0
508 self.buffer2 = 0
510 self.buffer2 = 0
509 self.buffer3 = 0
511 self.buffer3 = 0
510
512
511
513
512 def setup(self,dataOut,min_hei,max_hei,n, timeInterval,factor_stdv):
514 def setup(self,dataOut,min_hei,max_hei,n, timeInterval,factor_stdv):
513
515
514 self.nChannels = dataOut.nChannels
516 self.nChannels = dataOut.nChannels
515 self.nProf = dataOut.nProfiles
517 self.nProf = dataOut.nProfiles
516 self.nPairs = dataOut.data_cspc.shape[0]
518 self.nPairs = dataOut.data_cspc.shape[0]
517 self.pairsArray = numpy.array(dataOut.pairsList)
519 self.pairsArray = numpy.array(dataOut.pairsList)
518 self.spectra = dataOut.data_spc
520 self.spectra = dataOut.data_spc
519 self.cspectra = dataOut.data_cspc
521 self.cspectra = dataOut.data_cspc
520 self.heights = dataOut.heightList #alturas totales
522 self.heights = dataOut.heightList #alturas totales
521 self.nHeights = len(self.heights)
523 self.nHeights = len(self.heights)
522 self.min_hei = min_hei
524 self.min_hei = min_hei
523 self.max_hei = max_hei
525 self.max_hei = max_hei
524 if (self.min_hei == None):
526 if (self.min_hei == None):
525 self.min_hei = 0
527 self.min_hei = 0
526 if (self.max_hei == None):
528 if (self.max_hei == None):
527 self.max_hei = dataOut.heightList[-1]
529 self.max_hei = dataOut.heightList[-1]
528 self.hval = ((self.max_hei>=self.heights) & (self.heights >= self.min_hei)).nonzero()
530 self.hval = ((self.max_hei>=self.heights) & (self.heights >= self.min_hei)).nonzero()
529 self.heightsClean = self.heights[self.hval] #alturas filtradas
531 self.heightsClean = self.heights[self.hval] #alturas filtradas
530 self.hval = self.hval[0] # forma (N,), an solo N elementos -> Indices de alturas
532 self.hval = self.hval[0] # forma (N,), an solo N elementos -> Indices de alturas
531 self.nHeightsClean = len(self.heightsClean)
533 self.nHeightsClean = len(self.heightsClean)
532 self.channels = dataOut.channelList
534 self.channels = dataOut.channelList
533 self.nChan = len(self.channels)
535 self.nChan = len(self.channels)
534 self.nIncohInt = dataOut.nIncohInt
536 self.nIncohInt = dataOut.nIncohInt
535 self.__initime = dataOut.utctime
537 self.__initime = dataOut.utctime
536 self.maxAltInd = self.hval[-1]+1
538 self.maxAltInd = self.hval[-1]+1
537 self.minAltInd = self.hval[0]
539 self.minAltInd = self.hval[0]
538
540
539 self.crosspairs = dataOut.pairsList
541 self.crosspairs = dataOut.pairsList
540 self.nPairs = len(self.crosspairs)
542 self.nPairs = len(self.crosspairs)
541 self.normFactor = dataOut.normFactor
543 self.normFactor = dataOut.normFactor
542 self.nFFTPoints = dataOut.nFFTPoints
544 self.nFFTPoints = dataOut.nFFTPoints
543 self.ippSeconds = dataOut.ippSeconds
545 self.ippSeconds = dataOut.ippSeconds
544 self.currentTime = self.__initime
546 self.currentTime = self.__initime
545 self.pairsArray = numpy.array(dataOut.pairsList)
547 self.pairsArray = numpy.array(dataOut.pairsList)
546 self.factor_stdv = factor_stdv
548 self.factor_stdv = factor_stdv
547 #print("CHANNELS: ",[x for x in self.channels])
549 #print("CHANNELS: ",[x for x in self.channels])
548
550
549 if n != None :
551 if n != None :
550 self.byProfiles = True
552 self.byProfiles = True
551 self.nIntProfiles = n
553 self.nIntProfiles = n
552 else:
554 else:
553 self.__integrationtime = timeInterval
555 self.__integrationtime = timeInterval
554
556
555 self.__dataReady = False
557 self.__dataReady = False
556 self.isConfig = True
558 self.isConfig = True
557
559
558
560
559
561
560 def run(self, dataOut,min_hei=None,max_hei=None, n=None, timeInterval=10,factor_stdv=2.5):
562 def run(self, dataOut,min_hei=None,max_hei=None, n=None, timeInterval=10,factor_stdv=2.5):
561 #print (dataOut.utctime)
563 #print (dataOut.utctime)
562 if not self.isConfig :
564 if not self.isConfig :
563 #print("Setting config")
565 #print("Setting config")
564 self.setup(dataOut, min_hei,max_hei,n,timeInterval,factor_stdv)
566 self.setup(dataOut, min_hei,max_hei,n,timeInterval,factor_stdv)
565 #print("Config Done")
567 #print("Config Done")
566 tini=dataOut.utctime
568 tini=dataOut.utctime
567
569
568 if self.byProfiles:
570 if self.byProfiles:
569 if self.__profIndex == self.nIntProfiles:
571 if self.__profIndex == self.nIntProfiles:
570 self.__dataReady = True
572 self.__dataReady = True
571 else:
573 else:
572 if (tini - self.__initime) >= self.__integrationtime:
574 if (tini - self.__initime) >= self.__integrationtime:
573 #print(tini - self.__initime,self.__profIndex)
575 #print(tini - self.__initime,self.__profIndex)
574 self.__dataReady = True
576 self.__dataReady = True
575 self.__initime = tini
577 self.__initime = tini
576
578
577 #if (tini.tm_min % 2) == 0 and (tini.tm_sec < 5 and self.fint==0):
579 #if (tini.tm_min % 2) == 0 and (tini.tm_sec < 5 and self.fint==0):
578
580
579 if self.__dataReady:
581 if self.__dataReady:
580 #print("Data ready",self.__profIndex)
582 #print("Data ready",self.__profIndex)
581 self.__profIndex = 0
583 self.__profIndex = 0
582 jspc = self.buffer
584 jspc = self.buffer
583 jcspc = self.buffer2
585 jcspc = self.buffer2
584 #jnoise = self.buffer3
586 #jnoise = self.buffer3
585 self.buffer = dataOut.data_spc
587 self.buffer = dataOut.data_spc
586 self.buffer2 = dataOut.data_cspc
588 self.buffer2 = dataOut.data_cspc
587 #self.buffer3 = dataOut.noise
589 #self.buffer3 = dataOut.noise
588 self.currentTime = dataOut.utctime
590 self.currentTime = dataOut.utctime
589 if numpy.any(jspc) :
591 if numpy.any(jspc) :
590 #print( jspc.shape, jcspc.shape)
592 #print( jspc.shape, jcspc.shape)
591 jspc = numpy.reshape(jspc,(int(len(jspc)/self.nChannels),self.nChannels,self.nFFTPoints,self.nHeights))
593 jspc = numpy.reshape(jspc,(int(len(jspc)/self.nChannels),self.nChannels,self.nFFTPoints,self.nHeights))
592 jcspc= numpy.reshape(jcspc,(int(len(jcspc)/self.nPairs),self.nPairs,self.nFFTPoints,self.nHeights))
594 jcspc= numpy.reshape(jcspc,(int(len(jcspc)/self.nPairs),self.nPairs,self.nFFTPoints,self.nHeights))
593 self.__dataReady = False
595 self.__dataReady = False
594 #print( jspc.shape, jcspc.shape)
596 #print( jspc.shape, jcspc.shape)
595 dataOut.flagNoData = False
597 dataOut.flagNoData = False
596 else:
598 else:
597 dataOut.flagNoData = True
599 dataOut.flagNoData = True
598 self.__dataReady = False
600 self.__dataReady = False
599 return dataOut
601 return dataOut
600 else:
602 else:
601 #print( len(self.buffer))
603 #print( len(self.buffer))
602 if numpy.any(self.buffer):
604 if numpy.any(self.buffer):
603 self.buffer = numpy.concatenate((self.buffer,dataOut.data_spc), axis=0)
605 self.buffer = numpy.concatenate((self.buffer,dataOut.data_spc), axis=0)
604 self.buffer2 = numpy.concatenate((self.buffer2,dataOut.data_cspc), axis=0)
606 self.buffer2 = numpy.concatenate((self.buffer2,dataOut.data_cspc), axis=0)
605 self.buffer3 += dataOut.data_dc
607 self.buffer3 += dataOut.data_dc
606 else:
608 else:
607 self.buffer = dataOut.data_spc
609 self.buffer = dataOut.data_spc
608 self.buffer2 = dataOut.data_cspc
610 self.buffer2 = dataOut.data_cspc
609 self.buffer3 = dataOut.data_dc
611 self.buffer3 = dataOut.data_dc
610 #print self.index, self.fint
612 #print self.index, self.fint
611 #print self.buffer2.shape
613 #print self.buffer2.shape
612 dataOut.flagNoData = True ## NOTE: ?? revisar LUEGO
614 dataOut.flagNoData = True ## NOTE: ?? revisar LUEGO
613 self.__profIndex += 1
615 self.__profIndex += 1
614 return dataOut ## NOTE: REV
616 return dataOut ## NOTE: REV
615
617
616
618
617 #index = tini.tm_hour*12+tini.tm_min/5
619 #index = tini.tm_hour*12+tini.tm_min/5
618 '''REVISAR'''
620 '''REVISAR'''
619 # jspc = jspc/self.nFFTPoints/self.normFactor
621 # jspc = jspc/self.nFFTPoints/self.normFactor
620 # jcspc = jcspc/self.nFFTPoints/self.normFactor
622 # jcspc = jcspc/self.nFFTPoints/self.normFactor
621
623
622
624
623
625
624 tmp_spectra,tmp_cspectra = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
626 tmp_spectra,tmp_cspectra = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
625 dataOut.data_spc = tmp_spectra
627 dataOut.data_spc = tmp_spectra
626 dataOut.data_cspc = tmp_cspectra
628 dataOut.data_cspc = tmp_cspectra
627
629
628 #dataOut.data_spc,dataOut.data_cspc = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
630 #dataOut.data_spc,dataOut.data_cspc = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
629
631
630 dataOut.data_dc = self.buffer3
632 dataOut.data_dc = self.buffer3
631 dataOut.nIncohInt *= self.nIntProfiles
633 dataOut.nIncohInt *= self.nIntProfiles
632 dataOut.utctime = self.currentTime #tiempo promediado
634 dataOut.utctime = self.currentTime #tiempo promediado
633 #print("Time: ",time.localtime(dataOut.utctime))
635 #print("Time: ",time.localtime(dataOut.utctime))
634 # dataOut.data_spc = sat_spectra
636 # dataOut.data_spc = sat_spectra
635 # dataOut.data_cspc = sat_cspectra
637 # dataOut.data_cspc = sat_cspectra
636 self.buffer = 0
638 self.buffer = 0
637 self.buffer2 = 0
639 self.buffer2 = 0
638 self.buffer3 = 0
640 self.buffer3 = 0
639
641
640 return dataOut
642 return dataOut
641
643
642 def cleanRayleigh(self,dataOut,spectra,cspectra,factor_stdv):
644 def cleanRayleigh(self,dataOut,spectra,cspectra,factor_stdv):
643 #print("OP cleanRayleigh")
645 #print("OP cleanRayleigh")
644 #import matplotlib.pyplot as plt
646 import matplotlib.pyplot as plt
645 #for k in range(149):
647 #for k in range(149):
646
648 channelsProcssd = []
649 channelA_ok = False
647 rfunc = cspectra.copy() #self.bloques
650 rfunc = cspectra.copy() #self.bloques
648 #rfunc = cspectra
651 #rfunc = cspectra
649 #val_spc = spectra*0.0 #self.bloque0*0.0
652 #val_spc = spectra*0.0 #self.bloque0*0.0
650 #val_cspc = cspectra*0.0 #self.bloques*0.0
653 #val_cspc = cspectra*0.0 #self.bloques*0.0
651 #in_sat_spectra = spectra.copy() #self.bloque0
654 #in_sat_spectra = spectra.copy() #self.bloque0
652 #in_sat_cspectra = cspectra.copy() #self.bloques
655 #in_sat_cspectra = cspectra.copy() #self.bloques
653
656
654 #raxs = math.ceil(math.sqrt(self.nPairs))
655 #caxs = math.ceil(self.nPairs/raxs)
656
657
657 #print(self.hval)
658 ###ONLY FOR TEST:
659 raxs = math.ceil(math.sqrt(self.nPairs))
660 caxs = math.ceil(self.nPairs/raxs)
661 if self.nPairs <4:
662 raxs = 2
663 caxs = 2
664 #print(raxs, caxs)
665 fft_rev = 14 #nFFT to plot
666 hei_rev = ((self.heights >= 550) & (self.heights <= 551)).nonzero() #hei to plot
667 hei_rev = hei_rev[0]
668 #print(hei_rev)
669
658 #print numpy.absolute(rfunc[:,0,0,14])
670 #print numpy.absolute(rfunc[:,0,0,14])
671
659 gauss_fit, covariance = None, None
672 gauss_fit, covariance = None, None
660 for ih in range(self.minAltInd,self.maxAltInd):
673 for ih in range(self.minAltInd,self.maxAltInd):
661 for ifreq in range(self.nFFTPoints):
674 for ifreq in range(self.nFFTPoints):
662 # fig, axs = plt.subplots(raxs, caxs)
675 ###ONLY FOR TEST:
663 # fig2, axs2 = plt.subplots(raxs, caxs)
676 if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
664 # col_ax = 0
677 fig, axs = plt.subplots(raxs, caxs)
665 # row_ax = 0
678 fig2, axs2 = plt.subplots(raxs, caxs)
666 #print(len(self.nPairs))
679 col_ax = 0
667 for ii in range(self.nPairs): #PARES DE CANALES SELF y CROSS
680 row_ax = 0
668 #print("ii: ",ii)
681 #print(self.nPairs)
669 # if (col_ax%caxs==0 and col_ax!=0):
682 for ii in range(self.nPairs): #PARES DE CANALES SELF y CROSS
670 # col_ax = 0
683 if self.crosspairs[ii][1]-self.crosspairs[ii][0] > 1: # APLICAR SOLO EN PARES CONTIGUOS
671 # row_ax += 1
684 continue
685 if not self.crosspairs[ii][0] in channelsProcssd:
686 channelA_ok = True
687 #print("pair: ",self.crosspairs[ii])
688 if (col_ax%caxs==0 and col_ax!=0 and self.nPairs !=1): ###ONLY FOR TEST:
689 col_ax = 0
690 row_ax += 1
672 func2clean = 10*numpy.log10(numpy.absolute(rfunc[:,ii,ifreq,ih])) #Potencia?
691 func2clean = 10*numpy.log10(numpy.absolute(rfunc[:,ii,ifreq,ih])) #Potencia?
673 #print(func2clean.shape)
692 #print(func2clean.shape)
674 val = (numpy.isfinite(func2clean)==True).nonzero()
693 val = (numpy.isfinite(func2clean)==True).nonzero()
675
694
676 if len(val)>0: #limitador
695 if len(val)>0: #limitador
677 min_val = numpy.around(numpy.amin(func2clean)-2) #> (-40)
696 min_val = numpy.around(numpy.amin(func2clean)-2) #> (-40)
678 if min_val <= -40 :
697 if min_val <= -40 :
679 min_val = -40
698 min_val = -40
680 max_val = numpy.around(numpy.amax(func2clean)+2) #< 200
699 max_val = numpy.around(numpy.amax(func2clean)+2) #< 200
681 if max_val >= 200 :
700 if max_val >= 200 :
682 max_val = 200
701 max_val = 200
683 #print min_val, max_val
702 #print min_val, max_val
684 step = 1
703 step = 1
685 #print("Getting bins and the histogram")
704 #print("Getting bins and the histogram")
686 x_dist = min_val + numpy.arange(1 + ((max_val-(min_val))/step))*step
705 x_dist = min_val + numpy.arange(1 + ((max_val-(min_val))/step))*step
687 y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
706 y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
688 #print(len(y_dist),len(binstep[:-1]))
707 #print(len(y_dist),len(binstep[:-1]))
689 #print(row_ax,col_ax, " ..")
708 #print(row_ax,col_ax, " ..")
690 #print(self.pairsArray[ii][0],self.pairsArray[ii][1])
709 #print(self.pairsArray[ii][0],self.pairsArray[ii][1])
691 mean = numpy.sum(x_dist * y_dist) / numpy.sum(y_dist)
710 mean = numpy.sum(x_dist * y_dist) / numpy.sum(y_dist)
692 sigma = numpy.sqrt(numpy.sum(y_dist * (x_dist - mean)**2) / numpy.sum(y_dist))
711 sigma = numpy.sqrt(numpy.sum(y_dist * (x_dist - mean)**2) / numpy.sum(y_dist))
693 parg = [numpy.amax(y_dist),mean,sigma]
712 parg = [numpy.amax(y_dist),mean,sigma]
694
713
695 #newY = None
714 newY = None
696
715
697 try :
716 try :
698 gauss_fit, covariance = curve_fit(fit_func, x_dist, y_dist,p0=parg)
717 gauss_fit, covariance = curve_fit(fit_func, x_dist, y_dist,p0=parg)
699 mode = gauss_fit[1]
718 mode = gauss_fit[1]
700 stdv = gauss_fit[2]
719 stdv = gauss_fit[2]
701 #print(" FIT OK",gauss_fit)
720 #print(" FIT OK",gauss_fit)
702 '''
721
703 newY = fit_func(x_dist,gauss_fit[0],gauss_fit[1],gauss_fit[2])
722 ###ONLY FOR TEST:
704 axs[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
723 if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
705 axs[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
724 newY = fit_func(x_dist,gauss_fit[0],gauss_fit[1],gauss_fit[2])
706 axs[row_ax,col_ax].set_title("Pair "+str(self.crosspairs[ii]))'''
725 axs[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
726 axs[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
727 axs[row_ax,col_ax].set_title("Pair "+str(self.crosspairs[ii]))
728
707 except:
729 except:
708 mode = mean
730 mode = mean
709 stdv = sigma
731 stdv = sigma
710 #print("FIT FAIL")
732 #print("FIT FAIL")
733 continue
711
734
712
735
713 #print(mode,stdv)
736 #print(mode,stdv)
714 #Removing echoes greater than mode + std_factor*stdv
737 #Removing echoes greater than mode + std_factor*stdv
715 noval = (abs(func2clean - mode)>=(factor_stdv*stdv)).nonzero()
738 noval = (abs(func2clean - mode)>=(factor_stdv*stdv)).nonzero()
716 #noval tiene los indices que se van a remover
739 #noval tiene los indices que se van a remover
717 #print("Pair ",ii," novals: ",len(noval[0]))
740 #print("Pair ",ii," novals: ",len(noval[0]))
718 if len(noval[0]) > 0: #forma de array (N,) es igual a longitud (N)
741 if len(noval[0]) > 0: #forma de array (N,) es igual a longitud (N)
719 novall = ((func2clean - mode) >= (factor_stdv*stdv)).nonzero()
742 novall = ((func2clean - mode) >= (factor_stdv*stdv)).nonzero()
720 #print(novall)
743 #print(novall)
721 #print(" ",self.pairsArray[ii])
744 #print(" ",self.pairsArray[ii])
722 cross_pairs = self.pairsArray[ii]
745 cross_pairs = self.pairsArray[ii]
723 #Getting coherent echoes which are removed.
746 #Getting coherent echoes which are removed.
724 # if len(novall[0]) > 0:
747 # if len(novall[0]) > 0:
725 #
748 #
726 # val_spc[novall[0],cross_pairs[0],ifreq,ih] = 1
749 # val_spc[novall[0],cross_pairs[0],ifreq,ih] = 1
727 # val_spc[novall[0],cross_pairs[1],ifreq,ih] = 1
750 # val_spc[novall[0],cross_pairs[1],ifreq,ih] = 1
728 # val_cspc[novall[0],ii,ifreq,ih] = 1
751 # val_cspc[novall[0],ii,ifreq,ih] = 1
729 #print("OUT NOVALL 1")
752 #print("OUT NOVALL 1")
730 #Removing coherent from ISR data
731 chA = self.channels.index(cross_pairs[0])
732 chB = self.channels.index(cross_pairs[1])
733
753
734 new_a = numpy.delete(cspectra[:,ii,ifreq,ih], noval[0])
754 new_a = numpy.delete(cspectra[:,ii,ifreq,ih], noval[0])
735 cspectra[noval,ii,ifreq,ih] = numpy.mean(new_a) #mean CrossSpectra
755 cspectra[noval,ii,ifreq,ih] = numpy.mean(new_a) #mean CrossSpectra
736 new_b = numpy.delete(spectra[:,chA,ifreq,ih], noval[0])
756
737 spectra[noval,chA,ifreq,ih] = numpy.mean(new_b) #mean Spectra Pair A
757 if channelA_ok:
758 chA = self.channels.index(cross_pairs[0])
759 new_b = numpy.delete(spectra[:,chA,ifreq,ih], noval[0])
760 spectra[noval,chA,ifreq,ih] = numpy.mean(new_b) #mean Spectra Pair A
761 channelA_ok = False
762 chB = self.channels.index(cross_pairs[1])
738 new_c = numpy.delete(spectra[:,chB,ifreq,ih], noval[0])
763 new_c = numpy.delete(spectra[:,chB,ifreq,ih], noval[0])
739 spectra[noval,chB,ifreq,ih] = numpy.mean(new_c) #mean Spectra Pair B
764 spectra[noval,chB,ifreq,ih] = numpy.mean(new_c) #mean Spectra Pair B
740
765
766 channelsProcssd.append(self.crosspairs[ii][0]) # save channel A
767 channelsProcssd.append(self.crosspairs[ii][1]) # save channel B
741
768
742 '''
769 ###ONLY FOR TEST:
743 func2clean = 10*numpy.log10(numpy.absolute(cspectra[:,ii,ifreq,ih]))
770 if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
744 y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
771 func2clean = 10*numpy.log10(numpy.absolute(cspectra[:,ii,ifreq,ih]))
745 axs2[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
772 y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
746 axs2[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
773 axs2[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
747 axs2[row_ax,col_ax].set_title("Pair "+str(self.crosspairs[ii]))
774 axs2[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
748 '''
775 axs2[row_ax,col_ax].set_title("Pair "+str(self.crosspairs[ii]))
749
776
750 #col_ax += 1 #contador de ploteo columnas
777 ###ONLY FOR TEST:
778 col_ax += 1 #contador de ploteo columnas
751 ##print(col_ax)
779 ##print(col_ax)
752 '''
780 ###ONLY FOR TEST:
753 title = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km"
781 if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
754 title2 = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km CLEANED"
782 title = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km"
755 fig.suptitle(title)
783 title2 = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km CLEANED"
756 fig2.suptitle(title2)
784 fig.suptitle(title)
757 plt.show()'''
785 fig2.suptitle(title2)
758
786 plt.show()
759 ''' channels = channels
787
788
789 '''
790
791 channels = channels
760 cross_pairs = cross_pairs
792 cross_pairs = cross_pairs
761 #print("OUT NOVALL 2")
793 #print("OUT NOVALL 2")
762
794
763 vcross0 = (cross_pairs[0] == channels[ii]).nonzero()
795 vcross0 = (cross_pairs[0] == channels[ii]).nonzero()
764 vcross1 = (cross_pairs[1] == channels[ii]).nonzero()
796 vcross1 = (cross_pairs[1] == channels[ii]).nonzero()
765 vcross = numpy.concatenate((vcross0,vcross1),axis=None)
797 vcross = numpy.concatenate((vcross0,vcross1),axis=None)
766 #print('vcros =', vcross)
798 #print('vcros =', vcross)
767
799
768 #Getting coherent echoes which are removed.
800 #Getting coherent echoes which are removed.
769 if len(novall) > 0:
801 if len(novall) > 0:
770 #val_spc[novall,ii,ifreq,ih] = 1
802 #val_spc[novall,ii,ifreq,ih] = 1
771 val_spc[ii,ifreq,ih,novall] = 1
803 val_spc[ii,ifreq,ih,novall] = 1
772 if len(vcross) > 0:
804 if len(vcross) > 0:
773 val_cspc[vcross,ifreq,ih,novall] = 1
805 val_cspc[vcross,ifreq,ih,novall] = 1
774
806
775 #Removing coherent from ISR data.
807 #Removing coherent from ISR data.
776 self.bloque0[ii,ifreq,ih,noval] = numpy.nan
808 self.bloque0[ii,ifreq,ih,noval] = numpy.nan
777 if len(vcross) > 0:
809 if len(vcross) > 0:
778 self.bloques[vcross,ifreq,ih,noval] = numpy.nan
810 self.bloques[vcross,ifreq,ih,noval] = numpy.nan
779 '''
811 '''
780
812
781 #print("Getting average of the spectra and cross-spectra from incoherent echoes.")
813 #print("Getting average of the spectra and cross-spectra from incoherent echoes.")
782 out_spectra = numpy.zeros([self.nChan,self.nFFTPoints,self.nHeights], dtype=float) #+numpy.nan
814 out_spectra = numpy.zeros([self.nChan,self.nFFTPoints,self.nHeights], dtype=float) #+numpy.nan
783 out_cspectra = numpy.zeros([self.nPairs,self.nFFTPoints,self.nHeights], dtype=complex) #+numpy.nan
815 out_cspectra = numpy.zeros([self.nPairs,self.nFFTPoints,self.nHeights], dtype=complex) #+numpy.nan
784 for ih in range(self.nHeights):
816 for ih in range(self.nHeights):
785 for ifreq in range(self.nFFTPoints):
817 for ifreq in range(self.nFFTPoints):
786 for ich in range(self.nChan):
818 for ich in range(self.nChan):
787 tmp = spectra[:,ich,ifreq,ih]
819 tmp = spectra[:,ich,ifreq,ih]
788 valid = (numpy.isfinite(tmp[:])==True).nonzero()
820 valid = (numpy.isfinite(tmp[:])==True).nonzero()
789 # if ich == 0 and ifreq == 0 and ih == 17 :
821
790 # print tmp
791 # print valid
792 # print len(valid[0])
793 #print('TMP',tmp)
794 if len(valid[0]) >0 :
822 if len(valid[0]) >0 :
795 out_spectra[ich,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
823 out_spectra[ich,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
796 #for icr in range(nPairs):
824
797 for icr in range(self.nPairs):
825 for icr in range(self.nPairs):
798 tmp = numpy.squeeze(cspectra[:,icr,ifreq,ih])
826 tmp = numpy.squeeze(cspectra[:,icr,ifreq,ih])
799 valid = (numpy.isfinite(tmp)==True).nonzero()
827 valid = (numpy.isfinite(tmp)==True).nonzero()
800 if len(valid[0]) > 0:
828 if len(valid[0]) > 0:
801 out_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
829 out_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
802 '''
830 '''
803 # print('##########################################################')
831 # print('##########################################################')
804 print("Removing fake coherent echoes (at least 4 points around the point)")
832 print("Removing fake coherent echoes (at least 4 points around the point)")
805
833
806 val_spectra = numpy.sum(val_spc,0)
834 val_spectra = numpy.sum(val_spc,0)
807 val_cspectra = numpy.sum(val_cspc,0)
835 val_cspectra = numpy.sum(val_cspc,0)
808
836
809 val_spectra = self.REM_ISOLATED_POINTS(val_spectra,4)
837 val_spectra = self.REM_ISOLATED_POINTS(val_spectra,4)
810 val_cspectra = self.REM_ISOLATED_POINTS(val_cspectra,4)
838 val_cspectra = self.REM_ISOLATED_POINTS(val_cspectra,4)
811
839
812 for i in range(nChan):
840 for i in range(nChan):
813 for j in range(nProf):
841 for j in range(nProf):
814 for k in range(nHeights):
842 for k in range(nHeights):
815 if numpy.isfinite(val_spectra[i,j,k]) and val_spectra[i,j,k] < 1 :
843 if numpy.isfinite(val_spectra[i,j,k]) and val_spectra[i,j,k] < 1 :
816 val_spc[:,i,j,k] = 0.0
844 val_spc[:,i,j,k] = 0.0
817 for i in range(nPairs):
845 for i in range(nPairs):
818 for j in range(nProf):
846 for j in range(nProf):
819 for k in range(nHeights):
847 for k in range(nHeights):
820 if numpy.isfinite(val_cspectra[i,j,k]) and val_cspectra[i,j,k] < 1 :
848 if numpy.isfinite(val_cspectra[i,j,k]) and val_cspectra[i,j,k] < 1 :
821 val_cspc[:,i,j,k] = 0.0
849 val_cspc[:,i,j,k] = 0.0
822
850
823 # val_spc = numpy.reshape(val_spc, (len(spectra[:,0,0,0]),nProf*nHeights*nChan))
851 # val_spc = numpy.reshape(val_spc, (len(spectra[:,0,0,0]),nProf*nHeights*nChan))
824 # if numpy.isfinite(val_spectra)==str(True):
852 # if numpy.isfinite(val_spectra)==str(True):
825 # noval = (val_spectra<1).nonzero()
853 # noval = (val_spectra<1).nonzero()
826 # if len(noval) > 0:
854 # if len(noval) > 0:
827 # val_spc[:,noval] = 0.0
855 # val_spc[:,noval] = 0.0
828 # val_spc = numpy.reshape(val_spc, (149,nChan,nProf,nHeights))
856 # val_spc = numpy.reshape(val_spc, (149,nChan,nProf,nHeights))
829
857
830 #val_cspc = numpy.reshape(val_spc, (149,nChan*nHeights*nProf))
858 #val_cspc = numpy.reshape(val_spc, (149,nChan*nHeights*nProf))
831 #if numpy.isfinite(val_cspectra)==str(True):
859 #if numpy.isfinite(val_cspectra)==str(True):
832 # noval = (val_cspectra<1).nonzero()
860 # noval = (val_cspectra<1).nonzero()
833 # if len(noval) > 0:
861 # if len(noval) > 0:
834 # val_cspc[:,noval] = 0.0
862 # val_cspc[:,noval] = 0.0
835 # val_cspc = numpy.reshape(val_cspc, (149,nChan,nProf,nHeights))
863 # val_cspc = numpy.reshape(val_cspc, (149,nChan,nProf,nHeights))
836 tmp_sat_spectra = spectra.copy()
864 tmp_sat_spectra = spectra.copy()
837 tmp_sat_spectra = tmp_sat_spectra*numpy.nan
865 tmp_sat_spectra = tmp_sat_spectra*numpy.nan
838 tmp_sat_cspectra = cspectra.copy()
866 tmp_sat_cspectra = cspectra.copy()
839 tmp_sat_cspectra = tmp_sat_cspectra*numpy.nan
867 tmp_sat_cspectra = tmp_sat_cspectra*numpy.nan
840 '''
868 '''
841 # fig = plt.figure(figsize=(6,5))
869 # fig = plt.figure(figsize=(6,5))
842 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
870 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
843 # ax = fig.add_axes([left, bottom, width, height])
871 # ax = fig.add_axes([left, bottom, width, height])
844 # cp = ax.contour(10*numpy.log10(numpy.absolute(spectra[0,0,:,:])))
872 # cp = ax.contour(10*numpy.log10(numpy.absolute(spectra[0,0,:,:])))
845 # ax.clabel(cp, inline=True,fontsize=10)
873 # ax.clabel(cp, inline=True,fontsize=10)
846 # plt.show()
874 # plt.show()
847 '''
875 '''
848 val = (val_spc > 0).nonzero()
876 val = (val_spc > 0).nonzero()
849 if len(val[0]) > 0:
877 if len(val[0]) > 0:
850 tmp_sat_spectra[val] = in_sat_spectra[val]
878 tmp_sat_spectra[val] = in_sat_spectra[val]
851 val = (val_cspc > 0).nonzero()
879 val = (val_cspc > 0).nonzero()
852 if len(val[0]) > 0:
880 if len(val[0]) > 0:
853 tmp_sat_cspectra[val] = in_sat_cspectra[val]
881 tmp_sat_cspectra[val] = in_sat_cspectra[val]
854
882
855 print("Getting average of the spectra and cross-spectra from incoherent echoes 2")
883 print("Getting average of the spectra and cross-spectra from incoherent echoes 2")
856 sat_spectra = numpy.zeros((nChan,nProf,nHeights), dtype=float)
884 sat_spectra = numpy.zeros((nChan,nProf,nHeights), dtype=float)
857 sat_cspectra = numpy.zeros((nPairs,nProf,nHeights), dtype=complex)
885 sat_cspectra = numpy.zeros((nPairs,nProf,nHeights), dtype=complex)
858 for ih in range(nHeights):
886 for ih in range(nHeights):
859 for ifreq in range(nProf):
887 for ifreq in range(nProf):
860 for ich in range(nChan):
888 for ich in range(nChan):
861 tmp = numpy.squeeze(tmp_sat_spectra[:,ich,ifreq,ih])
889 tmp = numpy.squeeze(tmp_sat_spectra[:,ich,ifreq,ih])
862 valid = (numpy.isfinite(tmp)).nonzero()
890 valid = (numpy.isfinite(tmp)).nonzero()
863 if len(valid[0]) > 0:
891 if len(valid[0]) > 0:
864 sat_spectra[ich,ifreq,ih] = numpy.nansum(tmp)/len(valid[0])
892 sat_spectra[ich,ifreq,ih] = numpy.nansum(tmp)/len(valid[0])
865
893
866 for icr in range(nPairs):
894 for icr in range(nPairs):
867 tmp = numpy.squeeze(tmp_sat_cspectra[:,icr,ifreq,ih])
895 tmp = numpy.squeeze(tmp_sat_cspectra[:,icr,ifreq,ih])
868 valid = (numpy.isfinite(tmp)).nonzero()
896 valid = (numpy.isfinite(tmp)).nonzero()
869 if len(valid[0]) > 0:
897 if len(valid[0]) > 0:
870 sat_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)/len(valid[0])
898 sat_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)/len(valid[0])
871 '''
899 '''
872 #self.__dataReady= True
900 #self.__dataReady= True
873 #sat_spectra, sat_cspectra= sat_spectra, sat_cspectra
901 #sat_spectra, sat_cspectra= sat_spectra, sat_cspectra
874 #if not self.__dataReady:
902 #if not self.__dataReady:
875 #return None, None
903 #return None, None
876 #return out_spectra, out_cspectra ,sat_spectra,sat_cspectra
904 #return out_spectra, out_cspectra ,sat_spectra,sat_cspectra
877 return out_spectra, out_cspectra
905 return out_spectra, out_cspectra
878
906
879 def REM_ISOLATED_POINTS(self,array,rth):
907 def REM_ISOLATED_POINTS(self,array,rth):
880 # import matplotlib.pyplot as plt
908 # import matplotlib.pyplot as plt
881 if rth == None :
909 if rth == None :
882 rth = 4
910 rth = 4
883 print("REM ISO")
911 print("REM ISO")
884 num_prof = len(array[0,:,0])
912 num_prof = len(array[0,:,0])
885 num_hei = len(array[0,0,:])
913 num_hei = len(array[0,0,:])
886 n2d = len(array[:,0,0])
914 n2d = len(array[:,0,0])
887
915
888 for ii in range(n2d) :
916 for ii in range(n2d) :
889 #print ii,n2d
917 #print ii,n2d
890 tmp = array[ii,:,:]
918 tmp = array[ii,:,:]
891 #print tmp.shape, array[ii,101,:],array[ii,102,:]
919 #print tmp.shape, array[ii,101,:],array[ii,102,:]
892
920
893 # fig = plt.figure(figsize=(6,5))
921 # fig = plt.figure(figsize=(6,5))
894 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
922 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
895 # ax = fig.add_axes([left, bottom, width, height])
923 # ax = fig.add_axes([left, bottom, width, height])
896 # x = range(num_prof)
924 # x = range(num_prof)
897 # y = range(num_hei)
925 # y = range(num_hei)
898 # cp = ax.contour(y,x,tmp)
926 # cp = ax.contour(y,x,tmp)
899 # ax.clabel(cp, inline=True,fontsize=10)
927 # ax.clabel(cp, inline=True,fontsize=10)
900 # plt.show()
928 # plt.show()
901
929
902 #indxs = WHERE(FINITE(tmp) AND tmp GT 0,cindxs)
930 #indxs = WHERE(FINITE(tmp) AND tmp GT 0,cindxs)
903 tmp = numpy.reshape(tmp,num_prof*num_hei)
931 tmp = numpy.reshape(tmp,num_prof*num_hei)
904 indxs1 = (numpy.isfinite(tmp)==True).nonzero()
932 indxs1 = (numpy.isfinite(tmp)==True).nonzero()
905 indxs2 = (tmp > 0).nonzero()
933 indxs2 = (tmp > 0).nonzero()
906
934
907 indxs1 = (indxs1[0])
935 indxs1 = (indxs1[0])
908 indxs2 = indxs2[0]
936 indxs2 = indxs2[0]
909 #indxs1 = numpy.array(indxs1[0])
937 #indxs1 = numpy.array(indxs1[0])
910 #indxs2 = numpy.array(indxs2[0])
938 #indxs2 = numpy.array(indxs2[0])
911 indxs = None
939 indxs = None
912 #print indxs1 , indxs2
940 #print indxs1 , indxs2
913 for iv in range(len(indxs2)):
941 for iv in range(len(indxs2)):
914 indv = numpy.array((indxs1 == indxs2[iv]).nonzero())
942 indv = numpy.array((indxs1 == indxs2[iv]).nonzero())
915 #print len(indxs2), indv
943 #print len(indxs2), indv
916 if len(indv[0]) > 0 :
944 if len(indv[0]) > 0 :
917 indxs = numpy.concatenate((indxs,indxs2[iv]), axis=None)
945 indxs = numpy.concatenate((indxs,indxs2[iv]), axis=None)
918 # print indxs
946 # print indxs
919 indxs = indxs[1:]
947 indxs = indxs[1:]
920 #print(indxs, len(indxs))
948 #print(indxs, len(indxs))
921 if len(indxs) < 4 :
949 if len(indxs) < 4 :
922 array[ii,:,:] = 0.
950 array[ii,:,:] = 0.
923 return
951 return
924
952
925 xpos = numpy.mod(indxs ,num_hei)
953 xpos = numpy.mod(indxs ,num_hei)
926 ypos = (indxs / num_hei)
954 ypos = (indxs / num_hei)
927 sx = numpy.argsort(xpos) # Ordering respect to "x" (time)
955 sx = numpy.argsort(xpos) # Ordering respect to "x" (time)
928 #print sx
956 #print sx
929 xpos = xpos[sx]
957 xpos = xpos[sx]
930 ypos = ypos[sx]
958 ypos = ypos[sx]
931
959
932 # *********************************** Cleaning isolated points **********************************
960 # *********************************** Cleaning isolated points **********************************
933 ic = 0
961 ic = 0
934 while True :
962 while True :
935 r = numpy.sqrt(list(numpy.power((xpos[ic]-xpos),2)+ numpy.power((ypos[ic]-ypos),2)))
963 r = numpy.sqrt(list(numpy.power((xpos[ic]-xpos),2)+ numpy.power((ypos[ic]-ypos),2)))
936 #no_coh = WHERE(FINITE(r) AND (r LE rth),cno_coh)
964 #no_coh = WHERE(FINITE(r) AND (r LE rth),cno_coh)
937 #plt.plot(r)
965 #plt.plot(r)
938 #plt.show()
966 #plt.show()
939 no_coh1 = (numpy.isfinite(r)==True).nonzero()
967 no_coh1 = (numpy.isfinite(r)==True).nonzero()
940 no_coh2 = (r <= rth).nonzero()
968 no_coh2 = (r <= rth).nonzero()
941 #print r, no_coh1, no_coh2
969 #print r, no_coh1, no_coh2
942 no_coh1 = numpy.array(no_coh1[0])
970 no_coh1 = numpy.array(no_coh1[0])
943 no_coh2 = numpy.array(no_coh2[0])
971 no_coh2 = numpy.array(no_coh2[0])
944 no_coh = None
972 no_coh = None
945 #print valid1 , valid2
973 #print valid1 , valid2
946 for iv in range(len(no_coh2)):
974 for iv in range(len(no_coh2)):
947 indv = numpy.array((no_coh1 == no_coh2[iv]).nonzero())
975 indv = numpy.array((no_coh1 == no_coh2[iv]).nonzero())
948 if len(indv[0]) > 0 :
976 if len(indv[0]) > 0 :
949 no_coh = numpy.concatenate((no_coh,no_coh2[iv]), axis=None)
977 no_coh = numpy.concatenate((no_coh,no_coh2[iv]), axis=None)
950 no_coh = no_coh[1:]
978 no_coh = no_coh[1:]
951 #print len(no_coh), no_coh
979 #print len(no_coh), no_coh
952 if len(no_coh) < 4 :
980 if len(no_coh) < 4 :
953 #print xpos[ic], ypos[ic], ic
981 #print xpos[ic], ypos[ic], ic
954 # plt.plot(r)
982 # plt.plot(r)
955 # plt.show()
983 # plt.show()
956 xpos[ic] = numpy.nan
984 xpos[ic] = numpy.nan
957 ypos[ic] = numpy.nan
985 ypos[ic] = numpy.nan
958
986
959 ic = ic + 1
987 ic = ic + 1
960 if (ic == len(indxs)) :
988 if (ic == len(indxs)) :
961 break
989 break
962 #print( xpos, ypos)
990 #print( xpos, ypos)
963
991
964 indxs = (numpy.isfinite(list(xpos))==True).nonzero()
992 indxs = (numpy.isfinite(list(xpos))==True).nonzero()
965 #print indxs[0]
993 #print indxs[0]
966 if len(indxs[0]) < 4 :
994 if len(indxs[0]) < 4 :
967 array[ii,:,:] = 0.
995 array[ii,:,:] = 0.
968 return
996 return
969
997
970 xpos = xpos[indxs[0]]
998 xpos = xpos[indxs[0]]
971 ypos = ypos[indxs[0]]
999 ypos = ypos[indxs[0]]
972 for i in range(0,len(ypos)):
1000 for i in range(0,len(ypos)):
973 ypos[i]=int(ypos[i])
1001 ypos[i]=int(ypos[i])
974 junk = tmp
1002 junk = tmp
975 tmp = junk*0.0
1003 tmp = junk*0.0
976
1004
977 tmp[list(xpos + (ypos*num_hei))] = junk[list(xpos + (ypos*num_hei))]
1005 tmp[list(xpos + (ypos*num_hei))] = junk[list(xpos + (ypos*num_hei))]
978 array[ii,:,:] = numpy.reshape(tmp,(num_prof,num_hei))
1006 array[ii,:,:] = numpy.reshape(tmp,(num_prof,num_hei))
979
1007
980 #print array.shape
1008 #print array.shape
981 #tmp = numpy.reshape(tmp,(num_prof,num_hei))
1009 #tmp = numpy.reshape(tmp,(num_prof,num_hei))
982 #print tmp.shape
1010 #print tmp.shape
983
1011
984 # fig = plt.figure(figsize=(6,5))
1012 # fig = plt.figure(figsize=(6,5))
985 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
1013 # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
986 # ax = fig.add_axes([left, bottom, width, height])
1014 # ax = fig.add_axes([left, bottom, width, height])
987 # x = range(num_prof)
1015 # x = range(num_prof)
988 # y = range(num_hei)
1016 # y = range(num_hei)
989 # cp = ax.contour(y,x,array[ii,:,:])
1017 # cp = ax.contour(y,x,array[ii,:,:])
990 # ax.clabel(cp, inline=True,fontsize=10)
1018 # ax.clabel(cp, inline=True,fontsize=10)
991 # plt.show()
1019 # plt.show()
992 return array
1020 return array
993
1021
994 class removeInterference(Operation):
1022 class removeInterference(Operation):
995
1023
996 def removeInterference2(self):
1024 def removeInterference2(self):
997
1025
998 cspc = self.dataOut.data_cspc
1026 cspc = self.dataOut.data_cspc
999 spc = self.dataOut.data_spc
1027 spc = self.dataOut.data_spc
1000 Heights = numpy.arange(cspc.shape[2])
1028 Heights = numpy.arange(cspc.shape[2])
1001 realCspc = numpy.abs(cspc)
1029 realCspc = numpy.abs(cspc)
1002
1030
1003 for i in range(cspc.shape[0]):
1031 for i in range(cspc.shape[0]):
1004 LinePower= numpy.sum(realCspc[i], axis=0)
1032 LinePower= numpy.sum(realCspc[i], axis=0)
1005 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
1033 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
1006 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
1034 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
1007 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
1035 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
1008 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
1036 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
1009 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
1037 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
1010
1038
1011
1039
1012 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
1040 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
1013 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
1041 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
1014 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
1042 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
1015 cspc[i,InterferenceRange,:] = numpy.NaN
1043 cspc[i,InterferenceRange,:] = numpy.NaN
1016
1044
1017 self.dataOut.data_cspc = cspc
1045 self.dataOut.data_cspc = cspc
1018
1046
1019 def removeInterference(self, interf = 2, hei_interf = None, nhei_interf = None, offhei_interf = None):
1047 def removeInterference(self, interf = 2, hei_interf = None, nhei_interf = None, offhei_interf = None):
1020
1048
1021 jspectra = self.dataOut.data_spc
1049 jspectra = self.dataOut.data_spc
1022 jcspectra = self.dataOut.data_cspc
1050 jcspectra = self.dataOut.data_cspc
1023 jnoise = self.dataOut.getNoise()
1051 jnoise = self.dataOut.getNoise()
1024 num_incoh = self.dataOut.nIncohInt
1052 num_incoh = self.dataOut.nIncohInt
1025
1053
1026 num_channel = jspectra.shape[0]
1054 num_channel = jspectra.shape[0]
1027 num_prof = jspectra.shape[1]
1055 num_prof = jspectra.shape[1]
1028 num_hei = jspectra.shape[2]
1056 num_hei = jspectra.shape[2]
1029
1057
1030 # hei_interf
1058 # hei_interf
1031 if hei_interf is None:
1059 if hei_interf is None:
1032 count_hei = int(num_hei / 2)
1060 count_hei = int(num_hei / 2)
1033 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
1061 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
1034 hei_interf = numpy.asarray(hei_interf)[0]
1062 hei_interf = numpy.asarray(hei_interf)[0]
1035 # nhei_interf
1063 # nhei_interf
1036 if (nhei_interf == None):
1064 if (nhei_interf == None):
1037 nhei_interf = 5
1065 nhei_interf = 5
1038 if (nhei_interf < 1):
1066 if (nhei_interf < 1):
1039 nhei_interf = 1
1067 nhei_interf = 1
1040 if (nhei_interf > count_hei):
1068 if (nhei_interf > count_hei):
1041 nhei_interf = count_hei
1069 nhei_interf = count_hei
1042 if (offhei_interf == None):
1070 if (offhei_interf == None):
1043 offhei_interf = 0
1071 offhei_interf = 0
1044
1072
1045 ind_hei = list(range(num_hei))
1073 ind_hei = list(range(num_hei))
1046 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
1074 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
1047 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
1075 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
1048 mask_prof = numpy.asarray(list(range(num_prof)))
1076 mask_prof = numpy.asarray(list(range(num_prof)))
1049 num_mask_prof = mask_prof.size
1077 num_mask_prof = mask_prof.size
1050 comp_mask_prof = [0, num_prof / 2]
1078 comp_mask_prof = [0, num_prof / 2]
1051
1079
1052 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
1080 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
1053 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
1081 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
1054 jnoise = numpy.nan
1082 jnoise = numpy.nan
1055 noise_exist = jnoise[0] < numpy.Inf
1083 noise_exist = jnoise[0] < numpy.Inf
1056
1084
1057 # Subrutina de Remocion de la Interferencia
1085 # Subrutina de Remocion de la Interferencia
1058 for ich in range(num_channel):
1086 for ich in range(num_channel):
1059 # Se ordena los espectros segun su potencia (menor a mayor)
1087 # Se ordena los espectros segun su potencia (menor a mayor)
1060 power = jspectra[ich, mask_prof, :]
1088 power = jspectra[ich, mask_prof, :]
1061 power = power[:, hei_interf]
1089 power = power[:, hei_interf]
1062 power = power.sum(axis=0)
1090 power = power.sum(axis=0)
1063 psort = power.ravel().argsort()
1091 psort = power.ravel().argsort()
1064
1092
1065 # Se estima la interferencia promedio en los Espectros de Potencia empleando
1093 # Se estima la interferencia promedio en los Espectros de Potencia empleando
1066 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
1094 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
1067 offhei_interf, nhei_interf + offhei_interf))]]]
1095 offhei_interf, nhei_interf + offhei_interf))]]]
1068
1096
1069 if noise_exist:
1097 if noise_exist:
1070 # tmp_noise = jnoise[ich] / num_prof
1098 # tmp_noise = jnoise[ich] / num_prof
1071 tmp_noise = jnoise[ich]
1099 tmp_noise = jnoise[ich]
1072 junkspc_interf = junkspc_interf - tmp_noise
1100 junkspc_interf = junkspc_interf - tmp_noise
1073 #junkspc_interf[:,comp_mask_prof] = 0
1101 #junkspc_interf[:,comp_mask_prof] = 0
1074
1102
1075 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
1103 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
1076 jspc_interf = jspc_interf.transpose()
1104 jspc_interf = jspc_interf.transpose()
1077 # Calculando el espectro de interferencia promedio
1105 # Calculando el espectro de interferencia promedio
1078 noiseid = numpy.where(
1106 noiseid = numpy.where(
1079 jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
1107 jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
1080 noiseid = noiseid[0]
1108 noiseid = noiseid[0]
1081 cnoiseid = noiseid.size
1109 cnoiseid = noiseid.size
1082 interfid = numpy.where(
1110 interfid = numpy.where(
1083 jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
1111 jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
1084 interfid = interfid[0]
1112 interfid = interfid[0]
1085 cinterfid = interfid.size
1113 cinterfid = interfid.size
1086
1114
1087 if (cnoiseid > 0):
1115 if (cnoiseid > 0):
1088 jspc_interf[noiseid] = 0
1116 jspc_interf[noiseid] = 0
1089
1117
1090 # Expandiendo los perfiles a limpiar
1118 # Expandiendo los perfiles a limpiar
1091 if (cinterfid > 0):
1119 if (cinterfid > 0):
1092 new_interfid = (
1120 new_interfid = (
1093 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
1121 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
1094 new_interfid = numpy.asarray(new_interfid)
1122 new_interfid = numpy.asarray(new_interfid)
1095 new_interfid = {x for x in new_interfid}
1123 new_interfid = {x for x in new_interfid}
1096 new_interfid = numpy.array(list(new_interfid))
1124 new_interfid = numpy.array(list(new_interfid))
1097 new_cinterfid = new_interfid.size
1125 new_cinterfid = new_interfid.size
1098 else:
1126 else:
1099 new_cinterfid = 0
1127 new_cinterfid = 0
1100
1128
1101 for ip in range(new_cinterfid):
1129 for ip in range(new_cinterfid):
1102 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
1130 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
1103 jspc_interf[new_interfid[ip]
1131 jspc_interf[new_interfid[ip]
1104 ] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
1132 ] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
1105
1133
1106 jspectra[ich, :, ind_hei] = jspectra[ich, :,
1134 jspectra[ich, :, ind_hei] = jspectra[ich, :,
1107 ind_hei] - jspc_interf # Corregir indices
1135 ind_hei] - jspc_interf # Corregir indices
1108
1136
1109 # Removiendo la interferencia del punto de mayor interferencia
1137 # Removiendo la interferencia del punto de mayor interferencia
1110 ListAux = jspc_interf[mask_prof].tolist()
1138 ListAux = jspc_interf[mask_prof].tolist()
1111 maxid = ListAux.index(max(ListAux))
1139 maxid = ListAux.index(max(ListAux))
1112
1140
1113 if cinterfid > 0:
1141 if cinterfid > 0:
1114 for ip in range(cinterfid * (interf == 2) - 1):
1142 for ip in range(cinterfid * (interf == 2) - 1):
1115 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
1143 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
1116 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
1144 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
1117 cind = len(ind)
1145 cind = len(ind)
1118
1146
1119 if (cind > 0):
1147 if (cind > 0):
1120 jspectra[ich, interfid[ip], ind] = tmp_noise * \
1148 jspectra[ich, interfid[ip], ind] = tmp_noise * \
1121 (1 + (numpy.random.uniform(cind) - 0.5) /
1149 (1 + (numpy.random.uniform(cind) - 0.5) /
1122 numpy.sqrt(num_incoh))
1150 numpy.sqrt(num_incoh))
1123
1151
1124 ind = numpy.array([-2, -1, 1, 2])
1152 ind = numpy.array([-2, -1, 1, 2])
1125 xx = numpy.zeros([4, 4])
1153 xx = numpy.zeros([4, 4])
1126
1154
1127 for id1 in range(4):
1155 for id1 in range(4):
1128 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1156 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1129
1157
1130 xx_inv = numpy.linalg.inv(xx)
1158 xx_inv = numpy.linalg.inv(xx)
1131 xx = xx_inv[:, 0]
1159 xx = xx_inv[:, 0]
1132 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1160 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1133 yy = jspectra[ich, mask_prof[ind], :]
1161 yy = jspectra[ich, mask_prof[ind], :]
1134 jspectra[ich, mask_prof[maxid], :] = numpy.dot(
1162 jspectra[ich, mask_prof[maxid], :] = numpy.dot(
1135 yy.transpose(), xx)
1163 yy.transpose(), xx)
1136
1164
1137 indAux = (jspectra[ich, :, :] < tmp_noise *
1165 indAux = (jspectra[ich, :, :] < tmp_noise *
1138 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
1166 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
1139 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
1167 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
1140 (1 - 1 / numpy.sqrt(num_incoh))
1168 (1 - 1 / numpy.sqrt(num_incoh))
1141
1169
1142 # Remocion de Interferencia en el Cross Spectra
1170 # Remocion de Interferencia en el Cross Spectra
1143 if jcspectra is None:
1171 if jcspectra is None:
1144 return jspectra, jcspectra
1172 return jspectra, jcspectra
1145 num_pairs = int(jcspectra.size / (num_prof * num_hei))
1173 num_pairs = int(jcspectra.size / (num_prof * num_hei))
1146 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
1174 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
1147
1175
1148 for ip in range(num_pairs):
1176 for ip in range(num_pairs):
1149
1177
1150 #-------------------------------------------
1178 #-------------------------------------------
1151
1179
1152 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
1180 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
1153 cspower = cspower[:, hei_interf]
1181 cspower = cspower[:, hei_interf]
1154 cspower = cspower.sum(axis=0)
1182 cspower = cspower.sum(axis=0)
1155
1183
1156 cspsort = cspower.ravel().argsort()
1184 cspsort = cspower.ravel().argsort()
1157 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
1185 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
1158 offhei_interf, nhei_interf + offhei_interf))]]]
1186 offhei_interf, nhei_interf + offhei_interf))]]]
1159 junkcspc_interf = junkcspc_interf.transpose()
1187 junkcspc_interf = junkcspc_interf.transpose()
1160 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
1188 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
1161
1189
1162 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
1190 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
1163
1191
1164 median_real = int(numpy.median(numpy.real(
1192 median_real = int(numpy.median(numpy.real(
1165 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1193 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1166 median_imag = int(numpy.median(numpy.imag(
1194 median_imag = int(numpy.median(numpy.imag(
1167 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1195 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1168 comp_mask_prof = [int(e) for e in comp_mask_prof]
1196 comp_mask_prof = [int(e) for e in comp_mask_prof]
1169 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
1197 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
1170 median_real, median_imag)
1198 median_real, median_imag)
1171
1199
1172 for iprof in range(num_prof):
1200 for iprof in range(num_prof):
1173 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
1201 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
1174 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
1202 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
1175
1203
1176 # Removiendo la Interferencia
1204 # Removiendo la Interferencia
1177 jcspectra[ip, :, ind_hei] = jcspectra[ip,
1205 jcspectra[ip, :, ind_hei] = jcspectra[ip,
1178 :, ind_hei] - jcspc_interf
1206 :, ind_hei] - jcspc_interf
1179
1207
1180 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
1208 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
1181 maxid = ListAux.index(max(ListAux))
1209 maxid = ListAux.index(max(ListAux))
1182
1210
1183 ind = numpy.array([-2, -1, 1, 2])
1211 ind = numpy.array([-2, -1, 1, 2])
1184 xx = numpy.zeros([4, 4])
1212 xx = numpy.zeros([4, 4])
1185
1213
1186 for id1 in range(4):
1214 for id1 in range(4):
1187 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1215 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1188
1216
1189 xx_inv = numpy.linalg.inv(xx)
1217 xx_inv = numpy.linalg.inv(xx)
1190 xx = xx_inv[:, 0]
1218 xx = xx_inv[:, 0]
1191
1219
1192 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1220 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1193 yy = jcspectra[ip, mask_prof[ind], :]
1221 yy = jcspectra[ip, mask_prof[ind], :]
1194 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1222 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1195
1223
1196 # Guardar Resultados
1224 # Guardar Resultados
1197 self.dataOut.data_spc = jspectra
1225 self.dataOut.data_spc = jspectra
1198 self.dataOut.data_cspc = jcspectra
1226 self.dataOut.data_cspc = jcspectra
1199
1227
1200 return 1
1228 return 1
1201
1229
1202 def run(self, dataOut, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None, mode=1):
1230 def run(self, dataOut, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None, mode=1):
1203
1231
1204 self.dataOut = dataOut
1232 self.dataOut = dataOut
1205
1233
1206 if mode == 1:
1234 if mode == 1:
1207 self.removeInterference(interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None)
1235 self.removeInterference(interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None)
1208 elif mode == 2:
1236 elif mode == 2:
1209 self.removeInterference2()
1237 self.removeInterference2()
1210
1238
1211 return self.dataOut
1239 return self.dataOut
1212
1240
1213
1241
1214 class IncohInt(Operation):
1242 class IncohInt(Operation):
1215
1243
1216 __profIndex = 0
1244 __profIndex = 0
1217 __withOverapping = False
1245 __withOverapping = False
1218
1246
1219 __byTime = False
1247 __byTime = False
1220 __initime = None
1248 __initime = None
1221 __lastdatatime = None
1249 __lastdatatime = None
1222 __integrationtime = None
1250 __integrationtime = None
1223
1251
1224 __buffer_spc = None
1252 __buffer_spc = None
1225 __buffer_cspc = None
1253 __buffer_cspc = None
1226 __buffer_dc = None
1254 __buffer_dc = None
1227
1255
1228 __dataReady = False
1256 __dataReady = False
1229
1257
1230 __timeInterval = None
1258 __timeInterval = None
1231
1259
1232 n = None
1260 n = None
1233
1261
1234 def __init__(self):
1262 def __init__(self):
1235
1263
1236 Operation.__init__(self)
1264 Operation.__init__(self)
1237
1265
1238 def setup(self, n=None, timeInterval=None, overlapping=False):
1266 def setup(self, n=None, timeInterval=None, overlapping=False):
1239 """
1267 """
1240 Set the parameters of the integration class.
1268 Set the parameters of the integration class.
1241
1269
1242 Inputs:
1270 Inputs:
1243
1271
1244 n : Number of coherent integrations
1272 n : Number of coherent integrations
1245 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1273 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1246 overlapping :
1274 overlapping :
1247
1275
1248 """
1276 """
1249
1277
1250 self.__initime = None
1278 self.__initime = None
1251 self.__lastdatatime = 0
1279 self.__lastdatatime = 0
1252
1280
1253 self.__buffer_spc = 0
1281 self.__buffer_spc = 0
1254 self.__buffer_cspc = 0
1282 self.__buffer_cspc = 0
1255 self.__buffer_dc = 0
1283 self.__buffer_dc = 0
1256
1284
1257 self.__profIndex = 0
1285 self.__profIndex = 0
1258 self.__dataReady = False
1286 self.__dataReady = False
1259 self.__byTime = False
1287 self.__byTime = False
1260
1288
1261 if n is None and timeInterval is None:
1289 if n is None and timeInterval is None:
1262 raise ValueError("n or timeInterval should be specified ...")
1290 raise ValueError("n or timeInterval should be specified ...")
1263
1291
1264 if n is not None:
1292 if n is not None:
1265 self.n = int(n)
1293 self.n = int(n)
1266 else:
1294 else:
1267
1295
1268 self.__integrationtime = int(timeInterval)
1296 self.__integrationtime = int(timeInterval)
1269 self.n = None
1297 self.n = None
1270 self.__byTime = True
1298 self.__byTime = True
1271
1299
1272 def putData(self, data_spc, data_cspc, data_dc):
1300 def putData(self, data_spc, data_cspc, data_dc):
1273 """
1301 """
1274 Add a profile to the __buffer_spc and increase in one the __profileIndex
1302 Add a profile to the __buffer_spc and increase in one the __profileIndex
1275
1303
1276 """
1304 """
1277
1305
1278 self.__buffer_spc += data_spc
1306 self.__buffer_spc += data_spc
1279
1307
1280 if data_cspc is None:
1308 if data_cspc is None:
1281 self.__buffer_cspc = None
1309 self.__buffer_cspc = None
1282 else:
1310 else:
1283 self.__buffer_cspc += data_cspc
1311 self.__buffer_cspc += data_cspc
1284
1312
1285 if data_dc is None:
1313 if data_dc is None:
1286 self.__buffer_dc = None
1314 self.__buffer_dc = None
1287 else:
1315 else:
1288 self.__buffer_dc += data_dc
1316 self.__buffer_dc += data_dc
1289
1317
1290 self.__profIndex += 1
1318 self.__profIndex += 1
1291
1319
1292 return
1320 return
1293
1321
1294 def pushData(self):
1322 def pushData(self):
1295 """
1323 """
1296 Return the sum of the last profiles and the profiles used in the sum.
1324 Return the sum of the last profiles and the profiles used in the sum.
1297
1325
1298 Affected:
1326 Affected:
1299
1327
1300 self.__profileIndex
1328 self.__profileIndex
1301
1329
1302 """
1330 """
1303
1331
1304 data_spc = self.__buffer_spc
1332 data_spc = self.__buffer_spc
1305 data_cspc = self.__buffer_cspc
1333 data_cspc = self.__buffer_cspc
1306 data_dc = self.__buffer_dc
1334 data_dc = self.__buffer_dc
1307 n = self.__profIndex
1335 n = self.__profIndex
1308
1336
1309 self.__buffer_spc = 0
1337 self.__buffer_spc = 0
1310 self.__buffer_cspc = 0
1338 self.__buffer_cspc = 0
1311 self.__buffer_dc = 0
1339 self.__buffer_dc = 0
1312 self.__profIndex = 0
1340 self.__profIndex = 0
1313
1341
1314 return data_spc, data_cspc, data_dc, n
1342 return data_spc, data_cspc, data_dc, n
1315
1343
1316 def byProfiles(self, *args):
1344 def byProfiles(self, *args):
1317
1345
1318 self.__dataReady = False
1346 self.__dataReady = False
1319 avgdata_spc = None
1347 avgdata_spc = None
1320 avgdata_cspc = None
1348 avgdata_cspc = None
1321 avgdata_dc = None
1349 avgdata_dc = None
1322
1350
1323 self.putData(*args)
1351 self.putData(*args)
1324
1352
1325 if self.__profIndex == self.n:
1353 if self.__profIndex == self.n:
1326
1354
1327 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1355 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1328 self.n = n
1356 self.n = n
1329 self.__dataReady = True
1357 self.__dataReady = True
1330
1358
1331 return avgdata_spc, avgdata_cspc, avgdata_dc
1359 return avgdata_spc, avgdata_cspc, avgdata_dc
1332
1360
1333 def byTime(self, datatime, *args):
1361 def byTime(self, datatime, *args):
1334
1362
1335 self.__dataReady = False
1363 self.__dataReady = False
1336 avgdata_spc = None
1364 avgdata_spc = None
1337 avgdata_cspc = None
1365 avgdata_cspc = None
1338 avgdata_dc = None
1366 avgdata_dc = None
1339
1367
1340 self.putData(*args)
1368 self.putData(*args)
1341
1369
1342 if (datatime - self.__initime) >= self.__integrationtime:
1370 if (datatime - self.__initime) >= self.__integrationtime:
1343 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1371 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1344 self.n = n
1372 self.n = n
1345 self.__dataReady = True
1373 self.__dataReady = True
1346
1374
1347 return avgdata_spc, avgdata_cspc, avgdata_dc
1375 return avgdata_spc, avgdata_cspc, avgdata_dc
1348
1376
1349 def integrate(self, datatime, *args):
1377 def integrate(self, datatime, *args):
1350
1378
1351 if self.__profIndex == 0:
1379 if self.__profIndex == 0:
1352 self.__initime = datatime
1380 self.__initime = datatime
1353
1381
1354 if self.__byTime:
1382 if self.__byTime:
1355 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1383 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1356 datatime, *args)
1384 datatime, *args)
1357 else:
1385 else:
1358 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1386 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1359
1387
1360 if not self.__dataReady:
1388 if not self.__dataReady:
1361 return None, None, None, None
1389 return None, None, None, None
1362
1390
1363 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1391 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1364
1392
1365 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1393 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1366 if n == 1:
1394 if n == 1:
1367 return dataOut
1395 return dataOut
1368
1396
1369 dataOut.flagNoData = True
1397 dataOut.flagNoData = True
1370
1398
1371 if not self.isConfig:
1399 if not self.isConfig:
1372 self.setup(n, timeInterval, overlapping)
1400 self.setup(n, timeInterval, overlapping)
1373 self.isConfig = True
1401 self.isConfig = True
1374
1402
1375 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1403 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1376 dataOut.data_spc,
1404 dataOut.data_spc,
1377 dataOut.data_cspc,
1405 dataOut.data_cspc,
1378 dataOut.data_dc)
1406 dataOut.data_dc)
1379
1407
1380 if self.__dataReady:
1408 if self.__dataReady:
1381
1409
1382 dataOut.data_spc = avgdata_spc
1410 dataOut.data_spc = avgdata_spc
1383 dataOut.data_cspc = avgdata_cspc
1411 dataOut.data_cspc = avgdata_cspc
1384 dataOut.data_dc = avgdata_dc
1412 dataOut.data_dc = avgdata_dc
1385 dataOut.nIncohInt *= self.n
1413 dataOut.nIncohInt *= self.n
1386 dataOut.utctime = avgdatatime
1414 dataOut.utctime = avgdatatime
1387 dataOut.flagNoData = False
1415 dataOut.flagNoData = False
1388
1416
1389 return dataOut
1417 return dataOut
1390
1418
1391 class dopplerFlip(Operation):
1419 class dopplerFlip(Operation):
1392
1420
1393 def run(self, dataOut):
1421 def run(self, dataOut):
1394 # arreglo 1: (num_chan, num_profiles, num_heights)
1422 # arreglo 1: (num_chan, num_profiles, num_heights)
1395 self.dataOut = dataOut
1423 self.dataOut = dataOut
1396 # JULIA-oblicua, indice 2
1424 # JULIA-oblicua, indice 2
1397 # arreglo 2: (num_profiles, num_heights)
1425 # arreglo 2: (num_profiles, num_heights)
1398 jspectra = self.dataOut.data_spc[2]
1426 jspectra = self.dataOut.data_spc[2]
1399 jspectra_tmp = numpy.zeros(jspectra.shape)
1427 jspectra_tmp = numpy.zeros(jspectra.shape)
1400 num_profiles = jspectra.shape[0]
1428 num_profiles = jspectra.shape[0]
1401 freq_dc = int(num_profiles / 2)
1429 freq_dc = int(num_profiles / 2)
1402 # Flip con for
1430 # Flip con for
1403 for j in range(num_profiles):
1431 for j in range(num_profiles):
1404 jspectra_tmp[num_profiles-j-1]= jspectra[j]
1432 jspectra_tmp[num_profiles-j-1]= jspectra[j]
1405 # Intercambio perfil de DC con perfil inmediato anterior
1433 # Intercambio perfil de DC con perfil inmediato anterior
1406 jspectra_tmp[freq_dc-1]= jspectra[freq_dc-1]
1434 jspectra_tmp[freq_dc-1]= jspectra[freq_dc-1]
1407 jspectra_tmp[freq_dc]= jspectra[freq_dc]
1435 jspectra_tmp[freq_dc]= jspectra[freq_dc]
1408 # canal modificado es re-escrito en el arreglo de canales
1436 # canal modificado es re-escrito en el arreglo de canales
1409 self.dataOut.data_spc[2] = jspectra_tmp
1437 self.dataOut.data_spc[2] = jspectra_tmp
1410
1438
1411 return self.dataOut
1439 return self.dataOut
General Comments 0
You need to be logged in to leave comments. Login now