##// END OF EJS Templates
update remHeightsIppInterf
joabAM -
r1583:96ac032e04a6
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,1159 +1,1159
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 """Definition of diferent Data objects for different types of data
5 """Definition of diferent Data objects for different types of data
6
6
7 Here you will find the diferent data objects for the different types
7 Here you will find the diferent data objects for the different types
8 of data, this data objects must be used as dataIn or dataOut objects in
8 of data, this data objects must be used as dataIn or dataOut objects in
9 processing units and operations. Currently the supported data objects are:
9 processing units and operations. Currently the supported data objects are:
10 Voltage, Spectra, SpectraHeis, Fits, Correlation and Parameters
10 Voltage, Spectra, SpectraHeis, Fits, Correlation and Parameters
11 """
11 """
12
12
13 import copy
13 import copy
14 import numpy
14 import numpy
15 import datetime
15 import datetime
16 import json
16 import json
17
17
18 import schainpy.admin
18 import schainpy.admin
19 from schainpy.utils import log
19 from schainpy.utils import log
20 from .jroheaderIO import SystemHeader, RadarControllerHeader,ProcessingHeader
20 from .jroheaderIO import SystemHeader, RadarControllerHeader,ProcessingHeader
21 from schainpy.model.data import _noise
21 from schainpy.model.data import _noise
22 SPEED_OF_LIGHT = 3e8
22 SPEED_OF_LIGHT = 3e8
23
23
24 def getNumpyDtype(dataTypeCode):
24 def getNumpyDtype(dataTypeCode):
25
25
26 if dataTypeCode == 0:
26 if dataTypeCode == 0:
27 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
27 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
28 elif dataTypeCode == 1:
28 elif dataTypeCode == 1:
29 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
29 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
30 elif dataTypeCode == 2:
30 elif dataTypeCode == 2:
31 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
31 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
32 elif dataTypeCode == 3:
32 elif dataTypeCode == 3:
33 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
33 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
34 elif dataTypeCode == 4:
34 elif dataTypeCode == 4:
35 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
35 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
36 elif dataTypeCode == 5:
36 elif dataTypeCode == 5:
37 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
37 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
38 else:
38 else:
39 raise ValueError('dataTypeCode was not defined')
39 raise ValueError('dataTypeCode was not defined')
40
40
41 return numpyDtype
41 return numpyDtype
42
42
43
43
44 def getDataTypeCode(numpyDtype):
44 def getDataTypeCode(numpyDtype):
45
45
46 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
46 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
47 datatype = 0
47 datatype = 0
48 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
48 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
49 datatype = 1
49 datatype = 1
50 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
50 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
51 datatype = 2
51 datatype = 2
52 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
52 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
53 datatype = 3
53 datatype = 3
54 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
54 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
55 datatype = 4
55 datatype = 4
56 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
56 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
57 datatype = 5
57 datatype = 5
58 else:
58 else:
59 datatype = None
59 datatype = None
60
60
61 return datatype
61 return datatype
62
62
63
63
64 def hildebrand_sekhon(data, navg):
64 def hildebrand_sekhon(data, navg):
65 """
65 """
66 This method is for the objective determination of the noise level in Doppler spectra. This
66 This method is for the objective determination of the noise level in Doppler spectra. This
67 implementation technique is based on the fact that the standard deviation of the spectral
67 implementation technique is based on the fact that the standard deviation of the spectral
68 densities is equal to the mean spectral density for white Gaussian noise
68 densities is equal to the mean spectral density for white Gaussian noise
69
69
70 Inputs:
70 Inputs:
71 Data : heights
71 Data : heights
72 navg : numbers of averages
72 navg : numbers of averages
73
73
74 Return:
74 Return:
75 mean : noise's level
75 mean : noise's level
76 """
76 """
77
77
78 sortdata = numpy.sort(data, axis=None)
78 sortdata = numpy.sort(data, axis=None)
79 '''
79 '''
80 lenOfData = len(sortdata)
80 lenOfData = len(sortdata)
81 nums_min = lenOfData*0.5
81 nums_min = lenOfData*0.5
82
82
83 if nums_min <= 5:
83 if nums_min <= 5:
84
84
85 nums_min = 5
85 nums_min = 5
86
86
87 sump = 0.
87 sump = 0.
88 sumq = 0.
88 sumq = 0.
89
89
90 j = 0
90 j = 0
91 cont = 1
91 cont = 1
92
92
93 while((cont == 1)and(j < lenOfData)):
93 while((cont == 1)and(j < lenOfData)):
94
94
95 sump += sortdata[j]
95 sump += sortdata[j]
96 sumq += sortdata[j]**2
96 sumq += sortdata[j]**2
97
97
98 if j > nums_min:
98 if j > nums_min:
99 rtest = float(j)/(j-1) + 1.0/navg
99 rtest = float(j)/(j-1) + 1.0/navg
100 if ((sumq*j) > (rtest*sump**2)):
100 if ((sumq*j) > (rtest*sump**2)):
101 j = j - 1
101 j = j - 1
102 sump = sump - sortdata[j]
102 sump = sump - sortdata[j]
103 sumq = sumq - sortdata[j]**2
103 sumq = sumq - sortdata[j]**2
104 cont = 0
104 cont = 0
105
105
106 j += 1
106 j += 1
107
107
108 lnoise = sump / j
108 lnoise = sump / j
109 return lnoise
109 return lnoise
110 '''
110 '''
111 return _noise.hildebrand_sekhon(sortdata, navg)
111 return _noise.hildebrand_sekhon(sortdata, navg)
112
112
113
113
114 class Beam:
114 class Beam:
115
115
116 def __init__(self):
116 def __init__(self):
117 self.codeList = []
117 self.codeList = []
118 self.azimuthList = []
118 self.azimuthList = []
119 self.zenithList = []
119 self.zenithList = []
120
120
121
121
122
122
123 class GenericData(object):
123 class GenericData(object):
124
124
125 flagNoData = True
125 flagNoData = True
126
126
127 def copy(self, inputObj=None):
127 def copy(self, inputObj=None):
128
128
129 if inputObj == None:
129 if inputObj == None:
130 return copy.deepcopy(self)
130 return copy.deepcopy(self)
131
131
132 for key in list(inputObj.__dict__.keys()):
132 for key in list(inputObj.__dict__.keys()):
133
133
134 attribute = inputObj.__dict__[key]
134 attribute = inputObj.__dict__[key]
135
135
136 # If this attribute is a tuple or list
136 # If this attribute is a tuple or list
137 if type(inputObj.__dict__[key]) in (tuple, list):
137 if type(inputObj.__dict__[key]) in (tuple, list):
138 self.__dict__[key] = attribute[:]
138 self.__dict__[key] = attribute[:]
139 continue
139 continue
140
140
141 # If this attribute is another object or instance
141 # If this attribute is another object or instance
142 if hasattr(attribute, '__dict__'):
142 if hasattr(attribute, '__dict__'):
143 self.__dict__[key] = attribute.copy()
143 self.__dict__[key] = attribute.copy()
144 continue
144 continue
145
145
146 self.__dict__[key] = inputObj.__dict__[key]
146 self.__dict__[key] = inputObj.__dict__[key]
147
147
148 def deepcopy(self):
148 def deepcopy(self):
149
149
150 return copy.deepcopy(self)
150 return copy.deepcopy(self)
151
151
152 def isEmpty(self):
152 def isEmpty(self):
153
153
154 return self.flagNoData
154 return self.flagNoData
155
155
156 def isReady(self):
156 def isReady(self):
157
157
158 return not self.flagNoData
158 return not self.flagNoData
159
159
160
160
161 class JROData(GenericData):
161 class JROData(GenericData):
162
162
163 useInputBuffer = False
163 useInputBuffer = False
164 buffer_empty = True
164 buffer_empty = True
165
165
166 systemHeaderObj = SystemHeader()
166 systemHeaderObj = SystemHeader()
167 radarControllerHeaderObj = RadarControllerHeader()
167 radarControllerHeaderObj = RadarControllerHeader()
168 type = None
168 type = None
169 datatype = None # dtype but in string
169 datatype = None # dtype but in string
170 nProfiles = None
170 nProfiles = None
171 heightList = None
171 heightList = None
172 channelList = None
172 channelList = None
173 flagDiscontinuousBlock = False
173 flagDiscontinuousBlock = False
174 useLocalTime = False
174 useLocalTime = False
175 utctime = None
175 utctime = None
176 timeZone = None
176 timeZone = None
177 dstFlag = None
177 dstFlag = None
178 errorCount = None
178 errorCount = None
179 blocksize = None
179 blocksize = None
180 flagDecodeData = False # asumo q la data no esta decodificada
180 flagDecodeData = False # asumo q la data no esta decodificada
181 flagDeflipData = False # asumo q la data no esta sin flip
181 flagDeflipData = False # asumo q la data no esta sin flip
182 flagShiftFFT = False
182 flagShiftFFT = False
183 nCohInt = None
183 nCohInt = None
184 windowOfFilter = 1
184 windowOfFilter = 1
185 C = 3e8
185 C = 3e8
186 frequency = 49.92e6
186 frequency = 49.92e6
187 realtime = False
187 realtime = False
188 beacon_heiIndexList = None
188 beacon_heiIndexList = None
189 last_block = None
189 last_block = None
190 blocknow = None
190 blocknow = None
191 azimuth = None
191 azimuth = None
192 zenith = None
192 zenith = None
193
193
194 profileIndex = None
194 profileIndex = None
195 error = None
195 error = None
196 data = None
196 data = None
197 nmodes = None
197 nmodes = None
198 metadata_list = ['heightList', 'timeZone', 'type']
198 metadata_list = ['heightList', 'timeZone', 'type']
199 codeList = []
199 codeList = []
200 azimuthList = []
200 azimuthList = []
201 elevationList = []
201 elevationList = []
202 last_noise = None
202 last_noise = None
203 __ipp = None
203 __ipp = None
204 __ippSeconds = None
204 __ippSeconds = None
205 sampled_heightsFFT = None
205 sampled_heightsFFT = None
206 pulseLength_TxA = None
206 pulseLength_TxA = None
207 deltaHeight = None
207 deltaHeight = None
208 __code = None
208 __code = None
209 __nCode = None
209 __nCode = None
210 __nBaud = None
210 __nBaud = None
211 unitsDescription = "The units of the parameters are according to the International System of units (Seconds, Meter, Hertz, ...), except \
211 unitsDescription = "The units of the parameters are according to the International System of units (Seconds, Meter, Hertz, ...), except \
212 the parameters related to distances such as heightList, or heightResolution wich are in Km"
212 the parameters related to distances such as heightList, or heightResolution wich are in Km"
213
213
214
214
215 def __str__(self):
215 def __str__(self):
216
216
217 return '{} - {}'.format(self.type, self.datatime())
217 return '{} - {}'.format(self.type, self.datatime())
218
218
219 def getNoise(self):
219 def getNoise(self):
220
220
221 raise NotImplementedError
221 raise NotImplementedError
222
222
223 @property
223 @property
224 def nChannels(self):
224 def nChannels(self):
225
225
226 return len(self.channelList)
226 return len(self.channelList)
227
227
228 @property
228 @property
229 def channelIndexList(self):
229 def channelIndexList(self):
230
230
231 return list(range(self.nChannels))
231 return list(range(self.nChannels))
232
232
233 @property
233 @property
234 def nHeights(self):
234 def nHeights(self):
235
235
236 return len(self.heightList)
236 return len(self.heightList)
237
237
238 def getDeltaH(self):
238 def getDeltaH(self):
239
239
240 return self.heightList[1] - self.heightList[0]
240 return self.heightList[1] - self.heightList[0]
241
241
242 @property
242 @property
243 def ltctime(self):
243 def ltctime(self):
244
244
245 if self.useLocalTime:
245 if self.useLocalTime:
246 return self.utctime - self.timeZone * 60
246 return self.utctime - self.timeZone * 60
247
247
248 return self.utctime
248 return self.utctime
249
249
250 @property
250 @property
251 def datatime(self):
251 def datatime(self):
252
252
253 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
253 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
254 return datatimeValue
254 return datatimeValue
255
255
256 def getTimeRange(self):
256 def getTimeRange(self):
257
257
258 datatime = []
258 datatime = []
259
259
260 datatime.append(self.ltctime)
260 datatime.append(self.ltctime)
261 datatime.append(self.ltctime + self.timeInterval + 1)
261 datatime.append(self.ltctime + self.timeInterval + 1)
262
262
263 datatime = numpy.array(datatime)
263 datatime = numpy.array(datatime)
264
264
265 return datatime
265 return datatime
266
266
267 def getFmaxTimeResponse(self):
267 def getFmaxTimeResponse(self):
268
268
269 period = (10**-6) * self.getDeltaH() / (0.15)
269 period = (10**-6) * self.getDeltaH() / (0.15)
270
270
271 PRF = 1. / (period * self.nCohInt)
271 PRF = 1. / (period * self.nCohInt)
272
272
273 fmax = PRF
273 fmax = PRF
274
274
275 return fmax
275 return fmax
276
276
277 def getFmax(self):
277 def getFmax(self):
278 PRF = 1. / (self.__ippSeconds * self.nCohInt)
278 PRF = 1. / (self.__ippSeconds * self.nCohInt)
279
279
280 fmax = PRF
280 fmax = PRF
281 return fmax
281 return fmax
282
282
283 def getVmax(self):
283 def getVmax(self):
284
284
285 _lambda = self.C / self.frequency
285 _lambda = self.C / self.frequency
286
286
287 vmax = self.getFmax() * _lambda / 2
287 vmax = self.getFmax() * _lambda / 2
288
288
289 return vmax
289 return vmax
290
290
291 @property
291 @property
292 def ippSeconds(self):
292 def ippSeconds(self):
293 '''
293 '''
294 '''
294 '''
295 #return self.radarControllerHeaderObj.ippSeconds
295 #return self.radarControllerHeaderObj.ippSeconds
296 return self.__ippSeconds
296 return self.__ippSeconds
297
297
298 @ippSeconds.setter
298 @ippSeconds.setter
299 def ippSeconds(self, ippSeconds):
299 def ippSeconds(self, ippSeconds):
300 '''
300 '''
301 '''
301 '''
302 #self.radarControllerHeaderObj.ippSeconds = ippSeconds
302 #self.radarControllerHeaderObj.ippSeconds = ippSeconds
303 self.__ippSeconds = ippSeconds
303 self.__ippSeconds = ippSeconds
304 self.__ipp = ippSeconds*SPEED_OF_LIGHT/2000.0
304 self.__ipp = ippSeconds*SPEED_OF_LIGHT/2000.0
305
305
306
306
307 @property
307 @property
308 def code(self):
308 def code(self):
309 '''
309 '''
310 '''
310 '''
311 return self.__code
311 return self.__code
312
312
313 @code.setter
313 @code.setter
314 def code(self, code):
314 def code(self, code):
315 '''
315 '''
316 '''
316 '''
317 self.__code = code
317 self.__code = code
318 #
318 #
319 @property
319 @property
320 def nCode(self):
320 def nCode(self):
321 '''
321 '''
322 '''
322 '''
323 return self.__nCode
323 return self.__nCode
324
324
325 @nCode.setter
325 @nCode.setter
326 def nCode(self, ncode):
326 def nCode(self, ncode):
327 '''
327 '''
328 '''
328 '''
329 self.__nCode = ncode
329 self.__nCode = ncode
330
330
331 @property
331 @property
332 def nBaud(self):
332 def nBaud(self):
333 '''
333 '''
334 '''
334 '''
335 return self.__nBaud
335 return self.__nBaud
336
336
337 @nBaud.setter
337 @nBaud.setter
338 def nBaud(self, nbaud):
338 def nBaud(self, nbaud):
339 '''
339 '''
340 '''
340 '''
341 self.__nBaud = nbaud
341 self.__nBaud = nbaud
342
342
343 @property
343 @property
344 def ipp(self):
344 def ipp(self):
345 '''
345 '''
346 '''
346 '''
347 return self.__ipp
347 return self.__ipp
348 #return self.radarControllerHeaderObj.ipp
348 #return self.radarControllerHeaderObj.ipp
349
349
350 @ipp.setter
350 @ipp.setter
351 def ipp(self, ipp):
351 def ipp(self, ipp):
352 '''
352 '''
353 '''
353 '''
354 self.__ipp = ipp
354 self.__ipp = ipp
355 #self.radarControllerHeaderObj.ipp = ipp
355 #self.radarControllerHeaderObj.ipp = ipp
356
356
357 @property
357 @property
358 def metadata(self):
358 def metadata(self):
359 '''
359 '''
360 '''
360 '''
361
361
362 return {attr: getattr(self, attr) for attr in self.metadata_list}
362 return {attr: getattr(self, attr) for attr in self.metadata_list}
363
363
364
364
365 class Voltage(JROData):
365 class Voltage(JROData):
366
366
367 dataPP_POW = None
367 dataPP_POW = None
368 dataPP_DOP = None
368 dataPP_DOP = None
369 dataPP_WIDTH = None
369 dataPP_WIDTH = None
370 dataPP_SNR = None
370 dataPP_SNR = None
371 flagProfilesByRange = False
371 flagProfilesByRange = False
372 nProfilesByRange = None
372 nProfilesByRange = None
373
373
374 def __init__(self):
374 def __init__(self):
375 '''
375 '''
376 Constructor
376 Constructor
377 '''
377 '''
378
378
379 self.useLocalTime = True
379 self.useLocalTime = True
380 self.radarControllerHeaderObj = RadarControllerHeader()
380 self.radarControllerHeaderObj = RadarControllerHeader()
381 self.systemHeaderObj = SystemHeader()
381 self.systemHeaderObj = SystemHeader()
382 self.processingHeaderObj = ProcessingHeader()
382 self.processingHeaderObj = ProcessingHeader()
383 self.type = "Voltage"
383 self.type = "Voltage"
384 self.data = None
384 self.data = None
385 self.nProfiles = None
385 self.nProfiles = None
386 self.heightList = None
386 self.heightList = None
387 self.channelList = None
387 self.channelList = None
388 self.flagNoData = True
388 self.flagNoData = True
389 self.flagDiscontinuousBlock = False
389 self.flagDiscontinuousBlock = False
390 self.utctime = None
390 self.utctime = None
391 self.timeZone = 0
391 self.timeZone = 0
392 self.dstFlag = None
392 self.dstFlag = None
393 self.errorCount = None
393 self.errorCount = None
394 self.nCohInt = None
394 self.nCohInt = None
395 self.blocksize = None
395 self.blocksize = None
396 self.flagCohInt = False
396 self.flagCohInt = False
397 self.flagDecodeData = False # asumo q la data no esta decodificada
397 self.flagDecodeData = False # asumo q la data no esta decodificada
398 self.flagDeflipData = False # asumo q la data no esta sin flip
398 self.flagDeflipData = False # asumo q la data no esta sin flip
399 self.flagShiftFFT = False
399 self.flagShiftFFT = False
400 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
400 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
401 self.profileIndex = 0
401 self.profileIndex = 0
402 self.metadata_list = ['type', 'heightList', 'timeZone', 'nProfiles', 'channelList', 'nCohInt',
402 self.metadata_list = ['type', 'heightList', 'timeZone', 'nProfiles', 'channelList', 'nCohInt',
403 'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp']
403 'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp']
404
404
405 def getNoisebyHildebrand(self, channel=None, ymin_index=None, ymax_index=None):
405 def getNoisebyHildebrand(self, channel=None, ymin_index=None, ymax_index=None):
406 """
406 """
407 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
407 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
408
408
409 Return:
409 Return:
410 noiselevel
410 noiselevel
411 """
411 """
412
412
413 if channel != None:
413 if channel != None:
414 data = self.data[channel,ymin_index:ymax_index]
414 data = self.data[channel,ymin_index:ymax_index]
415 nChannels = 1
415 nChannels = 1
416 else:
416 else:
417 data = self.data[:,ymin_index:ymax_index]
417 data = self.data[:,ymin_index:ymax_index]
418 nChannels = self.nChannels
418 nChannels = self.nChannels
419
419
420 noise = numpy.zeros(nChannels)
420 noise = numpy.zeros(nChannels)
421 power = data * numpy.conjugate(data)
421 power = data * numpy.conjugate(data)
422
422
423 for thisChannel in range(nChannels):
423 for thisChannel in range(nChannels):
424 if nChannels == 1:
424 if nChannels == 1:
425 daux = power[:].real
425 daux = power[:].real
426 else:
426 else:
427 daux = power[thisChannel, :].real
427 daux = power[thisChannel, :].real
428 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
428 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
429
429
430 return noise
430 return noise
431
431
432 def getNoise(self, type=1, channel=None,ymin_index=None, ymax_index=None):
432 def getNoise(self, type=1, channel=None,ymin_index=None, ymax_index=None):
433
433
434 if type == 1:
434 if type == 1:
435 noise = self.getNoisebyHildebrand(channel,ymin_index, ymax_index)
435 noise = self.getNoisebyHildebrand(channel,ymin_index, ymax_index)
436
436
437 return noise
437 return noise
438
438
439 def getPower(self, channel=None):
439 def getPower(self, channel=None):
440
440
441 if channel != None:
441 if channel != None:
442 data = self.data[channel]
442 data = self.data[channel]
443 else:
443 else:
444 data = self.data
444 data = self.data
445
445
446 power = data * numpy.conjugate(data)
446 power = data * numpy.conjugate(data)
447 powerdB = 10 * numpy.log10(power.real)
447 powerdB = 10 * numpy.log10(power.real)
448 powerdB = numpy.squeeze(powerdB)
448 powerdB = numpy.squeeze(powerdB)
449
449
450 return powerdB
450 return powerdB
451
451
452 @property
452 @property
453 def timeInterval(self):
453 def timeInterval(self):
454
454
455 return self.ippSeconds * self.nCohInt
455 return self.ippSeconds * self.nCohInt
456
456
457 noise = property(getNoise, "I'm the 'nHeights' property.")
457 noise = property(getNoise, "I'm the 'nHeights' property.")
458
458
459
459
460 class Spectra(JROData):
460 class Spectra(JROData):
461
461
462 data_outlier = None
462 data_outlier = None
463 flagProfilesByRange = False
463 flagProfilesByRange = False
464 nProfilesByRange = None
464 nProfilesByRange = None
465
465
466 def __init__(self):
466 def __init__(self):
467 '''
467 '''
468 Constructor
468 Constructor
469 '''
469 '''
470
470
471 self.data_dc = None
471 self.data_dc = None
472 self.data_spc = None
472 self.data_spc = None
473 self.data_cspc = None
473 self.data_cspc = None
474 self.useLocalTime = True
474 self.useLocalTime = True
475 self.radarControllerHeaderObj = RadarControllerHeader()
475 self.radarControllerHeaderObj = RadarControllerHeader()
476 self.systemHeaderObj = SystemHeader()
476 self.systemHeaderObj = SystemHeader()
477 self.processingHeaderObj = ProcessingHeader()
477 self.processingHeaderObj = ProcessingHeader()
478 self.type = "Spectra"
478 self.type = "Spectra"
479 self.timeZone = 0
479 self.timeZone = 0
480 self.nProfiles = None
480 self.nProfiles = None
481 self.heightList = None
481 self.heightList = None
482 self.channelList = None
482 self.channelList = None
483 self.pairsList = None
483 self.pairsList = None
484 self.flagNoData = True
484 self.flagNoData = True
485 self.flagDiscontinuousBlock = False
485 self.flagDiscontinuousBlock = False
486 self.utctime = None
486 self.utctime = None
487 self.nCohInt = None
487 self.nCohInt = None
488 self.nIncohInt = None
488 self.nIncohInt = None
489 self.blocksize = None
489 self.blocksize = None
490 self.nFFTPoints = None
490 self.nFFTPoints = None
491 self.wavelength = None
491 self.wavelength = None
492 self.flagDecodeData = False # asumo q la data no esta decodificada
492 self.flagDecodeData = False # asumo q la data no esta decodificada
493 self.flagDeflipData = False # asumo q la data no esta sin flip
493 self.flagDeflipData = False # asumo q la data no esta sin flip
494 self.flagShiftFFT = False
494 self.flagShiftFFT = False
495 self.ippFactor = 1
495 self.ippFactor = 1
496 self.beacon_heiIndexList = []
496 self.beacon_heiIndexList = []
497 self.noise_estimation = None
497 self.noise_estimation = None
498 self.codeList = []
498 self.codeList = []
499 self.azimuthList = []
499 self.azimuthList = []
500 self.elevationList = []
500 self.elevationList = []
501 self.metadata_list = ['type', 'heightList', 'timeZone', 'pairsList', 'channelList', 'nCohInt',
501 self.metadata_list = ['type', 'heightList', 'timeZone', 'pairsList', 'channelList', 'nCohInt',
502 'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp','nIncohInt', 'nFFTPoints', 'nProfiles']
502 'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp','nIncohInt', 'nFFTPoints', 'nProfiles']
503
503
504
504
505
505
506
506
507 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
507 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
508 """
508 """
509 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
509 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
510
510
511 Return:
511 Return:
512 noiselevel
512 noiselevel
513 """
513 """
514 # if hasattr(self.nIncohInt, "__len__"): #nIncohInt is a matrix
514 # if hasattr(self.nIncohInt, "__len__"): #nIncohInt is a matrix
515 #
515 #
516 # heis = self.data_spc.shape[2]
516 # heis = self.data_spc.shape[2]
517 #
517 #
518 # noise = numpy.zeros((self.nChannels, heis))
518 # noise = numpy.zeros((self.nChannels, heis))
519 # for hei in range(heis):
519 # for hei in range(heis):
520 # for channel in range(self.nChannels):
520 # for channel in range(self.nChannels):
521 # daux = self.data_spc[channel, xmin_index:xmax_index, hei]
521 # daux = self.data_spc[channel, xmin_index:xmax_index, hei]
522 #
522 #
523 # noise[channel,hei] = hildebrand_sekhon(daux, self.nIncohInt[channel,hei])
523 # noise[channel,hei] = hildebrand_sekhon(daux, self.nIncohInt[channel,hei])
524 #
524 #
525 # else:
525 # else:
526 # noise = numpy.zeros(self.nChannels)
526 # noise = numpy.zeros(self.nChannels)
527 # for channel in range(self.nChannels):
527 # for channel in range(self.nChannels):
528 # daux = self.data_spc[channel,xmin_index:xmax_index, ymin_index:ymax_index]
528 # daux = self.data_spc[channel,xmin_index:xmax_index, ymin_index:ymax_index]
529 #
529 #
530 # noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
530 # noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
531 noise = numpy.zeros(self.nChannels)
531 noise = numpy.zeros(self.nChannels)
532
532
533 for channel in range(self.nChannels):
533 for channel in range(self.nChannels):
534 daux = self.data_spc[channel,xmin_index:xmax_index, ymin_index:ymax_index]
534 daux = self.data_spc[channel,xmin_index:xmax_index, ymin_index:ymax_index]
535
535
536 noise[channel] = hildebrand_sekhon(daux, self.max_nIncohInt[channel])
536 noise[channel] = hildebrand_sekhon(daux, self.max_nIncohInt[channel])
537
537
538 return noise
538 return noise
539
539
540 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
540 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
541
541
542 if self.noise_estimation is not None:
542 if self.noise_estimation is not None:
543 # this was estimated by getNoise Operation defined in jroproc_spectra.py
543 # this was estimated by getNoise Operation defined in jroproc_spectra.py
544 return self.noise_estimation
544 return self.noise_estimation
545 else:
545 else:
546 noise = self.getNoisebyHildebrand(
546 noise = self.getNoisebyHildebrand(
547 xmin_index, xmax_index, ymin_index, ymax_index)
547 xmin_index, xmax_index, ymin_index, ymax_index)
548 return noise
548 return noise
549
549
550 def getFreqRangeTimeResponse(self, extrapoints=0):
550 def getFreqRangeTimeResponse(self, extrapoints=0):
551
551
552 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
552 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
553 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.) - deltafreq / 2
553 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.) - deltafreq / 2
554
554
555 return freqrange
555 return freqrange
556
556
557 def getAcfRange(self, extrapoints=0):
557 def getAcfRange(self, extrapoints=0):
558
558
559 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
559 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
560 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
560 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
561
561
562 return freqrange
562 return freqrange
563
563
564 def getFreqRange(self, extrapoints=0):
564 def getFreqRange(self, extrapoints=0):
565
565
566 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
566 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
567 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
567 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
568
568
569 return freqrange
569 return freqrange
570
570
571 def getVelRange(self, extrapoints=0):
571 def getVelRange(self, extrapoints=0):
572
572
573 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
573 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
574 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
574 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
575
575
576 if self.nmodes:
576 if self.nmodes:
577 return velrange/self.nmodes
577 return velrange/self.nmodes
578 else:
578 else:
579 return velrange
579 return velrange
580
580
581 @property
581 @property
582 def nPairs(self):
582 def nPairs(self):
583
583
584 return len(self.pairsList)
584 return len(self.pairsList)
585
585
586 @property
586 @property
587 def pairsIndexList(self):
587 def pairsIndexList(self):
588
588
589 return list(range(self.nPairs))
589 return list(range(self.nPairs))
590
590
591 @property
591 @property
592 def normFactor(self):
592 def normFactor(self):
593
593
594 pwcode = 1
594 pwcode = 1
595 if self.flagDecodeData:
595 if self.flagDecodeData:
596 pwcode = numpy.sum(self.code[0]**2)
596 pwcode = numpy.sum(self.code[0]**2)
597 #print(self.flagDecodeData, pwcode)
597 #print(self.flagDecodeData, pwcode)
598 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
598 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
599 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
599 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
600 if self.flagProfilesByRange:
600 if self.flagProfilesByRange:
601 normFactor *= (self.nProfilesByRange/self.nProfilesByRange.max())
601 normFactor *= (self.nProfilesByRange/self.nProfilesByRange.max())
602
602 #print("normFactor: ", normFactor)
603 return normFactor
603 return normFactor
604
604
605 @property
605 @property
606 def flag_cspc(self):
606 def flag_cspc(self):
607
607
608 if self.data_cspc is None:
608 if self.data_cspc is None:
609 return True
609 return True
610
610
611 return False
611 return False
612
612
613 @property
613 @property
614 def flag_dc(self):
614 def flag_dc(self):
615
615
616 if self.data_dc is None:
616 if self.data_dc is None:
617 return True
617 return True
618
618
619 return False
619 return False
620
620
621 @property
621 @property
622 def timeInterval(self):
622 def timeInterval(self):
623
623
624 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
624 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
625 if self.nmodes:
625 if self.nmodes:
626 return self.nmodes*timeInterval
626 return self.nmodes*timeInterval
627 else:
627 else:
628 return timeInterval
628 return timeInterval
629
629
630 def getPower(self):
630 def getPower(self):
631
631
632 factor = self.normFactor
632 factor = self.normFactor
633 power = numpy.zeros( (self.nChannels,self.nHeights) )
633 power = numpy.zeros( (self.nChannels,self.nHeights) )
634 for ch in range(self.nChannels):
634 for ch in range(self.nChannels):
635 z = None
635 z = None
636 if hasattr(factor,'shape'):
636 if hasattr(factor,'shape'):
637 if factor.ndim > 1:
637 if factor.ndim > 1:
638 z = self.data_spc[ch]/factor[ch]
638 z = self.data_spc[ch]/factor[ch]
639 else:
639 else:
640 z = self.data_spc[ch]/factor
640 z = self.data_spc[ch]/factor
641 else:
641 else:
642 z = self.data_spc[ch]/factor
642 z = self.data_spc[ch]/factor
643 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
643 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
644 avg = numpy.average(z, axis=0)
644 avg = numpy.average(z, axis=0)
645 power[ch] = 10 * numpy.log10(avg)
645 power[ch] = 10 * numpy.log10(avg)
646 return power
646 return power
647
647
648 @property
648 @property
649 def max_nIncohInt(self):
649 def max_nIncohInt(self):
650
650
651 ints = numpy.zeros(self.nChannels)
651 ints = numpy.zeros(self.nChannels)
652 for ch in range(self.nChannels):
652 for ch in range(self.nChannels):
653 if hasattr(self.nIncohInt,'shape'):
653 if hasattr(self.nIncohInt,'shape'):
654 if self.nIncohInt.ndim > 1:
654 if self.nIncohInt.ndim > 1:
655 ints[ch,] = self.nIncohInt[ch].max()
655 ints[ch,] = self.nIncohInt[ch].max()
656 else:
656 else:
657 ints[ch,] = self.nIncohInt
657 ints[ch,] = self.nIncohInt
658 self.nIncohInt = int(self.nIncohInt)
658 self.nIncohInt = int(self.nIncohInt)
659 else:
659 else:
660 ints[ch,] = self.nIncohInt
660 ints[ch,] = self.nIncohInt
661
661
662 return ints
662 return ints
663
663
664
664
665 def getCoherence(self, pairsList=None, phase=False):
665 def getCoherence(self, pairsList=None, phase=False):
666
666
667 z = []
667 z = []
668 if pairsList is None:
668 if pairsList is None:
669 pairsIndexList = self.pairsIndexList
669 pairsIndexList = self.pairsIndexList
670 else:
670 else:
671 pairsIndexList = []
671 pairsIndexList = []
672 for pair in pairsList:
672 for pair in pairsList:
673 if pair not in self.pairsList:
673 if pair not in self.pairsList:
674 raise ValueError("Pair %s is not in dataOut.pairsList" % (
674 raise ValueError("Pair %s is not in dataOut.pairsList" % (
675 pair))
675 pair))
676 pairsIndexList.append(self.pairsList.index(pair))
676 pairsIndexList.append(self.pairsList.index(pair))
677 for i in range(len(pairsIndexList)):
677 for i in range(len(pairsIndexList)):
678 pair = self.pairsList[pairsIndexList[i]]
678 pair = self.pairsList[pairsIndexList[i]]
679 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
679 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
680 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
680 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
681 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
681 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
682 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
682 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
683 if phase:
683 if phase:
684 data = numpy.arctan2(avgcoherenceComplex.imag,
684 data = numpy.arctan2(avgcoherenceComplex.imag,
685 avgcoherenceComplex.real) * 180 / numpy.pi
685 avgcoherenceComplex.real) * 180 / numpy.pi
686 else:
686 else:
687 data = numpy.abs(avgcoherenceComplex)
687 data = numpy.abs(avgcoherenceComplex)
688
688
689 z.append(data)
689 z.append(data)
690
690
691 return numpy.array(z)
691 return numpy.array(z)
692
692
693 def setValue(self, value):
693 def setValue(self, value):
694
694
695 print("This property should not be initialized", value)
695 print("This property should not be initialized", value)
696
696
697 return
697 return
698
698
699 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
699 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
700
700
701
701
702 class SpectraHeis(Spectra):
702 class SpectraHeis(Spectra):
703
703
704 def __init__(self):
704 def __init__(self):
705
705
706 self.radarControllerHeaderObj = RadarControllerHeader()
706 self.radarControllerHeaderObj = RadarControllerHeader()
707 self.systemHeaderObj = SystemHeader()
707 self.systemHeaderObj = SystemHeader()
708 self.type = "SpectraHeis"
708 self.type = "SpectraHeis"
709 self.nProfiles = None
709 self.nProfiles = None
710 self.heightList = None
710 self.heightList = None
711 self.channelList = None
711 self.channelList = None
712 self.flagNoData = True
712 self.flagNoData = True
713 self.flagDiscontinuousBlock = False
713 self.flagDiscontinuousBlock = False
714 self.utctime = None
714 self.utctime = None
715 self.blocksize = None
715 self.blocksize = None
716 self.profileIndex = 0
716 self.profileIndex = 0
717 self.nCohInt = 1
717 self.nCohInt = 1
718 self.nIncohInt = 1
718 self.nIncohInt = 1
719
719
720 @property
720 @property
721 def normFactor(self):
721 def normFactor(self):
722 pwcode = 1
722 pwcode = 1
723 if self.flagDecodeData:
723 if self.flagDecodeData:
724 pwcode = numpy.sum(self.code[0]**2)
724 pwcode = numpy.sum(self.code[0]**2)
725
725
726 normFactor = self.nIncohInt * self.nCohInt * pwcode
726 normFactor = self.nIncohInt * self.nCohInt * pwcode
727
727
728 return normFactor
728 return normFactor
729
729
730 @property
730 @property
731 def timeInterval(self):
731 def timeInterval(self):
732
732
733 return self.ippSeconds * self.nCohInt * self.nIncohInt
733 return self.ippSeconds * self.nCohInt * self.nIncohInt
734
734
735
735
736 class Fits(JROData):
736 class Fits(JROData):
737
737
738 def __init__(self):
738 def __init__(self):
739
739
740 self.type = "Fits"
740 self.type = "Fits"
741 self.nProfiles = None
741 self.nProfiles = None
742 self.heightList = None
742 self.heightList = None
743 self.channelList = None
743 self.channelList = None
744 self.flagNoData = True
744 self.flagNoData = True
745 self.utctime = None
745 self.utctime = None
746 self.nCohInt = 1
746 self.nCohInt = 1
747 self.nIncohInt = 1
747 self.nIncohInt = 1
748 self.useLocalTime = True
748 self.useLocalTime = True
749 self.profileIndex = 0
749 self.profileIndex = 0
750 self.timeZone = 0
750 self.timeZone = 0
751
751
752 def getTimeRange(self):
752 def getTimeRange(self):
753
753
754 datatime = []
754 datatime = []
755
755
756 datatime.append(self.ltctime)
756 datatime.append(self.ltctime)
757 datatime.append(self.ltctime + self.timeInterval)
757 datatime.append(self.ltctime + self.timeInterval)
758
758
759 datatime = numpy.array(datatime)
759 datatime = numpy.array(datatime)
760
760
761 return datatime
761 return datatime
762
762
763 def getChannelIndexList(self):
763 def getChannelIndexList(self):
764
764
765 return list(range(self.nChannels))
765 return list(range(self.nChannels))
766
766
767 def getNoise(self, type=1):
767 def getNoise(self, type=1):
768
768
769
769
770 if type == 1:
770 if type == 1:
771 noise = self.getNoisebyHildebrand()
771 noise = self.getNoisebyHildebrand()
772
772
773 if type == 2:
773 if type == 2:
774 noise = self.getNoisebySort()
774 noise = self.getNoisebySort()
775
775
776 if type == 3:
776 if type == 3:
777 noise = self.getNoisebyWindow()
777 noise = self.getNoisebyWindow()
778
778
779 return noise
779 return noise
780
780
781 @property
781 @property
782 def timeInterval(self):
782 def timeInterval(self):
783
783
784 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
784 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
785
785
786 return timeInterval
786 return timeInterval
787
787
788 @property
788 @property
789 def ippSeconds(self):
789 def ippSeconds(self):
790 '''
790 '''
791 '''
791 '''
792 return self.ipp_sec
792 return self.ipp_sec
793
793
794 noise = property(getNoise, "I'm the 'nHeights' property.")
794 noise = property(getNoise, "I'm the 'nHeights' property.")
795
795
796
796
797 class Correlation(JROData):
797 class Correlation(JROData):
798
798
799 def __init__(self):
799 def __init__(self):
800 '''
800 '''
801 Constructor
801 Constructor
802 '''
802 '''
803 self.radarControllerHeaderObj = RadarControllerHeader()
803 self.radarControllerHeaderObj = RadarControllerHeader()
804 self.systemHeaderObj = SystemHeader()
804 self.systemHeaderObj = SystemHeader()
805 self.type = "Correlation"
805 self.type = "Correlation"
806 self.data = None
806 self.data = None
807 self.dtype = None
807 self.dtype = None
808 self.nProfiles = None
808 self.nProfiles = None
809 self.heightList = None
809 self.heightList = None
810 self.channelList = None
810 self.channelList = None
811 self.flagNoData = True
811 self.flagNoData = True
812 self.flagDiscontinuousBlock = False
812 self.flagDiscontinuousBlock = False
813 self.utctime = None
813 self.utctime = None
814 self.timeZone = 0
814 self.timeZone = 0
815 self.dstFlag = None
815 self.dstFlag = None
816 self.errorCount = None
816 self.errorCount = None
817 self.blocksize = None
817 self.blocksize = None
818 self.flagDecodeData = False # asumo q la data no esta decodificada
818 self.flagDecodeData = False # asumo q la data no esta decodificada
819 self.flagDeflipData = False # asumo q la data no esta sin flip
819 self.flagDeflipData = False # asumo q la data no esta sin flip
820 self.pairsList = None
820 self.pairsList = None
821 self.nPoints = None
821 self.nPoints = None
822
822
823 def getPairsList(self):
823 def getPairsList(self):
824
824
825 return self.pairsList
825 return self.pairsList
826
826
827 def getNoise(self, mode=2):
827 def getNoise(self, mode=2):
828
828
829 indR = numpy.where(self.lagR == 0)[0][0]
829 indR = numpy.where(self.lagR == 0)[0][0]
830 indT = numpy.where(self.lagT == 0)[0][0]
830 indT = numpy.where(self.lagT == 0)[0][0]
831
831
832 jspectra0 = self.data_corr[:, :, indR, :]
832 jspectra0 = self.data_corr[:, :, indR, :]
833 jspectra = copy.copy(jspectra0)
833 jspectra = copy.copy(jspectra0)
834
834
835 num_chan = jspectra.shape[0]
835 num_chan = jspectra.shape[0]
836 num_hei = jspectra.shape[2]
836 num_hei = jspectra.shape[2]
837
837
838 freq_dc = jspectra.shape[1] / 2
838 freq_dc = jspectra.shape[1] / 2
839 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
839 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
840
840
841 if ind_vel[0] < 0:
841 if ind_vel[0] < 0:
842 ind_vel[list(range(0, 1))] = ind_vel[list(
842 ind_vel[list(range(0, 1))] = ind_vel[list(
843 range(0, 1))] + self.num_prof
843 range(0, 1))] + self.num_prof
844
844
845 if mode == 1:
845 if mode == 1:
846 jspectra[:, freq_dc, :] = (
846 jspectra[:, freq_dc, :] = (
847 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
847 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
848
848
849 if mode == 2:
849 if mode == 2:
850
850
851 vel = numpy.array([-2, -1, 1, 2])
851 vel = numpy.array([-2, -1, 1, 2])
852 xx = numpy.zeros([4, 4])
852 xx = numpy.zeros([4, 4])
853
853
854 for fil in range(4):
854 for fil in range(4):
855 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
855 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
856
856
857 xx_inv = numpy.linalg.inv(xx)
857 xx_inv = numpy.linalg.inv(xx)
858 xx_aux = xx_inv[0, :]
858 xx_aux = xx_inv[0, :]
859
859
860 for ich in range(num_chan):
860 for ich in range(num_chan):
861 yy = jspectra[ich, ind_vel, :]
861 yy = jspectra[ich, ind_vel, :]
862 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
862 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
863
863
864 junkid = jspectra[ich, freq_dc, :] <= 0
864 junkid = jspectra[ich, freq_dc, :] <= 0
865 cjunkid = sum(junkid)
865 cjunkid = sum(junkid)
866
866
867 if cjunkid.any():
867 if cjunkid.any():
868 jspectra[ich, freq_dc, junkid.nonzero()] = (
868 jspectra[ich, freq_dc, junkid.nonzero()] = (
869 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
869 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
870
870
871 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
871 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
872
872
873 return noise
873 return noise
874
874
875 @property
875 @property
876 def timeInterval(self):
876 def timeInterval(self):
877
877
878 return self.ippSeconds * self.nCohInt * self.nProfiles
878 return self.ippSeconds * self.nCohInt * self.nProfiles
879
879
880 def splitFunctions(self):
880 def splitFunctions(self):
881
881
882 pairsList = self.pairsList
882 pairsList = self.pairsList
883 ccf_pairs = []
883 ccf_pairs = []
884 acf_pairs = []
884 acf_pairs = []
885 ccf_ind = []
885 ccf_ind = []
886 acf_ind = []
886 acf_ind = []
887 for l in range(len(pairsList)):
887 for l in range(len(pairsList)):
888 chan0 = pairsList[l][0]
888 chan0 = pairsList[l][0]
889 chan1 = pairsList[l][1]
889 chan1 = pairsList[l][1]
890
890
891 # Obteniendo pares de Autocorrelacion
891 # Obteniendo pares de Autocorrelacion
892 if chan0 == chan1:
892 if chan0 == chan1:
893 acf_pairs.append(chan0)
893 acf_pairs.append(chan0)
894 acf_ind.append(l)
894 acf_ind.append(l)
895 else:
895 else:
896 ccf_pairs.append(pairsList[l])
896 ccf_pairs.append(pairsList[l])
897 ccf_ind.append(l)
897 ccf_ind.append(l)
898
898
899 data_acf = self.data_cf[acf_ind]
899 data_acf = self.data_cf[acf_ind]
900 data_ccf = self.data_cf[ccf_ind]
900 data_ccf = self.data_cf[ccf_ind]
901
901
902 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
902 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
903
903
904 @property
904 @property
905 def normFactor(self):
905 def normFactor(self):
906 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
906 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
907 acf_pairs = numpy.array(acf_pairs)
907 acf_pairs = numpy.array(acf_pairs)
908 normFactor = numpy.zeros((self.nPairs, self.nHeights))
908 normFactor = numpy.zeros((self.nPairs, self.nHeights))
909
909
910 for p in range(self.nPairs):
910 for p in range(self.nPairs):
911 pair = self.pairsList[p]
911 pair = self.pairsList[p]
912
912
913 ch0 = pair[0]
913 ch0 = pair[0]
914 ch1 = pair[1]
914 ch1 = pair[1]
915
915
916 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
916 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
917 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
917 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
918 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
918 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
919
919
920 return normFactor
920 return normFactor
921
921
922
922
923 class Parameters(Spectra):
923 class Parameters(Spectra):
924
924
925 radarControllerHeaderTxt=None #header Controller like text
925 radarControllerHeaderTxt=None #header Controller like text
926 groupList = None # List of Pairs, Groups, etc
926 groupList = None # List of Pairs, Groups, etc
927 data_param = None # Parameters obtained
927 data_param = None # Parameters obtained
928 data_pre = None # Data Pre Parametrization
928 data_pre = None # Data Pre Parametrization
929 data_SNR = None # Signal to Noise Ratio
929 data_SNR = None # Signal to Noise Ratio
930 data_outlier = None
930 data_outlier = None
931 abscissaList = None # Abscissa, can be velocities, lags or time
931 abscissaList = None # Abscissa, can be velocities, lags or time
932 utctimeInit = None # Initial UTC time
932 utctimeInit = None # Initial UTC time
933 paramInterval = None # Time interval to calculate Parameters in seconds
933 paramInterval = None # Time interval to calculate Parameters in seconds
934 useLocalTime = True
934 useLocalTime = True
935 # Fitting
935 # Fitting
936 data_error = None # Error of the estimation
936 data_error = None # Error of the estimation
937 constants = None
937 constants = None
938 library = None
938 library = None
939 # Output signal
939 # Output signal
940 outputInterval = None # Time interval to calculate output signal in seconds
940 outputInterval = None # Time interval to calculate output signal in seconds
941 data_output = None # Out signal
941 data_output = None # Out signal
942 nAvg = None
942 nAvg = None
943 noise_estimation = None
943 noise_estimation = None
944 GauSPC = None # Fit gaussian SPC
944 GauSPC = None # Fit gaussian SPC
945 txPower = None
945 txPower = None
946 flagProfilesByRange = False
946 flagProfilesByRange = False
947 nProfilesByRange = None
947 nProfilesByRange = None
948
948
949 def __init__(self):
949 def __init__(self):
950 '''
950 '''
951 Constructor
951 Constructor
952 '''
952 '''
953 self.radarControllerHeaderObj = RadarControllerHeader()
953 self.radarControllerHeaderObj = RadarControllerHeader()
954 self.systemHeaderObj = SystemHeader()
954 self.systemHeaderObj = SystemHeader()
955 self.processingHeaderObj = ProcessingHeader()
955 self.processingHeaderObj = ProcessingHeader()
956 self.type = "Parameters"
956 self.type = "Parameters"
957 self.timeZone = 0
957 self.timeZone = 0
958
958
959 def getTimeRange1(self, interval):
959 def getTimeRange1(self, interval):
960
960
961 datatime = []
961 datatime = []
962
962
963 if self.useLocalTime:
963 if self.useLocalTime:
964 time1 = self.utctimeInit - self.timeZone * 60
964 time1 = self.utctimeInit - self.timeZone * 60
965 else:
965 else:
966 time1 = self.utctimeInit
966 time1 = self.utctimeInit
967
967
968 datatime.append(time1)
968 datatime.append(time1)
969 datatime.append(time1 + interval)
969 datatime.append(time1 + interval)
970 datatime = numpy.array(datatime)
970 datatime = numpy.array(datatime)
971
971
972 return datatime
972 return datatime
973
973
974 @property
974 @property
975 def timeInterval(self):
975 def timeInterval(self):
976
976
977 if hasattr(self, 'timeInterval1'):
977 if hasattr(self, 'timeInterval1'):
978 return self.timeInterval1
978 return self.timeInterval1
979 else:
979 else:
980 return self.paramInterval
980 return self.paramInterval
981
981
982 def setValue(self, value):
982 def setValue(self, value):
983
983
984 print("This property should not be initialized")
984 print("This property should not be initialized")
985
985
986 return
986 return
987
987
988 def getNoise(self):
988 def getNoise(self):
989
989
990 return self.spc_noise
990 return self.spc_noise
991
991
992 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
992 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
993
993
994
994
995 class PlotterData(object):
995 class PlotterData(object):
996 '''
996 '''
997 Object to hold data to be plotted
997 Object to hold data to be plotted
998 '''
998 '''
999
999
1000 MAXNUMX = 200
1000 MAXNUMX = 200
1001 MAXNUMY = 200
1001 MAXNUMY = 200
1002
1002
1003 def __init__(self, code, exp_code, localtime=True):
1003 def __init__(self, code, exp_code, localtime=True):
1004
1004
1005 self.key = code
1005 self.key = code
1006 self.exp_code = exp_code
1006 self.exp_code = exp_code
1007 self.ready = False
1007 self.ready = False
1008 self.flagNoData = False
1008 self.flagNoData = False
1009 self.localtime = localtime
1009 self.localtime = localtime
1010 self.data = {}
1010 self.data = {}
1011 self.meta = {}
1011 self.meta = {}
1012 self.__heights = []
1012 self.__heights = []
1013
1013
1014 def __str__(self):
1014 def __str__(self):
1015 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1015 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1016 return 'Data[{}][{}]'.format(';'.join(dum), len(self.times))
1016 return 'Data[{}][{}]'.format(';'.join(dum), len(self.times))
1017
1017
1018 def __len__(self):
1018 def __len__(self):
1019 return len(self.data)
1019 return len(self.data)
1020
1020
1021 def __getitem__(self, key):
1021 def __getitem__(self, key):
1022 if isinstance(key, int):
1022 if isinstance(key, int):
1023 return self.data[self.times[key]]
1023 return self.data[self.times[key]]
1024 elif isinstance(key, str):
1024 elif isinstance(key, str):
1025 ret = numpy.array([self.data[x][key] for x in self.times])
1025 ret = numpy.array([self.data[x][key] for x in self.times])
1026 if ret.ndim > 1:
1026 if ret.ndim > 1:
1027 ret = numpy.swapaxes(ret, 0, 1)
1027 ret = numpy.swapaxes(ret, 0, 1)
1028 return ret
1028 return ret
1029
1029
1030 def __contains__(self, key):
1030 def __contains__(self, key):
1031 return key in self.data[self.min_time]
1031 return key in self.data[self.min_time]
1032
1032
1033 def setup(self):
1033 def setup(self):
1034 '''
1034 '''
1035 Configure object
1035 Configure object
1036 '''
1036 '''
1037 self.type = ''
1037 self.type = ''
1038 self.ready = False
1038 self.ready = False
1039 del self.data
1039 del self.data
1040 self.data = {}
1040 self.data = {}
1041 self.__heights = []
1041 self.__heights = []
1042 self.__all_heights = set()
1042 self.__all_heights = set()
1043
1043
1044 def shape(self, key):
1044 def shape(self, key):
1045 '''
1045 '''
1046 Get the shape of the one-element data for the given key
1046 Get the shape of the one-element data for the given key
1047 '''
1047 '''
1048
1048
1049 if len(self.data[self.min_time][key]):
1049 if len(self.data[self.min_time][key]):
1050 return self.data[self.min_time][key].shape
1050 return self.data[self.min_time][key].shape
1051 return (0,)
1051 return (0,)
1052
1052
1053 def update(self, data, tm, meta={}):
1053 def update(self, data, tm, meta={}):
1054 '''
1054 '''
1055 Update data object with new dataOut
1055 Update data object with new dataOut
1056 '''
1056 '''
1057
1057
1058 self.data[tm] = data
1058 self.data[tm] = data
1059
1059
1060 for key, value in meta.items():
1060 for key, value in meta.items():
1061 setattr(self, key, value)
1061 setattr(self, key, value)
1062
1062
1063 def normalize_heights(self):
1063 def normalize_heights(self):
1064 '''
1064 '''
1065 Ensure same-dimension of the data for different heighList
1065 Ensure same-dimension of the data for different heighList
1066 '''
1066 '''
1067
1067
1068 H = numpy.array(list(self.__all_heights))
1068 H = numpy.array(list(self.__all_heights))
1069 H.sort()
1069 H.sort()
1070 for key in self.data:
1070 for key in self.data:
1071 shape = self.shape(key)[:-1] + H.shape
1071 shape = self.shape(key)[:-1] + H.shape
1072 for tm, obj in list(self.data[key].items()):
1072 for tm, obj in list(self.data[key].items()):
1073 h = self.__heights[self.times.tolist().index(tm)]
1073 h = self.__heights[self.times.tolist().index(tm)]
1074 if H.size == h.size:
1074 if H.size == h.size:
1075 continue
1075 continue
1076 index = numpy.where(numpy.in1d(H, h))[0]
1076 index = numpy.where(numpy.in1d(H, h))[0]
1077 dummy = numpy.zeros(shape) + numpy.nan
1077 dummy = numpy.zeros(shape) + numpy.nan
1078 if len(shape) == 2:
1078 if len(shape) == 2:
1079 dummy[:, index] = obj
1079 dummy[:, index] = obj
1080 else:
1080 else:
1081 dummy[index] = obj
1081 dummy[index] = obj
1082 self.data[key][tm] = dummy
1082 self.data[key][tm] = dummy
1083
1083
1084 self.__heights = [H for tm in self.times]
1084 self.__heights = [H for tm in self.times]
1085
1085
1086 def jsonify(self, tm, plot_name, plot_type, decimate=False):
1086 def jsonify(self, tm, plot_name, plot_type, decimate=False):
1087 '''
1087 '''
1088 Convert data to json
1088 Convert data to json
1089 '''
1089 '''
1090
1090
1091 meta = {}
1091 meta = {}
1092 meta['xrange'] = []
1092 meta['xrange'] = []
1093 dy = int(len(self.yrange)/self.MAXNUMY) + 1
1093 dy = int(len(self.yrange)/self.MAXNUMY) + 1
1094 tmp = self.data[tm][self.key]
1094 tmp = self.data[tm][self.key]
1095 shape = tmp.shape
1095 shape = tmp.shape
1096 if len(shape) == 2:
1096 if len(shape) == 2:
1097 data = self.roundFloats(self.data[tm][self.key][::, ::dy].tolist())
1097 data = self.roundFloats(self.data[tm][self.key][::, ::dy].tolist())
1098 elif len(shape) == 3:
1098 elif len(shape) == 3:
1099 dx = int(self.data[tm][self.key].shape[1]/self.MAXNUMX) + 1
1099 dx = int(self.data[tm][self.key].shape[1]/self.MAXNUMX) + 1
1100 data = self.roundFloats(
1100 data = self.roundFloats(
1101 self.data[tm][self.key][::, ::dx, ::dy].tolist())
1101 self.data[tm][self.key][::, ::dx, ::dy].tolist())
1102 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1102 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1103 else:
1103 else:
1104 data = self.roundFloats(self.data[tm][self.key].tolist())
1104 data = self.roundFloats(self.data[tm][self.key].tolist())
1105
1105
1106 ret = {
1106 ret = {
1107 'plot': plot_name,
1107 'plot': plot_name,
1108 'code': self.exp_code,
1108 'code': self.exp_code,
1109 'time': float(tm),
1109 'time': float(tm),
1110 'data': data,
1110 'data': data,
1111 }
1111 }
1112 meta['type'] = plot_type
1112 meta['type'] = plot_type
1113 meta['interval'] = float(self.interval)
1113 meta['interval'] = float(self.interval)
1114 meta['localtime'] = self.localtime
1114 meta['localtime'] = self.localtime
1115 meta['yrange'] = self.roundFloats(self.yrange[::dy].tolist())
1115 meta['yrange'] = self.roundFloats(self.yrange[::dy].tolist())
1116 meta.update(self.meta)
1116 meta.update(self.meta)
1117 ret['metadata'] = meta
1117 ret['metadata'] = meta
1118 return json.dumps(ret)
1118 return json.dumps(ret)
1119
1119
1120 @property
1120 @property
1121 def times(self):
1121 def times(self):
1122 '''
1122 '''
1123 Return the list of times of the current data
1123 Return the list of times of the current data
1124 '''
1124 '''
1125
1125
1126 ret = [t for t in self.data]
1126 ret = [t for t in self.data]
1127 ret.sort()
1127 ret.sort()
1128 return numpy.array(ret)
1128 return numpy.array(ret)
1129
1129
1130 @property
1130 @property
1131 def min_time(self):
1131 def min_time(self):
1132 '''
1132 '''
1133 Return the minimun time value
1133 Return the minimun time value
1134 '''
1134 '''
1135
1135
1136 return self.times[0]
1136 return self.times[0]
1137
1137
1138 @property
1138 @property
1139 def max_time(self):
1139 def max_time(self):
1140 '''
1140 '''
1141 Return the maximun time value
1141 Return the maximun time value
1142 '''
1142 '''
1143
1143
1144 return self.times[-1]
1144 return self.times[-1]
1145
1145
1146 # @property
1146 # @property
1147 # def heights(self):
1147 # def heights(self):
1148 # '''
1148 # '''
1149 # Return the list of heights of the current data
1149 # Return the list of heights of the current data
1150 # '''
1150 # '''
1151
1151
1152 # return numpy.array(self.__heights[-1])
1152 # return numpy.array(self.__heights[-1])
1153
1153
1154 @staticmethod
1154 @staticmethod
1155 def roundFloats(obj):
1155 def roundFloats(obj):
1156 if isinstance(obj, list):
1156 if isinstance(obj, list):
1157 return list(map(PlotterData.roundFloats, obj))
1157 return list(map(PlotterData.roundFloats, obj))
1158 elif isinstance(obj, float):
1158 elif isinstance(obj, float):
1159 return round(obj, 2)
1159 return round(obj, 2)
@@ -1,1465 +1,1464
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 from itertools import combinations
13 from itertools import combinations
14 from matplotlib.ticker import LinearLocator
14 from matplotlib.ticker import LinearLocator
15
15
16 from matplotlib import __version__ as plt_version
16 from matplotlib import __version__ as plt_version
17
17
18 if plt_version >='3.3.4':
18 if plt_version >='3.3.4':
19 EXTRA_POINTS = 0
19 EXTRA_POINTS = 0
20 else:
20 else:
21 EXTRA_POINTS = 1
21 EXTRA_POINTS = 1
22
22
23 class SpectraPlot(Plot):
23 class SpectraPlot(Plot):
24 '''
24 '''
25 Plot for Spectra data
25 Plot for Spectra data
26 '''
26 '''
27
27
28 CODE = 'spc'
28 CODE = 'spc'
29 colormap = 'jet'
29 colormap = 'jet'
30 plot_type = 'pcolor'
30 plot_type = 'pcolor'
31 buffering = False
31 buffering = False
32 channelList = []
32 channelList = []
33 elevationList = []
33 elevationList = []
34 azimuthList = []
34 azimuthList = []
35
35
36 def setup(self):
36 def setup(self):
37
37
38 self.nplots = len(self.data.channels)
38 self.nplots = len(self.data.channels)
39 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
39 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
40 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
40 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
41 self.height = 3.4 * self.nrows
41 self.height = 3.4 * self.nrows
42
42
43 self.cb_label = 'dB'
43 self.cb_label = 'dB'
44 if self.showprofile:
44 if self.showprofile:
45 self.width = 5.2 * self.ncols
45 self.width = 5.2 * self.ncols
46 else:
46 else:
47 self.width = 4.2* self.ncols
47 self.width = 4.2* self.ncols
48 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.12})
48 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.9, 'bottom': 0.12})
49 self.ylabel = 'Range [km]'
49 self.ylabel = 'Range [km]'
50
50
51
51
52 def update_list(self,dataOut):
52 def update_list(self,dataOut):
53 if len(self.channelList) == 0:
53 if len(self.channelList) == 0:
54 self.channelList = dataOut.channelList
54 self.channelList = dataOut.channelList
55 if len(self.elevationList) == 0:
55 if len(self.elevationList) == 0:
56 self.elevationList = dataOut.elevationList
56 self.elevationList = dataOut.elevationList
57 if len(self.azimuthList) == 0:
57 if len(self.azimuthList) == 0:
58 self.azimuthList = dataOut.azimuthList
58 self.azimuthList = dataOut.azimuthList
59
59
60 def update(self, dataOut):
60 def update(self, dataOut):
61
61
62 self.update_list(dataOut)
62 self.update_list(dataOut)
63 data = {}
63 data = {}
64 meta = {}
64 meta = {}
65
65
66 #data['rti'] = dataOut.getPower()
66 #data['rti'] = dataOut.getPower()
67 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
67 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
68 noise = 10*numpy.log10(dataOut.getNoise()/norm)
68 noise = 10*numpy.log10(dataOut.getNoise()/norm)
69
69
70
70
71 z = numpy.zeros((dataOut.nChannels, dataOut.nFFTPoints, dataOut.nHeights))
71 z = numpy.zeros((dataOut.nChannels, dataOut.nFFTPoints, dataOut.nHeights))
72 for ch in range(dataOut.nChannels):
72 for ch in range(dataOut.nChannels):
73 if hasattr(dataOut.normFactor,'ndim'):
73 if hasattr(dataOut.normFactor,'ndim'):
74 if dataOut.normFactor.ndim > 1:
74 if dataOut.normFactor.ndim > 1:
75 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
75 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
76
76
77 else:
77 else:
78 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
78 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
79 else:
79 else:
80 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
80 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
81
81
82
82
83 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
83 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
84 spc = 10*numpy.log10(z)
84 spc = 10*numpy.log10(z)
85
85
86 data['spc'] = spc
86 data['spc'] = spc
87 #print(spc[0].shape)
87 #print(spc[0].shape)
88 data['rti'] = spc.mean(axis=1)
88 data['rti'] = spc.mean(axis=1)
89 data['noise'] = noise
89 data['noise'] = noise
90 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
90 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
91 if self.CODE == 'spc_moments':
91 if self.CODE == 'spc_moments':
92 data['moments'] = dataOut.moments
92 data['moments'] = dataOut.moments
93
93
94 return data, meta
94 return data, meta
95
95
96 def plot(self):
96 def plot(self):
97 if self.xaxis == "frequency":
97 if self.xaxis == "frequency":
98 x = self.data.xrange[0]
98 x = self.data.xrange[0]
99 self.xlabel = "Frequency (kHz)"
99 self.xlabel = "Frequency (kHz)"
100 elif self.xaxis == "time":
100 elif self.xaxis == "time":
101 x = self.data.xrange[1]
101 x = self.data.xrange[1]
102 self.xlabel = "Time (ms)"
102 self.xlabel = "Time (ms)"
103 else:
103 else:
104 x = self.data.xrange[2]
104 x = self.data.xrange[2]
105 self.xlabel = "Velocity (m/s)"
105 self.xlabel = "Velocity (m/s)"
106
106
107 if self.CODE == 'spc_moments':
107 if self.CODE == 'spc_moments':
108 x = self.data.xrange[2]
108 x = self.data.xrange[2]
109 self.xlabel = "Velocity (m/s)"
109 self.xlabel = "Velocity (m/s)"
110
110
111 self.titles = []
111 self.titles = []
112 y = self.data.yrange
112 y = self.data.yrange
113 self.y = y
113 self.y = y
114
114
115 data = self.data[-1]
115 data = self.data[-1]
116 z = data['spc']
116 z = data['spc']
117 #print(z.shape, x.shape, y.shape)
117 #print(z.shape, x.shape, y.shape)
118 for n, ax in enumerate(self.axes):
118 for n, ax in enumerate(self.axes):
119 noise = self.data['noise'][n][0]
119 noise = self.data['noise'][n][0]
120 #print(noise)
120 #print(noise)
121 if self.CODE == 'spc_moments':
121 if self.CODE == 'spc_moments':
122 mean = data['moments'][n, 1]
122 mean = data['moments'][n, 1]
123 if ax.firsttime:
123 if ax.firsttime:
124 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
124 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
125 self.xmin = self.xmin if self.xmin else -self.xmax
125 self.xmin = self.xmin if self.xmin else -self.xmax
126 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
126 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
127 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
127 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
128 ax.plt = ax.pcolormesh(x, y, z[n].T,
128 ax.plt = ax.pcolormesh(x, y, z[n].T,
129 vmin=self.zmin,
129 vmin=self.zmin,
130 vmax=self.zmax,
130 vmax=self.zmax,
131 cmap=plt.get_cmap(self.colormap)
131 cmap=plt.get_cmap(self.colormap)
132 )
132 )
133
133
134 if self.showprofile:
134 if self.showprofile:
135 ax.plt_profile = self.pf_axes[n].plot(
135 ax.plt_profile = self.pf_axes[n].plot(
136 data['rti'][n], y)[0]
136 data['rti'][n], y)[0]
137 # ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
137 # ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
138 # color="k", linestyle="dashed", lw=1)[0]
138 # color="k", linestyle="dashed", lw=1)[0]
139 if self.CODE == 'spc_moments':
139 if self.CODE == 'spc_moments':
140 ax.plt_mean = ax.plot(mean, y, color='k')[0]
140 ax.plt_mean = ax.plot(mean, y, color='k')[0]
141 else:
141 else:
142 ax.plt.set_array(z[n].T.ravel())
142 ax.plt.set_array(z[n].T.ravel())
143 if self.showprofile:
143 if self.showprofile:
144 ax.plt_profile.set_data(data['rti'][n], y)
144 ax.plt_profile.set_data(data['rti'][n], y)
145 #ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
145 #ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
146 if self.CODE == 'spc_moments':
146 if self.CODE == 'spc_moments':
147 ax.plt_mean.set_data(mean, y)
147 ax.plt_mean.set_data(mean, y)
148 if len(self.azimuthList) > 0 and len(self.elevationList) > 0:
148 if len(self.azimuthList) > 0 and len(self.elevationList) > 0:
149 self.titles.append('CH {}: {:2.1f}elv {:2.1f}az {:3.2f}dB'.format(self.channelList[n], noise, self.elevationList[n], self.azimuthList[n]))
149 self.titles.append('CH {}: {:2.1f}elv {:2.1f}az {:3.2f}dB'.format(self.channelList[n], noise, self.elevationList[n], self.azimuthList[n]))
150 else:
150 else:
151 self.titles.append('CH {}: {:3.2f}dB'.format(self.channelList[n], noise))
151 self.titles.append('CH {}: {:3.2f}dB'.format(self.channelList[n], noise))
152
152
153
153
154 class CrossSpectraPlot(Plot):
154 class CrossSpectraPlot(Plot):
155
155
156 CODE = 'cspc'
156 CODE = 'cspc'
157 colormap = 'jet'
157 colormap = 'jet'
158 plot_type = 'pcolor'
158 plot_type = 'pcolor'
159 zmin_coh = None
159 zmin_coh = None
160 zmax_coh = None
160 zmax_coh = None
161 zmin_phase = None
161 zmin_phase = None
162 zmax_phase = None
162 zmax_phase = None
163 realChannels = None
163 realChannels = None
164 crossPairs = None
164 crossPairs = None
165
165
166 def setup(self):
166 def setup(self):
167
167
168 self.ncols = 4
168 self.ncols = 4
169 self.nplots = len(self.data.pairs) * 2
169 self.nplots = len(self.data.pairs) * 2
170 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
170 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
171 self.width = 3.1 * self.ncols
171 self.width = 3.1 * self.ncols
172 self.height = 2.6 * self.nrows
172 self.height = 2.6 * self.nrows
173 self.ylabel = 'Range [km]'
173 self.ylabel = 'Range [km]'
174 self.showprofile = False
174 self.showprofile = False
175 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
175 self.plots_adjust.update({'left': 0.08, 'right': 0.92, 'wspace': 0.5, 'hspace':0.4, 'top':0.95, 'bottom': 0.08})
176
176
177 def update(self, dataOut):
177 def update(self, dataOut):
178
178
179 data = {}
179 data = {}
180 meta = {}
180 meta = {}
181
181
182 spc = dataOut.data_spc
182 spc = dataOut.data_spc
183 cspc = dataOut.data_cspc
183 cspc = dataOut.data_cspc
184 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
184 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
185 rawPairs = list(combinations(list(range(dataOut.nChannels)), 2))
185 rawPairs = list(combinations(list(range(dataOut.nChannels)), 2))
186 meta['pairs'] = rawPairs
186 meta['pairs'] = rawPairs
187
187
188 if self.crossPairs == None:
188 if self.crossPairs == None:
189 self.crossPairs = dataOut.pairsList
189 self.crossPairs = dataOut.pairsList
190
190
191 tmp = []
191 tmp = []
192
192
193 for n, pair in enumerate(meta['pairs']):
193 for n, pair in enumerate(meta['pairs']):
194
194
195 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
195 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
196 coh = numpy.abs(out)
196 coh = numpy.abs(out)
197 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
197 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
198 tmp.append(coh)
198 tmp.append(coh)
199 tmp.append(phase)
199 tmp.append(phase)
200
200
201 data['cspc'] = numpy.array(tmp)
201 data['cspc'] = numpy.array(tmp)
202
202
203 return data, meta
203 return data, meta
204
204
205 def plot(self):
205 def plot(self):
206
206
207 if self.xaxis == "frequency":
207 if self.xaxis == "frequency":
208 x = self.data.xrange[0]
208 x = self.data.xrange[0]
209 self.xlabel = "Frequency (kHz)"
209 self.xlabel = "Frequency (kHz)"
210 elif self.xaxis == "time":
210 elif self.xaxis == "time":
211 x = self.data.xrange[1]
211 x = self.data.xrange[1]
212 self.xlabel = "Time (ms)"
212 self.xlabel = "Time (ms)"
213 else:
213 else:
214 x = self.data.xrange[2]
214 x = self.data.xrange[2]
215 self.xlabel = "Velocity (m/s)"
215 self.xlabel = "Velocity (m/s)"
216
216
217 self.titles = []
217 self.titles = []
218
218
219 y = self.data.yrange
219 y = self.data.yrange
220 self.y = y
220 self.y = y
221
221
222 data = self.data[-1]
222 data = self.data[-1]
223 cspc = data['cspc']
223 cspc = data['cspc']
224
224
225 for n in range(len(self.data.pairs)):
225 for n in range(len(self.data.pairs)):
226
226
227 pair = self.crossPairs[n]
227 pair = self.crossPairs[n]
228
228
229 coh = cspc[n*2]
229 coh = cspc[n*2]
230 phase = cspc[n*2+1]
230 phase = cspc[n*2+1]
231 ax = self.axes[2 * n]
231 ax = self.axes[2 * n]
232
232
233 if ax.firsttime:
233 if ax.firsttime:
234 ax.plt = ax.pcolormesh(x, y, coh.T,
234 ax.plt = ax.pcolormesh(x, y, coh.T,
235 vmin=self.zmin_coh,
235 vmin=self.zmin_coh,
236 vmax=self.zmax_coh,
236 vmax=self.zmax_coh,
237 cmap=plt.get_cmap(self.colormap_coh)
237 cmap=plt.get_cmap(self.colormap_coh)
238 )
238 )
239 else:
239 else:
240 ax.plt.set_array(coh.T.ravel())
240 ax.plt.set_array(coh.T.ravel())
241 self.titles.append(
241 self.titles.append(
242 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
242 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
243
243
244 ax = self.axes[2 * n + 1]
244 ax = self.axes[2 * n + 1]
245 if ax.firsttime:
245 if ax.firsttime:
246 ax.plt = ax.pcolormesh(x, y, phase.T,
246 ax.plt = ax.pcolormesh(x, y, phase.T,
247 vmin=-180,
247 vmin=-180,
248 vmax=180,
248 vmax=180,
249 cmap=plt.get_cmap(self.colormap_phase)
249 cmap=plt.get_cmap(self.colormap_phase)
250 )
250 )
251 else:
251 else:
252 ax.plt.set_array(phase.T.ravel())
252 ax.plt.set_array(phase.T.ravel())
253
253
254 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
254 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
255
255
256
256
257 class RTIPlot(Plot):
257 class RTIPlot(Plot):
258 '''
258 '''
259 Plot for RTI data
259 Plot for RTI data
260 '''
260 '''
261
261
262 CODE = 'rti'
262 CODE = 'rti'
263 colormap = 'jet'
263 colormap = 'jet'
264 plot_type = 'pcolorbuffer'
264 plot_type = 'pcolorbuffer'
265 titles = None
265 titles = None
266 channelList = []
266 channelList = []
267 elevationList = []
267 elevationList = []
268 azimuthList = []
268 azimuthList = []
269
269
270 def setup(self):
270 def setup(self):
271 self.xaxis = 'time'
271 self.xaxis = 'time'
272 self.ncols = 1
272 self.ncols = 1
273 #print("dataChannels ",self.data.channels)
273 #print("dataChannels ",self.data.channels)
274 self.nrows = len(self.data.channels)
274 self.nrows = len(self.data.channels)
275 self.nplots = len(self.data.channels)
275 self.nplots = len(self.data.channels)
276 self.ylabel = 'Range [km]'
276 self.ylabel = 'Range [km]'
277 self.xlabel = 'Time'
277 self.xlabel = 'Time'
278 self.cb_label = 'dB'
278 self.cb_label = 'dB'
279 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
279 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
280 self.titles = ['{} Channel {}'.format(
280 self.titles = ['{} Channel {}'.format(
281 self.CODE.upper(), x) for x in range(self.nplots)]
281 self.CODE.upper(), x) for x in range(self.nplots)]
282
282
283 def update_list(self,dataOut):
283 def update_list(self,dataOut):
284
284
285 if len(self.channelList) == 0:
285 if len(self.channelList) == 0:
286 self.channelList = dataOut.channelList
286 self.channelList = dataOut.channelList
287 if len(self.elevationList) == 0:
287 if len(self.elevationList) == 0:
288 self.elevationList = dataOut.elevationList
288 self.elevationList = dataOut.elevationList
289 if len(self.azimuthList) == 0:
289 if len(self.azimuthList) == 0:
290 self.azimuthList = dataOut.azimuthList
290 self.azimuthList = dataOut.azimuthList
291
291
292
292
293 def update(self, dataOut):
293 def update(self, dataOut):
294 if len(self.channelList) == 0:
294 if len(self.channelList) == 0:
295 self.update_list(dataOut)
295 self.update_list(dataOut)
296 data = {}
296 data = {}
297 meta = {}
297 meta = {}
298
298
299 data['rti'] = dataOut.getPower()
299 data['rti'] = dataOut.getPower()
300
300
301 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
301 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
302 noise = 10*numpy.log10(dataOut.getNoise()/norm)
302 noise = 10*numpy.log10(dataOut.getNoise()/norm)
303 data['noise'] = noise
303 data['noise'] = noise
304
304
305 return data, meta
305 return data, meta
306
306
307 def plot(self):
307 def plot(self):
308
308
309 self.x = self.data.times
309 self.x = self.data.times
310 self.y = self.data.yrange
310 self.y = self.data.yrange
311 #print(" x, y: ",self.x, self.y)
311 #print(" x, y: ",self.x, self.y)
312 self.z = self.data[self.CODE]
312 self.z = self.data[self.CODE]
313 self.z = numpy.array(self.z, dtype=float)
313 self.z = numpy.array(self.z, dtype=float)
314 self.z = numpy.ma.masked_invalid(self.z)
314 self.z = numpy.ma.masked_invalid(self.z)
315
315
316 try:
316 try:
317 if self.channelList != None:
317 if self.channelList != None:
318 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
318 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
319 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
319 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
320 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
320 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
321 else:
321 else:
322 self.titles = ['{} Channel {}'.format(
322 self.titles = ['{} Channel {}'.format(
323 self.CODE.upper(), x) for x in self.channelList]
323 self.CODE.upper(), x) for x in self.channelList]
324 except:
324 except:
325 if self.channelList.any() != None:
325 if self.channelList.any() != None:
326 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
326 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
327 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
327 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
328 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
328 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
329 else:
329 else:
330 self.titles = ['{} Channel {}'.format(
330 self.titles = ['{} Channel {}'.format(
331 self.CODE.upper(), x) for x in self.channelList]
331 self.CODE.upper(), x) for x in self.channelList]
332
332
333 if self.decimation is None:
333 if self.decimation is None:
334 x, y, z = self.fill_gaps(self.x, self.y, self.z)
334 x, y, z = self.fill_gaps(self.x, self.y, self.z)
335 else:
335 else:
336 x, y, z = self.fill_gaps(*self.decimate())
336 x, y, z = self.fill_gaps(*self.decimate())
337
337
338 #dummy_var = self.axes #Extrañamente esto actualiza el valor axes
338 #dummy_var = self.axes #Extrañamente esto actualiza el valor axes
339 for n, ax in enumerate(self.axes):
339 for n, ax in enumerate(self.axes):
340 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
340 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
341 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
341 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
342 data = self.data[-1]
342 data = self.data[-1]
343
343
344 if ax.firsttime:
344 if ax.firsttime:
345 ax.plt = ax.pcolormesh(x, y, z[n].T,
345 ax.plt = ax.pcolormesh(x, y, z[n].T,
346 vmin=self.zmin,
346 vmin=self.zmin,
347 vmax=self.zmax,
347 vmax=self.zmax,
348 cmap=plt.get_cmap(self.colormap)
348 cmap=plt.get_cmap(self.colormap)
349 )
349 )
350 if self.showprofile:
350 if self.showprofile:
351 ax.plot_profile = self.pf_axes[n].plot(data[self.CODE][n], self.y)[0]
351 ax.plot_profile = self.pf_axes[n].plot(data[self.CODE][n], self.y)[0]
352 if "noise" in self.data:
352 if "noise" in self.data:
353
353
354 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
354 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(data['noise'][n], len(self.y)), self.y,
355 color="k", linestyle="dashed", lw=1)[0]
355 color="k", linestyle="dashed", lw=1)[0]
356 else:
356 else:
357 ax.collections.remove(ax.collections[0])
357 ax.collections.remove(ax.collections[0])
358 ax.plt = ax.pcolormesh(x, y, z[n].T,
358 ax.plt = ax.pcolormesh(x, y, z[n].T,
359 vmin=self.zmin,
359 vmin=self.zmin,
360 vmax=self.zmax,
360 vmax=self.zmax,
361 cmap=plt.get_cmap(self.colormap)
361 cmap=plt.get_cmap(self.colormap)
362 )
362 )
363 if self.showprofile:
363 if self.showprofile:
364 ax.plot_profile.set_data(data[self.CODE][n], self.y)
364 ax.plot_profile.set_data(data[self.CODE][n], self.y)
365 if "noise" in self.data:
365 if "noise" in self.data:
366 ax.plot_noise.set_data(numpy.repeat(data['noise'][n], len(self.y)), self.y)
366 ax.plot_noise.set_data(numpy.repeat(data['noise'][n], len(self.y)), self.y)
367
367
368
368
369 class CoherencePlot(RTIPlot):
369 class CoherencePlot(RTIPlot):
370 '''
370 '''
371 Plot for Coherence data
371 Plot for Coherence data
372 '''
372 '''
373
373
374 CODE = 'coh'
374 CODE = 'coh'
375 titles = None
375 titles = None
376
376
377 def setup(self):
377 def setup(self):
378 self.xaxis = 'time'
378 self.xaxis = 'time'
379 self.ncols = 1
379 self.ncols = 1
380 self.nrows = len(self.data.pairs)
380 self.nrows = len(self.data.pairs)
381 self.nplots = len(self.data.pairs)
381 self.nplots = len(self.data.pairs)
382 self.ylabel = 'Range [km]'
382 self.ylabel = 'Range [km]'
383 self.xlabel = 'Time'
383 self.xlabel = 'Time'
384 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
384 self.plots_adjust.update({'hspace':0.6, 'left': 0.1, 'bottom': 0.1,'right':0.95})
385 if self.CODE == 'coh':
385 if self.CODE == 'coh':
386 self.cb_label = ''
386 self.cb_label = ''
387 self.titles = [
387 self.titles = [
388 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
388 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
389 else:
389 else:
390 self.cb_label = 'Degrees'
390 self.cb_label = 'Degrees'
391 self.titles = [
391 self.titles = [
392 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
392 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
393
393
394
394
395 def update(self, dataOut):
395 def update(self, dataOut):
396
396
397 data = {}
397 data = {}
398 meta = {}
398 meta = {}
399 data['coh'] = dataOut.getCoherence()
399 data['coh'] = dataOut.getCoherence()
400 meta['pairs'] = dataOut.pairsList
400 meta['pairs'] = dataOut.pairsList
401
401
402
402
403 return data, meta
403 return data, meta
404
404
405 def plot(self):
405 def plot(self):
406
406
407 self.x = self.data.times
407 self.x = self.data.times
408 self.y = self.data.yrange
408 self.y = self.data.yrange
409 self.z = self.data[self.CODE]
409 self.z = self.data[self.CODE]
410
410
411 self.z = numpy.ma.masked_invalid(self.z)
411 self.z = numpy.ma.masked_invalid(self.z)
412
412
413 if self.decimation is None:
413 if self.decimation is None:
414 x, y, z = self.fill_gaps(self.x, self.y, self.z)
414 x, y, z = self.fill_gaps(self.x, self.y, self.z)
415 else:
415 else:
416 x, y, z = self.fill_gaps(*self.decimate())
416 x, y, z = self.fill_gaps(*self.decimate())
417
417
418 for n, ax in enumerate(self.axes):
418 for n, ax in enumerate(self.axes):
419 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
419 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
420 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
420 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
421 if ax.firsttime:
421 if ax.firsttime:
422 ax.plt = ax.pcolormesh(x, y, z[n].T,
422 ax.plt = ax.pcolormesh(x, y, z[n].T,
423 vmin=self.zmin,
423 vmin=self.zmin,
424 vmax=self.zmax,
424 vmax=self.zmax,
425 cmap=plt.get_cmap(self.colormap)
425 cmap=plt.get_cmap(self.colormap)
426 )
426 )
427 if self.showprofile:
427 if self.showprofile:
428 ax.plot_profile = self.pf_axes[n].plot(
428 ax.plot_profile = self.pf_axes[n].plot(
429 self.data[self.CODE][n][-1], self.y)[0]
429 self.data[self.CODE][n][-1], self.y)[0]
430 # ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
430 # ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
431 # color="k", linestyle="dashed", lw=1)[0]
431 # color="k", linestyle="dashed", lw=1)[0]
432 else:
432 else:
433 ax.collections.remove(ax.collections[0])
433 ax.collections.remove(ax.collections[0])
434 ax.plt = ax.pcolormesh(x, y, z[n].T,
434 ax.plt = ax.pcolormesh(x, y, z[n].T,
435 vmin=self.zmin,
435 vmin=self.zmin,
436 vmax=self.zmax,
436 vmax=self.zmax,
437 cmap=plt.get_cmap(self.colormap)
437 cmap=plt.get_cmap(self.colormap)
438 )
438 )
439 if self.showprofile:
439 if self.showprofile:
440 ax.plot_profile.set_data(self.data[self.CODE][n][-1], self.y)
440 ax.plot_profile.set_data(self.data[self.CODE][n][-1], self.y)
441 # ax.plot_noise.set_data(numpy.repeat(
441 # ax.plot_noise.set_data(numpy.repeat(
442 # self.data['noise'][n][-1], len(self.y)), self.y)
442 # self.data['noise'][n][-1], len(self.y)), self.y)
443
443
444
444
445
445
446 class PhasePlot(CoherencePlot):
446 class PhasePlot(CoherencePlot):
447 '''
447 '''
448 Plot for Phase map data
448 Plot for Phase map data
449 '''
449 '''
450
450
451 CODE = 'phase'
451 CODE = 'phase'
452 colormap = 'seismic'
452 colormap = 'seismic'
453
453
454 def update(self, dataOut):
454 def update(self, dataOut):
455
455
456 data = {}
456 data = {}
457 meta = {}
457 meta = {}
458 data['phase'] = dataOut.getCoherence(phase=True)
458 data['phase'] = dataOut.getCoherence(phase=True)
459 meta['pairs'] = dataOut.pairsList
459 meta['pairs'] = dataOut.pairsList
460
460
461 return data, meta
461 return data, meta
462
462
463 class NoisePlot(Plot):
463 class NoisePlot(Plot):
464 '''
464 '''
465 Plot for noise
465 Plot for noise
466 '''
466 '''
467
467
468 CODE = 'noise'
468 CODE = 'noise'
469 plot_type = 'scatterbuffer'
469 plot_type = 'scatterbuffer'
470
470
471 def setup(self):
471 def setup(self):
472 self.xaxis = 'time'
472 self.xaxis = 'time'
473 self.ncols = 1
473 self.ncols = 1
474 self.nrows = 1
474 self.nrows = 1
475 self.nplots = 1
475 self.nplots = 1
476 self.ylabel = 'Intensity [dB]'
476 self.ylabel = 'Intensity [dB]'
477 self.xlabel = 'Time'
477 self.xlabel = 'Time'
478 self.titles = ['Noise']
478 self.titles = ['Noise']
479 self.colorbar = False
479 self.colorbar = False
480 self.plots_adjust.update({'right': 0.85 })
480 self.plots_adjust.update({'right': 0.85 })
481 #if not self.titles:
481 #if not self.titles:
482 self.titles = ['Noise Plot']
482 self.titles = ['Noise Plot']
483
483
484 def update(self, dataOut):
484 def update(self, dataOut):
485
485
486 data = {}
486 data = {}
487 meta = {}
487 meta = {}
488 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
488 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
489 noise = 10*numpy.log10(dataOut.getNoise())
489 noise = 10*numpy.log10(dataOut.getNoise())
490 noise = noise.reshape(dataOut.nChannels, 1)
490 noise = noise.reshape(dataOut.nChannels, 1)
491 data['noise'] = noise
491 data['noise'] = noise
492 meta['yrange'] = numpy.array([])
492 meta['yrange'] = numpy.array([])
493
493
494 return data, meta
494 return data, meta
495
495
496 def plot(self):
496 def plot(self):
497
497
498 x = self.data.times
498 x = self.data.times
499 xmin = self.data.min_time
499 xmin = self.data.min_time
500 xmax = xmin + self.xrange * 60 * 60
500 xmax = xmin + self.xrange * 60 * 60
501 Y = self.data['noise']
501 Y = self.data['noise']
502
502
503 if self.axes[0].firsttime:
503 if self.axes[0].firsttime:
504 if self.ymin is None: self.ymin = numpy.nanmin(Y) - 5
504 if self.ymin is None: self.ymin = numpy.nanmin(Y) - 5
505 if self.ymax is None: self.ymax = numpy.nanmax(Y) + 5
505 if self.ymax is None: self.ymax = numpy.nanmax(Y) + 5
506 for ch in self.data.channels:
506 for ch in self.data.channels:
507 y = Y[ch]
507 y = Y[ch]
508 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
508 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
509 plt.legend(bbox_to_anchor=(1.18, 1.0))
509 plt.legend(bbox_to_anchor=(1.18, 1.0))
510 else:
510 else:
511 for ch in self.data.channels:
511 for ch in self.data.channels:
512 y = Y[ch]
512 y = Y[ch]
513 self.axes[0].lines[ch].set_data(x, y)
513 self.axes[0].lines[ch].set_data(x, y)
514
514
515
515
516 class PowerProfilePlot(Plot):
516 class PowerProfilePlot(Plot):
517
517
518 CODE = 'pow_profile'
518 CODE = 'pow_profile'
519 plot_type = 'scatter'
519 plot_type = 'scatter'
520
520
521 def setup(self):
521 def setup(self):
522
522
523 self.ncols = 1
523 self.ncols = 1
524 self.nrows = 1
524 self.nrows = 1
525 self.nplots = 1
525 self.nplots = 1
526 self.height = 4
526 self.height = 4
527 self.width = 3
527 self.width = 3
528 self.ylabel = 'Range [km]'
528 self.ylabel = 'Range [km]'
529 self.xlabel = 'Intensity [dB]'
529 self.xlabel = 'Intensity [dB]'
530 self.titles = ['Power Profile']
530 self.titles = ['Power Profile']
531 self.colorbar = False
531 self.colorbar = False
532
532
533 def update(self, dataOut):
533 def update(self, dataOut):
534
534
535 data = {}
535 data = {}
536 meta = {}
536 meta = {}
537 data[self.CODE] = dataOut.getPower()
537 data[self.CODE] = dataOut.getPower()
538
538
539 return data, meta
539 return data, meta
540
540
541 def plot(self):
541 def plot(self):
542
542
543 y = self.data.yrange
543 y = self.data.yrange
544 self.y = y
544 self.y = y
545
545
546 x = self.data[-1][self.CODE]
546 x = self.data[-1][self.CODE]
547
547
548 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
548 if self.xmin is None: self.xmin = numpy.nanmin(x)*0.9
549 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
549 if self.xmax is None: self.xmax = numpy.nanmax(x)*1.1
550
550
551 if self.axes[0].firsttime:
551 if self.axes[0].firsttime:
552 for ch in self.data.channels:
552 for ch in self.data.channels:
553 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
553 self.axes[0].plot(x[ch], y, lw=1, label='Ch{}'.format(ch))
554 plt.legend()
554 plt.legend()
555 else:
555 else:
556 for ch in self.data.channels:
556 for ch in self.data.channels:
557 self.axes[0].lines[ch].set_data(x[ch], y)
557 self.axes[0].lines[ch].set_data(x[ch], y)
558
558
559
559
560 class SpectraCutPlot(Plot):
560 class SpectraCutPlot(Plot):
561
561
562 CODE = 'spc_cut'
562 CODE = 'spc_cut'
563 plot_type = 'scatter'
563 plot_type = 'scatter'
564 buffering = False
564 buffering = False
565 heights = []
565 heights = []
566 channelList = []
566 channelList = []
567 maintitle = "Spectra Cuts"
567 maintitle = "Spectra Cuts"
568 flag_setIndex = False
568 flag_setIndex = False
569
569
570 def setup(self):
570 def setup(self):
571
571
572 self.nplots = len(self.data.channels)
572 self.nplots = len(self.data.channels)
573 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
573 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
574 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
574 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
575 self.width = 4.5 * self.ncols + 2.5
575 self.width = 4.5 * self.ncols + 2.5
576 self.height = 4.8 * self.nrows
576 self.height = 4.8 * self.nrows
577 self.ylabel = 'Power [dB]'
577 self.ylabel = 'Power [dB]'
578 self.colorbar = False
578 self.colorbar = False
579 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.9, 'bottom':0.08})
579 self.plots_adjust.update({'left':0.1, 'hspace':0.3, 'right': 0.9, 'bottom':0.08})
580
580
581 if len(self.selectedHeightsList) > 0:
581 if len(self.selectedHeightsList) > 0:
582 self.maintitle = "Spectra Cut"# for %d km " %(int(self.selectedHeight))
582 self.maintitle = "Spectra Cut"# for %d km " %(int(self.selectedHeight))
583
583
584
584
585
585
586 def update(self, dataOut):
586 def update(self, dataOut):
587 if len(self.channelList) == 0:
587 if len(self.channelList) == 0:
588 self.channelList = dataOut.channelList
588 self.channelList = dataOut.channelList
589
589
590 self.heights = dataOut.heightList
590 self.heights = dataOut.heightList
591 #print("sels: ",self.selectedHeightsList)
591 #print("sels: ",self.selectedHeightsList)
592 if len(self.selectedHeightsList)>0 and not self.flag_setIndex:
592 if len(self.selectedHeightsList)>0 and not self.flag_setIndex:
593
593
594 for sel_height in self.selectedHeightsList:
594 for sel_height in self.selectedHeightsList:
595 index_list = numpy.where(self.heights >= sel_height)
595 index_list = numpy.where(self.heights >= sel_height)
596 index_list = index_list[0]
596 index_list = index_list[0]
597 self.height_index.append(index_list[0])
597 self.height_index.append(index_list[0])
598 #print("sels i:"", self.height_index)
598 #print("sels i:"", self.height_index)
599 self.flag_setIndex = True
599 self.flag_setIndex = True
600 #print(self.height_index)
600 #print(self.height_index)
601 data = {}
601 data = {}
602 meta = {}
602 meta = {}
603
603
604 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter#*dataOut.nFFTPoints
604 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter#*dataOut.nFFTPoints
605 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
605 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
606 noise = numpy.repeat(n0,(dataOut.nFFTPoints*dataOut.nHeights)).reshape(dataOut.nChannels,dataOut.nFFTPoints,dataOut.nHeights)
606 noise = numpy.repeat(n0,(dataOut.nFFTPoints*dataOut.nHeights)).reshape(dataOut.nChannels,dataOut.nFFTPoints,dataOut.nHeights)
607
607
608
608
609 z = []
609 z = []
610 for ch in range(dataOut.nChannels):
610 for ch in range(dataOut.nChannels):
611 if hasattr(dataOut.normFactor,'shape'):
611 if hasattr(dataOut.normFactor,'shape'):
612 z.append(numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
612 z.append(numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
613 else:
613 else:
614 z.append(numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
614 z.append(numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
615
615
616 z = numpy.asarray(z)
616 z = numpy.asarray(z)
617 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
617 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
618 spc = 10*numpy.log10(z)
618 spc = 10*numpy.log10(z)
619
619
620
620
621 data['spc'] = spc - noise
621 data['spc'] = spc - noise
622 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
622 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
623
623
624 return data, meta
624 return data, meta
625
625
626 def plot(self):
626 def plot(self):
627 if self.xaxis == "frequency":
627 if self.xaxis == "frequency":
628 x = self.data.xrange[0][1:]
628 x = self.data.xrange[0][1:]
629 self.xlabel = "Frequency (kHz)"
629 self.xlabel = "Frequency (kHz)"
630 elif self.xaxis == "time":
630 elif self.xaxis == "time":
631 x = self.data.xrange[1]
631 x = self.data.xrange[1]
632 self.xlabel = "Time (ms)"
632 self.xlabel = "Time (ms)"
633 else:
633 else:
634 x = self.data.xrange[2]
634 x = self.data.xrange[2]
635 self.xlabel = "Velocity (m/s)"
635 self.xlabel = "Velocity (m/s)"
636
636
637 self.titles = []
637 self.titles = []
638
638
639 y = self.data.yrange
639 y = self.data.yrange
640 z = self.data[-1]['spc']
640 z = self.data[-1]['spc']
641 #print(z.shape)
641 #print(z.shape)
642 if len(self.height_index) > 0:
642 if len(self.height_index) > 0:
643 index = self.height_index
643 index = self.height_index
644 else:
644 else:
645 index = numpy.arange(0, len(y), int((len(y))/9))
645 index = numpy.arange(0, len(y), int((len(y))/9))
646 #print("inde x ", index, self.axes)
646 #print("inde x ", index, self.axes)
647
647
648 for n, ax in enumerate(self.axes):
648 for n, ax in enumerate(self.axes):
649
649
650 if ax.firsttime:
650 if ax.firsttime:
651
651
652
652
653 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
653 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
654 self.xmin = self.xmin if self.xmin else -self.xmax
654 self.xmin = self.xmin if self.xmin else -self.xmax
655 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
655 self.ymin = self.ymin if self.ymin else numpy.nanmin(z)
656 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
656 self.ymax = self.ymax if self.ymax else numpy.nanmax(z)
657
657
658
658
659 ax.plt = ax.plot(x, z[n, :, index].T)
659 ax.plt = ax.plot(x, z[n, :, index].T)
660 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
660 labels = ['Range = {:2.1f}km'.format(y[i]) for i in index]
661 self.figures[0].legend(ax.plt, labels, loc='center right', prop={'size': 8})
661 self.figures[0].legend(ax.plt, labels, loc='center right', prop={'size': 8})
662 ax.minorticks_on()
662 ax.minorticks_on()
663 ax.grid(which='major', axis='both')
663 ax.grid(which='major', axis='both')
664 ax.grid(which='minor', axis='x')
664 ax.grid(which='minor', axis='x')
665 else:
665 else:
666 for i, line in enumerate(ax.plt):
666 for i, line in enumerate(ax.plt):
667 line.set_data(x, z[n, :, index[i]])
667 line.set_data(x, z[n, :, index[i]])
668
668
669
669
670 self.titles.append('CH {}'.format(self.channelList[n]))
670 self.titles.append('CH {}'.format(self.channelList[n]))
671 plt.suptitle(self.maintitle, fontsize=10)
671 plt.suptitle(self.maintitle, fontsize=10)
672
672
673
673
674 class BeaconPhase(Plot):
674 class BeaconPhase(Plot):
675
675
676 __isConfig = None
676 __isConfig = None
677 __nsubplots = None
677 __nsubplots = None
678
678
679 PREFIX = 'beacon_phase'
679 PREFIX = 'beacon_phase'
680
680
681 def __init__(self):
681 def __init__(self):
682 Plot.__init__(self)
682 Plot.__init__(self)
683 self.timerange = 24*60*60
683 self.timerange = 24*60*60
684 self.isConfig = False
684 self.isConfig = False
685 self.__nsubplots = 1
685 self.__nsubplots = 1
686 self.counter_imagwr = 0
686 self.counter_imagwr = 0
687 self.WIDTH = 800
687 self.WIDTH = 800
688 self.HEIGHT = 400
688 self.HEIGHT = 400
689 self.WIDTHPROF = 120
689 self.WIDTHPROF = 120
690 self.HEIGHTPROF = 0
690 self.HEIGHTPROF = 0
691 self.xdata = None
691 self.xdata = None
692 self.ydata = None
692 self.ydata = None
693
693
694 self.PLOT_CODE = BEACON_CODE
694 self.PLOT_CODE = BEACON_CODE
695
695
696 self.FTP_WEI = None
696 self.FTP_WEI = None
697 self.EXP_CODE = None
697 self.EXP_CODE = None
698 self.SUB_EXP_CODE = None
698 self.SUB_EXP_CODE = None
699 self.PLOT_POS = None
699 self.PLOT_POS = None
700
700
701 self.filename_phase = None
701 self.filename_phase = None
702
702
703 self.figfile = None
703 self.figfile = None
704
704
705 self.xmin = None
705 self.xmin = None
706 self.xmax = None
706 self.xmax = None
707
707
708 def getSubplots(self):
708 def getSubplots(self):
709
709
710 ncol = 1
710 ncol = 1
711 nrow = 1
711 nrow = 1
712
712
713 return nrow, ncol
713 return nrow, ncol
714
714
715 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
715 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
716
716
717 self.__showprofile = showprofile
717 self.__showprofile = showprofile
718 self.nplots = nplots
718 self.nplots = nplots
719
719
720 ncolspan = 7
720 ncolspan = 7
721 colspan = 6
721 colspan = 6
722 self.__nsubplots = 2
722 self.__nsubplots = 2
723
723
724 self.createFigure(id = id,
724 self.createFigure(id = id,
725 wintitle = wintitle,
725 wintitle = wintitle,
726 widthplot = self.WIDTH+self.WIDTHPROF,
726 widthplot = self.WIDTH+self.WIDTHPROF,
727 heightplot = self.HEIGHT+self.HEIGHTPROF,
727 heightplot = self.HEIGHT+self.HEIGHTPROF,
728 show=show)
728 show=show)
729
729
730 nrow, ncol = self.getSubplots()
730 nrow, ncol = self.getSubplots()
731
731
732 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
732 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
733
733
734 def save_phase(self, filename_phase):
734 def save_phase(self, filename_phase):
735 f = open(filename_phase,'w+')
735 f = open(filename_phase,'w+')
736 f.write('\n\n')
736 f.write('\n\n')
737 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
737 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
738 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
738 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
739 f.close()
739 f.close()
740
740
741 def save_data(self, filename_phase, data, data_datetime):
741 def save_data(self, filename_phase, data, data_datetime):
742 f=open(filename_phase,'a')
742 f=open(filename_phase,'a')
743 timetuple_data = data_datetime.timetuple()
743 timetuple_data = data_datetime.timetuple()
744 day = str(timetuple_data.tm_mday)
744 day = str(timetuple_data.tm_mday)
745 month = str(timetuple_data.tm_mon)
745 month = str(timetuple_data.tm_mon)
746 year = str(timetuple_data.tm_year)
746 year = str(timetuple_data.tm_year)
747 hour = str(timetuple_data.tm_hour)
747 hour = str(timetuple_data.tm_hour)
748 minute = str(timetuple_data.tm_min)
748 minute = str(timetuple_data.tm_min)
749 second = str(timetuple_data.tm_sec)
749 second = str(timetuple_data.tm_sec)
750 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
750 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
751 f.close()
751 f.close()
752
752
753 def plot(self):
753 def plot(self):
754 log.warning('TODO: Not yet implemented...')
754 log.warning('TODO: Not yet implemented...')
755
755
756 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
756 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
757 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
757 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
758 timerange=None,
758 timerange=None,
759 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
759 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
760 server=None, folder=None, username=None, password=None,
760 server=None, folder=None, username=None, password=None,
761 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
761 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
762
762
763 if dataOut.flagNoData:
763 if dataOut.flagNoData:
764 return dataOut
764 return dataOut
765
765
766 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
766 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
767 return
767 return
768
768
769 if pairsList == None:
769 if pairsList == None:
770 pairsIndexList = dataOut.pairsIndexList[:10]
770 pairsIndexList = dataOut.pairsIndexList[:10]
771 else:
771 else:
772 pairsIndexList = []
772 pairsIndexList = []
773 for pair in pairsList:
773 for pair in pairsList:
774 if pair not in dataOut.pairsList:
774 if pair not in dataOut.pairsList:
775 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
775 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
776 pairsIndexList.append(dataOut.pairsList.index(pair))
776 pairsIndexList.append(dataOut.pairsList.index(pair))
777
777
778 if pairsIndexList == []:
778 if pairsIndexList == []:
779 return
779 return
780
780
781 # if len(pairsIndexList) > 4:
781 # if len(pairsIndexList) > 4:
782 # pairsIndexList = pairsIndexList[0:4]
782 # pairsIndexList = pairsIndexList[0:4]
783
783
784 hmin_index = None
784 hmin_index = None
785 hmax_index = None
785 hmax_index = None
786
786
787 if hmin != None and hmax != None:
787 if hmin != None and hmax != None:
788 indexes = numpy.arange(dataOut.nHeights)
788 indexes = numpy.arange(dataOut.nHeights)
789 hmin_list = indexes[dataOut.heightList >= hmin]
789 hmin_list = indexes[dataOut.heightList >= hmin]
790 hmax_list = indexes[dataOut.heightList <= hmax]
790 hmax_list = indexes[dataOut.heightList <= hmax]
791
791
792 if hmin_list.any():
792 if hmin_list.any():
793 hmin_index = hmin_list[0]
793 hmin_index = hmin_list[0]
794
794
795 if hmax_list.any():
795 if hmax_list.any():
796 hmax_index = hmax_list[-1]+1
796 hmax_index = hmax_list[-1]+1
797
797
798 x = dataOut.getTimeRange()
798 x = dataOut.getTimeRange()
799
799
800 thisDatetime = dataOut.datatime
800 thisDatetime = dataOut.datatime
801
801
802 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
802 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
803 xlabel = "Local Time"
803 xlabel = "Local Time"
804 ylabel = "Phase (degrees)"
804 ylabel = "Phase (degrees)"
805
805
806 update_figfile = False
806 update_figfile = False
807
807
808 nplots = len(pairsIndexList)
808 nplots = len(pairsIndexList)
809 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
809 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
810 phase_beacon = numpy.zeros(len(pairsIndexList))
810 phase_beacon = numpy.zeros(len(pairsIndexList))
811 for i in range(nplots):
811 for i in range(nplots):
812 pair = dataOut.pairsList[pairsIndexList[i]]
812 pair = dataOut.pairsList[pairsIndexList[i]]
813 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
813 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
814 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
814 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
815 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
815 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
816 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
816 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
817 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
817 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
818
818
819 if dataOut.beacon_heiIndexList:
819 if dataOut.beacon_heiIndexList:
820 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
820 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
821 else:
821 else:
822 phase_beacon[i] = numpy.average(phase)
822 phase_beacon[i] = numpy.average(phase)
823
823
824 if not self.isConfig:
824 if not self.isConfig:
825
825
826 nplots = len(pairsIndexList)
826 nplots = len(pairsIndexList)
827
827
828 self.setup(id=id,
828 self.setup(id=id,
829 nplots=nplots,
829 nplots=nplots,
830 wintitle=wintitle,
830 wintitle=wintitle,
831 showprofile=showprofile,
831 showprofile=showprofile,
832 show=show)
832 show=show)
833
833
834 if timerange != None:
834 if timerange != None:
835 self.timerange = timerange
835 self.timerange = timerange
836
836
837 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
837 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
838
838
839 if ymin == None: ymin = 0
839 if ymin == None: ymin = 0
840 if ymax == None: ymax = 360
840 if ymax == None: ymax = 360
841
841
842 self.FTP_WEI = ftp_wei
842 self.FTP_WEI = ftp_wei
843 self.EXP_CODE = exp_code
843 self.EXP_CODE = exp_code
844 self.SUB_EXP_CODE = sub_exp_code
844 self.SUB_EXP_CODE = sub_exp_code
845 self.PLOT_POS = plot_pos
845 self.PLOT_POS = plot_pos
846
846
847 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
847 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
848 self.isConfig = True
848 self.isConfig = True
849 self.figfile = figfile
849 self.figfile = figfile
850 self.xdata = numpy.array([])
850 self.xdata = numpy.array([])
851 self.ydata = numpy.array([])
851 self.ydata = numpy.array([])
852
852
853 update_figfile = True
853 update_figfile = True
854
854
855 #open file beacon phase
855 #open file beacon phase
856 path = '%s%03d' %(self.PREFIX, self.id)
856 path = '%s%03d' %(self.PREFIX, self.id)
857 beacon_file = os.path.join(path,'%s.txt'%self.name)
857 beacon_file = os.path.join(path,'%s.txt'%self.name)
858 self.filename_phase = os.path.join(figpath,beacon_file)
858 self.filename_phase = os.path.join(figpath,beacon_file)
859 #self.save_phase(self.filename_phase)
859 #self.save_phase(self.filename_phase)
860
860
861
861
862 #store data beacon phase
862 #store data beacon phase
863 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
863 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
864
864
865 self.setWinTitle(title)
865 self.setWinTitle(title)
866
866
867
867
868 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
868 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
869
869
870 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
870 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
871
871
872 axes = self.axesList[0]
872 axes = self.axesList[0]
873
873
874 self.xdata = numpy.hstack((self.xdata, x[0:1]))
874 self.xdata = numpy.hstack((self.xdata, x[0:1]))
875
875
876 if len(self.ydata)==0:
876 if len(self.ydata)==0:
877 self.ydata = phase_beacon.reshape(-1,1)
877 self.ydata = phase_beacon.reshape(-1,1)
878 else:
878 else:
879 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
879 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
880
880
881
881
882 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
882 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
883 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
883 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
884 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
884 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
885 XAxisAsTime=True, grid='both'
885 XAxisAsTime=True, grid='both'
886 )
886 )
887
887
888 self.draw()
888 self.draw()
889
889
890 if dataOut.ltctime >= self.xmax:
890 if dataOut.ltctime >= self.xmax:
891 self.counter_imagwr = wr_period
891 self.counter_imagwr = wr_period
892 self.isConfig = False
892 self.isConfig = False
893 update_figfile = True
893 update_figfile = True
894
894
895 self.save(figpath=figpath,
895 self.save(figpath=figpath,
896 figfile=figfile,
896 figfile=figfile,
897 save=save,
897 save=save,
898 ftp=ftp,
898 ftp=ftp,
899 wr_period=wr_period,
899 wr_period=wr_period,
900 thisDatetime=thisDatetime,
900 thisDatetime=thisDatetime,
901 update_figfile=update_figfile)
901 update_figfile=update_figfile)
902
902
903 return dataOut
903 return dataOut
904
904
905 class NoiselessSpectraPlot(Plot):
905 class NoiselessSpectraPlot(Plot):
906 '''
906 '''
907 Plot for Spectra data, subtracting
907 Plot for Spectra data, subtracting
908 the noise in all channels, using for
908 the noise in all channels, using for
909 amisr-14 data
909 amisr-14 data
910 '''
910 '''
911
911
912 CODE = 'noiseless_spc'
912 CODE = 'noiseless_spc'
913 colormap = 'jet'
913 colormap = 'jet'
914 plot_type = 'pcolor'
914 plot_type = 'pcolor'
915 buffering = False
915 buffering = False
916 channelList = []
916 channelList = []
917 last_noise = None
917 last_noise = None
918
918
919 def setup(self):
919 def setup(self):
920
920
921 self.nplots = len(self.data.channels)
921 self.nplots = len(self.data.channels)
922 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
922 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
923 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
923 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
924 self.height = 3.5 * self.nrows
924 self.height = 3.5 * self.nrows
925
925
926 self.cb_label = 'dB'
926 self.cb_label = 'dB'
927 if self.showprofile:
927 if self.showprofile:
928 self.width = 5.8 * self.ncols
928 self.width = 5.8 * self.ncols
929 else:
929 else:
930 self.width = 4.8* self.ncols
930 self.width = 4.8* self.ncols
931 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.92, 'bottom': 0.12})
931 self.plots_adjust.update({'wspace': 0.4, 'hspace':0.4, 'left': 0.1, 'right': 0.92, 'bottom': 0.12})
932
932
933 self.ylabel = 'Range [km]'
933 self.ylabel = 'Range [km]'
934
934
935
935
936 def update_list(self,dataOut):
936 def update_list(self,dataOut):
937 if len(self.channelList) == 0:
937 if len(self.channelList) == 0:
938 self.channelList = dataOut.channelList
938 self.channelList = dataOut.channelList
939
939
940 def update(self, dataOut):
940 def update(self, dataOut):
941
941
942 self.update_list(dataOut)
942 self.update_list(dataOut)
943 data = {}
943 data = {}
944 meta = {}
944 meta = {}
945
945
946 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
946 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
947 n0 = (dataOut.getNoise()/norm)
947 n0 = (dataOut.getNoise()/norm)
948 noise = numpy.repeat(n0,(dataOut.nFFTPoints*dataOut.nHeights)).reshape(dataOut.nChannels,dataOut.nFFTPoints,dataOut.nHeights)
948 noise = numpy.repeat(n0,(dataOut.nFFTPoints*dataOut.nHeights)).reshape(dataOut.nChannels,dataOut.nFFTPoints,dataOut.nHeights)
949 noise = 10*numpy.log10(noise)
949 noise = 10*numpy.log10(noise)
950
950
951 z = numpy.zeros((dataOut.nChannels, dataOut.nFFTPoints, dataOut.nHeights))
951 z = numpy.zeros((dataOut.nChannels, dataOut.nFFTPoints, dataOut.nHeights))
952 for ch in range(dataOut.nChannels):
952 for ch in range(dataOut.nChannels):
953 if hasattr(dataOut.normFactor,'ndim'):
953 if hasattr(dataOut.normFactor,'ndim'):
954 if dataOut.normFactor.ndim > 1:
954 if dataOut.normFactor.ndim > 1:
955 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
955 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor[ch]))
956 else:
956 else:
957 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
957 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
958 else:
958 else:
959 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
959 z[ch] = (numpy.divide(dataOut.data_spc[ch],dataOut.normFactor))
960
960
961 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
961 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
962 spc = 10*numpy.log10(z)
962 spc = 10*numpy.log10(z)
963
963
964
964
965 data['spc'] = spc - noise
965 data['spc'] = spc - noise
966 #print(spc.shape)
966 #print(spc.shape)
967 data['rti'] = spc.mean(axis=1)
967 data['rti'] = spc.mean(axis=1)
968 data['noise'] = noise
968 data['noise'] = noise
969
969
970
970
971
971
972 # data['noise'] = noise
972 # data['noise'] = noise
973 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
973 meta['xrange'] = (dataOut.getFreqRange(EXTRA_POINTS)/1000., dataOut.getAcfRange(EXTRA_POINTS), dataOut.getVelRange(EXTRA_POINTS))
974
974
975 return data, meta
975 return data, meta
976
976
977 def plot(self):
977 def plot(self):
978 if self.xaxis == "frequency":
978 if self.xaxis == "frequency":
979 x = self.data.xrange[0]
979 x = self.data.xrange[0]
980 self.xlabel = "Frequency (kHz)"
980 self.xlabel = "Frequency (kHz)"
981 elif self.xaxis == "time":
981 elif self.xaxis == "time":
982 x = self.data.xrange[1]
982 x = self.data.xrange[1]
983 self.xlabel = "Time (ms)"
983 self.xlabel = "Time (ms)"
984 else:
984 else:
985 x = self.data.xrange[2]
985 x = self.data.xrange[2]
986 self.xlabel = "Velocity (m/s)"
986 self.xlabel = "Velocity (m/s)"
987
987
988 self.titles = []
988 self.titles = []
989 y = self.data.yrange
989 y = self.data.yrange
990 self.y = y
990 self.y = y
991
991
992 data = self.data[-1]
992 data = self.data[-1]
993 z = data['spc']
993 z = data['spc']
994
994
995 for n, ax in enumerate(self.axes):
995 for n, ax in enumerate(self.axes):
996 #noise = data['noise'][n]
996 #noise = data['noise'][n]
997
997
998 if ax.firsttime:
998 if ax.firsttime:
999 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
999 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
1000 self.xmin = self.xmin if self.xmin else -self.xmax
1000 self.xmin = self.xmin if self.xmin else -self.xmax
1001 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
1001 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
1002 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
1002 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
1003 ax.plt = ax.pcolormesh(x, y, z[n].T,
1003 ax.plt = ax.pcolormesh(x, y, z[n].T,
1004 vmin=self.zmin,
1004 vmin=self.zmin,
1005 vmax=self.zmax,
1005 vmax=self.zmax,
1006 cmap=plt.get_cmap(self.colormap)
1006 cmap=plt.get_cmap(self.colormap)
1007 )
1007 )
1008
1008
1009 if self.showprofile:
1009 if self.showprofile:
1010 ax.plt_profile = self.pf_axes[n].plot(
1010 ax.plt_profile = self.pf_axes[n].plot(
1011 data['rti'][n], y)[0]
1011 data['rti'][n], y)[0]
1012
1012
1013
1013
1014 else:
1014 else:
1015 ax.plt.set_array(z[n].T.ravel())
1015 ax.plt.set_array(z[n].T.ravel())
1016 if self.showprofile:
1016 if self.showprofile:
1017 ax.plt_profile.set_data(data['rti'][n], y)
1017 ax.plt_profile.set_data(data['rti'][n], y)
1018
1018
1019
1019
1020 self.titles.append('CH {}'.format(self.channelList[n]))
1020 self.titles.append('CH {}'.format(self.channelList[n]))
1021
1021
1022
1022
1023 class NoiselessRTIPlot(RTIPlot):
1023 class NoiselessRTIPlot(RTIPlot):
1024 '''
1024 '''
1025 Plot for RTI data
1025 Plot for RTI data
1026 '''
1026 '''
1027
1027
1028 CODE = 'noiseless_rti'
1028 CODE = 'noiseless_rti'
1029 colormap = 'jet'
1029 colormap = 'jet'
1030 plot_type = 'pcolorbuffer'
1030 plot_type = 'pcolorbuffer'
1031 titles = None
1031 titles = None
1032 channelList = []
1032 channelList = []
1033 elevationList = []
1033 elevationList = []
1034 azimuthList = []
1034 azimuthList = []
1035 last_noise = None
1035 last_noise = None
1036
1036
1037 def setup(self):
1037 def setup(self):
1038 self.xaxis = 'time'
1038 self.xaxis = 'time'
1039 self.ncols = 1
1039 self.ncols = 1
1040 #print("dataChannels ",self.data.channels)
1040 #print("dataChannels ",self.data.channels)
1041 self.nrows = len(self.data.channels)
1041 self.nrows = len(self.data.channels)
1042 self.nplots = len(self.data.channels)
1042 self.nplots = len(self.data.channels)
1043 self.ylabel = 'Range [km]'
1043 self.ylabel = 'Range [km]'
1044 self.xlabel = 'Time'
1044 self.xlabel = 'Time'
1045 self.cb_label = 'dB'
1045 self.cb_label = 'dB'
1046 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1046 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1047 self.titles = ['{} Channel {}'.format(
1047 self.titles = ['{} Channel {}'.format(
1048 self.CODE.upper(), x) for x in range(self.nplots)]
1048 self.CODE.upper(), x) for x in range(self.nplots)]
1049
1049
1050 def update_list(self,dataOut):
1050 def update_list(self,dataOut):
1051 if len(self.channelList) == 0:
1051 if len(self.channelList) == 0:
1052 self.channelList = dataOut.channelList
1052 self.channelList = dataOut.channelList
1053 if len(self.elevationList) == 0:
1053 if len(self.elevationList) == 0:
1054 self.elevationList = dataOut.elevationList
1054 self.elevationList = dataOut.elevationList
1055 if len(self.azimuthList) == 0:
1055 if len(self.azimuthList) == 0:
1056 self.azimuthList = dataOut.azimuthList
1056 self.azimuthList = dataOut.azimuthList
1057
1057
1058 def update(self, dataOut):
1058 def update(self, dataOut):
1059 if len(self.channelList) == 0:
1059 if len(self.channelList) == 0:
1060 self.update_list(dataOut)
1060 self.update_list(dataOut)
1061
1061
1062 data = {}
1062 data = {}
1063 meta = {}
1063 meta = {}
1064 #print(dataOut.max_nIncohInt, dataOut.nIncohInt)
1064 #print(dataOut.max_nIncohInt, dataOut.nIncohInt)
1065 #print(dataOut.windowOfFilter,dataOut.nCohInt,dataOut.nProfiles,dataOut.max_nIncohInt,dataOut.nIncohInt)
1065 #print(dataOut.windowOfFilter,dataOut.nCohInt,dataOut.nProfiles,dataOut.max_nIncohInt,dataOut.nIncohInt
1066 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1066 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1067 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1067 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1068 data['noise'] = n0
1068 data['noise'] = n0
1069 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1069 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1070 noiseless_data = dataOut.getPower() - noise
1070 noiseless_data = dataOut.getPower() - noise
1071
1071
1072 #print("power, noise:", dataOut.getPower(), n0)
1072 #print("power, noise:", dataOut.getPower(), n0)
1073 #print(noise)
1073 #print(noise)
1074 #print(noiseless_data)
1074 #print(noiseless_data)
1075
1075
1076 data['noiseless_rti'] = noiseless_data
1076 data['noiseless_rti'] = noiseless_data
1077
1077
1078 return data, meta
1078 return data, meta
1079
1079
1080 def plot(self):
1080 def plot(self):
1081 from matplotlib import pyplot as plt
1081 from matplotlib import pyplot as plt
1082 self.x = self.data.times
1082 self.x = self.data.times
1083 self.y = self.data.yrange
1083 self.y = self.data.yrange
1084 self.z = self.data['noiseless_rti']
1084 self.z = self.data['noiseless_rti']
1085 self.z = numpy.array(self.z, dtype=float)
1085 self.z = numpy.array(self.z, dtype=float)
1086 self.z = numpy.ma.masked_invalid(self.z)
1086 self.z = numpy.ma.masked_invalid(self.z)
1087
1087
1088
1088
1089 try:
1089 try:
1090 if self.channelList != None:
1090 if self.channelList != None:
1091 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
1091 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
1092 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
1092 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
1093 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
1093 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
1094 else:
1094 else:
1095 self.titles = ['{} Channel {}'.format(
1095 self.titles = ['{} Channel {}'.format(
1096 self.CODE.upper(), x) for x in self.channelList]
1096 self.CODE.upper(), x) for x in self.channelList]
1097 except:
1097 except:
1098 if self.channelList.any() != None:
1098 if self.channelList.any() != None:
1099 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
1099 if len(self.elevationList) > 0 and len(self.azimuthList) > 0:
1100 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
1100 self.titles = ['{} Channel {} ({:2.1f} Elev, {:2.1f} Azth)'.format(
1101 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
1101 self.CODE.upper(), x, self.elevationList[x], self.azimuthList[x]) for x in self.channelList]
1102 else:
1102 else:
1103 self.titles = ['{} Channel {}'.format(
1103 self.titles = ['{} Channel {}'.format(
1104 self.CODE.upper(), x) for x in self.channelList]
1104 self.CODE.upper(), x) for x in self.channelList]
1105
1105
1106
1106
1107 if self.decimation is None:
1107 if self.decimation is None:
1108 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1108 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1109 else:
1109 else:
1110 x, y, z = self.fill_gaps(*self.decimate())
1110 x, y, z = self.fill_gaps(*self.decimate())
1111
1111
1112 dummy_var = self.axes #Extrañamente esto actualiza el valor axes
1112 dummy_var = self.axes #Extrañamente esto actualiza el valor axes
1113 #print("plot shapes ", z.shape, x.shape, y.shape)
1113 #print("plot shapes ", z.shape, x.shape, y.shape)
1114 #print(self.axes)
1114 #print(self.axes)
1115 for n, ax in enumerate(self.axes):
1115 for n, ax in enumerate(self.axes):
1116
1116
1117
1117
1118 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
1118 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
1119 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
1119 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
1120 data = self.data[-1]
1120 data = self.data[-1]
1121 if ax.firsttime:
1121 if ax.firsttime:
1122 ax.plt = ax.pcolormesh(x, y, z[n].T,
1122 ax.plt = ax.pcolormesh(x, y, z[n].T,
1123 vmin=self.zmin,
1123 vmin=self.zmin,
1124 vmax=self.zmax,
1124 vmax=self.zmax,
1125 cmap=plt.get_cmap(self.colormap)
1125 cmap=plt.get_cmap(self.colormap)
1126 )
1126 )
1127 if self.showprofile:
1127 if self.showprofile:
1128 ax.plot_profile = self.pf_axes[n].plot(data['noiseless_rti'][n], self.y)[0]
1128 ax.plot_profile = self.pf_axes[n].plot(data['noiseless_rti'][n], self.y)[0]
1129
1129
1130 else:
1130 else:
1131 ax.collections.remove(ax.collections[0])
1131 ax.collections.remove(ax.collections[0])
1132 ax.plt = ax.pcolormesh(x, y, z[n].T,
1132 ax.plt = ax.pcolormesh(x, y, z[n].T,
1133 vmin=self.zmin,
1133 vmin=self.zmin,
1134 vmax=self.zmax,
1134 vmax=self.zmax,
1135 cmap=plt.get_cmap(self.colormap)
1135 cmap=plt.get_cmap(self.colormap)
1136 )
1136 )
1137 if self.showprofile:
1137 if self.showprofile:
1138 ax.plot_profile.set_data(data['noiseless_rti'][n], self.y)
1138 ax.plot_profile.set_data(data['noiseless_rti'][n], self.y)
1139 # if "noise" in self.data:
1139 # if "noise" in self.data:
1140 # #ax.plot_noise.set_data(numpy.repeat(data['noise'][n], len(self.y)), self.y)
1140 # #ax.plot_noise.set_data(numpy.repeat(data['noise'][n], len(self.y)), self.y)
1141 # ax.plot_noise.set_data(data['noise'][n], self.y)
1141 # ax.plot_noise.set_data(data['noise'][n], self.y)
1142
1142
1143
1143
1144 class OutliersRTIPlot(Plot):
1144 class OutliersRTIPlot(Plot):
1145 '''
1145 '''
1146 Plot for data_xxxx object
1146 Plot for data_xxxx object
1147 '''
1147 '''
1148
1148
1149 CODE = 'outlier_rtc' # Range Time Counts
1149 CODE = 'outlier_rtc' # Range Time Counts
1150 colormap = 'cool'
1150 colormap = 'cool'
1151 plot_type = 'pcolorbuffer'
1151 plot_type = 'pcolorbuffer'
1152
1152
1153 def setup(self):
1153 def setup(self):
1154 self.xaxis = 'time'
1154 self.xaxis = 'time'
1155 self.ncols = 1
1155 self.ncols = 1
1156 self.nrows = self.data.shape('outlier_rtc')[0]
1156 self.nrows = self.data.shape('outlier_rtc')[0]
1157 self.nplots = self.nrows
1157 self.nplots = self.nrows
1158 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1158 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1159
1159
1160
1160
1161 if not self.xlabel:
1161 if not self.xlabel:
1162 self.xlabel = 'Time'
1162 self.xlabel = 'Time'
1163
1163
1164 self.ylabel = 'Height [km]'
1164 self.ylabel = 'Height [km]'
1165 if not self.titles:
1165 if not self.titles:
1166 self.titles = ['Outliers Ch:{}'.format(x) for x in range(self.nrows)]
1166 self.titles = ['Outliers Ch:{}'.format(x) for x in range(self.nrows)]
1167
1167
1168 def update(self, dataOut):
1168 def update(self, dataOut):
1169
1169
1170 data = {}
1170 data = {}
1171 data['outlier_rtc'] = dataOut.data_outlier
1171 data['outlier_rtc'] = dataOut.data_outlier
1172
1172
1173 meta = {}
1173 meta = {}
1174
1174
1175 return data, meta
1175 return data, meta
1176
1176
1177 def plot(self):
1177 def plot(self):
1178 # self.data.normalize_heights()
1178 # self.data.normalize_heights()
1179 self.x = self.data.times
1179 self.x = self.data.times
1180 self.y = self.data.yrange
1180 self.y = self.data.yrange
1181 self.z = self.data['outlier_rtc']
1181 self.z = self.data['outlier_rtc']
1182
1182
1183 #self.z = numpy.ma.masked_invalid(self.z)
1183 #self.z = numpy.ma.masked_invalid(self.z)
1184
1184
1185 if self.decimation is None:
1185 if self.decimation is None:
1186 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1186 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1187 else:
1187 else:
1188 x, y, z = self.fill_gaps(*self.decimate())
1188 x, y, z = self.fill_gaps(*self.decimate())
1189
1189
1190 for n, ax in enumerate(self.axes):
1190 for n, ax in enumerate(self.axes):
1191
1191
1192 self.zmax = self.zmax if self.zmax is not None else numpy.max(
1192 self.zmax = self.zmax if self.zmax is not None else numpy.max(
1193 self.z[n])
1193 self.z[n])
1194 self.zmin = self.zmin if self.zmin is not None else numpy.min(
1194 self.zmin = self.zmin if self.zmin is not None else numpy.min(
1195 self.z[n])
1195 self.z[n])
1196 data = self.data[-1]
1196 data = self.data[-1]
1197 if ax.firsttime:
1197 if ax.firsttime:
1198 if self.zlimits is not None:
1198 if self.zlimits is not None:
1199 self.zmin, self.zmax = self.zlimits[n]
1199 self.zmin, self.zmax = self.zlimits[n]
1200
1200
1201 ax.plt = ax.pcolormesh(x, y, z[n].T,
1201 ax.plt = ax.pcolormesh(x, y, z[n].T,
1202 vmin=self.zmin,
1202 vmin=self.zmin,
1203 vmax=self.zmax,
1203 vmax=self.zmax,
1204 cmap=self.cmaps[n]
1204 cmap=self.cmaps[n]
1205 )
1205 )
1206 if self.showprofile:
1206 if self.showprofile:
1207 ax.plot_profile = self.pf_axes[n].plot(data['outlier_rtc'][n], self.y)[0]
1207 ax.plot_profile = self.pf_axes[n].plot(data['outlier_rtc'][n], self.y)[0]
1208 self.pf_axes[n].set_xlabel('')
1208 self.pf_axes[n].set_xlabel('')
1209 else:
1209 else:
1210 if self.zlimits is not None:
1210 if self.zlimits is not None:
1211 self.zmin, self.zmax = self.zlimits[n]
1211 self.zmin, self.zmax = self.zlimits[n]
1212 ax.collections.remove(ax.collections[0])
1212 ax.collections.remove(ax.collections[0])
1213 ax.plt = ax.pcolormesh(x, y, z[n].T ,
1213 ax.plt = ax.pcolormesh(x, y, z[n].T ,
1214 vmin=self.zmin,
1214 vmin=self.zmin,
1215 vmax=self.zmax,
1215 vmax=self.zmax,
1216 cmap=self.cmaps[n]
1216 cmap=self.cmaps[n]
1217 )
1217 )
1218 if self.showprofile:
1218 if self.showprofile:
1219 ax.plot_profile.set_data(data['outlier_rtc'][n], self.y)
1219 ax.plot_profile.set_data(data['outlier_rtc'][n], self.y)
1220 self.pf_axes[n].set_xlabel('')
1220 self.pf_axes[n].set_xlabel('')
1221
1221
1222 class NIncohIntRTIPlot(Plot):
1222 class NIncohIntRTIPlot(Plot):
1223 '''
1223 '''
1224 Plot for data_xxxx object
1224 Plot for data_xxxx object
1225 '''
1225 '''
1226
1226
1227 CODE = 'integrations_rtc' # Range Time Counts
1227 CODE = 'integrations_rtc' # Range Time Counts
1228 colormap = 'BuGn'
1228 colormap = 'BuGn'
1229 plot_type = 'pcolorbuffer'
1229 plot_type = 'pcolorbuffer'
1230
1230
1231 def setup(self):
1231 def setup(self):
1232 self.xaxis = 'time'
1232 self.xaxis = 'time'
1233 self.ncols = 1
1233 self.ncols = 1
1234 self.nrows = self.data.shape('integrations_rtc')[0]
1234 self.nrows = self.data.shape('integrations_rtc')[0]
1235 self.nplots = self.nrows
1235 self.nplots = self.nrows
1236 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1236 self.plots_adjust.update({'hspace':0.8, 'left': 0.08, 'bottom': 0.2, 'right':0.94})
1237
1237
1238
1238
1239 if not self.xlabel:
1239 if not self.xlabel:
1240 self.xlabel = 'Time'
1240 self.xlabel = 'Time'
1241
1241
1242 self.ylabel = 'Height [km]'
1242 self.ylabel = 'Height [km]'
1243 if not self.titles:
1243 if not self.titles:
1244 self.titles = ['Integration Ch:{}'.format(x) for x in range(self.nrows)]
1244 self.titles = ['Integration Ch:{}'.format(x) for x in range(self.nrows)]
1245
1245
1246 def update(self, dataOut):
1246 def update(self, dataOut):
1247
1247
1248 data = {}
1248 data = {}
1249 data['integrations_rtc'] = dataOut.nIncohInt
1249 data['integrations_rtc'] = dataOut.nIncohInt
1250
1250
1251 meta = {}
1251 meta = {}
1252
1252
1253 return data, meta
1253 return data, meta
1254
1254
1255 def plot(self):
1255 def plot(self):
1256 # self.data.normalize_heights()
1256 # self.data.normalize_heights()
1257 self.x = self.data.times
1257 self.x = self.data.times
1258 self.y = self.data.yrange
1258 self.y = self.data.yrange
1259 self.z = self.data['integrations_rtc']
1259 self.z = self.data['integrations_rtc']
1260
1260
1261 #self.z = numpy.ma.masked_invalid(self.z)
1261 #self.z = numpy.ma.masked_invalid(self.z)
1262
1262
1263 if self.decimation is None:
1263 if self.decimation is None:
1264 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1264 x, y, z = self.fill_gaps(self.x, self.y, self.z)
1265 else:
1265 else:
1266 x, y, z = self.fill_gaps(*self.decimate())
1266 x, y, z = self.fill_gaps(*self.decimate())
1267
1267
1268 for n, ax in enumerate(self.axes):
1268 for n, ax in enumerate(self.axes):
1269
1269
1270 self.zmax = self.zmax if self.zmax is not None else numpy.max(
1270 self.zmax = self.zmax if self.zmax is not None else numpy.max(
1271 self.z[n])
1271 self.z[n])
1272 self.zmin = self.zmin if self.zmin is not None else numpy.min(
1272 self.zmin = self.zmin if self.zmin is not None else numpy.min(
1273 self.z[n])
1273 self.z[n])
1274 data = self.data[-1]
1274 data = self.data[-1]
1275 if ax.firsttime:
1275 if ax.firsttime:
1276 if self.zlimits is not None:
1276 if self.zlimits is not None:
1277 self.zmin, self.zmax = self.zlimits[n]
1277 self.zmin, self.zmax = self.zlimits[n]
1278
1278
1279 ax.plt = ax.pcolormesh(x, y, z[n].T,
1279 ax.plt = ax.pcolormesh(x, y, z[n].T,
1280 vmin=self.zmin,
1280 vmin=self.zmin,
1281 vmax=self.zmax,
1281 vmax=self.zmax,
1282 cmap=self.cmaps[n]
1282 cmap=self.cmaps[n]
1283 )
1283 )
1284 if self.showprofile:
1284 if self.showprofile:
1285 ax.plot_profile = self.pf_axes[n].plot(data['integrations_rtc'][n], self.y)[0]
1285 ax.plot_profile = self.pf_axes[n].plot(data['integrations_rtc'][n], self.y)[0]
1286 self.pf_axes[n].set_xlabel('')
1286 self.pf_axes[n].set_xlabel('')
1287 else:
1287 else:
1288 if self.zlimits is not None:
1288 if self.zlimits is not None:
1289 self.zmin, self.zmax = self.zlimits[n]
1289 self.zmin, self.zmax = self.zlimits[n]
1290 ax.collections.remove(ax.collections[0])
1290 ax.collections.remove(ax.collections[0])
1291 ax.plt = ax.pcolormesh(x, y, z[n].T ,
1291 ax.plt = ax.pcolormesh(x, y, z[n].T ,
1292 vmin=self.zmin,
1292 vmin=self.zmin,
1293 vmax=self.zmax,
1293 vmax=self.zmax,
1294 cmap=self.cmaps[n]
1294 cmap=self.cmaps[n]
1295 )
1295 )
1296 if self.showprofile:
1296 if self.showprofile:
1297 ax.plot_profile.set_data(data['integrations_rtc'][n], self.y)
1297 ax.plot_profile.set_data(data['integrations_rtc'][n], self.y)
1298 self.pf_axes[n].set_xlabel('')
1298 self.pf_axes[n].set_xlabel('')
1299
1299
1300
1300
1301 import datetime
1301 import datetime
1302 class NoiselessRTILinePlot(Plot):
1302 class NoiselessRTILinePlot(Plot):
1303 '''
1303 '''
1304 Plot for RTI data
1304 Plot for RTI data
1305 '''
1305 '''
1306
1306
1307 CODE = 'noiseless_rtiLine'
1307 CODE = 'noiseless_rtiLine'
1308
1308
1309 plot_type = 'scatter'
1309 plot_type = 'scatter'
1310 titles = None
1310 titles = None
1311 channelList = []
1311 channelList = []
1312 elevationList = []
1312 elevationList = []
1313 azimuthList = []
1313 azimuthList = []
1314 last_noise = None
1314 last_noise = None
1315
1315
1316 def setup(self):
1316 def setup(self):
1317 self.xaxis = 'Range (Km)'
1317 self.xaxis = 'Range (Km)'
1318 self.nplots = len(self.data.channels)
1318 self.nplots = len(self.data.channels)
1319 self.nrows = int(numpy.ceil(self.nplots/2))
1319 self.nrows = int(numpy.ceil(self.nplots/2))
1320 self.ncols = int(numpy.ceil(self.nplots/self.nrows))
1320 self.ncols = int(numpy.ceil(self.nplots/self.nrows))
1321 self.ylabel = 'Intensity [dB]'
1321 self.ylabel = 'Intensity [dB]'
1322 self.titles = ['Channel '+str(self.data.channels[i])+" " for i in self.data.channels]
1322 self.titles = ['Channel '+str(self.data.channels[i])+" " for i in self.data.channels]
1323 self.colorbar = False
1323 self.colorbar = False
1324 self.width = 6
1324 self.width = 6
1325 self.height = 4
1325 self.height = 4
1326
1326
1327 def update_list(self,dataOut):
1327 def update_list(self,dataOut):
1328 if len(self.channelList) == 0:
1328 if len(self.channelList) == 0:
1329 self.channelList = dataOut.channelList
1329 self.channelList = dataOut.channelList
1330 if len(self.elevationList) == 0:
1330 if len(self.elevationList) == 0:
1331 self.elevationList = dataOut.elevationList
1331 self.elevationList = dataOut.elevationList
1332 if len(self.azimuthList) == 0:
1332 if len(self.azimuthList) == 0:
1333 self.azimuthList = dataOut.azimuthList
1333 self.azimuthList = dataOut.azimuthList
1334
1334
1335 def update(self, dataOut):
1335 def update(self, dataOut):
1336 if len(self.channelList) == 0:
1336 if len(self.channelList) == 0:
1337 self.update_list(dataOut)
1337 self.update_list(dataOut)
1338
1338
1339 data = {}
1339 data = {}
1340 meta = {}
1340 meta = {}
1341 #print(dataOut.max_nIncohInt, dataOut.nIncohInt)
1341 #print(dataOut.max_nIncohInt, dataOut.nIncohInt)
1342 #print(dataOut.windowOfFilter,dataOut.nCohInt,dataOut.nProfiles,dataOut.max_nIncohInt,dataOut.nIncohInt)
1342 #print(dataOut.windowOfFilter,dataOut.nCohInt,dataOut.nProfiles,dataOut.max_nIncohInt,dataOut.nIncohInt)
1343 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1343 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1344
1344
1345
1346 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1345 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1347 data['noise'] = n0
1346 data['noise'] = n0
1348
1347
1349 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1348 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1350 noiseless_data = dataOut.getPower() - noise
1349 noiseless_data = dataOut.getPower() - noise
1351
1350
1352 #print("power, noise:", dataOut.getPower(), n0)
1351 #print("power, noise:", dataOut.getPower(), n0)
1353 #print(noise)
1352 #print(noise)
1354 #print(noiseless_data)
1353 #print(noiseless_data)
1355
1354
1356 data['noiseless_rtiLine'] = noiseless_data
1355 data['noiseless_rtiLine'] = noiseless_data
1357
1356
1358 print(noiseless_data.shape, self.name)
1357 #print(noiseless_data.shape, self.name)
1359 data['time'] = dataOut.utctime
1358 data['time'] = dataOut.utctime
1360
1359
1361 return data, meta
1360 return data, meta
1362
1361
1363 def plot(self):
1362 def plot(self):
1364
1363
1365 self.x = self.data.times
1364 self.x = self.data.times
1366 self.y = self.data.yrange
1365 self.y = self.data.yrange
1367 print(self.data['noiseless_rtiLine'].shape, self.y.shape, self.name)
1366 #print(self.data['noiseless_rtiLine'].shape, self.y.shape, self.name)
1368 #ts = self.data['time'][0].squeeze()
1367 #ts = self.data['time'][0].squeeze()
1369 if len(self.data['noiseless_rtiLine'])>2 :
1368 if len(self.data['noiseless_rtiLine'])>2 :
1370 self.z = self.data['noiseless_rtiLine'][:, -1,:]
1369 self.z = self.data['noiseless_rtiLine'][:, -1,:]
1371 else:
1370 else:
1372 self.z = self.data['noiseless_rtiLine']
1371 self.z = self.data['noiseless_rtiLine']
1373 #print(self.z.shape, self.y.shape, ts)
1372 #print(self.z.shape, self.y.shape, ts)
1374 #thisDatetime = datetime.datetime.utcfromtimestamp(ts)
1373 #thisDatetime = datetime.datetime.utcfromtimestamp(ts)
1375
1374
1376 for i,ax in enumerate(self.axes):
1375 for i,ax in enumerate(self.axes):
1377 #self.titles[i] = "Channel {} {}".format(i, thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1376 #self.titles[i] = "Channel {} {}".format(i, thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1378
1377
1379
1378
1380 if ax.firsttime:
1379 if ax.firsttime:
1381 #self.xmin = min(self.z)
1380 #self.xmin = min(self.z)
1382 #self.xmax = max(self.z)
1381 #self.xmax = max(self.z)
1383 ax.plt_r = ax.plot(self.z[i], self.y)[0]
1382 ax.plt_r = ax.plot(self.z[i], self.y)[0]
1384 else:
1383 else:
1385 ax.plt_r.set_data(self.z[i], self.y)
1384 ax.plt_r.set_data(self.z[i], self.y)
1386
1385
1387
1386
1388
1387
1389 class GeneralProfilePlot(Plot):
1388 class GeneralProfilePlot(Plot):
1390 '''
1389 '''
1391 Plot for RTI data
1390 Plot for RTI data
1392 '''
1391 '''
1393
1392
1394 CODE = 'general_profilePlot'
1393 CODE = 'general_profilePlot'
1395
1394
1396 plot_type = 'scatter'
1395 plot_type = 'scatter'
1397 titles = None
1396 titles = None
1398 channelList = []
1397 channelList = []
1399 elevationList = []
1398 elevationList = []
1400 azimuthList = []
1399 azimuthList = []
1401 last_noise = None
1400 last_noise = None
1402
1401
1403 def setup(self):
1402 def setup(self):
1404 self.xaxis = 'Range (Km)'
1403 self.xaxis = 'Range (Km)'
1405 self.nplots = len(self.data.channels)
1404 self.nplots = len(self.data.channels)
1406 self.nrows = int(numpy.ceil(self.nplots/2))
1405 self.nrows = int(numpy.ceil(self.nplots/2))
1407 self.ncols = int(numpy.ceil(self.nplots/self.nrows))
1406 self.ncols = int(numpy.ceil(self.nplots/self.nrows))
1408 self.ylabel = 'Intensity [dB]'
1407 self.ylabel = 'Intensity [dB]'
1409 self.titles = ['Channel '+str(self.data.channels[i])+" " for i in self.data.channels]
1408 self.titles = ['Channel '+str(self.data.channels[i])+" " for i in self.data.channels]
1410 self.colorbar = False
1409 self.colorbar = False
1411 self.width = 6
1410 self.width = 6
1412 self.height = 4
1411 self.height = 4
1413
1412
1414 def update_list(self,dataOut):
1413 def update_list(self,dataOut):
1415 if len(self.channelList) == 0:
1414 if len(self.channelList) == 0:
1416 self.channelList = dataOut.channelList
1415 self.channelList = dataOut.channelList
1417 if len(self.elevationList) == 0:
1416 if len(self.elevationList) == 0:
1418 self.elevationList = dataOut.elevationList
1417 self.elevationList = dataOut.elevationList
1419 if len(self.azimuthList) == 0:
1418 if len(self.azimuthList) == 0:
1420 self.azimuthList = dataOut.azimuthList
1419 self.azimuthList = dataOut.azimuthList
1421
1420
1422 def update(self, dataOut):
1421 def update(self, dataOut):
1423 if len(self.channelList) == 0:
1422 if len(self.channelList) == 0:
1424 self.update_list(dataOut)
1423 self.update_list(dataOut)
1425
1424
1426 data = {}
1425 data = {}
1427 meta = {}
1426 meta = {}
1428
1427
1429 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1428 norm = dataOut.nProfiles * dataOut.max_nIncohInt * dataOut.nCohInt * dataOut.windowOfFilter
1430 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1429 n0 = 10*numpy.log10(dataOut.getNoise()/norm)
1431 data['noise'] = n0
1430 data['noise'] = n0
1432
1431
1433 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1432 noise = numpy.repeat(n0,dataOut.nHeights).reshape(dataOut.nChannels,dataOut.nHeights)
1434 noiseless_data = dataOut.getPower() - noise
1433 noiseless_data = dataOut.getPower() - noise
1435
1434
1436 data['noiseless_rtiLine'] = noiseless_data
1435 data['noiseless_rtiLine'] = noiseless_data
1437
1436
1438 print(noiseless_data.shape, self.name)
1437 #print(noiseless_data.shape, self.name)
1439 data['time'] = dataOut.utctime
1438 data['time'] = dataOut.utctime
1440
1439
1441 return data, meta
1440 return data, meta
1442
1441
1443 def plot(self):
1442 def plot(self):
1444
1443
1445 self.x = self.data.times
1444 self.x = self.data.times
1446 self.y = self.data.yrange
1445 self.y = self.data.yrange
1447 print(self.data['noiseless_rtiLine'].shape, self.y.shape, self.name)
1446 #print(self.data['noiseless_rtiLine'].shape, self.y.shape, self.name)
1448 #ts = self.data['time'][0].squeeze()
1447 #ts = self.data['time'][0].squeeze()
1449 if len(self.data['noiseless_rtiLine'])>2 :
1448 if len(self.data['noiseless_rtiLine'])>2 :
1450 self.z = self.data['noiseless_rtiLine'][:, -1,:]
1449 self.z = self.data['noiseless_rtiLine'][:, -1,:]
1451 else:
1450 else:
1452 self.z = self.data['noiseless_rtiLine']
1451 self.z = self.data['noiseless_rtiLine']
1453 #print(self.z.shape, self.y.shape, ts)
1452 #print(self.z.shape, self.y.shape, ts)
1454 #thisDatetime = datetime.datetime.utcfromtimestamp(ts)
1453 #thisDatetime = datetime.datetime.utcfromtimestamp(ts)
1455
1454
1456 for i,ax in enumerate(self.axes):
1455 for i,ax in enumerate(self.axes):
1457 #self.titles[i] = "Channel {} {}".format(i, thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1456 #self.titles[i] = "Channel {} {}".format(i, thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1458
1457
1459
1458
1460 if ax.firsttime:
1459 if ax.firsttime:
1461 #self.xmin = min(self.z)
1460 #self.xmin = min(self.z)
1462 #self.xmax = max(self.z)
1461 #self.xmax = max(self.z)
1463 ax.plt_r = ax.plot(self.z[i], self.y)[0]
1462 ax.plt_r = ax.plot(self.z[i], self.y)[0]
1464 else:
1463 else:
1465 ax.plt_r.set_data(self.z[i], self.y) No newline at end of file
1464 ax.plt_r.set_data(self.z[i], self.y)
@@ -1,2287 +1,2290
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.model.data import _noise
20 from schainpy.model.data import _noise
21
21
22 from schainpy.utils import log
22 from schainpy.utils import log
23 import matplotlib.pyplot as plt
23 import matplotlib.pyplot as plt
24 #from scipy.optimize import curve_fit
24 #from scipy.optimize import curve_fit
25 from schainpy.model.io.utilsIO import getHei_index
25 from schainpy.model.io.utilsIO import getHei_index
26 import datetime
26 import datetime
27
27
28 class SpectraProc(ProcessingUnit):
28 class SpectraProc(ProcessingUnit):
29
29
30 def __init__(self):
30 def __init__(self):
31
31
32 ProcessingUnit.__init__(self)
32 ProcessingUnit.__init__(self)
33
33
34 self.buffer = None
34 self.buffer = None
35 self.firstdatatime = None
35 self.firstdatatime = None
36 self.profIndex = 0
36 self.profIndex = 0
37 self.dataOut = Spectra()
37 self.dataOut = Spectra()
38 self.id_min = None
38 self.id_min = None
39 self.id_max = None
39 self.id_max = None
40 self.setupReq = False #Agregar a todas las unidades de proc
40 self.setupReq = False #Agregar a todas las unidades de proc
41 self.nsamplesFFT = 0
41 self.nsamplesFFT = 0
42
42
43 def __updateSpecFromVoltage(self):
43 def __updateSpecFromVoltage(self):
44
44
45
45
46
46
47 self.dataOut.timeZone = self.dataIn.timeZone
47 self.dataOut.timeZone = self.dataIn.timeZone
48 self.dataOut.dstFlag = self.dataIn.dstFlag
48 self.dataOut.dstFlag = self.dataIn.dstFlag
49 self.dataOut.errorCount = self.dataIn.errorCount
49 self.dataOut.errorCount = self.dataIn.errorCount
50 self.dataOut.useLocalTime = self.dataIn.useLocalTime
50 self.dataOut.useLocalTime = self.dataIn.useLocalTime
51
51
52 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
52 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
53 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
53 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
54 self.dataOut.ippSeconds = self.dataIn.ippSeconds
54 self.dataOut.ippSeconds = self.dataIn.ippSeconds
55 self.dataOut.ipp = self.dataIn.ipp
55 self.dataOut.ipp = self.dataIn.ipp
56 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
56 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
57 self.dataOut.channelList = self.dataIn.channelList
57 self.dataOut.channelList = self.dataIn.channelList
58 self.dataOut.heightList = self.dataIn.heightList
58 self.dataOut.heightList = self.dataIn.heightList
59 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
59 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
60 self.dataOut.nProfiles = self.dataOut.nFFTPoints
60 self.dataOut.nProfiles = self.dataOut.nFFTPoints
61 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
61 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
62 self.dataOut.utctime = self.firstdatatime
62 self.dataOut.utctime = self.firstdatatime
63 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
63 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
64 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
64 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
65 self.dataOut.flagShiftFFT = False
65 self.dataOut.flagShiftFFT = False
66 self.dataOut.nCohInt = self.dataIn.nCohInt
66 self.dataOut.nCohInt = self.dataIn.nCohInt
67 self.dataOut.nIncohInt = 1
67 self.dataOut.nIncohInt = 1
68 self.dataOut.deltaHeight = self.dataIn.deltaHeight
68 self.dataOut.deltaHeight = self.dataIn.deltaHeight
69 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
69 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
70 self.dataOut.frequency = self.dataIn.frequency
70 self.dataOut.frequency = self.dataIn.frequency
71 self.dataOut.realtime = self.dataIn.realtime
71 self.dataOut.realtime = self.dataIn.realtime
72 self.dataOut.azimuth = self.dataIn.azimuth
72 self.dataOut.azimuth = self.dataIn.azimuth
73 self.dataOut.zenith = self.dataIn.zenith
73 self.dataOut.zenith = self.dataIn.zenith
74 self.dataOut.codeList = self.dataIn.codeList
74 self.dataOut.codeList = self.dataIn.codeList
75 self.dataOut.azimuthList = self.dataIn.azimuthList
75 self.dataOut.azimuthList = self.dataIn.azimuthList
76 self.dataOut.elevationList = self.dataIn.elevationList
76 self.dataOut.elevationList = self.dataIn.elevationList
77 self.dataOut.code = self.dataIn.code
77 self.dataOut.code = self.dataIn.code
78 self.dataOut.nCode = self.dataIn.nCode
78 self.dataOut.nCode = self.dataIn.nCode
79 self.dataOut.flagProfilesByRange = self.dataIn.flagProfilesByRange
79 self.dataOut.flagProfilesByRange = self.dataIn.flagProfilesByRange
80 self.dataOut.nProfilesByRange = self.dataIn.nProfilesByRange
80 self.dataOut.nProfilesByRange = self.dataIn.nProfilesByRange
81
81
82
82
83 def __getFft(self):
83 def __getFft(self):
84 # print("fft donw")
84 # print("fft donw")
85 """
85 """
86 Convierte valores de Voltaje a Spectra
86 Convierte valores de Voltaje a Spectra
87
87
88 Affected:
88 Affected:
89 self.dataOut.data_spc
89 self.dataOut.data_spc
90 self.dataOut.data_cspc
90 self.dataOut.data_cspc
91 self.dataOut.data_dc
91 self.dataOut.data_dc
92 self.dataOut.heightList
92 self.dataOut.heightList
93 self.profIndex
93 self.profIndex
94 self.buffer
94 self.buffer
95 self.dataOut.flagNoData
95 self.dataOut.flagNoData
96 """
96 """
97 fft_volt = numpy.fft.fft(
97 fft_volt = numpy.fft.fft(
98 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
98 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
99 fft_volt = fft_volt.astype(numpy.dtype('complex'))
99 fft_volt = fft_volt.astype(numpy.dtype('complex'))
100 dc = fft_volt[:, 0, :]
100 dc = fft_volt[:, 0, :]
101
101
102 # calculo de self-spectra
102 # calculo de self-spectra
103 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
103 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
104 spc = fft_volt * numpy.conjugate(fft_volt)
104 spc = fft_volt * numpy.conjugate(fft_volt)
105 spc = spc.real
105 spc = spc.real
106
106
107 blocksize = 0
107 blocksize = 0
108 blocksize += dc.size
108 blocksize += dc.size
109 blocksize += spc.size
109 blocksize += spc.size
110
110
111 cspc = None
111 cspc = None
112 pairIndex = 0
112 pairIndex = 0
113 if self.dataOut.pairsList != None:
113 if self.dataOut.pairsList != None:
114 # calculo de cross-spectra
114 # calculo de cross-spectra
115 cspc = numpy.zeros(
115 cspc = numpy.zeros(
116 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
116 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
117 for pair in self.dataOut.pairsList:
117 for pair in self.dataOut.pairsList:
118 if pair[0] not in self.dataOut.channelList:
118 if pair[0] not in self.dataOut.channelList:
119 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
119 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
120 str(pair), str(self.dataOut.channelList)))
120 str(pair), str(self.dataOut.channelList)))
121 if pair[1] not in self.dataOut.channelList:
121 if pair[1] not in self.dataOut.channelList:
122 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
122 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
123 str(pair), str(self.dataOut.channelList)))
123 str(pair), str(self.dataOut.channelList)))
124
124
125 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
125 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
126 numpy.conjugate(fft_volt[pair[1], :, :])
126 numpy.conjugate(fft_volt[pair[1], :, :])
127 pairIndex += 1
127 pairIndex += 1
128 blocksize += cspc.size
128 blocksize += cspc.size
129
129
130 self.dataOut.data_spc = spc
130 self.dataOut.data_spc = spc
131 self.dataOut.data_cspc = cspc
131 self.dataOut.data_cspc = cspc
132 self.dataOut.data_dc = dc
132 self.dataOut.data_dc = dc
133 self.dataOut.blockSize = blocksize
133 self.dataOut.blockSize = blocksize
134 self.dataOut.flagShiftFFT = False
134 self.dataOut.flagShiftFFT = False
135
135
136 def run(self, nProfiles=None, nFFTPoints=None, pairsList=None, ippFactor=None, shift_fft=False, zeroPad=False):
136 def run(self, nProfiles=None, nFFTPoints=None, pairsList=None, ippFactor=None, shift_fft=False, zeroPad=False):
137
137
138
138
139 try:
139 try:
140 type = self.dataIn.type.decode("utf-8")
140 type = self.dataIn.type.decode("utf-8")
141 self.dataIn.type = type
141 self.dataIn.type = type
142 except:
142 except:
143 pass
143 pass
144 if self.dataIn.type == "Spectra":
144 if self.dataIn.type == "Spectra":
145
145
146 try:
146 try:
147 self.dataOut.copy(self.dataIn)
147 self.dataOut.copy(self.dataIn)
148 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
148 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
149 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
149 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
150 self.dataOut.nProfiles = self.dataOut.nFFTPoints
150 self.dataOut.nProfiles = self.dataOut.nFFTPoints
151 #self.dataOut.nHeights = len(self.dataOut.heightList)
151 #self.dataOut.nHeights = len(self.dataOut.heightList)
152 except Exception as e:
152 except Exception as e:
153 print("Error dataIn ",e)
153 print("Error dataIn ",e)
154
154
155
155
156
156
157 if shift_fft:
157 if shift_fft:
158 #desplaza a la derecha en el eje 2 determinadas posiciones
158 #desplaza a la derecha en el eje 2 determinadas posiciones
159 shift = int(self.dataOut.nFFTPoints/2)
159 shift = int(self.dataOut.nFFTPoints/2)
160 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
160 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
161
161
162 if self.dataOut.data_cspc is not None:
162 if self.dataOut.data_cspc is not None:
163 #desplaza a la derecha en el eje 2 determinadas posiciones
163 #desplaza a la derecha en el eje 2 determinadas posiciones
164 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
164 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
165 if pairsList:
165 if pairsList:
166 self.__selectPairs(pairsList)
166 self.__selectPairs(pairsList)
167
167
168
168
169 elif self.dataIn.type == "Voltage":
169 elif self.dataIn.type == "Voltage":
170
170
171 self.dataOut.flagNoData = True
171 self.dataOut.flagNoData = True
172 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
172 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
173 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
173 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
174 if nFFTPoints == None:
174 if nFFTPoints == None:
175 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
175 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
176
176
177 if nProfiles == None:
177 if nProfiles == None:
178 nProfiles = nFFTPoints
178 nProfiles = nFFTPoints
179
179
180 if ippFactor == None:
180 if ippFactor == None:
181 self.dataOut.ippFactor = 1
181 self.dataOut.ippFactor = 1
182
182
183 self.dataOut.nFFTPoints = nFFTPoints
183 self.dataOut.nFFTPoints = nFFTPoints
184 #print(" volts ch,prof, h: ", self.dataIn.data.shape)
184 #print(" volts ch,prof, h: ", self.dataIn.data.shape)
185 if self.buffer is None:
185 if self.buffer is None:
186 if not zeroPad:
186 if not zeroPad:
187 self.buffer = numpy.zeros((self.dataIn.nChannels,
187 self.buffer = numpy.zeros((self.dataIn.nChannels,
188 nProfiles,
188 nProfiles,
189 self.dataIn.nHeights),
189 self.dataIn.nHeights),
190 dtype='complex')
190 dtype='complex')
191 else:
191 else:
192 self.buffer = numpy.zeros((self.dataIn.nChannels,
192 self.buffer = numpy.zeros((self.dataIn.nChannels,
193 nFFTPoints,
193 nFFTPoints,
194 self.dataIn.nHeights),
194 self.dataIn.nHeights),
195 dtype='complex')
195 dtype='complex')
196
196
197 if self.dataIn.flagDataAsBlock:
197 if self.dataIn.flagDataAsBlock:
198 nVoltProfiles = self.dataIn.data.shape[1]
198 nVoltProfiles = self.dataIn.data.shape[1]
199
199
200 if nVoltProfiles == nProfiles or zeroPad:
200 if nVoltProfiles == nProfiles or zeroPad:
201 self.buffer = self.dataIn.data.copy()
201 self.buffer = self.dataIn.data.copy()
202 self.profIndex = nVoltProfiles
202 self.profIndex = nVoltProfiles
203
203
204 elif nVoltProfiles < nProfiles:
204 elif nVoltProfiles < nProfiles:
205
205
206 if self.profIndex == 0:
206 if self.profIndex == 0:
207 self.id_min = 0
207 self.id_min = 0
208 self.id_max = nVoltProfiles
208 self.id_max = nVoltProfiles
209
209
210 self.buffer[:, self.id_min:self.id_max,
210 self.buffer[:, self.id_min:self.id_max,
211 :] = self.dataIn.data
211 :] = self.dataIn.data
212 self.profIndex += nVoltProfiles
212 self.profIndex += nVoltProfiles
213 self.id_min += nVoltProfiles
213 self.id_min += nVoltProfiles
214 self.id_max += nVoltProfiles
214 self.id_max += nVoltProfiles
215 else:
215 else:
216 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
216 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
217 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
217 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
218 self.dataOut.flagNoData = True
218 self.dataOut.flagNoData = True
219 else:
219 else:
220 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
220 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
221 self.profIndex += 1
221 self.profIndex += 1
222
222
223 if self.firstdatatime == None:
223 if self.firstdatatime == None:
224 self.firstdatatime = self.dataIn.utctime
224 self.firstdatatime = self.dataIn.utctime
225
225
226 if self.profIndex == nProfiles or zeroPad:
226 if self.profIndex == nProfiles or zeroPad:
227
227
228 self.__updateSpecFromVoltage()
228 self.__updateSpecFromVoltage()
229
229
230 if pairsList == None:
230 if pairsList == None:
231 self.dataOut.pairsList = [pair for pair in itertools.combinations(self.dataOut.channelList, 2)]
231 self.dataOut.pairsList = [pair for pair in itertools.combinations(self.dataOut.channelList, 2)]
232 else:
232 else:
233 self.dataOut.pairsList = pairsList
233 self.dataOut.pairsList = pairsList
234 self.__getFft()
234 self.__getFft()
235 self.dataOut.flagNoData = False
235 self.dataOut.flagNoData = False
236 self.firstdatatime = None
236 self.firstdatatime = None
237 self.nsamplesFFT = self.profIndex
237 self.nsamplesFFT = self.profIndex
238 self.profIndex = 0
238 self.profIndex = 0
239
239
240 #update Processing Header:
240 #update Processing Header:
241 self.dataOut.processingHeaderObj.dtype = "Spectra"
241 self.dataOut.processingHeaderObj.dtype = "Spectra"
242 self.dataOut.processingHeaderObj.nFFTPoints = self.dataOut.nFFTPoints
242 self.dataOut.processingHeaderObj.nFFTPoints = self.dataOut.nFFTPoints
243 self.dataOut.processingHeaderObj.nSamplesFFT = self.nsamplesFFT
243 self.dataOut.processingHeaderObj.nSamplesFFT = self.nsamplesFFT
244 self.dataOut.processingHeaderObj.nIncohInt = 1
244 self.dataOut.processingHeaderObj.nIncohInt = 1
245
245
246
246
247 elif self.dataIn.type == "Parameters":
247 elif self.dataIn.type == "Parameters":
248
248
249 self.dataOut.data_spc = self.dataIn.data_spc
249 self.dataOut.data_spc = self.dataIn.data_spc
250 self.dataOut.data_cspc = self.dataIn.data_cspc
250 self.dataOut.data_cspc = self.dataIn.data_cspc
251 self.dataOut.data_outlier = self.dataIn.data_outlier
251 self.dataOut.data_outlier = self.dataIn.data_outlier
252 self.dataOut.nProfiles = self.dataIn.nProfiles
252 self.dataOut.nProfiles = self.dataIn.nProfiles
253 self.dataOut.nIncohInt = self.dataIn.nIncohInt
253 self.dataOut.nIncohInt = self.dataIn.nIncohInt
254 self.dataOut.nFFTPoints = self.dataIn.nFFTPoints
254 self.dataOut.nFFTPoints = self.dataIn.nFFTPoints
255 self.dataOut.ippFactor = self.dataIn.ippFactor
255 self.dataOut.ippFactor = self.dataIn.ippFactor
256 self.dataOut.max_nIncohInt = self.dataIn.max_nIncohInt
256 self.dataOut.max_nIncohInt = self.dataIn.max_nIncohInt
257 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
257 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
258 self.dataOut.ProcessingHeader = self.dataIn.ProcessingHeader.copy()
258 self.dataOut.ProcessingHeader = self.dataIn.ProcessingHeader.copy()
259 self.dataOut.ippSeconds = self.dataIn.ippSeconds
259 self.dataOut.ippSeconds = self.dataIn.ippSeconds
260 self.dataOut.ipp = self.dataIn.ipp
260 self.dataOut.ipp = self.dataIn.ipp
261 #self.dataOut.abscissaList = self.dataIn.getVelRange(1)
261 #self.dataOut.abscissaList = self.dataIn.getVelRange(1)
262 #self.dataOut.spc_noise = self.dataIn.getNoise()
262 #self.dataOut.spc_noise = self.dataIn.getNoise()
263 #self.dataOut.spc_range = (self.dataIn.getFreqRange(1) , self.dataIn.getAcfRange(1) , self.dataIn.getVelRange(1))
263 #self.dataOut.spc_range = (self.dataIn.getFreqRange(1) , self.dataIn.getAcfRange(1) , self.dataIn.getVelRange(1))
264 # self.dataOut.normFactor = self.dataIn.normFactor
264 # self.dataOut.normFactor = self.dataIn.normFactor
265 if hasattr(self.dataIn, 'channelList'):
265 if hasattr(self.dataIn, 'channelList'):
266 self.dataOut.channelList = self.dataIn.channelList
266 self.dataOut.channelList = self.dataIn.channelList
267 if hasattr(self.dataIn, 'pairsList'):
267 if hasattr(self.dataIn, 'pairsList'):
268 self.dataOut.pairsList = self.dataIn.pairsList
268 self.dataOut.pairsList = self.dataIn.pairsList
269 self.dataOut.groupList = self.dataIn.pairsList
269 self.dataOut.groupList = self.dataIn.pairsList
270
270
271 self.dataOut.flagNoData = False
271 self.dataOut.flagNoData = False
272
272
273 if hasattr(self.dataIn, 'ChanDist'): #Distances of receiver channels
273 if hasattr(self.dataIn, 'ChanDist'): #Distances of receiver channels
274 self.dataOut.ChanDist = self.dataIn.ChanDist
274 self.dataOut.ChanDist = self.dataIn.ChanDist
275 else: self.dataOut.ChanDist = None
275 else: self.dataOut.ChanDist = None
276
276
277 #if hasattr(self.dataIn, 'VelRange'): #Velocities range
277 #if hasattr(self.dataIn, 'VelRange'): #Velocities range
278 # self.dataOut.VelRange = self.dataIn.VelRange
278 # self.dataOut.VelRange = self.dataIn.VelRange
279 #else: self.dataOut.VelRange = None
279 #else: self.dataOut.VelRange = None
280
280
281
281
282
282
283 else:
283 else:
284 raise ValueError("The type of input object {} is not valid".format(
284 raise ValueError("The type of input object {} is not valid".format(
285 self.dataIn.type))
285 self.dataIn.type))
286
286
287
287
288
288
289
289
290 #print("spc proc Done", self.dataOut.data_spc.shape)
290 #print("spc proc Done", self.dataOut.data_spc.shape)
291 #print(self.dataOut.data_spc)
291 #print(self.dataOut.data_spc)
292 return
292 return
293
293
294 def __selectPairs(self, pairsList):
294 def __selectPairs(self, pairsList):
295
295
296 if not pairsList:
296 if not pairsList:
297 return
297 return
298
298
299 pairs = []
299 pairs = []
300 pairsIndex = []
300 pairsIndex = []
301
301
302 for pair in pairsList:
302 for pair in pairsList:
303 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
303 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
304 continue
304 continue
305 pairs.append(pair)
305 pairs.append(pair)
306 pairsIndex.append(pairs.index(pair))
306 pairsIndex.append(pairs.index(pair))
307
307
308 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
308 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
309 self.dataOut.pairsList = pairs
309 self.dataOut.pairsList = pairs
310
310
311 return
311 return
312
312
313 def selectFFTs(self, minFFT, maxFFT ):
313 def selectFFTs(self, minFFT, maxFFT ):
314 """
314 """
315 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
315 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
316 minFFT<= FFT <= maxFFT
316 minFFT<= FFT <= maxFFT
317 """
317 """
318
318
319 if (minFFT > maxFFT):
319 if (minFFT > maxFFT):
320 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
320 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
321
321
322 if (minFFT < self.dataOut.getFreqRange()[0]):
322 if (minFFT < self.dataOut.getFreqRange()[0]):
323 minFFT = self.dataOut.getFreqRange()[0]
323 minFFT = self.dataOut.getFreqRange()[0]
324
324
325 if (maxFFT > self.dataOut.getFreqRange()[-1]):
325 if (maxFFT > self.dataOut.getFreqRange()[-1]):
326 maxFFT = self.dataOut.getFreqRange()[-1]
326 maxFFT = self.dataOut.getFreqRange()[-1]
327
327
328 minIndex = 0
328 minIndex = 0
329 maxIndex = 0
329 maxIndex = 0
330 FFTs = self.dataOut.getFreqRange()
330 FFTs = self.dataOut.getFreqRange()
331
331
332 inda = numpy.where(FFTs >= minFFT)
332 inda = numpy.where(FFTs >= minFFT)
333 indb = numpy.where(FFTs <= maxFFT)
333 indb = numpy.where(FFTs <= maxFFT)
334
334
335 try:
335 try:
336 minIndex = inda[0][0]
336 minIndex = inda[0][0]
337 except:
337 except:
338 minIndex = 0
338 minIndex = 0
339
339
340 try:
340 try:
341 maxIndex = indb[0][-1]
341 maxIndex = indb[0][-1]
342 except:
342 except:
343 maxIndex = len(FFTs)
343 maxIndex = len(FFTs)
344
344
345 self.selectFFTsByIndex(minIndex, maxIndex)
345 self.selectFFTsByIndex(minIndex, maxIndex)
346
346
347 return 1
347 return 1
348
348
349 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
349 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
350 newheis = numpy.where(
350 newheis = numpy.where(
351 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
351 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
352
352
353 if hei_ref != None:
353 if hei_ref != None:
354 newheis = numpy.where(self.dataOut.heightList > hei_ref)
354 newheis = numpy.where(self.dataOut.heightList > hei_ref)
355
355
356 minIndex = min(newheis[0])
356 minIndex = min(newheis[0])
357 maxIndex = max(newheis[0])
357 maxIndex = max(newheis[0])
358 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
358 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
359 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
359 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
360
360
361 # determina indices
361 # determina indices
362 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
362 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
363 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
363 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
364 avg_dB = 10 * \
364 avg_dB = 10 * \
365 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
365 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
366 beacon_dB = numpy.sort(avg_dB)[-nheis:]
366 beacon_dB = numpy.sort(avg_dB)[-nheis:]
367 beacon_heiIndexList = []
367 beacon_heiIndexList = []
368 for val in avg_dB.tolist():
368 for val in avg_dB.tolist():
369 if val >= beacon_dB[0]:
369 if val >= beacon_dB[0]:
370 beacon_heiIndexList.append(avg_dB.tolist().index(val))
370 beacon_heiIndexList.append(avg_dB.tolist().index(val))
371
371
372 #data_spc = data_spc[:,:,beacon_heiIndexList]
372 #data_spc = data_spc[:,:,beacon_heiIndexList]
373 data_cspc = None
373 data_cspc = None
374 if self.dataOut.data_cspc is not None:
374 if self.dataOut.data_cspc is not None:
375 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
375 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
376 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
376 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
377
377
378 data_dc = None
378 data_dc = None
379 if self.dataOut.data_dc is not None:
379 if self.dataOut.data_dc is not None:
380 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
380 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
381 #data_dc = data_dc[:,beacon_heiIndexList]
381 #data_dc = data_dc[:,beacon_heiIndexList]
382
382
383 self.dataOut.data_spc = data_spc
383 self.dataOut.data_spc = data_spc
384 self.dataOut.data_cspc = data_cspc
384 self.dataOut.data_cspc = data_cspc
385 self.dataOut.data_dc = data_dc
385 self.dataOut.data_dc = data_dc
386 self.dataOut.heightList = heightList
386 self.dataOut.heightList = heightList
387 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
387 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
388
388
389 return 1
389 return 1
390
390
391 def selectFFTsByIndex(self, minIndex, maxIndex):
391 def selectFFTsByIndex(self, minIndex, maxIndex):
392 """
392 """
393
393
394 """
394 """
395
395
396 if (minIndex < 0) or (minIndex > maxIndex):
396 if (minIndex < 0) or (minIndex > maxIndex):
397 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
397 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
398
398
399 if (maxIndex >= self.dataOut.nProfiles):
399 if (maxIndex >= self.dataOut.nProfiles):
400 maxIndex = self.dataOut.nProfiles-1
400 maxIndex = self.dataOut.nProfiles-1
401
401
402 #Spectra
402 #Spectra
403 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
403 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
404
404
405 data_cspc = None
405 data_cspc = None
406 if self.dataOut.data_cspc is not None:
406 if self.dataOut.data_cspc is not None:
407 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
407 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
408
408
409 data_dc = None
409 data_dc = None
410 if self.dataOut.data_dc is not None:
410 if self.dataOut.data_dc is not None:
411 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
411 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
412
412
413 self.dataOut.data_spc = data_spc
413 self.dataOut.data_spc = data_spc
414 self.dataOut.data_cspc = data_cspc
414 self.dataOut.data_cspc = data_cspc
415 self.dataOut.data_dc = data_dc
415 self.dataOut.data_dc = data_dc
416
416
417 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
417 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
418 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
418 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
419 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
419 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
420
420
421 return 1
421 return 1
422
422
423 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
423 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
424 # validacion de rango
424 # validacion de rango
425 if minHei == None:
425 if minHei == None:
426 minHei = self.dataOut.heightList[0]
426 minHei = self.dataOut.heightList[0]
427
427
428 if maxHei == None:
428 if maxHei == None:
429 maxHei = self.dataOut.heightList[-1]
429 maxHei = self.dataOut.heightList[-1]
430
430
431 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
431 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
432 print('minHei: %.2f is out of the heights range' % (minHei))
432 print('minHei: %.2f is out of the heights range' % (minHei))
433 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
433 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
434 minHei = self.dataOut.heightList[0]
434 minHei = self.dataOut.heightList[0]
435
435
436 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
436 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
437 print('maxHei: %.2f is out of the heights range' % (maxHei))
437 print('maxHei: %.2f is out of the heights range' % (maxHei))
438 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
438 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
439 maxHei = self.dataOut.heightList[-1]
439 maxHei = self.dataOut.heightList[-1]
440
440
441 # validacion de velocidades
441 # validacion de velocidades
442 velrange = self.dataOut.getVelRange(1)
442 velrange = self.dataOut.getVelRange(1)
443
443
444 if minVel == None:
444 if minVel == None:
445 minVel = velrange[0]
445 minVel = velrange[0]
446
446
447 if maxVel == None:
447 if maxVel == None:
448 maxVel = velrange[-1]
448 maxVel = velrange[-1]
449
449
450 if (minVel < velrange[0]) or (minVel > maxVel):
450 if (minVel < velrange[0]) or (minVel > maxVel):
451 print('minVel: %.2f is out of the velocity range' % (minVel))
451 print('minVel: %.2f is out of the velocity range' % (minVel))
452 print('minVel is setting to %.2f' % (velrange[0]))
452 print('minVel is setting to %.2f' % (velrange[0]))
453 minVel = velrange[0]
453 minVel = velrange[0]
454
454
455 if (maxVel > velrange[-1]) or (maxVel < minVel):
455 if (maxVel > velrange[-1]) or (maxVel < minVel):
456 print('maxVel: %.2f is out of the velocity range' % (maxVel))
456 print('maxVel: %.2f is out of the velocity range' % (maxVel))
457 print('maxVel is setting to %.2f' % (velrange[-1]))
457 print('maxVel is setting to %.2f' % (velrange[-1]))
458 maxVel = velrange[-1]
458 maxVel = velrange[-1]
459
459
460 # seleccion de indices para rango
460 # seleccion de indices para rango
461 minIndex = 0
461 minIndex = 0
462 maxIndex = 0
462 maxIndex = 0
463 heights = self.dataOut.heightList
463 heights = self.dataOut.heightList
464
464
465 inda = numpy.where(heights >= minHei)
465 inda = numpy.where(heights >= minHei)
466 indb = numpy.where(heights <= maxHei)
466 indb = numpy.where(heights <= maxHei)
467
467
468 try:
468 try:
469 minIndex = inda[0][0]
469 minIndex = inda[0][0]
470 except:
470 except:
471 minIndex = 0
471 minIndex = 0
472
472
473 try:
473 try:
474 maxIndex = indb[0][-1]
474 maxIndex = indb[0][-1]
475 except:
475 except:
476 maxIndex = len(heights)
476 maxIndex = len(heights)
477
477
478 if (minIndex < 0) or (minIndex > maxIndex):
478 if (minIndex < 0) or (minIndex > maxIndex):
479 raise ValueError("some value in (%d,%d) is not valid" % (
479 raise ValueError("some value in (%d,%d) is not valid" % (
480 minIndex, maxIndex))
480 minIndex, maxIndex))
481
481
482 if (maxIndex >= self.dataOut.nHeights):
482 if (maxIndex >= self.dataOut.nHeights):
483 maxIndex = self.dataOut.nHeights - 1
483 maxIndex = self.dataOut.nHeights - 1
484
484
485 # seleccion de indices para velocidades
485 # seleccion de indices para velocidades
486 indminvel = numpy.where(velrange >= minVel)
486 indminvel = numpy.where(velrange >= minVel)
487 indmaxvel = numpy.where(velrange <= maxVel)
487 indmaxvel = numpy.where(velrange <= maxVel)
488 try:
488 try:
489 minIndexVel = indminvel[0][0]
489 minIndexVel = indminvel[0][0]
490 except:
490 except:
491 minIndexVel = 0
491 minIndexVel = 0
492
492
493 try:
493 try:
494 maxIndexVel = indmaxvel[0][-1]
494 maxIndexVel = indmaxvel[0][-1]
495 except:
495 except:
496 maxIndexVel = len(velrange)
496 maxIndexVel = len(velrange)
497
497
498 # seleccion del espectro
498 # seleccion del espectro
499 data_spc = self.dataOut.data_spc[:,
499 data_spc = self.dataOut.data_spc[:,
500 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
500 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
501 # estimacion de ruido
501 # estimacion de ruido
502 noise = numpy.zeros(self.dataOut.nChannels)
502 noise = numpy.zeros(self.dataOut.nChannels)
503
503
504 for channel in range(self.dataOut.nChannels):
504 for channel in range(self.dataOut.nChannels):
505 daux = data_spc[channel, :, :]
505 daux = data_spc[channel, :, :]
506 sortdata = numpy.sort(daux, axis=None)
506 sortdata = numpy.sort(daux, axis=None)
507 noise[channel] = hildebrand_sekhon(sortdata, self.dataOut.nIncohInt)
507 noise[channel] = hildebrand_sekhon(sortdata, self.dataOut.nIncohInt)
508
508
509 self.dataOut.noise_estimation = noise.copy()
509 self.dataOut.noise_estimation = noise.copy()
510
510
511 return 1
511 return 1
512
512
513 class removeDC(Operation):
513 class removeDC(Operation):
514
514
515 def run(self, dataOut, mode=2):
515 def run(self, dataOut, mode=2):
516 self.dataOut = dataOut
516 self.dataOut = dataOut
517 jspectra = self.dataOut.data_spc
517 jspectra = self.dataOut.data_spc
518 jcspectra = self.dataOut.data_cspc
518 jcspectra = self.dataOut.data_cspc
519
519
520 num_chan = jspectra.shape[0]
520 num_chan = jspectra.shape[0]
521 num_hei = jspectra.shape[2]
521 num_hei = jspectra.shape[2]
522
522
523 if jcspectra is not None:
523 if jcspectra is not None:
524 jcspectraExist = True
524 jcspectraExist = True
525 num_pairs = jcspectra.shape[0]
525 num_pairs = jcspectra.shape[0]
526 else:
526 else:
527 jcspectraExist = False
527 jcspectraExist = False
528
528
529 freq_dc = int(jspectra.shape[1] / 2)
529 freq_dc = int(jspectra.shape[1] / 2)
530 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
530 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
531 ind_vel = ind_vel.astype(int)
531 ind_vel = ind_vel.astype(int)
532
532
533 if ind_vel[0] < 0:
533 if ind_vel[0] < 0:
534 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
534 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
535
535
536 if mode == 1:
536 if mode == 1:
537 jspectra[:, freq_dc, :] = (
537 jspectra[:, freq_dc, :] = (
538 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
538 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
539
539
540 if jcspectraExist:
540 if jcspectraExist:
541 jcspectra[:, freq_dc, :] = (
541 jcspectra[:, freq_dc, :] = (
542 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
542 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
543
543
544 if mode == 2:
544 if mode == 2:
545
545
546 vel = numpy.array([-2, -1, 1, 2])
546 vel = numpy.array([-2, -1, 1, 2])
547 xx = numpy.zeros([4, 4])
547 xx = numpy.zeros([4, 4])
548
548
549 for fil in range(4):
549 for fil in range(4):
550 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
550 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
551
551
552 xx_inv = numpy.linalg.inv(xx)
552 xx_inv = numpy.linalg.inv(xx)
553 xx_aux = xx_inv[0, :]
553 xx_aux = xx_inv[0, :]
554
554
555 for ich in range(num_chan):
555 for ich in range(num_chan):
556 yy = jspectra[ich, ind_vel, :]
556 yy = jspectra[ich, ind_vel, :]
557 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
557 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
558
558
559 junkid = jspectra[ich, freq_dc, :] <= 0
559 junkid = jspectra[ich, freq_dc, :] <= 0
560 cjunkid = sum(junkid)
560 cjunkid = sum(junkid)
561
561
562 if cjunkid.any():
562 if cjunkid.any():
563 jspectra[ich, freq_dc, junkid.nonzero()] = (
563 jspectra[ich, freq_dc, junkid.nonzero()] = (
564 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
564 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
565
565
566 if jcspectraExist:
566 if jcspectraExist:
567 for ip in range(num_pairs):
567 for ip in range(num_pairs):
568 yy = jcspectra[ip, ind_vel, :]
568 yy = jcspectra[ip, ind_vel, :]
569 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
569 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
570
570
571 self.dataOut.data_spc = jspectra
571 self.dataOut.data_spc = jspectra
572 self.dataOut.data_cspc = jcspectra
572 self.dataOut.data_cspc = jcspectra
573
573
574 return self.dataOut
574 return self.dataOut
575
575
576 class getNoiseB(Operation):
576 class getNoiseB(Operation):
577
577
578 __slots__ =('offset','warnings', 'isConfig', 'minIndex','maxIndex','minIndexFFT','maxIndexFFT')
578 __slots__ =('offset','warnings', 'isConfig', 'minIndex','maxIndex','minIndexFFT','maxIndexFFT')
579 def __init__(self):
579 def __init__(self):
580
580
581 Operation.__init__(self)
581 Operation.__init__(self)
582 self.isConfig = False
582 self.isConfig = False
583
583
584 def setup(self, offset=None, minHei=None, maxHei=None,minVel=None, maxVel=None, minFreq= None, maxFreq=None, warnings=False):
584 def setup(self, offset=None, minHei=None, maxHei=None,minVel=None, maxVel=None, minFreq= None, maxFreq=None, warnings=False):
585
585
586 self.warnings = warnings
586 self.warnings = warnings
587 if minHei == None:
587 if minHei == None:
588 minHei = self.dataOut.heightList[0]
588 minHei = self.dataOut.heightList[0]
589
589
590 if maxHei == None:
590 if maxHei == None:
591 maxHei = self.dataOut.heightList[-1]
591 maxHei = self.dataOut.heightList[-1]
592
592
593 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
593 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
594 if self.warnings:
594 if self.warnings:
595 print('minHei: %.2f is out of the heights range' % (minHei))
595 print('minHei: %.2f is out of the heights range' % (minHei))
596 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
596 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
597 minHei = self.dataOut.heightList[0]
597 minHei = self.dataOut.heightList[0]
598
598
599 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
599 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
600 if self.warnings:
600 if self.warnings:
601 print('maxHei: %.2f is out of the heights range' % (maxHei))
601 print('maxHei: %.2f is out of the heights range' % (maxHei))
602 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
602 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
603 maxHei = self.dataOut.heightList[-1]
603 maxHei = self.dataOut.heightList[-1]
604
604
605
605
606 #indices relativos a los puntos de fft, puede ser de acuerdo a velocidad o frecuencia
606 #indices relativos a los puntos de fft, puede ser de acuerdo a velocidad o frecuencia
607 minIndexFFT = 0
607 minIndexFFT = 0
608 maxIndexFFT = 0
608 maxIndexFFT = 0
609 # validacion de velocidades
609 # validacion de velocidades
610 indminPoint = None
610 indminPoint = None
611 indmaxPoint = None
611 indmaxPoint = None
612 if self.dataOut.type == 'Spectra':
612 if self.dataOut.type == 'Spectra':
613 if minVel == None and maxVel == None :
613 if minVel == None and maxVel == None :
614
614
615 freqrange = self.dataOut.getFreqRange(1)
615 freqrange = self.dataOut.getFreqRange(1)
616
616
617 if minFreq == None:
617 if minFreq == None:
618 minFreq = freqrange[0]
618 minFreq = freqrange[0]
619
619
620 if maxFreq == None:
620 if maxFreq == None:
621 maxFreq = freqrange[-1]
621 maxFreq = freqrange[-1]
622
622
623 if (minFreq < freqrange[0]) or (minFreq > maxFreq):
623 if (minFreq < freqrange[0]) or (minFreq > maxFreq):
624 if self.warnings:
624 if self.warnings:
625 print('minFreq: %.2f is out of the frequency range' % (minFreq))
625 print('minFreq: %.2f is out of the frequency range' % (minFreq))
626 print('minFreq is setting to %.2f' % (freqrange[0]))
626 print('minFreq is setting to %.2f' % (freqrange[0]))
627 minFreq = freqrange[0]
627 minFreq = freqrange[0]
628
628
629 if (maxFreq > freqrange[-1]) or (maxFreq < minFreq):
629 if (maxFreq > freqrange[-1]) or (maxFreq < minFreq):
630 if self.warnings:
630 if self.warnings:
631 print('maxFreq: %.2f is out of the frequency range' % (maxFreq))
631 print('maxFreq: %.2f is out of the frequency range' % (maxFreq))
632 print('maxFreq is setting to %.2f' % (freqrange[-1]))
632 print('maxFreq is setting to %.2f' % (freqrange[-1]))
633 maxFreq = freqrange[-1]
633 maxFreq = freqrange[-1]
634
634
635 indminPoint = numpy.where(freqrange >= minFreq)
635 indminPoint = numpy.where(freqrange >= minFreq)
636 indmaxPoint = numpy.where(freqrange <= maxFreq)
636 indmaxPoint = numpy.where(freqrange <= maxFreq)
637
637
638 else:
638 else:
639
639
640 velrange = self.dataOut.getVelRange(1)
640 velrange = self.dataOut.getVelRange(1)
641
641
642 if minVel == None:
642 if minVel == None:
643 minVel = velrange[0]
643 minVel = velrange[0]
644
644
645 if maxVel == None:
645 if maxVel == None:
646 maxVel = velrange[-1]
646 maxVel = velrange[-1]
647
647
648 if (minVel < velrange[0]) or (minVel > maxVel):
648 if (minVel < velrange[0]) or (minVel > maxVel):
649 if self.warnings:
649 if self.warnings:
650 print('minVel: %.2f is out of the velocity range' % (minVel))
650 print('minVel: %.2f is out of the velocity range' % (minVel))
651 print('minVel is setting to %.2f' % (velrange[0]))
651 print('minVel is setting to %.2f' % (velrange[0]))
652 minVel = velrange[0]
652 minVel = velrange[0]
653
653
654 if (maxVel > velrange[-1]) or (maxVel < minVel):
654 if (maxVel > velrange[-1]) or (maxVel < minVel):
655 if self.warnings:
655 if self.warnings:
656 print('maxVel: %.2f is out of the velocity range' % (maxVel))
656 print('maxVel: %.2f is out of the velocity range' % (maxVel))
657 print('maxVel is setting to %.2f' % (velrange[-1]))
657 print('maxVel is setting to %.2f' % (velrange[-1]))
658 maxVel = velrange[-1]
658 maxVel = velrange[-1]
659
659
660 indminPoint = numpy.where(velrange >= minVel)
660 indminPoint = numpy.where(velrange >= minVel)
661 indmaxPoint = numpy.where(velrange <= maxVel)
661 indmaxPoint = numpy.where(velrange <= maxVel)
662
662
663
663
664 # seleccion de indices para rango
664 # seleccion de indices para rango
665 minIndex = 0
665 minIndex = 0
666 maxIndex = 0
666 maxIndex = 0
667 heights = self.dataOut.heightList
667 heights = self.dataOut.heightList
668
668
669 inda = numpy.where(heights >= minHei)
669 inda = numpy.where(heights >= minHei)
670 indb = numpy.where(heights <= maxHei)
670 indb = numpy.where(heights <= maxHei)
671
671
672 try:
672 try:
673 minIndex = inda[0][0]
673 minIndex = inda[0][0]
674 except:
674 except:
675 minIndex = 0
675 minIndex = 0
676
676
677 try:
677 try:
678 maxIndex = indb[0][-1]
678 maxIndex = indb[0][-1]
679 except:
679 except:
680 maxIndex = len(heights)
680 maxIndex = len(heights)
681
681
682 if (minIndex < 0) or (minIndex > maxIndex):
682 if (minIndex < 0) or (minIndex > maxIndex):
683 raise ValueError("some value in (%d,%d) is not valid" % (
683 raise ValueError("some value in (%d,%d) is not valid" % (
684 minIndex, maxIndex))
684 minIndex, maxIndex))
685
685
686 if (maxIndex >= self.dataOut.nHeights):
686 if (maxIndex >= self.dataOut.nHeights):
687 maxIndex = self.dataOut.nHeights - 1
687 maxIndex = self.dataOut.nHeights - 1
688 #############################################################3
688 #############################################################3
689 # seleccion de indices para velocidades
689 # seleccion de indices para velocidades
690 if self.dataOut.type == 'Spectra':
690 if self.dataOut.type == 'Spectra':
691 try:
691 try:
692 minIndexFFT = indminPoint[0][0]
692 minIndexFFT = indminPoint[0][0]
693 except:
693 except:
694 minIndexFFT = 0
694 minIndexFFT = 0
695
695
696 try:
696 try:
697 maxIndexFFT = indmaxPoint[0][-1]
697 maxIndexFFT = indmaxPoint[0][-1]
698 except:
698 except:
699 maxIndexFFT = len( self.dataOut.getFreqRange(1))
699 maxIndexFFT = len( self.dataOut.getFreqRange(1))
700
700
701 self.minIndex, self.maxIndex, self.minIndexFFT, self.maxIndexFFT = minIndex, maxIndex, minIndexFFT, maxIndexFFT
701 self.minIndex, self.maxIndex, self.minIndexFFT, self.maxIndexFFT = minIndex, maxIndex, minIndexFFT, maxIndexFFT
702 self.isConfig = True
702 self.isConfig = True
703 self.offset = 1
703 self.offset = 1
704 if offset!=None:
704 if offset!=None:
705 self.offset = 10**(offset/10)
705 self.offset = 10**(offset/10)
706 #print("config getNoiseB Done")
706 #print("config getNoiseB Done")
707
707
708 def run(self, dataOut, offset=None, minHei=None, maxHei=None,minVel=None, maxVel=None, minFreq= None, maxFreq=None, warnings=False):
708 def run(self, dataOut, offset=None, minHei=None, maxHei=None,minVel=None, maxVel=None, minFreq= None, maxFreq=None, warnings=False):
709 self.dataOut = dataOut
709 self.dataOut = dataOut
710
710
711 if not self.isConfig:
711 if not self.isConfig:
712 self.setup(offset, minHei, maxHei,minVel, maxVel, minFreq, maxFreq, warnings)
712 self.setup(offset, minHei, maxHei,minVel, maxVel, minFreq, maxFreq, warnings)
713
713
714 self.dataOut.noise_estimation = None
714 self.dataOut.noise_estimation = None
715 noise = None
715 noise = None
716 #print("data type: ",self.dataOut.type, self.dataOut.nIncohInt, self.dataOut.max_nIncohInt)
716 #print("data type: ",self.dataOut.type, self.dataOut.nIncohInt, self.dataOut.max_nIncohInt)
717 if self.dataOut.type == 'Voltage':
717 if self.dataOut.type == 'Voltage':
718 noise = self.dataOut.getNoise(ymin_index=self.minIndex, ymax_index=self.maxIndex)
718 noise = self.dataOut.getNoise(ymin_index=self.minIndex, ymax_index=self.maxIndex)
719 #print(minIndex, maxIndex,minIndexVel, maxIndexVel)
719 #print(minIndex, maxIndex,minIndexVel, maxIndexVel)
720 elif self.dataOut.type == 'Spectra':
720 elif self.dataOut.type == 'Spectra':
721 #print(self.dataOut.nChannels, self.minIndex, self.maxIndex,self.minIndexFFT, self.maxIndexFFT, self.dataOut.max_nIncohInt, self.dataOut.nIncohInt)
721 #print(self.dataOut.nChannels, self.minIndex, self.maxIndex,self.minIndexFFT, self.maxIndexFFT, self.dataOut.max_nIncohInt, self.dataOut.nIncohInt)
722 noise = numpy.zeros( self.dataOut.nChannels)
722 noise = numpy.zeros( self.dataOut.nChannels)
723 norm = 1
723 norm = 1
724
724
725 for channel in range( self.dataOut.nChannels):
725 for channel in range( self.dataOut.nChannels):
726 if not hasattr(self.dataOut.nIncohInt,'__len__'):
726 if not hasattr(self.dataOut.nIncohInt,'__len__'):
727 norm = 1
727 norm = 1
728 else:
728 else:
729 norm = self.dataOut.max_nIncohInt[channel]/self.dataOut.nIncohInt[channel, self.minIndex:self.maxIndex]
729 norm = self.dataOut.max_nIncohInt[channel]/self.dataOut.nIncohInt[channel, self.minIndex:self.maxIndex]
730
730 #print("norm nIncoh: ", norm ,self.dataOut.data_spc.shape, self.dataOut.max_nIncohInt)
731 #print("norm nIncoh: ", norm ,self.dataOut.data_spc.shape, self.dataOut.max_nIncohInt)
731 daux = self.dataOut.data_spc[channel,self.minIndexFFT:self.maxIndexFFT, self.minIndex:self.maxIndex]
732 daux = self.dataOut.data_spc[channel,self.minIndexFFT:self.maxIndexFFT, self.minIndex:self.maxIndex]
732 daux = numpy.multiply(daux, norm)
733 daux = numpy.multiply(daux, norm)
733 #print("offset: ", self.offset, 10*numpy.log10(self.offset))
734 #print("offset: ", self.offset, 10*numpy.log10(self.offset))
734 # noise[channel] = self.getNoiseByMean(daux)/self.offset
735 # noise[channel] = self.getNoiseByMean(daux)/self.offset
735 #print(daux.shape, daux)
736 #print(daux.shape, daux)
736 #noise[channel] = self.getNoiseByHS(daux, self.dataOut.max_nIncohInt)/self.offset
737 #noise[channel] = self.getNoiseByHS(daux, self.dataOut.max_nIncohInt)/self.offset
737 sortdata = numpy.sort(daux, axis=None)
738 sortdata = numpy.sort(daux, axis=None)
738
739
739 noise[channel] = _noise.hildebrand_sekhon(sortdata, self.dataOut.max_nIncohInt[channel])/self.offset
740 noise[channel] = _noise.hildebrand_sekhon(sortdata, self.dataOut.max_nIncohInt[channel])/self.offset
740 #print("noise shape", noise[channel], self.name)
741 #print("noise shape", noise[channel], self.name)
741
742
742 #noise = self.dataOut.getNoise(xmin_index=self.minIndexFFT, xmax_index=self.maxIndexFFT, ymin_index=self.minIndex, ymax_index=self.maxIndex)
743 #noise = self.dataOut.getNoise(xmin_index=self.minIndexFFT, xmax_index=self.maxIndexFFT, ymin_index=self.minIndex, ymax_index=self.maxIndex)
743 else:
744 else:
744 noise = self.dataOut.getNoise(xmin_index=self.minIndexFFT, xmax_index=self.maxIndexFFT, ymin_index=self.minIndex, ymax_index=self.maxIndex)
745 noise = self.dataOut.getNoise(xmin_index=self.minIndexFFT, xmax_index=self.maxIndexFFT, ymin_index=self.minIndex, ymax_index=self.maxIndex)
746
745 self.dataOut.noise_estimation = noise.copy() # dataOut.noise
747 self.dataOut.noise_estimation = noise.copy() # dataOut.noise
746 #print("2: ",10*numpy.log10(self.dataOut.noise_estimation/64))
748 #print("2: ",10*numpy.log10(self.dataOut.noise_estimation/64))
747 #print("2: ",self.dataOut.noise_estimation)
749 #print("2: ",self.dataOut.noise_estimation)
748 #print(self.dataOut.flagNoData)
750 #print(self.dataOut.flagNoData)
749 #print("getNoise Done", noise, self.dataOut.nProfiles ,self.dataOut.ippFactor)
751 #print("getNoise Done", 10*numpy.log10(noise))
750 return self.dataOut
752 return self.dataOut
751
753
752 def getNoiseByMean(self,data):
754 def getNoiseByMean(self,data):
753 #data debe estar ordenado
755 #data debe estar ordenado
754 data = numpy.mean(data,axis=1)
756 data = numpy.mean(data,axis=1)
755 sortdata = numpy.sort(data, axis=None)
757 sortdata = numpy.sort(data, axis=None)
756 #sortID=data.argsort()
758 #sortID=data.argsort()
757 #print(data.shape)
759 #print(data.shape)
758
760
759 pnoise = None
761 pnoise = None
760 j = 0
762 j = 0
761
763
762 mean = numpy.mean(sortdata)
764 mean = numpy.mean(sortdata)
763 min = numpy.min(sortdata)
765 min = numpy.min(sortdata)
764 delta = mean - min
766 delta = mean - min
765 indexes = numpy.where(sortdata > (mean+delta))[0] #only array of indexes
767 indexes = numpy.where(sortdata > (mean+delta))[0] #only array of indexes
766 #print(len(indexes))
768 #print(len(indexes))
767 if len(indexes)==0:
769 if len(indexes)==0:
768 pnoise = numpy.mean(sortdata)
770 pnoise = numpy.mean(sortdata)
769 else:
771 else:
770 j = indexes[0]
772 j = indexes[0]
771 pnoise = numpy.mean(sortdata[0:j])
773 pnoise = numpy.mean(sortdata[0:j])
772
774
773 # from matplotlib import pyplot as plt
775 # from matplotlib import pyplot as plt
774 # plt.plot(sortdata)
776 # plt.plot(sortdata)
775 # plt.vlines(j,(pnoise-delta),(pnoise+delta), color='r')
777 # plt.vlines(j,(pnoise-delta),(pnoise+delta), color='r')
776 # plt.show()
778 # plt.show()
777 #print("noise: ", 10*numpy.log10(pnoise))
779 #print("noise: ", 10*numpy.log10(pnoise))
778 return pnoise
780 return pnoise
779
781
780 def getNoiseByHS(self,data, navg):
782 def getNoiseByHS(self,data, navg):
781 #data debe estar ordenado
783 #data debe estar ordenado
782 #data = numpy.mean(data,axis=1)
784 #data = numpy.mean(data,axis=1)
783 sortdata = numpy.sort(data, axis=None)
785 sortdata = numpy.sort(data, axis=None)
784
786
785 lenOfData = len(sortdata)
787 lenOfData = len(sortdata)
786 nums_min = lenOfData*0.2
788 nums_min = lenOfData*0.2
787
789
788 if nums_min <= 5:
790 if nums_min <= 5:
789
791
790 nums_min = 5
792 nums_min = 5
791
793
792 sump = 0.
794 sump = 0.
793 sumq = 0.
795 sumq = 0.
794
796
795 j = 0
797 j = 0
796 cont = 1
798 cont = 1
797
799
798 while((cont == 1)and(j < lenOfData)):
800 while((cont == 1)and(j < lenOfData)):
799
801
800 sump += sortdata[j]
802 sump += sortdata[j]
801 sumq += sortdata[j]**2
803 sumq += sortdata[j]**2
802 #sumq -= sump**2
804 #sumq -= sump**2
803 if j > nums_min:
805 if j > nums_min:
804 rtest = float(j)/(j-1) + 1.0/navg
806 rtest = float(j)/(j-1) + 1.0/navg
805 #if ((sumq*j) > (sump**2)):
807 #if ((sumq*j) > (sump**2)):
806 if ((sumq*j) > (rtest*sump**2)):
808 if ((sumq*j) > (rtest*sump**2)):
807 j = j - 1
809 j = j - 1
808 sump = sump - sortdata[j]
810 sump = sump - sortdata[j]
809 sumq = sumq - sortdata[j]**2
811 sumq = sumq - sortdata[j]**2
810 cont = 0
812 cont = 0
811
813
812 j += 1
814 j += 1
813
815
814 lnoise = sump / j
816 lnoise = sump / j
815
817
816 return lnoise
818 return lnoise
817
819
818
820
819
821
820 def fit_func( x, a0, a1, a2): #, a3, a4, a5):
822 def fit_func( x, a0, a1, a2): #, a3, a4, a5):
821 z = (x - a1) / a2
823 z = (x - a1) / a2
822 y = a0 * numpy.exp(-z**2 / a2) #+ a3 + a4 * x + a5 * x**2
824 y = a0 * numpy.exp(-z**2 / a2) #+ a3 + a4 * x + a5 * x**2
823 return y
825 return y
824
826
825
827
826 # class CleanRayleigh(Operation):
828 # class CleanRayleigh(Operation):
827 #
829 #
828 # def __init__(self):
830 # def __init__(self):
829 #
831 #
830 # Operation.__init__(self)
832 # Operation.__init__(self)
831 # self.i=0
833 # self.i=0
832 # self.isConfig = False
834 # self.isConfig = False
833 # self.__dataReady = False
835 # self.__dataReady = False
834 # self.__profIndex = 0
836 # self.__profIndex = 0
835 # self.byTime = False
837 # self.byTime = False
836 # self.byProfiles = False
838 # self.byProfiles = False
837 #
839 #
838 # self.bloques = None
840 # self.bloques = None
839 # self.bloque0 = None
841 # self.bloque0 = None
840 #
842 #
841 # self.index = 0
843 # self.index = 0
842 #
844 #
843 # self.buffer = 0
845 # self.buffer = 0
844 # self.buffer2 = 0
846 # self.buffer2 = 0
845 # self.buffer3 = 0
847 # self.buffer3 = 0
846 #
848 #
847 #
849 #
848 # def setup(self,dataOut,min_hei,max_hei,n, timeInterval,factor_stdv):
850 # def setup(self,dataOut,min_hei,max_hei,n, timeInterval,factor_stdv):
849 #
851 #
850 # self.nChannels = dataOut.nChannels
852 # self.nChannels = dataOut.nChannels
851 # self.nProf = dataOut.nProfiles
853 # self.nProf = dataOut.nProfiles
852 # self.nPairs = dataOut.data_cspc.shape[0]
854 # self.nPairs = dataOut.data_cspc.shape[0]
853 # self.pairsArray = numpy.array(dataOut.pairsList)
855 # self.pairsArray = numpy.array(dataOut.pairsList)
854 # self.spectra = dataOut.data_spc
856 # self.spectra = dataOut.data_spc
855 # self.cspectra = dataOut.data_cspc
857 # self.cspectra = dataOut.data_cspc
856 # self.heights = dataOut.heightList #alturas totales
858 # self.heights = dataOut.heightList #alturas totales
857 # self.nHeights = len(self.heights)
859 # self.nHeights = len(self.heights)
858 # self.min_hei = min_hei
860 # self.min_hei = min_hei
859 # self.max_hei = max_hei
861 # self.max_hei = max_hei
860 # if (self.min_hei == None):
862 # if (self.min_hei == None):
861 # self.min_hei = 0
863 # self.min_hei = 0
862 # if (self.max_hei == None):
864 # if (self.max_hei == None):
863 # self.max_hei = dataOut.heightList[-1]
865 # self.max_hei = dataOut.heightList[-1]
864 # self.hval = ((self.max_hei>=self.heights) & (self.heights >= self.min_hei)).nonzero()
866 # self.hval = ((self.max_hei>=self.heights) & (self.heights >= self.min_hei)).nonzero()
865 # self.heightsClean = self.heights[self.hval] #alturas filtradas
867 # self.heightsClean = self.heights[self.hval] #alturas filtradas
866 # self.hval = self.hval[0] # forma (N,), an solo N elementos -> Indices de alturas
868 # self.hval = self.hval[0] # forma (N,), an solo N elementos -> Indices de alturas
867 # self.nHeightsClean = len(self.heightsClean)
869 # self.nHeightsClean = len(self.heightsClean)
868 # self.channels = dataOut.channelList
870 # self.channels = dataOut.channelList
869 # self.nChan = len(self.channels)
871 # self.nChan = len(self.channels)
870 # self.nIncohInt = dataOut.nIncohInt
872 # self.nIncohInt = dataOut.nIncohInt
871 # self.__initime = dataOut.utctime
873 # self.__initime = dataOut.utctime
872 # self.maxAltInd = self.hval[-1]+1
874 # self.maxAltInd = self.hval[-1]+1
873 # self.minAltInd = self.hval[0]
875 # self.minAltInd = self.hval[0]
874 #
876 #
875 # self.crosspairs = dataOut.pairsList
877 # self.crosspairs = dataOut.pairsList
876 # self.nPairs = len(self.crosspairs)
878 # self.nPairs = len(self.crosspairs)
877 # self.normFactor = dataOut.normFactor
879 # self.normFactor = dataOut.normFactor
878 # self.nFFTPoints = dataOut.nFFTPoints
880 # self.nFFTPoints = dataOut.nFFTPoints
879 # self.ippSeconds = dataOut.ippSeconds
881 # self.ippSeconds = dataOut.ippSeconds
880 # self.currentTime = self.__initime
882 # self.currentTime = self.__initime
881 # self.pairsArray = numpy.array(dataOut.pairsList)
883 # self.pairsArray = numpy.array(dataOut.pairsList)
882 # self.factor_stdv = factor_stdv
884 # self.factor_stdv = factor_stdv
883 #
885 #
884 # if n != None :
886 # if n != None :
885 # self.byProfiles = True
887 # self.byProfiles = True
886 # self.nIntProfiles = n
888 # self.nIntProfiles = n
887 # else:
889 # else:
888 # self.__integrationtime = timeInterval
890 # self.__integrationtime = timeInterval
889 #
891 #
890 # self.__dataReady = False
892 # self.__dataReady = False
891 # self.isConfig = True
893 # self.isConfig = True
892 #
894 #
893 #
895 #
894 #
896 #
895 # def run(self, dataOut,min_hei=None,max_hei=None, n=None, timeInterval=10,factor_stdv=2.5):
897 # def run(self, dataOut,min_hei=None,max_hei=None, n=None, timeInterval=10,factor_stdv=2.5):
896 # #print("runing cleanRayleigh")
898 # #print("runing cleanRayleigh")
897 # if not self.isConfig :
899 # if not self.isConfig :
898 #
900 #
899 # self.setup(dataOut, min_hei,max_hei,n,timeInterval,factor_stdv)
901 # self.setup(dataOut, min_hei,max_hei,n,timeInterval,factor_stdv)
900 #
902 #
901 # tini=dataOut.utctime
903 # tini=dataOut.utctime
902 #
904 #
903 # if self.byProfiles:
905 # if self.byProfiles:
904 # if self.__profIndex == self.nIntProfiles:
906 # if self.__profIndex == self.nIntProfiles:
905 # self.__dataReady = True
907 # self.__dataReady = True
906 # else:
908 # else:
907 # if (tini - self.__initime) >= self.__integrationtime:
909 # if (tini - self.__initime) >= self.__integrationtime:
908 #
910 #
909 # self.__dataReady = True
911 # self.__dataReady = True
910 # self.__initime = tini
912 # self.__initime = tini
911 #
913 #
912 # #if (tini.tm_min % 2) == 0 and (tini.tm_sec < 5 and self.fint==0):
914 # #if (tini.tm_min % 2) == 0 and (tini.tm_sec < 5 and self.fint==0):
913 #
915 #
914 # if self.__dataReady:
916 # if self.__dataReady:
915 #
917 #
916 # self.__profIndex = 0
918 # self.__profIndex = 0
917 # jspc = self.buffer
919 # jspc = self.buffer
918 # jcspc = self.buffer2
920 # jcspc = self.buffer2
919 # #jnoise = self.buffer3
921 # #jnoise = self.buffer3
920 # self.buffer = dataOut.data_spc
922 # self.buffer = dataOut.data_spc
921 # self.buffer2 = dataOut.data_cspc
923 # self.buffer2 = dataOut.data_cspc
922 # #self.buffer3 = dataOut.noise
924 # #self.buffer3 = dataOut.noise
923 # self.currentTime = dataOut.utctime
925 # self.currentTime = dataOut.utctime
924 # if numpy.any(jspc) :
926 # if numpy.any(jspc) :
925 # #print( jspc.shape, jcspc.shape)
927 # #print( jspc.shape, jcspc.shape)
926 # jspc = numpy.reshape(jspc,(int(len(jspc)/self.nChannels),self.nChannels,self.nFFTPoints,self.nHeights))
928 # jspc = numpy.reshape(jspc,(int(len(jspc)/self.nChannels),self.nChannels,self.nFFTPoints,self.nHeights))
927 # try:
929 # try:
928 # jcspc= numpy.reshape(jcspc,(int(len(jcspc)/self.nPairs),self.nPairs,self.nFFTPoints,self.nHeights))
930 # jcspc= numpy.reshape(jcspc,(int(len(jcspc)/self.nPairs),self.nPairs,self.nFFTPoints,self.nHeights))
929 # except:
931 # except:
930 # print("no cspc")
932 # print("no cspc")
931 # self.__dataReady = False
933 # self.__dataReady = False
932 # #print( jspc.shape, jcspc.shape)
934 # #print( jspc.shape, jcspc.shape)
933 # dataOut.flagNoData = False
935 # dataOut.flagNoData = False
934 # else:
936 # else:
935 # dataOut.flagNoData = True
937 # dataOut.flagNoData = True
936 # self.__dataReady = False
938 # self.__dataReady = False
937 # return dataOut
939 # return dataOut
938 # else:
940 # else:
939 # #print( len(self.buffer))
941 # #print( len(self.buffer))
940 # if numpy.any(self.buffer):
942 # if numpy.any(self.buffer):
941 # self.buffer = numpy.concatenate((self.buffer,dataOut.data_spc), axis=0)
943 # self.buffer = numpy.concatenate((self.buffer,dataOut.data_spc), axis=0)
942 # try:
944 # try:
943 # self.buffer2 = numpy.concatenate((self.buffer2,dataOut.data_cspc), axis=0)
945 # self.buffer2 = numpy.concatenate((self.buffer2,dataOut.data_cspc), axis=0)
944 # self.buffer3 += dataOut.data_dc
946 # self.buffer3 += dataOut.data_dc
945 # except:
947 # except:
946 # pass
948 # pass
947 # else:
949 # else:
948 # self.buffer = dataOut.data_spc
950 # self.buffer = dataOut.data_spc
949 # self.buffer2 = dataOut.data_cspc
951 # self.buffer2 = dataOut.data_cspc
950 # self.buffer3 = dataOut.data_dc
952 # self.buffer3 = dataOut.data_dc
951 # #print self.index, self.fint
953 # #print self.index, self.fint
952 # #print self.buffer2.shape
954 # #print self.buffer2.shape
953 # dataOut.flagNoData = True ## NOTE: ?? revisar LUEGO
955 # dataOut.flagNoData = True ## NOTE: ?? revisar LUEGO
954 # self.__profIndex += 1
956 # self.__profIndex += 1
955 # return dataOut ## NOTE: REV
957 # return dataOut ## NOTE: REV
956 #
958 #
957 #
959 #
958 # #index = tini.tm_hour*12+tini.tm_min/5
960 # #index = tini.tm_hour*12+tini.tm_min/5
959 # '''
961 # '''
960 # #REVISAR
962 # #REVISAR
961 # '''
963 # '''
962 # # jspc = jspc/self.nFFTPoints/self.normFactor
964 # # jspc = jspc/self.nFFTPoints/self.normFactor
963 # # jcspc = jcspc/self.nFFTPoints/self.normFactor
965 # # jcspc = jcspc/self.nFFTPoints/self.normFactor
964 #
966 #
965 #
967 #
966 #
968 #
967 # tmp_spectra,tmp_cspectra = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
969 # tmp_spectra,tmp_cspectra = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
968 # dataOut.data_spc = tmp_spectra
970 # dataOut.data_spc = tmp_spectra
969 # dataOut.data_cspc = tmp_cspectra
971 # dataOut.data_cspc = tmp_cspectra
970 #
972 #
971 # #dataOut.data_spc,dataOut.data_cspc = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
973 # #dataOut.data_spc,dataOut.data_cspc = self.cleanRayleigh(dataOut,jspc,jcspc,self.factor_stdv)
972 #
974 #
973 # dataOut.data_dc = self.buffer3
975 # dataOut.data_dc = self.buffer3
974 # dataOut.nIncohInt *= self.nIntProfiles
976 # dataOut.nIncohInt *= self.nIntProfiles
975 # dataOut.max_nIncohInt = self.nIntProfiles
977 # dataOut.max_nIncohInt = self.nIntProfiles
976 # dataOut.utctime = self.currentTime #tiempo promediado
978 # dataOut.utctime = self.currentTime #tiempo promediado
977 # #print("Time: ",time.localtime(dataOut.utctime))
979 # #print("Time: ",time.localtime(dataOut.utctime))
978 # # dataOut.data_spc = sat_spectra
980 # # dataOut.data_spc = sat_spectra
979 # # dataOut.data_cspc = sat_cspectra
981 # # dataOut.data_cspc = sat_cspectra
980 # self.buffer = 0
982 # self.buffer = 0
981 # self.buffer2 = 0
983 # self.buffer2 = 0
982 # self.buffer3 = 0
984 # self.buffer3 = 0
983 #
985 #
984 # return dataOut
986 # return dataOut
985 #
987 #
986 # def cleanRayleigh(self,dataOut,spectra,cspectra,factor_stdv):
988 # def cleanRayleigh(self,dataOut,spectra,cspectra,factor_stdv):
987 # print("OP cleanRayleigh")
989 # print("OP cleanRayleigh")
988 # #import matplotlib.pyplot as plt
990 # #import matplotlib.pyplot as plt
989 # #for k in range(149):
991 # #for k in range(149):
990 # #channelsProcssd = []
992 # #channelsProcssd = []
991 # #channelA_ok = False
993 # #channelA_ok = False
992 # #rfunc = cspectra.copy() #self.bloques
994 # #rfunc = cspectra.copy() #self.bloques
993 # rfunc = spectra.copy()
995 # rfunc = spectra.copy()
994 # #rfunc = cspectra
996 # #rfunc = cspectra
995 # #val_spc = spectra*0.0 #self.bloque0*0.0
997 # #val_spc = spectra*0.0 #self.bloque0*0.0
996 # #val_cspc = cspectra*0.0 #self.bloques*0.0
998 # #val_cspc = cspectra*0.0 #self.bloques*0.0
997 # #in_sat_spectra = spectra.copy() #self.bloque0
999 # #in_sat_spectra = spectra.copy() #self.bloque0
998 # #in_sat_cspectra = cspectra.copy() #self.bloques
1000 # #in_sat_cspectra = cspectra.copy() #self.bloques
999 #
1001 #
1000 #
1002 #
1001 # ###ONLY FOR TEST:
1003 # ###ONLY FOR TEST:
1002 # raxs = math.ceil(math.sqrt(self.nPairs))
1004 # raxs = math.ceil(math.sqrt(self.nPairs))
1003 # if raxs == 0:
1005 # if raxs == 0:
1004 # raxs = 1
1006 # raxs = 1
1005 # caxs = math.ceil(self.nPairs/raxs)
1007 # caxs = math.ceil(self.nPairs/raxs)
1006 # if self.nPairs <4:
1008 # if self.nPairs <4:
1007 # raxs = 2
1009 # raxs = 2
1008 # caxs = 2
1010 # caxs = 2
1009 # #print(raxs, caxs)
1011 # #print(raxs, caxs)
1010 # fft_rev = 14 #nFFT to plot
1012 # fft_rev = 14 #nFFT to plot
1011 # hei_rev = ((self.heights >= 550) & (self.heights <= 551)).nonzero() #hei to plot
1013 # hei_rev = ((self.heights >= 550) & (self.heights <= 551)).nonzero() #hei to plot
1012 # hei_rev = hei_rev[0]
1014 # hei_rev = hei_rev[0]
1013 # #print(hei_rev)
1015 # #print(hei_rev)
1014 #
1016 #
1015 # #print numpy.absolute(rfunc[:,0,0,14])
1017 # #print numpy.absolute(rfunc[:,0,0,14])
1016 #
1018 #
1017 # gauss_fit, covariance = None, None
1019 # gauss_fit, covariance = None, None
1018 # for ih in range(self.minAltInd,self.maxAltInd):
1020 # for ih in range(self.minAltInd,self.maxAltInd):
1019 # for ifreq in range(self.nFFTPoints):
1021 # for ifreq in range(self.nFFTPoints):
1020 # '''
1022 # '''
1021 # ###ONLY FOR TEST:
1023 # ###ONLY FOR TEST:
1022 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1024 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1023 # fig, axs = plt.subplots(raxs, caxs)
1025 # fig, axs = plt.subplots(raxs, caxs)
1024 # fig2, axs2 = plt.subplots(raxs, caxs)
1026 # fig2, axs2 = plt.subplots(raxs, caxs)
1025 # col_ax = 0
1027 # col_ax = 0
1026 # row_ax = 0
1028 # row_ax = 0
1027 # '''
1029 # '''
1028 # #print(self.nPairs)
1030 # #print(self.nPairs)
1029 # for ii in range(self.nChan): #PARES DE CANALES SELF y CROSS
1031 # for ii in range(self.nChan): #PARES DE CANALES SELF y CROSS
1030 # # if self.crosspairs[ii][1]-self.crosspairs[ii][0] > 1: # APLICAR SOLO EN PARES CONTIGUOS
1032 # # if self.crosspairs[ii][1]-self.crosspairs[ii][0] > 1: # APLICAR SOLO EN PARES CONTIGUOS
1031 # # continue
1033 # # continue
1032 # # if not self.crosspairs[ii][0] in channelsProcssd:
1034 # # if not self.crosspairs[ii][0] in channelsProcssd:
1033 # # channelA_ok = True
1035 # # channelA_ok = True
1034 # #print("pair: ",self.crosspairs[ii])
1036 # #print("pair: ",self.crosspairs[ii])
1035 # '''
1037 # '''
1036 # ###ONLY FOR TEST:
1038 # ###ONLY FOR TEST:
1037 # if (col_ax%caxs==0 and col_ax!=0 and self.nPairs !=1):
1039 # if (col_ax%caxs==0 and col_ax!=0 and self.nPairs !=1):
1038 # col_ax = 0
1040 # col_ax = 0
1039 # row_ax += 1
1041 # row_ax += 1
1040 # '''
1042 # '''
1041 # func2clean = 10*numpy.log10(numpy.absolute(rfunc[:,ii,ifreq,ih])) #Potencia?
1043 # func2clean = 10*numpy.log10(numpy.absolute(rfunc[:,ii,ifreq,ih])) #Potencia?
1042 # #print(func2clean.shape)
1044 # #print(func2clean.shape)
1043 # val = (numpy.isfinite(func2clean)==True).nonzero()
1045 # val = (numpy.isfinite(func2clean)==True).nonzero()
1044 #
1046 #
1045 # if len(val)>0: #limitador
1047 # if len(val)>0: #limitador
1046 # min_val = numpy.around(numpy.amin(func2clean)-2) #> (-40)
1048 # min_val = numpy.around(numpy.amin(func2clean)-2) #> (-40)
1047 # if min_val <= -40 :
1049 # if min_val <= -40 :
1048 # min_val = -40
1050 # min_val = -40
1049 # max_val = numpy.around(numpy.amax(func2clean)+2) #< 200
1051 # max_val = numpy.around(numpy.amax(func2clean)+2) #< 200
1050 # if max_val >= 200 :
1052 # if max_val >= 200 :
1051 # max_val = 200
1053 # max_val = 200
1052 # #print min_val, max_val
1054 # #print min_val, max_val
1053 # step = 1
1055 # step = 1
1054 # #print("Getting bins and the histogram")
1056 # #print("Getting bins and the histogram")
1055 # x_dist = min_val + numpy.arange(1 + ((max_val-(min_val))/step))*step
1057 # x_dist = min_val + numpy.arange(1 + ((max_val-(min_val))/step))*step
1056 # y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
1058 # y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
1057 # #print(len(y_dist),len(binstep[:-1]))
1059 # #print(len(y_dist),len(binstep[:-1]))
1058 # #print(row_ax,col_ax, " ..")
1060 # #print(row_ax,col_ax, " ..")
1059 # #print(self.pairsArray[ii][0],self.pairsArray[ii][1])
1061 # #print(self.pairsArray[ii][0],self.pairsArray[ii][1])
1060 # mean = numpy.sum(x_dist * y_dist) / numpy.sum(y_dist)
1062 # mean = numpy.sum(x_dist * y_dist) / numpy.sum(y_dist)
1061 # sigma = numpy.sqrt(numpy.sum(y_dist * (x_dist - mean)**2) / numpy.sum(y_dist))
1063 # sigma = numpy.sqrt(numpy.sum(y_dist * (x_dist - mean)**2) / numpy.sum(y_dist))
1062 # parg = [numpy.amax(y_dist),mean,sigma]
1064 # parg = [numpy.amax(y_dist),mean,sigma]
1063 #
1065 #
1064 # newY = None
1066 # newY = None
1065 #
1067 #
1066 # try :
1068 # try :
1067 # gauss_fit, covariance = curve_fit(fit_func, x_dist, y_dist,p0=parg)
1069 # gauss_fit, covariance = curve_fit(fit_func, x_dist, y_dist,p0=parg)
1068 # mode = gauss_fit[1]
1070 # mode = gauss_fit[1]
1069 # stdv = gauss_fit[2]
1071 # stdv = gauss_fit[2]
1070 # #print(" FIT OK",gauss_fit)
1072 # #print(" FIT OK",gauss_fit)
1071 # '''
1073 # '''
1072 # ###ONLY FOR TEST:
1074 # ###ONLY FOR TEST:
1073 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1075 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1074 # newY = fit_func(x_dist,gauss_fit[0],gauss_fit[1],gauss_fit[2])
1076 # newY = fit_func(x_dist,gauss_fit[0],gauss_fit[1],gauss_fit[2])
1075 # axs[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
1077 # axs[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
1076 # axs[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
1078 # axs[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
1077 # axs[row_ax,col_ax].set_title("CH "+str(self.channels[ii]))
1079 # axs[row_ax,col_ax].set_title("CH "+str(self.channels[ii]))
1078 # '''
1080 # '''
1079 # except:
1081 # except:
1080 # mode = mean
1082 # mode = mean
1081 # stdv = sigma
1083 # stdv = sigma
1082 # #print("FIT FAIL")
1084 # #print("FIT FAIL")
1083 # #continue
1085 # #continue
1084 #
1086 #
1085 #
1087 #
1086 # #print(mode,stdv)
1088 # #print(mode,stdv)
1087 # #Removing echoes greater than mode + std_factor*stdv
1089 # #Removing echoes greater than mode + std_factor*stdv
1088 # noval = (abs(func2clean - mode)>=(factor_stdv*stdv)).nonzero()
1090 # noval = (abs(func2clean - mode)>=(factor_stdv*stdv)).nonzero()
1089 # #noval tiene los indices que se van a remover
1091 # #noval tiene los indices que se van a remover
1090 # #print("Chan ",ii," novals: ",len(noval[0]))
1092 # #print("Chan ",ii," novals: ",len(noval[0]))
1091 # if len(noval[0]) > 0: #forma de array (N,) es igual a longitud (N)
1093 # if len(noval[0]) > 0: #forma de array (N,) es igual a longitud (N)
1092 # novall = ((func2clean - mode) >= (factor_stdv*stdv)).nonzero()
1094 # novall = ((func2clean - mode) >= (factor_stdv*stdv)).nonzero()
1093 # #print(novall)
1095 # #print(novall)
1094 # #print(" ",self.pairsArray[ii])
1096 # #print(" ",self.pairsArray[ii])
1095 # #cross_pairs = self.pairsArray[ii]
1097 # #cross_pairs = self.pairsArray[ii]
1096 # #Getting coherent echoes which are removed.
1098 # #Getting coherent echoes which are removed.
1097 # # if len(novall[0]) > 0:
1099 # # if len(novall[0]) > 0:
1098 # #
1100 # #
1099 # # val_spc[novall[0],cross_pairs[0],ifreq,ih] = 1
1101 # # val_spc[novall[0],cross_pairs[0],ifreq,ih] = 1
1100 # # val_spc[novall[0],cross_pairs[1],ifreq,ih] = 1
1102 # # val_spc[novall[0],cross_pairs[1],ifreq,ih] = 1
1101 # # val_cspc[novall[0],ii,ifreq,ih] = 1
1103 # # val_cspc[novall[0],ii,ifreq,ih] = 1
1102 # #print("OUT NOVALL 1")
1104 # #print("OUT NOVALL 1")
1103 # try:
1105 # try:
1104 # pair = (self.channels[ii],self.channels[ii + 1])
1106 # pair = (self.channels[ii],self.channels[ii + 1])
1105 # except:
1107 # except:
1106 # pair = (99,99)
1108 # pair = (99,99)
1107 # #print("par ", pair)
1109 # #print("par ", pair)
1108 # if ( pair in self.crosspairs):
1110 # if ( pair in self.crosspairs):
1109 # q = self.crosspairs.index(pair)
1111 # q = self.crosspairs.index(pair)
1110 # #print("está aqui: ", q, (ii,ii + 1))
1112 # #print("está aqui: ", q, (ii,ii + 1))
1111 # new_a = numpy.delete(cspectra[:,q,ifreq,ih], noval[0])
1113 # new_a = numpy.delete(cspectra[:,q,ifreq,ih], noval[0])
1112 # cspectra[noval,q,ifreq,ih] = numpy.mean(new_a) #mean CrossSpectra
1114 # cspectra[noval,q,ifreq,ih] = numpy.mean(new_a) #mean CrossSpectra
1113 #
1115 #
1114 # #if channelA_ok:
1116 # #if channelA_ok:
1115 # #chA = self.channels.index(cross_pairs[0])
1117 # #chA = self.channels.index(cross_pairs[0])
1116 # new_b = numpy.delete(spectra[:,ii,ifreq,ih], noval[0])
1118 # new_b = numpy.delete(spectra[:,ii,ifreq,ih], noval[0])
1117 # spectra[noval,ii,ifreq,ih] = numpy.mean(new_b) #mean Spectra Pair A
1119 # spectra[noval,ii,ifreq,ih] = numpy.mean(new_b) #mean Spectra Pair A
1118 # #channelA_ok = False
1120 # #channelA_ok = False
1119 #
1121 #
1120 # # chB = self.channels.index(cross_pairs[1])
1122 # # chB = self.channels.index(cross_pairs[1])
1121 # # new_c = numpy.delete(spectra[:,chB,ifreq,ih], noval[0])
1123 # # new_c = numpy.delete(spectra[:,chB,ifreq,ih], noval[0])
1122 # # spectra[noval,chB,ifreq,ih] = numpy.mean(new_c) #mean Spectra Pair B
1124 # # spectra[noval,chB,ifreq,ih] = numpy.mean(new_c) #mean Spectra Pair B
1123 # #
1125 # #
1124 # # channelsProcssd.append(self.crosspairs[ii][0]) # save channel A
1126 # # channelsProcssd.append(self.crosspairs[ii][0]) # save channel A
1125 # # channelsProcssd.append(self.crosspairs[ii][1]) # save channel B
1127 # # channelsProcssd.append(self.crosspairs[ii][1]) # save channel B
1126 # '''
1128 # '''
1127 # ###ONLY FOR TEST:
1129 # ###ONLY FOR TEST:
1128 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1130 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1129 # func2clean = 10*numpy.log10(numpy.absolute(spectra[:,ii,ifreq,ih]))
1131 # func2clean = 10*numpy.log10(numpy.absolute(spectra[:,ii,ifreq,ih]))
1130 # y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
1132 # y_dist,binstep = numpy.histogram(func2clean,bins=range(int(min_val),int(max_val+2),step))
1131 # axs2[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
1133 # axs2[row_ax,col_ax].plot(binstep[:-1],newY,color='red')
1132 # axs2[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
1134 # axs2[row_ax,col_ax].plot(binstep[:-1],y_dist,color='green')
1133 # axs2[row_ax,col_ax].set_title("CH "+str(self.channels[ii]))
1135 # axs2[row_ax,col_ax].set_title("CH "+str(self.channels[ii]))
1134 # '''
1136 # '''
1135 # '''
1137 # '''
1136 # ###ONLY FOR TEST:
1138 # ###ONLY FOR TEST:
1137 # col_ax += 1 #contador de ploteo columnas
1139 # col_ax += 1 #contador de ploteo columnas
1138 # ##print(col_ax)
1140 # ##print(col_ax)
1139 # ###ONLY FOR TEST:
1141 # ###ONLY FOR TEST:
1140 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1142 # if ifreq ==fft_rev and ih==hei_rev: #TO VIEW A SIGNLE FREQUENCY
1141 # title = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km"
1143 # title = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km"
1142 # title2 = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km CLEANED"
1144 # title2 = str(dataOut.datatime)+" nFFT: "+str(ifreq)+" Alt: "+str(self.heights[ih])+ " km CLEANED"
1143 # fig.suptitle(title)
1145 # fig.suptitle(title)
1144 # fig2.suptitle(title2)
1146 # fig2.suptitle(title2)
1145 # plt.show()
1147 # plt.show()
1146 # '''
1148 # '''
1147 # ##################################################################################################
1149 # ##################################################################################################
1148 #
1150 #
1149 # #print("Getting average of the spectra and cross-spectra from incoherent echoes.")
1151 # #print("Getting average of the spectra and cross-spectra from incoherent echoes.")
1150 # out_spectra = numpy.zeros([self.nChan,self.nFFTPoints,self.nHeights], dtype=float) #+numpy.nan
1152 # out_spectra = numpy.zeros([self.nChan,self.nFFTPoints,self.nHeights], dtype=float) #+numpy.nan
1151 # out_cspectra = numpy.zeros([self.nPairs,self.nFFTPoints,self.nHeights], dtype=complex) #+numpy.nan
1153 # out_cspectra = numpy.zeros([self.nPairs,self.nFFTPoints,self.nHeights], dtype=complex) #+numpy.nan
1152 # for ih in range(self.nHeights):
1154 # for ih in range(self.nHeights):
1153 # for ifreq in range(self.nFFTPoints):
1155 # for ifreq in range(self.nFFTPoints):
1154 # for ich in range(self.nChan):
1156 # for ich in range(self.nChan):
1155 # tmp = spectra[:,ich,ifreq,ih]
1157 # tmp = spectra[:,ich,ifreq,ih]
1156 # valid = (numpy.isfinite(tmp[:])==True).nonzero()
1158 # valid = (numpy.isfinite(tmp[:])==True).nonzero()
1157 #
1159 #
1158 # if len(valid[0]) >0 :
1160 # if len(valid[0]) >0 :
1159 # out_spectra[ich,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
1161 # out_spectra[ich,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
1160 #
1162 #
1161 # for icr in range(self.nPairs):
1163 # for icr in range(self.nPairs):
1162 # tmp = numpy.squeeze(cspectra[:,icr,ifreq,ih])
1164 # tmp = numpy.squeeze(cspectra[:,icr,ifreq,ih])
1163 # valid = (numpy.isfinite(tmp)==True).nonzero()
1165 # valid = (numpy.isfinite(tmp)==True).nonzero()
1164 # if len(valid[0]) > 0:
1166 # if len(valid[0]) > 0:
1165 # out_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
1167 # out_cspectra[icr,ifreq,ih] = numpy.nansum(tmp)#/len(valid[0])
1166 #
1168 #
1167 # return out_spectra, out_cspectra
1169 # return out_spectra, out_cspectra
1168 #
1170 #
1169 # def REM_ISOLATED_POINTS(self,array,rth):
1171 # def REM_ISOLATED_POINTS(self,array,rth):
1170 # # import matplotlib.pyplot as plt
1172 # # import matplotlib.pyplot as plt
1171 # if rth == None :
1173 # if rth == None :
1172 # rth = 4
1174 # rth = 4
1173 # #print("REM ISO")
1175 # #print("REM ISO")
1174 # num_prof = len(array[0,:,0])
1176 # num_prof = len(array[0,:,0])
1175 # num_hei = len(array[0,0,:])
1177 # num_hei = len(array[0,0,:])
1176 # n2d = len(array[:,0,0])
1178 # n2d = len(array[:,0,0])
1177 #
1179 #
1178 # for ii in range(n2d) :
1180 # for ii in range(n2d) :
1179 # #print ii,n2d
1181 # #print ii,n2d
1180 # tmp = array[ii,:,:]
1182 # tmp = array[ii,:,:]
1181 # #print tmp.shape, array[ii,101,:],array[ii,102,:]
1183 # #print tmp.shape, array[ii,101,:],array[ii,102,:]
1182 #
1184 #
1183 # # fig = plt.figure(figsize=(6,5))
1185 # # fig = plt.figure(figsize=(6,5))
1184 # # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
1186 # # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
1185 # # ax = fig.add_axes([left, bottom, width, height])
1187 # # ax = fig.add_axes([left, bottom, width, height])
1186 # # x = range(num_prof)
1188 # # x = range(num_prof)
1187 # # y = range(num_hei)
1189 # # y = range(num_hei)
1188 # # cp = ax.contour(y,x,tmp)
1190 # # cp = ax.contour(y,x,tmp)
1189 # # ax.clabel(cp, inline=True,fontsize=10)
1191 # # ax.clabel(cp, inline=True,fontsize=10)
1190 # # plt.show()
1192 # # plt.show()
1191 #
1193 #
1192 # #indxs = WHERE(FINITE(tmp) AND tmp GT 0,cindxs)
1194 # #indxs = WHERE(FINITE(tmp) AND tmp GT 0,cindxs)
1193 # tmp = numpy.reshape(tmp,num_prof*num_hei)
1195 # tmp = numpy.reshape(tmp,num_prof*num_hei)
1194 # indxs1 = (numpy.isfinite(tmp)==True).nonzero()
1196 # indxs1 = (numpy.isfinite(tmp)==True).nonzero()
1195 # indxs2 = (tmp > 0).nonzero()
1197 # indxs2 = (tmp > 0).nonzero()
1196 #
1198 #
1197 # indxs1 = (indxs1[0])
1199 # indxs1 = (indxs1[0])
1198 # indxs2 = indxs2[0]
1200 # indxs2 = indxs2[0]
1199 # #indxs1 = numpy.array(indxs1[0])
1201 # #indxs1 = numpy.array(indxs1[0])
1200 # #indxs2 = numpy.array(indxs2[0])
1202 # #indxs2 = numpy.array(indxs2[0])
1201 # indxs = None
1203 # indxs = None
1202 # #print indxs1 , indxs2
1204 # #print indxs1 , indxs2
1203 # for iv in range(len(indxs2)):
1205 # for iv in range(len(indxs2)):
1204 # indv = numpy.array((indxs1 == indxs2[iv]).nonzero())
1206 # indv = numpy.array((indxs1 == indxs2[iv]).nonzero())
1205 # #print len(indxs2), indv
1207 # #print len(indxs2), indv
1206 # if len(indv[0]) > 0 :
1208 # if len(indv[0]) > 0 :
1207 # indxs = numpy.concatenate((indxs,indxs2[iv]), axis=None)
1209 # indxs = numpy.concatenate((indxs,indxs2[iv]), axis=None)
1208 # # print indxs
1210 # # print indxs
1209 # indxs = indxs[1:]
1211 # indxs = indxs[1:]
1210 # #print(indxs, len(indxs))
1212 # #print(indxs, len(indxs))
1211 # if len(indxs) < 4 :
1213 # if len(indxs) < 4 :
1212 # array[ii,:,:] = 0.
1214 # array[ii,:,:] = 0.
1213 # return
1215 # return
1214 #
1216 #
1215 # xpos = numpy.mod(indxs ,num_hei)
1217 # xpos = numpy.mod(indxs ,num_hei)
1216 # ypos = (indxs / num_hei)
1218 # ypos = (indxs / num_hei)
1217 # sx = numpy.argsort(xpos) # Ordering respect to "x" (time)
1219 # sx = numpy.argsort(xpos) # Ordering respect to "x" (time)
1218 # #print sx
1220 # #print sx
1219 # xpos = xpos[sx]
1221 # xpos = xpos[sx]
1220 # ypos = ypos[sx]
1222 # ypos = ypos[sx]
1221 #
1223 #
1222 # # *********************************** Cleaning isolated points **********************************
1224 # # *********************************** Cleaning isolated points **********************************
1223 # ic = 0
1225 # ic = 0
1224 # while True :
1226 # while True :
1225 # r = numpy.sqrt(list(numpy.power((xpos[ic]-xpos),2)+ numpy.power((ypos[ic]-ypos),2)))
1227 # r = numpy.sqrt(list(numpy.power((xpos[ic]-xpos),2)+ numpy.power((ypos[ic]-ypos),2)))
1226 # #no_coh = WHERE(FINITE(r) AND (r LE rth),cno_coh)
1228 # #no_coh = WHERE(FINITE(r) AND (r LE rth),cno_coh)
1227 # #plt.plot(r)
1229 # #plt.plot(r)
1228 # #plt.show()
1230 # #plt.show()
1229 # no_coh1 = (numpy.isfinite(r)==True).nonzero()
1231 # no_coh1 = (numpy.isfinite(r)==True).nonzero()
1230 # no_coh2 = (r <= rth).nonzero()
1232 # no_coh2 = (r <= rth).nonzero()
1231 # #print r, no_coh1, no_coh2
1233 # #print r, no_coh1, no_coh2
1232 # no_coh1 = numpy.array(no_coh1[0])
1234 # no_coh1 = numpy.array(no_coh1[0])
1233 # no_coh2 = numpy.array(no_coh2[0])
1235 # no_coh2 = numpy.array(no_coh2[0])
1234 # no_coh = None
1236 # no_coh = None
1235 # #print valid1 , valid2
1237 # #print valid1 , valid2
1236 # for iv in range(len(no_coh2)):
1238 # for iv in range(len(no_coh2)):
1237 # indv = numpy.array((no_coh1 == no_coh2[iv]).nonzero())
1239 # indv = numpy.array((no_coh1 == no_coh2[iv]).nonzero())
1238 # if len(indv[0]) > 0 :
1240 # if len(indv[0]) > 0 :
1239 # no_coh = numpy.concatenate((no_coh,no_coh2[iv]), axis=None)
1241 # no_coh = numpy.concatenate((no_coh,no_coh2[iv]), axis=None)
1240 # no_coh = no_coh[1:]
1242 # no_coh = no_coh[1:]
1241 # #print len(no_coh), no_coh
1243 # #print len(no_coh), no_coh
1242 # if len(no_coh) < 4 :
1244 # if len(no_coh) < 4 :
1243 # #print xpos[ic], ypos[ic], ic
1245 # #print xpos[ic], ypos[ic], ic
1244 # # plt.plot(r)
1246 # # plt.plot(r)
1245 # # plt.show()
1247 # # plt.show()
1246 # xpos[ic] = numpy.nan
1248 # xpos[ic] = numpy.nan
1247 # ypos[ic] = numpy.nan
1249 # ypos[ic] = numpy.nan
1248 #
1250 #
1249 # ic = ic + 1
1251 # ic = ic + 1
1250 # if (ic == len(indxs)) :
1252 # if (ic == len(indxs)) :
1251 # break
1253 # break
1252 # #print( xpos, ypos)
1254 # #print( xpos, ypos)
1253 #
1255 #
1254 # indxs = (numpy.isfinite(list(xpos))==True).nonzero()
1256 # indxs = (numpy.isfinite(list(xpos))==True).nonzero()
1255 # #print indxs[0]
1257 # #print indxs[0]
1256 # if len(indxs[0]) < 4 :
1258 # if len(indxs[0]) < 4 :
1257 # array[ii,:,:] = 0.
1259 # array[ii,:,:] = 0.
1258 # return
1260 # return
1259 #
1261 #
1260 # xpos = xpos[indxs[0]]
1262 # xpos = xpos[indxs[0]]
1261 # ypos = ypos[indxs[0]]
1263 # ypos = ypos[indxs[0]]
1262 # for i in range(0,len(ypos)):
1264 # for i in range(0,len(ypos)):
1263 # ypos[i]=int(ypos[i])
1265 # ypos[i]=int(ypos[i])
1264 # junk = tmp
1266 # junk = tmp
1265 # tmp = junk*0.0
1267 # tmp = junk*0.0
1266 #
1268 #
1267 # tmp[list(xpos + (ypos*num_hei))] = junk[list(xpos + (ypos*num_hei))]
1269 # tmp[list(xpos + (ypos*num_hei))] = junk[list(xpos + (ypos*num_hei))]
1268 # array[ii,:,:] = numpy.reshape(tmp,(num_prof,num_hei))
1270 # array[ii,:,:] = numpy.reshape(tmp,(num_prof,num_hei))
1269 #
1271 #
1270 # #print array.shape
1272 # #print array.shape
1271 # #tmp = numpy.reshape(tmp,(num_prof,num_hei))
1273 # #tmp = numpy.reshape(tmp,(num_prof,num_hei))
1272 # #print tmp.shape
1274 # #print tmp.shape
1273 #
1275 #
1274 # # fig = plt.figure(figsize=(6,5))
1276 # # fig = plt.figure(figsize=(6,5))
1275 # # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
1277 # # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
1276 # # ax = fig.add_axes([left, bottom, width, height])
1278 # # ax = fig.add_axes([left, bottom, width, height])
1277 # # x = range(num_prof)
1279 # # x = range(num_prof)
1278 # # y = range(num_hei)
1280 # # y = range(num_hei)
1279 # # cp = ax.contour(y,x,array[ii,:,:])
1281 # # cp = ax.contour(y,x,array[ii,:,:])
1280 # # ax.clabel(cp, inline=True,fontsize=10)
1282 # # ax.clabel(cp, inline=True,fontsize=10)
1281 # # plt.show()
1283 # # plt.show()
1282 # return array
1284 # return array
1283 #
1285 #
1284
1286
1285 class IntegrationFaradaySpectra(Operation):
1287 class IntegrationFaradaySpectra(Operation):
1286
1288
1287 __profIndex = 0
1289 __profIndex = 0
1288 __withOverapping = False
1290 __withOverapping = False
1289
1291
1290 __byTime = False
1292 __byTime = False
1291 __initime = None
1293 __initime = None
1292 __lastdatatime = None
1294 __lastdatatime = None
1293 __integrationtime = None
1295 __integrationtime = None
1294
1296
1295 __buffer_spc = None
1297 __buffer_spc = None
1296 __buffer_cspc = None
1298 __buffer_cspc = None
1297 __buffer_dc = None
1299 __buffer_dc = None
1298
1300
1299 __dataReady = False
1301 __dataReady = False
1300
1302
1301 __timeInterval = None
1303 __timeInterval = None
1302 n_ints = None #matriz de numero de integracions (CH,HEI)
1304 n_ints = None #matriz de numero de integracions (CH,HEI)
1303 n = None
1305 n = None
1304 minHei_ind = None
1306 minHei_ind = None
1305 maxHei_ind = None
1307 maxHei_ind = None
1306 navg = 1.0
1308 navg = 1.0
1307 factor = 0.0
1309 factor = 0.0
1308 dataoutliers = None # (CHANNELS, HEIGHTS)
1310 dataoutliers = None # (CHANNELS, HEIGHTS)
1309
1311
1310 _flagProfilesByRange = False
1312 _flagProfilesByRange = False
1311 _nProfilesByRange = 0
1313 _nProfilesByRange = 0
1312
1314
1313 def __init__(self):
1315 def __init__(self):
1314
1316
1315 Operation.__init__(self)
1317 Operation.__init__(self)
1316
1318
1317 def setup(self, dataOut,n=None, timeInterval=None, overlapping=False, DPL=None, minHei=None, maxHei=None, avg=1,factor=0.75):
1319 def setup(self, dataOut,n=None, timeInterval=None, overlapping=False, DPL=None, minHei=None, maxHei=None, avg=1,factor=0.75):
1318 """
1320 """
1319 Set the parameters of the integration class.
1321 Set the parameters of the integration class.
1320
1322
1321 Inputs:
1323 Inputs:
1322
1324
1323 n : Number of coherent integrations
1325 n : Number of coherent integrations
1324 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1326 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1325 overlapping :
1327 overlapping :
1326
1328
1327 """
1329 """
1328
1330
1329 self.__initime = None
1331 self.__initime = None
1330 self.__lastdatatime = 0
1332 self.__lastdatatime = 0
1331
1333
1332 self.__buffer_spc = []
1334 self.__buffer_spc = []
1333 self.__buffer_cspc = []
1335 self.__buffer_cspc = []
1334 self.__buffer_dc = 0
1336 self.__buffer_dc = 0
1335
1337
1336 self.__profIndex = 0
1338 self.__profIndex = 0
1337 self.__dataReady = False
1339 self.__dataReady = False
1338 self.__byTime = False
1340 self.__byTime = False
1339
1341
1340 self.factor = factor
1342 self.factor = factor
1341 self.navg = avg
1343 self.navg = avg
1342 #self.ByLags = dataOut.ByLags ###REDEFINIR
1344 #self.ByLags = dataOut.ByLags ###REDEFINIR
1343 self.ByLags = False
1345 self.ByLags = False
1344 self.maxProfilesInt = 0
1346 self.maxProfilesInt = 0
1345 self.__nChannels = dataOut.nChannels
1347 self.__nChannels = dataOut.nChannels
1346 if DPL != None:
1348 if DPL != None:
1347 self.DPL=DPL
1349 self.DPL=DPL
1348 else:
1350 else:
1349 #self.DPL=dataOut.DPL ###REDEFINIR
1351 #self.DPL=dataOut.DPL ###REDEFINIR
1350 self.DPL=0
1352 self.DPL=0
1351
1353
1352 if n is None and timeInterval is None:
1354 if n is None and timeInterval is None:
1353 raise ValueError("n or timeInterval should be specified ...")
1355 raise ValueError("n or timeInterval should be specified ...")
1354
1356
1355 if n is not None:
1357 if n is not None:
1356 self.n = int(n)
1358 self.n = int(n)
1357 else:
1359 else:
1358 self.__integrationtime = int(timeInterval)
1360 self.__integrationtime = int(timeInterval)
1359 self.n = None
1361 self.n = None
1360 self.__byTime = True
1362 self.__byTime = True
1361
1363
1362
1364
1363 if minHei == None:
1365 if minHei == None:
1364 minHei = self.dataOut.heightList[0]
1366 minHei = self.dataOut.heightList[0]
1365
1367
1366 if maxHei == None:
1368 if maxHei == None:
1367 maxHei = self.dataOut.heightList[-1]
1369 maxHei = self.dataOut.heightList[-1]
1368
1370
1369 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
1371 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
1370 print('minHei: %.2f is out of the heights range' % (minHei))
1372 print('minHei: %.2f is out of the heights range' % (minHei))
1371 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
1373 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
1372 minHei = self.dataOut.heightList[0]
1374 minHei = self.dataOut.heightList[0]
1373
1375
1374 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
1376 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
1375 print('maxHei: %.2f is out of the heights range' % (maxHei))
1377 print('maxHei: %.2f is out of the heights range' % (maxHei))
1376 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
1378 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
1377 maxHei = self.dataOut.heightList[-1]
1379 maxHei = self.dataOut.heightList[-1]
1378
1380
1379 ind_list1 = numpy.where(self.dataOut.heightList >= minHei)
1381 ind_list1 = numpy.where(self.dataOut.heightList >= minHei)
1380 ind_list2 = numpy.where(self.dataOut.heightList <= maxHei)
1382 ind_list2 = numpy.where(self.dataOut.heightList <= maxHei)
1381 self.minHei_ind = ind_list1[0][0]
1383 self.minHei_ind = ind_list1[0][0]
1382 self.maxHei_ind = ind_list2[0][-1]
1384 self.maxHei_ind = ind_list2[0][-1]
1383
1385
1384
1385 def putData(self, data_spc, data_cspc, data_dc):
1386 def putData(self, data_spc, data_cspc, data_dc):
1386 """
1387 """
1387 Add a profile to the __buffer_spc and increase in one the __profileIndex
1388 Add a profile to the __buffer_spc and increase in one the __profileIndex
1388
1389
1389 """
1390 """
1390
1391
1391 self.__buffer_spc.append(data_spc)
1392 self.__buffer_spc.append(data_spc)
1392
1393
1393 if self.__nChannels < 2:
1394 if self.__nChannels < 2:
1394 self.__buffer_cspc = None
1395 self.__buffer_cspc = None
1395 else:
1396 else:
1396 self.__buffer_cspc.append(data_cspc)
1397 self.__buffer_cspc.append(data_cspc)
1397
1398
1398 if data_dc is None:
1399 if data_dc is None:
1399 self.__buffer_dc = None
1400 self.__buffer_dc = None
1400 else:
1401 else:
1401 self.__buffer_dc += data_dc
1402 self.__buffer_dc += data_dc
1402
1403
1403 self.__profIndex += 1
1404 self.__profIndex += 1
1404
1405
1405 return
1406 return
1406
1407
1407 def hildebrand_sekhon_Integration(self,sortdata,navg, factor):
1408 def hildebrand_sekhon_Integration(self,sortdata,navg, factor):
1408 #data debe estar ordenado
1409 #data debe estar ordenado
1409 #sortdata = numpy.sort(data, axis=None)
1410 #sortdata = numpy.sort(data, axis=None)
1410 #sortID=data.argsort()
1411 #sortID=data.argsort()
1411 lenOfData = len(sortdata)
1412 lenOfData = len(sortdata)
1412 nums_min = lenOfData*factor
1413 nums_min = lenOfData*factor
1413 if nums_min <= 5:
1414 if nums_min <= 5:
1414 nums_min = 5
1415 nums_min = 5
1415 sump = 0.
1416 sump = 0.
1416 sumq = 0.
1417 sumq = 0.
1417 j = 0
1418 j = 0
1418 cont = 1
1419 cont = 1
1419 while((cont == 1)and(j < lenOfData)):
1420 while((cont == 1)and(j < lenOfData)):
1420 sump += sortdata[j]
1421 sump += sortdata[j]
1421 sumq += sortdata[j]**2
1422 sumq += sortdata[j]**2
1422 if j > nums_min:
1423 if j > nums_min:
1423 rtest = float(j)/(j-1) + 1.0/navg
1424 rtest = float(j)/(j-1) + 1.0/navg
1424 if ((sumq*j) > (rtest*sump**2)):
1425 if ((sumq*j) > (rtest*sump**2)):
1425 j = j - 1
1426 j = j - 1
1426 sump = sump - sortdata[j]
1427 sump = sump - sortdata[j]
1427 sumq = sumq - sortdata[j]**2
1428 sumq = sumq - sortdata[j]**2
1428 cont = 0
1429 cont = 0
1429 j += 1
1430 j += 1
1430 #lnoise = sump / j
1431 #lnoise = sump / j
1431 #print("H S done")
1432 #print("H S done")
1432 #return j,sortID
1433 #return j,sortID
1433 return j
1434 return j
1434
1435
1435
1436
1436 def pushData(self):
1437 def pushData(self):
1437 """
1438 """
1438 Return the sum of the last profiles and the profiles used in the sum.
1439 Return the sum of the last profiles and the profiles used in the sum.
1439
1440
1440 Affected:
1441 Affected:
1441
1442
1442 self.__profileIndex
1443 self.__profileIndex
1443
1444
1444 """
1445 """
1445 bufferH=None
1446 bufferH=None
1446 buffer=None
1447 buffer=None
1447 buffer1=None
1448 buffer1=None
1448 buffer_cspc=None
1449 buffer_cspc=None
1449 #print("aes: ", self.__buffer_cspc)
1450 #print("aes: ", self.__buffer_cspc)
1450 self.__buffer_spc=numpy.array(self.__buffer_spc)
1451 self.__buffer_spc=numpy.array(self.__buffer_spc)
1451 if self.__nChannels > 1 :
1452 if self.__nChannels > 1 :
1452 self.__buffer_cspc=numpy.array(self.__buffer_cspc)
1453 self.__buffer_cspc=numpy.array(self.__buffer_cspc)
1453
1454
1454 #print("FREQ_DC",self.__buffer_spc.shape,self.__buffer_cspc.shape)
1455 #print("FREQ_DC",self.__buffer_spc.shape,self.__buffer_cspc.shape)
1455
1456
1456 freq_dc = int(self.__buffer_spc.shape[2] / 2)
1457 freq_dc = int(self.__buffer_spc.shape[2] / 2)
1457 #print("FREQ_DC",freq_dc,self.__buffer_spc.shape,self.nHeights)
1458 #print("FREQ_DC",freq_dc,self.__buffer_spc.shape,self.nHeights)
1458
1459
1459 self.dataOutliers = numpy.zeros((self.nChannels,self.nHeights)) # --> almacen de outliers
1460 self.dataOutliers = numpy.zeros((self.nChannels,self.nHeights)) # --> almacen de outliers
1460
1461
1461 for k in range(self.minHei_ind,self.maxHei_ind):
1462 for k in range(self.minHei_ind,self.maxHei_ind):
1462 if self.__nChannels > 1:
1463 if self.__nChannels > 1:
1463 buffer_cspc=numpy.copy(self.__buffer_cspc[:,:,:,k])
1464 buffer_cspc=numpy.copy(self.__buffer_cspc[:,:,:,k])
1464
1465
1465 outliers_IDs_cspc=[]
1466 outliers_IDs_cspc=[]
1466 cspc_outliers_exist=False
1467 cspc_outliers_exist=False
1467 for i in range(self.nChannels):#dataOut.nChannels):
1468 for i in range(self.nChannels):#dataOut.nChannels):
1468
1469
1469 buffer1=numpy.copy(self.__buffer_spc[:,i,:,k])
1470 buffer1=numpy.copy(self.__buffer_spc[:,i,:,k])
1470 indexes=[]
1471 indexes=[]
1471 #sortIDs=[]
1472 #sortIDs=[]
1472 outliers_IDs=[]
1473 outliers_IDs=[]
1473
1474
1474 for j in range(self.nProfiles): #frecuencias en el tiempo
1475 for j in range(self.nProfiles): #frecuencias en el tiempo
1475 # if i==0 and j==freq_dc: #NOT CONSIDERING DC PROFILE AT CHANNEL 0
1476 # if i==0 and j==freq_dc: #NOT CONSIDERING DC PROFILE AT CHANNEL 0
1476 # continue
1477 # continue
1477 # if i==1 and j==0: #NOT CONSIDERING DC PROFILE AT CHANNEL 1
1478 # if i==1 and j==0: #NOT CONSIDERING DC PROFILE AT CHANNEL 1
1478 # continue
1479 # continue
1479 buffer=buffer1[:,j]
1480 buffer=buffer1[:,j]
1480 sortdata = numpy.sort(buffer, axis=None)
1481 sortdata = numpy.sort(buffer, axis=None)
1481
1482
1482 sortID=buffer.argsort()
1483 sortID=buffer.argsort()
1483 index = _noise.hildebrand_sekhon2(sortdata,self.navg)
1484 index = _noise.hildebrand_sekhon2(sortdata,self.navg)
1484
1485
1485 #index,sortID=self.hildebrand_sekhon_Integration(buffer,1,self.factor)
1486 #index,sortID=self.hildebrand_sekhon_Integration(buffer,1,self.factor)
1486
1487
1487 # fig,ax = plt.subplots()
1488 # fig,ax = plt.subplots()
1488 # ax.set_title(str(k)+" "+str(j))
1489 # ax.set_title(str(k)+" "+str(j))
1489 # x=range(len(sortdata))
1490 # x=range(len(sortdata))
1490 # ax.scatter(x,sortdata)
1491 # ax.scatter(x,sortdata)
1491 # ax.axvline(index)
1492 # ax.axvline(index)
1492 # plt.show()
1493 # plt.show()
1493
1494
1494 indexes.append(index)
1495 indexes.append(index)
1495 #sortIDs.append(sortID)
1496 #sortIDs.append(sortID)
1496 outliers_IDs=numpy.append(outliers_IDs,sortID[index:])
1497 outliers_IDs=numpy.append(outliers_IDs,sortID[index:])
1497
1498
1498 #print("Outliers: ",outliers_IDs)
1499 #print("Outliers: ",outliers_IDs)
1499 outliers_IDs=numpy.array(outliers_IDs)
1500 outliers_IDs=numpy.array(outliers_IDs)
1500 outliers_IDs=outliers_IDs.ravel()
1501 outliers_IDs=outliers_IDs.ravel()
1501 outliers_IDs=numpy.unique(outliers_IDs)
1502 outliers_IDs=numpy.unique(outliers_IDs)
1502 outliers_IDs=outliers_IDs.astype(numpy.dtype('int64'))
1503 outliers_IDs=outliers_IDs.astype(numpy.dtype('int64'))
1503 indexes=numpy.array(indexes)
1504 indexes=numpy.array(indexes)
1504 indexmin=numpy.min(indexes)
1505 indexmin=numpy.min(indexes)
1505
1506
1506
1507
1507 #print(indexmin,buffer1.shape[0], k)
1508 #print(indexmin,buffer1.shape[0], k)
1508
1509
1509 # fig,ax = plt.subplots()
1510 # fig,ax = plt.subplots()
1510 # ax.plot(sortdata)
1511 # ax.plot(sortdata)
1511 # ax2 = ax.twinx()
1512 # ax2 = ax.twinx()
1512 # x=range(len(indexes))
1513 # x=range(len(indexes))
1513 # #plt.scatter(x,indexes)
1514 # #plt.scatter(x,indexes)
1514 # ax2.scatter(x,indexes)
1515 # ax2.scatter(x,indexes)
1515 # plt.show()
1516 # plt.show()
1516
1517
1517 if indexmin != buffer1.shape[0]:
1518 if indexmin != buffer1.shape[0]:
1518 if self.__nChannels > 1:
1519 if self.__nChannels > 1:
1519 cspc_outliers_exist= True
1520 cspc_outliers_exist= True
1520
1521
1521 lt=outliers_IDs
1522 lt=outliers_IDs
1522 #avg=numpy.mean(buffer1[[t for t in range(buffer1.shape[0]) if t not in lt],:],axis=0)
1523 #avg=numpy.mean(buffer1[[t for t in range(buffer1.shape[0]) if t not in lt],:],axis=0)
1523
1524
1524 for p in list(outliers_IDs):
1525 for p in list(outliers_IDs):
1525 #buffer1[p,:]=avg
1526 #buffer1[p,:]=avg
1526 buffer1[p,:] = numpy.NaN
1527 buffer1[p,:] = numpy.NaN
1527
1528
1528 self.dataOutliers[i,k] = len(outliers_IDs)
1529 self.dataOutliers[i,k] = len(outliers_IDs)
1529
1530
1530
1531
1531 self.__buffer_spc[:,i,:,k]=numpy.copy(buffer1)
1532 self.__buffer_spc[:,i,:,k]=numpy.copy(buffer1)
1532
1533
1533
1534
1534 if self.__nChannels > 1:
1535 if self.__nChannels > 1:
1535 outliers_IDs_cspc=numpy.append(outliers_IDs_cspc,outliers_IDs)
1536 outliers_IDs_cspc=numpy.append(outliers_IDs_cspc,outliers_IDs)
1536
1537
1537
1538
1538 if self.__nChannels > 1:
1539 if self.__nChannels > 1:
1539 outliers_IDs_cspc=outliers_IDs_cspc.astype(numpy.dtype('int64'))
1540 outliers_IDs_cspc=outliers_IDs_cspc.astype(numpy.dtype('int64'))
1540 if cspc_outliers_exist:
1541 if cspc_outliers_exist:
1541
1542
1542 lt=outliers_IDs_cspc
1543 lt=outliers_IDs_cspc
1543
1544
1544 #avg=numpy.mean(buffer_cspc[[t for t in range(buffer_cspc.shape[0]) if t not in lt],:],axis=0)
1545 #avg=numpy.mean(buffer_cspc[[t for t in range(buffer_cspc.shape[0]) if t not in lt],:],axis=0)
1545 for p in list(outliers_IDs_cspc):
1546 for p in list(outliers_IDs_cspc):
1546 #buffer_cspc[p,:]=avg
1547 #buffer_cspc[p,:]=avg
1547 buffer_cspc[p,:] = numpy.NaN
1548 buffer_cspc[p,:] = numpy.NaN
1548
1549
1549 if self.__nChannels > 1:
1550 if self.__nChannels > 1:
1550 self.__buffer_cspc[:,:,:,k]=numpy.copy(buffer_cspc)
1551 self.__buffer_cspc[:,:,:,k]=numpy.copy(buffer_cspc)
1551
1552
1552
1553
1553
1554
1554
1555
1555 nOutliers = len(outliers_IDs)
1556 nOutliers = len(outliers_IDs)
1556 #print("Outliers n: ",self.dataOutliers,nOutliers)
1557 #print("Outliers n: ",self.dataOutliers,nOutliers)
1557 buffer=None
1558 buffer=None
1558 bufferH=None
1559 bufferH=None
1559 buffer1=None
1560 buffer1=None
1560 buffer_cspc=None
1561 buffer_cspc=None
1561
1562
1562
1563
1563 buffer=None
1564 buffer=None
1564
1565
1565 #data_spc = numpy.sum(self.__buffer_spc,axis=0)
1566 #data_spc = numpy.sum(self.__buffer_spc,axis=0)
1566 data_spc = numpy.nansum(self.__buffer_spc,axis=0)
1567 data_spc = numpy.nansum(self.__buffer_spc,axis=0)
1567 if self.__nChannels > 1:
1568 if self.__nChannels > 1:
1568 #data_cspc = numpy.sum(self.__buffer_cspc,axis=0)
1569 #data_cspc = numpy.sum(self.__buffer_cspc,axis=0)
1569 data_cspc = numpy.nansum(self.__buffer_cspc,axis=0)
1570 data_cspc = numpy.nansum(self.__buffer_cspc,axis=0)
1570 else:
1571 else:
1571 data_cspc = None
1572 data_cspc = None
1572 data_dc = self.__buffer_dc
1573 data_dc = self.__buffer_dc
1573 #(CH, HEIGH)
1574 #(CH, HEIGH)
1574 self.maxProfilesInt = self.__profIndex - 1
1575 self.maxProfilesInt = self.__profIndex - 1
1575 n = self.__profIndex - self.dataOutliers # n becomes a matrix
1576 n = self.__profIndex - self.dataOutliers # n becomes a matrix
1576
1577
1577 self.__buffer_spc = []
1578 self.__buffer_spc = []
1578 self.__buffer_cspc = []
1579 self.__buffer_cspc = []
1579 self.__buffer_dc = 0
1580 self.__buffer_dc = 0
1580 self.__profIndex = 0
1581 self.__profIndex = 0
1581 #print("cleaned ",data_cspc)
1582 #print("cleaned ",data_cspc)
1582 return data_spc, data_cspc, data_dc, n
1583 return data_spc, data_cspc, data_dc, n
1583
1584
1584 def byProfiles(self, *args):
1585 def byProfiles(self, *args):
1585
1586
1586 self.__dataReady = False
1587 self.__dataReady = False
1587 avgdata_spc = None
1588 avgdata_spc = None
1588 avgdata_cspc = None
1589 avgdata_cspc = None
1589 avgdata_dc = None
1590 avgdata_dc = None
1590
1591
1591 self.putData(*args)
1592 self.putData(*args)
1592
1593
1593 if self.__profIndex == self.n:
1594 if self.__profIndex == self.n:
1594
1595
1595 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1596 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1596 self.n_ints = n
1597 self.n_ints = n
1597 self.__dataReady = True
1598 self.__dataReady = True
1598
1599
1599 return avgdata_spc, avgdata_cspc, avgdata_dc
1600 return avgdata_spc, avgdata_cspc, avgdata_dc
1600
1601
1601 def byTime(self, datatime, *args):
1602 def byTime(self, datatime, *args):
1602
1603
1603 self.__dataReady = False
1604 self.__dataReady = False
1604 avgdata_spc = None
1605 avgdata_spc = None
1605 avgdata_cspc = None
1606 avgdata_cspc = None
1606 avgdata_dc = None
1607 avgdata_dc = None
1607
1608
1608 self.putData(*args)
1609 self.putData(*args)
1609
1610
1610 if (datatime - self.__initime) >= self.__integrationtime:
1611 if (datatime - self.__initime) >= self.__integrationtime:
1611 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1612 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1612 self.n_ints = n
1613 self.n_ints = n
1613 self.__dataReady = True
1614 self.__dataReady = True
1614
1615
1615 return avgdata_spc, avgdata_cspc, avgdata_dc
1616 return avgdata_spc, avgdata_cspc, avgdata_dc
1616
1617
1617 def integrate(self, datatime, *args):
1618 def integrate(self, datatime, *args):
1618
1619
1619 if self.__profIndex == 0:
1620 if self.__profIndex == 0:
1620 self.__initime = datatime
1621 self.__initime = datatime
1621
1622
1622 if self.__byTime:
1623 if self.__byTime:
1623 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1624 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1624 datatime, *args)
1625 datatime, *args)
1625 else:
1626 else:
1626 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1627 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1627
1628
1628 if not self.__dataReady:
1629 if not self.__dataReady:
1629 return None, None, None, None
1630 return None, None, None, None
1630
1631
1631 #print("integrate", avgdata_cspc)
1632 #print("integrate", avgdata_cspc)
1632 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1633 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1633
1634
1634 def run(self, dataOut, n=None, DPL = None,timeInterval=None, overlapping=False, minHei=None, maxHei=None, avg=1, factor=0.75):
1635 def run(self, dataOut, n=None, DPL = None,timeInterval=None, overlapping=False, minHei=None, maxHei=None, avg=1, factor=0.75):
1635 self.dataOut = dataOut
1636 self.dataOut = dataOut
1636 if n == 1:
1637 if n == 1:
1637 return self.dataOut
1638 return self.dataOut
1638 self.dataOut.processingHeaderObj.timeIncohInt = timeInterval
1639 self.dataOut.processingHeaderObj.timeIncohInt = timeInterval
1639
1640
1640 if dataOut.flagProfilesByRange == True:
1641 if dataOut.flagProfilesByRange:
1641 self._flagProfilesByRange = True
1642 self._flagProfilesByRange = True
1642
1643
1643 if self.dataOut.nChannels == 1:
1644 if self.dataOut.nChannels == 1:
1644 self.dataOut.data_cspc = None #si es un solo canal no vale la pena acumular DATOS
1645 self.dataOut.data_cspc = None #si es un solo canal no vale la pena acumular DATOS
1645 #print("IN spc:", self.dataOut.data_spc.shape, self.dataOut.data_cspc)
1646 #print("IN spc:", self.dataOut.data_spc.shape, self.dataOut.data_cspc)
1646 if not self.isConfig:
1647 if not self.isConfig:
1647 self.setup(self.dataOut, n, timeInterval, overlapping,DPL ,minHei, maxHei, avg, factor)
1648 self.setup(self.dataOut, n, timeInterval, overlapping,DPL ,minHei, maxHei, avg, factor)
1648 self.isConfig = True
1649 self.isConfig = True
1649
1650
1650 if not self.ByLags:
1651 if not self.ByLags:
1651 self.nProfiles=self.dataOut.nProfiles
1652 self.nProfiles=self.dataOut.nProfiles
1652 self.nChannels=self.dataOut.nChannels
1653 self.nChannels=self.dataOut.nChannels
1653 self.nHeights=self.dataOut.nHeights
1654 self.nHeights=self.dataOut.nHeights
1654 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(self.dataOut.utctime,
1655 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(self.dataOut.utctime,
1655 self.dataOut.data_spc,
1656 self.dataOut.data_spc,
1656 self.dataOut.data_cspc,
1657 self.dataOut.data_cspc,
1657 self.dataOut.data_dc)
1658 self.dataOut.data_dc)
1658 else:
1659 else:
1659 self.nProfiles=self.dataOut.nProfiles
1660 self.nProfiles=self.dataOut.nProfiles
1660 self.nChannels=self.dataOut.nChannels
1661 self.nChannels=self.dataOut.nChannels
1661 self.nHeights=self.dataOut.nHeights
1662 self.nHeights=self.dataOut.nHeights
1662 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(self.dataOut.utctime,
1663 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(self.dataOut.utctime,
1663 self.dataOut.dataLag_spc,
1664 self.dataOut.dataLag_spc,
1664 self.dataOut.dataLag_cspc,
1665 self.dataOut.dataLag_cspc,
1665 self.dataOut.dataLag_dc)
1666 self.dataOut.dataLag_dc)
1666 self.dataOut.flagNoData = True
1667 self.dataOut.flagNoData = True
1667
1668
1668 if self._flagProfilesByRange:
1669 if self._flagProfilesByRange:
1669 dataOut.flagProfilesByRange = True
1670 dataOut.flagProfilesByRange = True
1670 self._nProfilesByRange += dataOut.nProfilesByRange
1671 self._nProfilesByRange += dataOut.nProfilesByRange
1671
1672
1672 if self.__dataReady:
1673 if self.__dataReady:
1673
1674
1674 if not self.ByLags:
1675 if not self.ByLags:
1675 if self.nChannels == 1:
1676 if self.nChannels == 1:
1676 #print("f int", avgdata_spc.shape)
1677 #print("f int", avgdata_spc.shape)
1677 self.dataOut.data_spc = avgdata_spc
1678 self.dataOut.data_spc = avgdata_spc
1678 self.dataOut.data_cspc = None
1679 self.dataOut.data_cspc = None
1679 else:
1680 else:
1680 self.dataOut.data_spc = numpy.squeeze(avgdata_spc)
1681 self.dataOut.data_spc = numpy.squeeze(avgdata_spc)
1681 self.dataOut.data_cspc = numpy.squeeze(avgdata_cspc)
1682 self.dataOut.data_cspc = numpy.squeeze(avgdata_cspc)
1682 self.dataOut.data_dc = avgdata_dc
1683 self.dataOut.data_dc = avgdata_dc
1683 self.dataOut.data_outlier = self.dataOutliers
1684 self.dataOut.data_outlier = self.dataOutliers
1684
1685
1685
1686
1686 else:
1687 else:
1687 self.dataOut.dataLag_spc = avgdata_spc
1688 self.dataOut.dataLag_spc = avgdata_spc
1688 self.dataOut.dataLag_cspc = avgdata_cspc
1689 self.dataOut.dataLag_cspc = avgdata_cspc
1689 self.dataOut.dataLag_dc = avgdata_dc
1690 self.dataOut.dataLag_dc = avgdata_dc
1690
1691
1691 self.dataOut.data_spc=self.dataOut.dataLag_spc[:,:,:,self.dataOut.LagPlot]
1692 self.dataOut.data_spc=self.dataOut.dataLag_spc[:,:,:,self.dataOut.LagPlot]
1692 self.dataOut.data_cspc=self.dataOut.dataLag_cspc[:,:,:,self.dataOut.LagPlot]
1693 self.dataOut.data_cspc=self.dataOut.dataLag_cspc[:,:,:,self.dataOut.LagPlot]
1693 self.dataOut.data_dc=self.dataOut.dataLag_dc[:,:,self.dataOut.LagPlot]
1694 self.dataOut.data_dc=self.dataOut.dataLag_dc[:,:,self.dataOut.LagPlot]
1694
1695
1695
1696
1696 self.dataOut.nIncohInt *= self.n_ints
1697 self.dataOut.nIncohInt *= self.n_ints
1697 #print("maxProfilesInt: ",self.maxProfilesInt)
1698 #print("maxProfilesInt: ",self.maxProfilesInt)
1698
1699
1699 self.dataOut.utctime = avgdatatime
1700 self.dataOut.utctime = avgdatatime
1700 self.dataOut.flagNoData = False
1701 self.dataOut.flagNoData = False
1701
1702
1702 dataOut.nProfilesByRange = self._nProfilesByRange
1703 dataOut.nProfilesByRange = self._nProfilesByRange
1703 self._nProfilesByRange = 0
1704 self._nProfilesByRange = numpy.zeros(len(dataOut.heightList))
1704 self._flagProfilesByRange = False
1705 self._flagProfilesByRange = False
1705
1706
1706 # #update Processing Header:
1707 # #update Processing Header:
1707 # self.dataOut.processingHeaderObj.nIncohInt =
1708 # self.dataOut.processingHeaderObj.nIncohInt =
1708 # self.dataOut.processingHeaderObj.nFFTPoints = self.dataOut.nFFTPoints
1709 # self.dataOut.processingHeaderObj.nFFTPoints = self.dataOut.nFFTPoints
1709
1710
1710 #print("Faraday Integration DONE...", self.dataOut.data_cspc)
1711 #print("Faraday Integration DONE...", self.dataOut.data_cspc)
1711 #print(self.dataOut.flagNoData)
1712 #print(self.dataOut.flagNoData)
1712 return self.dataOut
1713 return self.dataOut
1713
1714
1714
1715
1715
1716
1716 class removeInterference(Operation):
1717 class removeInterference(Operation):
1717
1718
1718 def removeInterference3(self, min_hei = None, max_hei = None):
1719 def removeInterference3(self, min_hei = None, max_hei = None):
1719
1720
1720 jspectra = self.dataOut.data_spc
1721 jspectra = self.dataOut.data_spc
1721 #jcspectra = self.dataOut.data_cspc
1722 #jcspectra = self.dataOut.data_cspc
1722 jnoise = self.dataOut.getNoise()
1723 jnoise = self.dataOut.getNoise()
1723 num_incoh = self.dataOut.max_nIncohInt
1724 num_incoh = self.dataOut.max_nIncohInt
1724 #print(jspectra.shape)
1725 #print(jspectra.shape)
1725 num_channel, num_prof, num_hei = jspectra.shape
1726 num_channel, num_prof, num_hei = jspectra.shape
1726 minHei = min_hei
1727 minHei = min_hei
1727 maxHei = max_hei
1728 maxHei = max_hei
1728 ########################################################################
1729 ########################################################################
1729 if minHei == None or (minHei < self.dataOut.heightList[0]):
1730 if minHei == None or (minHei < self.dataOut.heightList[0]):
1730 minHei = self.dataOut.heightList[0]
1731 minHei = self.dataOut.heightList[0]
1731
1732
1732 if maxHei == None or (maxHei > self.dataOut.heightList[-1]):
1733 if maxHei == None or (maxHei > self.dataOut.heightList[-1]):
1733 maxHei = self.dataOut.heightList[-1]
1734 maxHei = self.dataOut.heightList[-1]
1734 minIndex = 0
1735 minIndex = 0
1735 maxIndex = 0
1736 maxIndex = 0
1736 heights = self.dataOut.heightList
1737 heights = self.dataOut.heightList
1737
1738
1738 inda = numpy.where(heights >= minHei)
1739 inda = numpy.where(heights >= minHei)
1739 indb = numpy.where(heights <= maxHei)
1740 indb = numpy.where(heights <= maxHei)
1740
1741
1741 try:
1742 try:
1742 minIndex = inda[0][0]
1743 minIndex = inda[0][0]
1743 except:
1744 except:
1744 minIndex = 0
1745 minIndex = 0
1745 try:
1746 try:
1746 maxIndex = indb[0][-1]
1747 maxIndex = indb[0][-1]
1747 except:
1748 except:
1748 maxIndex = len(heights)
1749 maxIndex = len(heights)
1749
1750
1750 if (minIndex < 0) or (minIndex > maxIndex):
1751 if (minIndex < 0) or (minIndex > maxIndex):
1751 raise ValueError("some value in (%d,%d) is not valid" % (
1752 raise ValueError("some value in (%d,%d) is not valid" % (
1752 minIndex, maxIndex))
1753 minIndex, maxIndex))
1753 if (maxIndex >= self.dataOut.nHeights):
1754 if (maxIndex >= self.dataOut.nHeights):
1754 maxIndex = self.dataOut.nHeights - 1
1755 maxIndex = self.dataOut.nHeights - 1
1755
1756
1756 ########################################################################
1757 ########################################################################
1757
1758
1758
1759
1759 #dataOut.max_nIncohInt * dataOut.nCohInt
1760 #dataOut.max_nIncohInt * dataOut.nCohInt
1760 norm = self.dataOut.nIncohInt /self.dataOut.max_nIncohInt
1761 norm = self.dataOut.nIncohInt /self.dataOut.max_nIncohInt
1761 #print(norm.shape)
1762 #print(norm.shape)
1762 # Subrutina de Remocion de la Interferencia
1763 # Subrutina de Remocion de la Interferencia
1763 for ich in range(num_channel):
1764 for ich in range(num_channel):
1764 # Se ordena los espectros segun su potencia (menor a mayor)
1765 # Se ordena los espectros segun su potencia (menor a mayor)
1765 #power = jspectra[ich, mask_prof, :]
1766 #power = jspectra[ich, mask_prof, :]
1766 interf = jspectra[ich, :, minIndex:maxIndex]
1767 interf = jspectra[ich, :, minIndex:maxIndex]
1767 #print(interf.shape)
1768 #print(interf.shape)
1768 inttef = interf.mean(axis=1)
1769 inttef = interf.mean(axis=1)
1769
1770
1770 for hei in range(num_hei):
1771 for hei in range(num_hei):
1771 temp = jspectra[ich,:, hei]
1772 temp = jspectra[ich,:, hei]
1772 temp -= inttef
1773 temp -= inttef
1773 temp += jnoise[ich]*norm[ich,hei]
1774 temp += jnoise[ich]*norm[ich,hei]
1774 jspectra[ich,:, hei] = temp
1775 jspectra[ich,:, hei] = temp
1775
1776
1776 # Guardar Resultados
1777 # Guardar Resultados
1777 self.dataOut.data_spc = jspectra
1778 self.dataOut.data_spc = jspectra
1778 #self.dataOut.data_cspc = jcspectra
1779 #self.dataOut.data_cspc = jcspectra
1779
1780
1780 return 1
1781 return 1
1781
1782
1782 def removeInterference2(self):
1783 def removeInterference2(self):
1783
1784
1784 cspc = self.dataOut.data_cspc
1785 cspc = self.dataOut.data_cspc
1785 spc = self.dataOut.data_spc
1786 spc = self.dataOut.data_spc
1786 Heights = numpy.arange(cspc.shape[2])
1787 Heights = numpy.arange(cspc.shape[2])
1787 realCspc = numpy.abs(cspc)
1788 realCspc = numpy.abs(cspc)
1788
1789
1789 for i in range(cspc.shape[0]):
1790 for i in range(cspc.shape[0]):
1790 LinePower= numpy.sum(realCspc[i], axis=0)
1791 LinePower= numpy.sum(realCspc[i], axis=0)
1791 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
1792 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
1792 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
1793 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
1793 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
1794 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
1794 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
1795 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
1795 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
1796 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
1796
1797
1797
1798
1798 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
1799 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
1799 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
1800 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
1800 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
1801 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
1801 cspc[i,InterferenceRange,:] = numpy.NaN
1802 cspc[i,InterferenceRange,:] = numpy.NaN
1802
1803
1803 self.dataOut.data_cspc = cspc
1804 self.dataOut.data_cspc = cspc
1804
1805
1805 def removeInterference(self, interf = 2, hei_interf = None, nhei_interf = None, offhei_interf = None):
1806 def removeInterference(self, interf = 2, hei_interf = None, nhei_interf = None, offhei_interf = None):
1806
1807
1807 jspectra = self.dataOut.data_spc
1808 jspectra = self.dataOut.data_spc
1808 jcspectra = self.dataOut.data_cspc
1809 jcspectra = self.dataOut.data_cspc
1809 jnoise = self.dataOut.getNoise()
1810 jnoise = self.dataOut.getNoise()
1810 #num_incoh = self.dataOut.nIncohInt
1811 #num_incoh = self.dataOut.nIncohInt
1811 num_incoh = self.dataOut.max_nIncohInt
1812 num_incoh = self.dataOut.max_nIncohInt
1812 #print("spc: ", jspectra.shape, jcspectra)
1813 #print("spc: ", jspectra.shape, jcspectra)
1813 num_channel = jspectra.shape[0]
1814 num_channel = jspectra.shape[0]
1814 num_prof = jspectra.shape[1]
1815 num_prof = jspectra.shape[1]
1815 num_hei = jspectra.shape[2]
1816 num_hei = jspectra.shape[2]
1816
1817
1817 # hei_interf
1818 # hei_interf
1818 if hei_interf is None:
1819 if hei_interf is None:
1819 count_hei = int(num_hei / 2) # a half of total ranges
1820 count_hei = int(num_hei / 2) # a half of total ranges
1820 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
1821 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
1821 hei_interf = numpy.asarray(hei_interf)[0]
1822 hei_interf = numpy.asarray(hei_interf)[0]
1822 #print(hei_interf)
1823 #print(hei_interf)
1823 # nhei_interf
1824 # nhei_interf
1824 if (nhei_interf == None):
1825 if (nhei_interf == None):
1825 nhei_interf = 5
1826 nhei_interf = 5
1826 if (nhei_interf < 1):
1827 if (nhei_interf < 1):
1827 nhei_interf = 1
1828 nhei_interf = 1
1828 if (nhei_interf > count_hei):
1829 if (nhei_interf > count_hei):
1829 nhei_interf = count_hei
1830 nhei_interf = count_hei
1830 if (offhei_interf == None):
1831 if (offhei_interf == None):
1831 offhei_interf = 0
1832 offhei_interf = 0
1832
1833
1833 ind_hei = list(range(num_hei))
1834 ind_hei = list(range(num_hei))
1834 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
1835 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
1835 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
1836 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
1836 mask_prof = numpy.asarray(list(range(num_prof)))
1837 mask_prof = numpy.asarray(list(range(num_prof)))
1837 num_mask_prof = mask_prof.size
1838 num_mask_prof = mask_prof.size
1838 comp_mask_prof = [0, num_prof / 2]
1839 comp_mask_prof = [0, num_prof / 2]
1839
1840
1840 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
1841 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
1841 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
1842 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
1842 jnoise = numpy.nan
1843 jnoise = numpy.nan
1843 noise_exist = jnoise[0] < numpy.Inf
1844 noise_exist = jnoise[0] < numpy.Inf
1844
1845
1845 # Subrutina de Remocion de la Interferencia
1846 # Subrutina de Remocion de la Interferencia
1846 for ich in range(num_channel):
1847 for ich in range(num_channel):
1847 # Se ordena los espectros segun su potencia (menor a mayor)
1848 # Se ordena los espectros segun su potencia (menor a mayor)
1848 power = jspectra[ich, mask_prof, :]
1849 power = jspectra[ich, mask_prof, :]
1849 power = power[:, hei_interf]
1850 power = power[:, hei_interf]
1850 power = power.sum(axis=0)
1851 power = power.sum(axis=0)
1851 psort = power.ravel().argsort()
1852 psort = power.ravel().argsort()
1852 print(hei_interf[psort[list(range(offhei_interf, nhei_interf + offhei_interf))]])
1853 #print(hei_interf[psort[list(range(offhei_interf, nhei_interf + offhei_interf))]])
1853 # Se estima la interferencia promedio en los Espectros de Potencia empleando
1854 # Se estima la interferencia promedio en los Espectros de Potencia empleando
1854 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
1855 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
1855 offhei_interf, nhei_interf + offhei_interf))]]]
1856 offhei_interf, nhei_interf + offhei_interf))]]]
1856
1857
1857 if noise_exist:
1858 if noise_exist:
1858 # tmp_noise = jnoise[ich] / num_prof
1859 # tmp_noise = jnoise[ich] / num_prof
1859 tmp_noise = jnoise[ich]
1860 tmp_noise = jnoise[ich]
1860 junkspc_interf = junkspc_interf - tmp_noise
1861 junkspc_interf = junkspc_interf - tmp_noise
1861 #junkspc_interf[:,comp_mask_prof] = 0
1862 #junkspc_interf[:,comp_mask_prof] = 0
1862 print(junkspc_interf.shape)
1863 #print(junkspc_interf.shape)
1863 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
1864 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
1864 jspc_interf = jspc_interf.transpose()
1865 jspc_interf = jspc_interf.transpose()
1865 # Calculando el espectro de interferencia promedio
1866 # Calculando el espectro de interferencia promedio
1866 noiseid = numpy.where(jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
1867 noiseid = numpy.where(jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
1867 noiseid = noiseid[0]
1868 noiseid = noiseid[0]
1868 cnoiseid = noiseid.size
1869 cnoiseid = noiseid.size
1869 interfid = numpy.where(jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
1870 interfid = numpy.where(jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
1870 interfid = interfid[0]
1871 interfid = interfid[0]
1871 cinterfid = interfid.size
1872 cinterfid = interfid.size
1872
1873
1873 if (cnoiseid > 0):
1874 if (cnoiseid > 0):
1874 jspc_interf[noiseid] = 0
1875 jspc_interf[noiseid] = 0
1875 # Expandiendo los perfiles a limpiar
1876 # Expandiendo los perfiles a limpiar
1876 if (cinterfid > 0):
1877 if (cinterfid > 0):
1877 new_interfid = (
1878 new_interfid = (
1878 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
1879 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
1879 new_interfid = numpy.asarray(new_interfid)
1880 new_interfid = numpy.asarray(new_interfid)
1880 new_interfid = {x for x in new_interfid}
1881 new_interfid = {x for x in new_interfid}
1881 new_interfid = numpy.array(list(new_interfid))
1882 new_interfid = numpy.array(list(new_interfid))
1882 new_cinterfid = new_interfid.size
1883 new_cinterfid = new_interfid.size
1883 else:
1884 else:
1884 new_cinterfid = 0
1885 new_cinterfid = 0
1885
1886
1886 for ip in range(new_cinterfid):
1887 for ip in range(new_cinterfid):
1887 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
1888 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
1888 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
1889 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
1889
1890
1890 jspectra[ich, :, ind_hei] = jspectra[ich, :,ind_hei] - jspc_interf # Corregir indices
1891 jspectra[ich, :, ind_hei] = jspectra[ich, :,ind_hei] - jspc_interf # Corregir indices
1891
1892
1892 # Removiendo la interferencia del punto de mayor interferencia
1893 # Removiendo la interferencia del punto de mayor interferencia
1893 ListAux = jspc_interf[mask_prof].tolist()
1894 ListAux = jspc_interf[mask_prof].tolist()
1894 maxid = ListAux.index(max(ListAux))
1895 maxid = ListAux.index(max(ListAux))
1895 print(cinterfid)
1896 #print(cinterfid)
1896 if cinterfid > 0:
1897 if cinterfid > 0:
1897 for ip in range(cinterfid * (interf == 2) - 1):
1898 for ip in range(cinterfid * (interf == 2) - 1):
1898 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
1899 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
1899 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
1900 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
1900 cind = len(ind)
1901 cind = len(ind)
1901
1902
1902 if (cind > 0):
1903 if (cind > 0):
1903 jspectra[ich, interfid[ip], ind] = tmp_noise * \
1904 jspectra[ich, interfid[ip], ind] = tmp_noise * \
1904 (1 + (numpy.random.uniform(cind) - 0.5) /
1905 (1 + (numpy.random.uniform(cind) - 0.5) /
1905 numpy.sqrt(num_incoh))
1906 numpy.sqrt(num_incoh))
1906
1907
1907 ind = numpy.array([-2, -1, 1, 2])
1908 ind = numpy.array([-2, -1, 1, 2])
1908 xx = numpy.zeros([4, 4])
1909 xx = numpy.zeros([4, 4])
1909
1910
1910 for id1 in range(4):
1911 for id1 in range(4):
1911 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1912 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1912 xx_inv = numpy.linalg.inv(xx)
1913 xx_inv = numpy.linalg.inv(xx)
1913 xx = xx_inv[:, 0]
1914 xx = xx_inv[:, 0]
1914 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1915 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1915 yy = jspectra[ich, mask_prof[ind], :]
1916 yy = jspectra[ich, mask_prof[ind], :]
1916 jspectra[ich, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1917 jspectra[ich, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1917
1918
1918 indAux = (jspectra[ich, :, :] < tmp_noise *
1919 indAux = (jspectra[ich, :, :] < tmp_noise *
1919 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
1920 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
1920 print(indAux)
1921 #print(indAux)
1921 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
1922 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
1922 (1 - 1 / numpy.sqrt(num_incoh))
1923 (1 - 1 / numpy.sqrt(num_incoh))
1923
1924
1924 # Remocion de Interferencia en el Cross Spectra
1925 # Remocion de Interferencia en el Cross Spectra
1925 if jcspectra is None:
1926 if jcspectra is None:
1926 return jspectra, jcspectra
1927 return jspectra, jcspectra
1927 num_pairs = int(jcspectra.size / (num_prof * num_hei))
1928 num_pairs = int(jcspectra.size / (num_prof * num_hei))
1928 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
1929 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
1929
1930
1930 for ip in range(num_pairs):
1931 for ip in range(num_pairs):
1931
1932
1932 #-------------------------------------------
1933 #-------------------------------------------
1933
1934
1934 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
1935 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
1935 cspower = cspower[:, hei_interf]
1936 cspower = cspower[:, hei_interf]
1936 cspower = cspower.sum(axis=0)
1937 cspower = cspower.sum(axis=0)
1937
1938
1938 cspsort = cspower.ravel().argsort()
1939 cspsort = cspower.ravel().argsort()
1939 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
1940 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
1940 offhei_interf, nhei_interf + offhei_interf))]]]
1941 offhei_interf, nhei_interf + offhei_interf))]]]
1941 junkcspc_interf = junkcspc_interf.transpose()
1942 junkcspc_interf = junkcspc_interf.transpose()
1942 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
1943 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
1943
1944
1944 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
1945 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
1945
1946
1946 median_real = int(numpy.median(numpy.real(
1947 median_real = int(numpy.median(numpy.real(
1947 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1948 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1948 median_imag = int(numpy.median(numpy.imag(
1949 median_imag = int(numpy.median(numpy.imag(
1949 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1950 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
1950 comp_mask_prof = [int(e) for e in comp_mask_prof]
1951 comp_mask_prof = [int(e) for e in comp_mask_prof]
1951 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
1952 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
1952 median_real, median_imag)
1953 median_real, median_imag)
1953
1954
1954 for iprof in range(num_prof):
1955 for iprof in range(num_prof):
1955 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
1956 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
1956 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
1957 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
1957
1958
1958 # Removiendo la Interferencia
1959 # Removiendo la Interferencia
1959 jcspectra[ip, :, ind_hei] = jcspectra[ip,
1960 jcspectra[ip, :, ind_hei] = jcspectra[ip,
1960 :, ind_hei] - jcspc_interf
1961 :, ind_hei] - jcspc_interf
1961
1962
1962 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
1963 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
1963 maxid = ListAux.index(max(ListAux))
1964 maxid = ListAux.index(max(ListAux))
1964
1965
1965 ind = numpy.array([-2, -1, 1, 2])
1966 ind = numpy.array([-2, -1, 1, 2])
1966 xx = numpy.zeros([4, 4])
1967 xx = numpy.zeros([4, 4])
1967
1968
1968 for id1 in range(4):
1969 for id1 in range(4):
1969 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1970 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
1970
1971
1971 xx_inv = numpy.linalg.inv(xx)
1972 xx_inv = numpy.linalg.inv(xx)
1972 xx = xx_inv[:, 0]
1973 xx = xx_inv[:, 0]
1973
1974
1974 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1975 ind = (ind + maxid + num_mask_prof) % num_mask_prof
1975 yy = jcspectra[ip, mask_prof[ind], :]
1976 yy = jcspectra[ip, mask_prof[ind], :]
1976 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1977 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
1977
1978
1978 # Guardar Resultados
1979 # Guardar Resultados
1979 self.dataOut.data_spc = jspectra
1980 self.dataOut.data_spc = jspectra
1980 self.dataOut.data_cspc = jcspectra
1981 self.dataOut.data_cspc = jcspectra
1981
1982
1982 return 1
1983 return 1
1983
1984
1984 def run(self, dataOut, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None, mode=1, minHei=None, maxHei=None):
1985 def run(self, dataOut, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None, mode=1, minHei=None, maxHei=None):
1985
1986
1986 self.dataOut = dataOut
1987 self.dataOut = dataOut
1987
1988
1988 if mode == 1:
1989 if mode == 1:
1989 self.removeInterference(interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None)
1990 self.removeInterference(interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None)
1990 elif mode == 2:
1991 elif mode == 2:
1991 self.removeInterference2()
1992 self.removeInterference2()
1992 elif mode == 3:
1993 elif mode == 3:
1993 self.removeInterference3(min_hei=minHei, max_hei=maxHei)
1994 self.removeInterference3(min_hei=minHei, max_hei=maxHei)
1994 return self.dataOut
1995 return self.dataOut
1995
1996
1996
1997
1997 class IncohInt(Operation):
1998 class IncohInt(Operation):
1998
1999
1999 __profIndex = 0
2000 __profIndex = 0
2000 __withOverapping = False
2001 __withOverapping = False
2001
2002
2002 __byTime = False
2003 __byTime = False
2003 __initime = None
2004 __initime = None
2004 __lastdatatime = None
2005 __lastdatatime = None
2005 __integrationtime = None
2006 __integrationtime = None
2006
2007
2007 __buffer_spc = None
2008 __buffer_spc = None
2008 __buffer_cspc = None
2009 __buffer_cspc = None
2009 __buffer_dc = None
2010 __buffer_dc = None
2010
2011
2011 __dataReady = False
2012 __dataReady = False
2012
2013
2013 __timeInterval = None
2014 __timeInterval = None
2014 incohInt = 0
2015 incohInt = 0
2015 nOutliers = 0
2016 nOutliers = 0
2016 n = None
2017 n = None
2017
2018
2018 _flagProfilesByRange = False
2019 _flagProfilesByRange = False
2019 _nProfilesByRange = 0
2020 _nProfilesByRange = 0
2020 def __init__(self):
2021 def __init__(self):
2021
2022
2022 Operation.__init__(self)
2023 Operation.__init__(self)
2023
2024
2024 def setup(self, n=None, timeInterval=None, overlapping=False):
2025 def setup(self, n=None, timeInterval=None, overlapping=False):
2025 """
2026 """
2026 Set the parameters of the integration class.
2027 Set the parameters of the integration class.
2027
2028
2028 Inputs:
2029 Inputs:
2029
2030
2030 n : Number of coherent integrations
2031 n : Number of coherent integrations
2031 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
2032 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
2032 overlapping :
2033 overlapping :
2033
2034
2034 """
2035 """
2035
2036
2036 self.__initime = None
2037 self.__initime = None
2037 self.__lastdatatime = 0
2038 self.__lastdatatime = 0
2038
2039
2039 self.__buffer_spc = 0
2040 self.__buffer_spc = 0
2040 self.__buffer_cspc = 0
2041 self.__buffer_cspc = 0
2041 self.__buffer_dc = 0
2042 self.__buffer_dc = 0
2042
2043
2043 self.__profIndex = 0
2044 self.__profIndex = 0
2044 self.__dataReady = False
2045 self.__dataReady = False
2045 self.__byTime = False
2046 self.__byTime = False
2046 self.incohInt = 0
2047 self.incohInt = 0
2047 self.nOutliers = 0
2048 self.nOutliers = 0
2048 if n is None and timeInterval is None:
2049 if n is None and timeInterval is None:
2049 raise ValueError("n or timeInterval should be specified ...")
2050 raise ValueError("n or timeInterval should be specified ...")
2050
2051
2051 if n is not None:
2052 if n is not None:
2052 self.n = int(n)
2053 self.n = int(n)
2053 else:
2054 else:
2054
2055
2055 self.__integrationtime = int(timeInterval)
2056 self.__integrationtime = int(timeInterval)
2056 self.n = None
2057 self.n = None
2057 self.__byTime = True
2058 self.__byTime = True
2058
2059
2059
2060
2061
2060 def putData(self, data_spc, data_cspc, data_dc):
2062 def putData(self, data_spc, data_cspc, data_dc):
2061 """
2063 """
2062 Add a profile to the __buffer_spc and increase in one the __profileIndex
2064 Add a profile to the __buffer_spc and increase in one the __profileIndex
2063
2065
2064 """
2066 """
2065 if data_spc.all() == numpy.nan :
2067 if data_spc.all() == numpy.nan :
2066 print("nan ")
2068 print("nan ")
2067 return
2069 return
2068 self.__buffer_spc += data_spc
2070 self.__buffer_spc += data_spc
2069
2071
2070 if data_cspc is None:
2072 if data_cspc is None:
2071 self.__buffer_cspc = None
2073 self.__buffer_cspc = None
2072 else:
2074 else:
2073 self.__buffer_cspc += data_cspc
2075 self.__buffer_cspc += data_cspc
2074
2076
2075 if data_dc is None:
2077 if data_dc is None:
2076 self.__buffer_dc = None
2078 self.__buffer_dc = None
2077 else:
2079 else:
2078 self.__buffer_dc += data_dc
2080 self.__buffer_dc += data_dc
2079
2081
2080 self.__profIndex += 1
2082 self.__profIndex += 1
2081
2083
2082 return
2084 return
2083
2085
2084 def pushData(self):
2086 def pushData(self):
2085 """
2087 """
2086 Return the sum of the last profiles and the profiles used in the sum.
2088 Return the sum of the last profiles and the profiles used in the sum.
2087
2089
2088 Affected:
2090 Affected:
2089
2091
2090 self.__profileIndex
2092 self.__profileIndex
2091
2093
2092 """
2094 """
2093
2095
2094 data_spc = self.__buffer_spc
2096 data_spc = self.__buffer_spc
2095 data_cspc = self.__buffer_cspc
2097 data_cspc = self.__buffer_cspc
2096 data_dc = self.__buffer_dc
2098 data_dc = self.__buffer_dc
2097 n = self.__profIndex
2099 n = self.__profIndex
2098
2100
2099 self.__buffer_spc = 0
2101 self.__buffer_spc = 0
2100 self.__buffer_cspc = 0
2102 self.__buffer_cspc = 0
2101 self.__buffer_dc = 0
2103 self.__buffer_dc = 0
2102
2104
2103
2105
2104 return data_spc, data_cspc, data_dc, n
2106 return data_spc, data_cspc, data_dc, n
2105
2107
2106 def byProfiles(self, *args):
2108 def byProfiles(self, *args):
2107
2109
2108 self.__dataReady = False
2110 self.__dataReady = False
2109 avgdata_spc = None
2111 avgdata_spc = None
2110 avgdata_cspc = None
2112 avgdata_cspc = None
2111 avgdata_dc = None
2113 avgdata_dc = None
2112
2114
2113 self.putData(*args)
2115 self.putData(*args)
2114
2116
2115 if self.__profIndex == self.n:
2117 if self.__profIndex == self.n:
2116
2118
2117 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
2119 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
2118 self.n = n
2120 self.n = n
2119 self.__dataReady = True
2121 self.__dataReady = True
2120
2122
2121 return avgdata_spc, avgdata_cspc, avgdata_dc
2123 return avgdata_spc, avgdata_cspc, avgdata_dc
2122
2124
2123 def byTime(self, datatime, *args):
2125 def byTime(self, datatime, *args):
2124
2126
2125 self.__dataReady = False
2127 self.__dataReady = False
2126 avgdata_spc = None
2128 avgdata_spc = None
2127 avgdata_cspc = None
2129 avgdata_cspc = None
2128 avgdata_dc = None
2130 avgdata_dc = None
2129
2131
2130 self.putData(*args)
2132 self.putData(*args)
2131
2133
2132 if (datatime - self.__initime) >= self.__integrationtime:
2134 if (datatime - self.__initime) >= self.__integrationtime:
2133 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
2135 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
2134 self.n = n
2136 self.n = n
2135 self.__dataReady = True
2137 self.__dataReady = True
2136
2138
2137 return avgdata_spc, avgdata_cspc, avgdata_dc
2139 return avgdata_spc, avgdata_cspc, avgdata_dc
2138
2140
2139 def integrate(self, datatime, *args):
2141 def integrate(self, datatime, *args):
2140
2142
2141 if self.__profIndex == 0:
2143 if self.__profIndex == 0:
2142 self.__initime = datatime
2144 self.__initime = datatime
2143
2145
2144 if self.__byTime:
2146 if self.__byTime:
2145 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
2147 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
2146 datatime, *args)
2148 datatime, *args)
2147 else:
2149 else:
2148 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
2150 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
2149
2151
2150 if not self.__dataReady:
2152 if not self.__dataReady:
2151 return None, None, None, None
2153 return None, None, None, None
2152
2154
2153 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
2155 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
2154
2156
2155 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
2157 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
2156 if n == 1:
2158 if n == 1:
2157 return dataOut
2159 return dataOut
2158
2160
2159 if dataOut.flagNoData == True:
2161 if dataOut.flagNoData == True:
2160 return dataOut
2162 return dataOut
2161
2163
2162 if dataOut.flagProfilesByRange == True:
2164 if dataOut.flagProfilesByRange == True:
2163 self._flagProfilesByRange = True
2165 self._flagProfilesByRange = True
2164
2166
2165 dataOut.flagNoData = True
2167 dataOut.flagNoData = True
2166 dataOut.processingHeaderObj.timeIncohInt = timeInterval
2168 dataOut.processingHeaderObj.timeIncohInt = timeInterval
2167 if not self.isConfig:
2169 if not self.isConfig:
2170 self._nProfilesByRange = numpy.zeros(len(dataOut.heightList))
2168 self.setup(n, timeInterval, overlapping)
2171 self.setup(n, timeInterval, overlapping)
2169 self.isConfig = True
2172 self.isConfig = True
2170
2173
2171
2174
2172 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
2175 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
2173 dataOut.data_spc,
2176 dataOut.data_spc,
2174 dataOut.data_cspc,
2177 dataOut.data_cspc,
2175 dataOut.data_dc)
2178 dataOut.data_dc)
2176
2179
2177 self.incohInt += dataOut.nIncohInt
2180 self.incohInt += dataOut.nIncohInt
2178
2181
2179
2182
2180 if isinstance(dataOut.data_outlier,numpy.ndarray) or isinstance(dataOut.data_outlier,int) or isinstance(dataOut.data_outlier, float):
2183 if isinstance(dataOut.data_outlier,numpy.ndarray) or isinstance(dataOut.data_outlier,int) or isinstance(dataOut.data_outlier, float):
2181 self.nOutliers += dataOut.data_outlier
2184 self.nOutliers += dataOut.data_outlier
2182
2185
2183 if self._flagProfilesByRange:
2186 if self._flagProfilesByRange:
2184 dataOut.flagProfilesByRange = True
2187 dataOut.flagProfilesByRange = True
2185 self._nProfilesByRange += dataOut.nProfilesByRange
2188 self._nProfilesByRange += dataOut.nProfilesByRange
2186
2189
2187 if self.__dataReady:
2190 if self.__dataReady:
2188 #print("prof: ",dataOut.max_nIncohInt,self.__profIndex)
2191 #print("prof: ",dataOut.max_nIncohInt,self.__profIndex)
2189 dataOut.data_spc = avgdata_spc
2192 dataOut.data_spc = avgdata_spc
2190 dataOut.data_cspc = avgdata_cspc
2193 dataOut.data_cspc = avgdata_cspc
2191 dataOut.data_dc = avgdata_dc
2194 dataOut.data_dc = avgdata_dc
2192 dataOut.nIncohInt = self.incohInt
2195 dataOut.nIncohInt = self.incohInt
2193 dataOut.data_outlier = self.nOutliers
2196 dataOut.data_outlier = self.nOutliers
2194 dataOut.utctime = avgdatatime
2197 dataOut.utctime = avgdatatime
2195 dataOut.flagNoData = False
2198 dataOut.flagNoData = False
2196 self.incohInt = 0
2199 self.incohInt = 0
2197 self.nOutliers = 0
2200 self.nOutliers = 0
2198 self.__profIndex = 0
2201 self.__profIndex = 0
2199 dataOut.nProfilesByRange = self._nProfilesByRange
2202 dataOut.nProfilesByRange = self._nProfilesByRange
2200 self._nProfilesByRange = 0
2203 self._nProfilesByRange = numpy.zeros(len(dataOut.heightList))
2201 self._flagProfilesByRange = False
2204 self._flagProfilesByRange = False
2202 #print("IncohInt Done")
2205 #print("IncohInt Done")
2203 return dataOut
2206 return dataOut
2204
2207
2205 class dopplerFlip(Operation):
2208 class dopplerFlip(Operation):
2206
2209
2207 def run(self, dataOut):
2210 def run(self, dataOut):
2208 # arreglo 1: (num_chan, num_profiles, num_heights)
2211 # arreglo 1: (num_chan, num_profiles, num_heights)
2209 self.dataOut = dataOut
2212 self.dataOut = dataOut
2210 # JULIA-oblicua, indice 2
2213 # JULIA-oblicua, indice 2
2211 # arreglo 2: (num_profiles, num_heights)
2214 # arreglo 2: (num_profiles, num_heights)
2212 jspectra = self.dataOut.data_spc[2]
2215 jspectra = self.dataOut.data_spc[2]
2213 jspectra_tmp = numpy.zeros(jspectra.shape)
2216 jspectra_tmp = numpy.zeros(jspectra.shape)
2214 num_profiles = jspectra.shape[0]
2217 num_profiles = jspectra.shape[0]
2215 freq_dc = int(num_profiles / 2)
2218 freq_dc = int(num_profiles / 2)
2216 # Flip con for
2219 # Flip con for
2217 for j in range(num_profiles):
2220 for j in range(num_profiles):
2218 jspectra_tmp[num_profiles-j-1]= jspectra[j]
2221 jspectra_tmp[num_profiles-j-1]= jspectra[j]
2219 # Intercambio perfil de DC con perfil inmediato anterior
2222 # Intercambio perfil de DC con perfil inmediato anterior
2220 jspectra_tmp[freq_dc-1]= jspectra[freq_dc-1]
2223 jspectra_tmp[freq_dc-1]= jspectra[freq_dc-1]
2221 jspectra_tmp[freq_dc]= jspectra[freq_dc]
2224 jspectra_tmp[freq_dc]= jspectra[freq_dc]
2222 # canal modificado es re-escrito en el arreglo de canales
2225 # canal modificado es re-escrito en el arreglo de canales
2223 self.dataOut.data_spc[2] = jspectra_tmp
2226 self.dataOut.data_spc[2] = jspectra_tmp
2224
2227
2225 return self.dataOut
2228 return self.dataOut
2226
2229
2227
2230
2228
2231
2229
2232
2230
2233
2231
2234
2232 class cleanJULIAInterf(Operation):
2235 class cleanJULIAInterf(Operation):
2233 """
2236 """
2234 Operación de prueba
2237 Operación de prueba
2235 """
2238 """
2236 __slots__ =('heights_indx', 'repeats','span' ,'step', 'factor', 'idate', 'idxs','isConfig','minHrefN', 'maxHrefN')
2239 __slots__ =('heights_indx', 'repeats','span' ,'step', 'factor', 'idate', 'idxs','isConfig','minHrefN', 'maxHrefN')
2237 def __init__(self):
2240 def __init__(self):
2238 self.repeats = 0
2241 self.repeats = 0
2239 self.factor=1
2242 self.factor=1
2240 self.isConfig = False
2243 self.isConfig = False
2241 self.idxs = None
2244 self.idxs = None
2242 self.heights_indx = None
2245 self.heights_indx = None
2243
2246
2244 def setup(self, dataOutHeightsList, heightsList, span=10, repeats=0, step=0, idate=None, startH=None, endH=None, minHref=None, maxHref=None):
2247 def setup(self, dataOutHeightsList, heightsList, span=10, repeats=0, step=0, idate=None, startH=None, endH=None, minHref=None, maxHref=None):
2245 totalHeihtList = dataOutHeightsList
2248 totalHeihtList = dataOutHeightsList
2246 heights = [float(hei) for hei in heightsList]
2249 heights = [float(hei) for hei in heightsList]
2247 for r in range(repeats):
2250 for r in range(repeats):
2248 heights += [ (h+(step*(r+1))) for h in heights]
2251 heights += [ (h+(step*(r+1))) for h in heights]
2249 #print(heights)
2252 #print(heights)
2250 self.heights_indx = [getHei_index(h,h,totalHeihtList)[0] for h in heights]
2253 self.heights_indx = [getHei_index(h,h,totalHeihtList)[0] for h in heights]
2251
2254
2252 self.minHrefN, self.maxHrefN = getHei_index(minHref,maxHref,totalHeihtList)
2255 self.minHrefN, self.maxHrefN = getHei_index(minHref,maxHref,totalHeihtList)
2253
2256
2254
2257
2255 self.config = True
2258 self.config = True
2256 self.span = span
2259 self.span = span
2257
2260
2258 def run(self, dataOut, heightsList, span=10, repeats=0, step=0, idate=None, startH=None, endH=None, minHref=None, maxHref=None):
2261 def run(self, dataOut, heightsList, span=10, repeats=0, step=0, idate=None, startH=None, endH=None, minHref=None, maxHref=None):
2259
2262
2260
2263
2261 self.dataOut = dataOut
2264 self.dataOut = dataOut
2262 startTime = datetime.datetime.combine(idate,startH)
2265 startTime = datetime.datetime.combine(idate,startH)
2263 endTime = datetime.datetime.combine(idate,endH)
2266 endTime = datetime.datetime.combine(idate,endH)
2264 currentTime = datetime.datetime.fromtimestamp(self.dataOut.utctime)
2267 currentTime = datetime.datetime.fromtimestamp(self.dataOut.utctime)
2265
2268
2266 if currentTime < startTime or currentTime > endTime:
2269 if currentTime < startTime or currentTime > endTime:
2267 return self.dataOut
2270 return self.dataOut
2268
2271
2269 if not self.isConfig:
2272 if not self.isConfig:
2270 self.setup(self.dataOut.heightList,heightsList, span=span, repeats=repeats, step=step, idate=idate, startH=startH, endH=endH, minHref=minHref, maxHref=maxHref )
2273 self.setup(self.dataOut.heightList,heightsList, span=span, repeats=repeats, step=step, idate=idate, startH=startH, endH=endH, minHref=minHref, maxHref=maxHref )
2271
2274
2272 for ch in range(self.dataOut.data_spc.shape[0]):
2275 for ch in range(self.dataOut.data_spc.shape[0]):
2273 i = 0
2276 i = 0
2274 N_ref = self.dataOut.data_spc[ch, :, self.minHrefN: self.maxHrefN].mean()
2277 N_ref = self.dataOut.data_spc[ch, :, self.minHrefN: self.maxHrefN].mean()
2275 mn = self.heights_indx[-1] - self.span/2
2278 mn = self.heights_indx[-1] - self.span/2
2276 mx = self.heights_indx[-1] + self.span/2
2279 mx = self.heights_indx[-1] + self.span/2
2277 J_lev = self.dataOut.data_spc[ch, :, mn: mx].mean() - N_ref
2280 J_lev = self.dataOut.data_spc[ch, :, mn: mx].mean() - N_ref
2278
2281
2279 for hei in self.heights_indx:
2282 for hei in self.heights_indx:
2280 h = hei - 1
2283 h = hei - 1
2281 mn_i = hei - self.span/2
2284 mn_i = hei - self.span/2
2282 mx_i = hei + self.span/2
2285 mx_i = hei + self.span/2
2283 self.dataOut.data_spc[ch, :,mn_i:mx_i ] -= J_lev
2286 self.dataOut.data_spc[ch, :,mn_i:mx_i ] -= J_lev
2284 i += 1
2287 i += 1
2285
2288
2286
2289
2287 return self.dataOut No newline at end of file
2290 return self.dataOut
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now