##// END OF EJS Templates
adicion de escritura de datos, calculo de ancho espectral y graficos pulsepair
avaldez -
r1303:ddb038395553
parent child
Show More
@@ -1,1393 +1,1398
1 '''
1 '''
2
2
3 $Author: murco $
3 $Author: murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 '''
5 '''
6
6
7 import copy
7 import copy
8 import numpy
8 import numpy
9 import datetime
9 import datetime
10 import json
10 import json
11
11
12 import schainpy.admin
12 import schainpy.admin
13 from schainpy.utils import log
13 from schainpy.utils import log
14 from .jroheaderIO import SystemHeader, RadarControllerHeader
14 from .jroheaderIO import SystemHeader, RadarControllerHeader
15 from schainpy.model.data import _noise
15 from schainpy.model.data import _noise
16
16
17
17
18 def getNumpyDtype(dataTypeCode):
18 def getNumpyDtype(dataTypeCode):
19
19
20 if dataTypeCode == 0:
20 if dataTypeCode == 0:
21 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
21 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
22 elif dataTypeCode == 1:
22 elif dataTypeCode == 1:
23 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
23 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
24 elif dataTypeCode == 2:
24 elif dataTypeCode == 2:
25 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
25 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
26 elif dataTypeCode == 3:
26 elif dataTypeCode == 3:
27 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
27 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
28 elif dataTypeCode == 4:
28 elif dataTypeCode == 4:
29 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
29 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
30 elif dataTypeCode == 5:
30 elif dataTypeCode == 5:
31 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
31 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
32 else:
32 else:
33 raise ValueError('dataTypeCode was not defined')
33 raise ValueError('dataTypeCode was not defined')
34
34
35 return numpyDtype
35 return numpyDtype
36
36
37
37
38 def getDataTypeCode(numpyDtype):
38 def getDataTypeCode(numpyDtype):
39
39
40 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
40 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
41 datatype = 0
41 datatype = 0
42 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
42 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
43 datatype = 1
43 datatype = 1
44 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
44 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
45 datatype = 2
45 datatype = 2
46 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
46 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
47 datatype = 3
47 datatype = 3
48 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
48 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
49 datatype = 4
49 datatype = 4
50 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
50 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
51 datatype = 5
51 datatype = 5
52 else:
52 else:
53 datatype = None
53 datatype = None
54
54
55 return datatype
55 return datatype
56
56
57
57
58 def hildebrand_sekhon(data, navg):
58 def hildebrand_sekhon(data, navg):
59 """
59 """
60 This method is for the objective determination of the noise level in Doppler spectra. This
60 This method is for the objective determination of the noise level in Doppler spectra. This
61 implementation technique is based on the fact that the standard deviation of the spectral
61 implementation technique is based on the fact that the standard deviation of the spectral
62 densities is equal to the mean spectral density for white Gaussian noise
62 densities is equal to the mean spectral density for white Gaussian noise
63
63
64 Inputs:
64 Inputs:
65 Data : heights
65 Data : heights
66 navg : numbers of averages
66 navg : numbers of averages
67
67
68 Return:
68 Return:
69 mean : noise's level
69 mean : noise's level
70 """
70 """
71
71
72 sortdata = numpy.sort(data, axis=None)
72 sortdata = numpy.sort(data, axis=None)
73 '''
73 '''
74 lenOfData = len(sortdata)
74 lenOfData = len(sortdata)
75 nums_min = lenOfData*0.2
75 nums_min = lenOfData*0.2
76
76
77 if nums_min <= 5:
77 if nums_min <= 5:
78
78
79 nums_min = 5
79 nums_min = 5
80
80
81 sump = 0.
81 sump = 0.
82 sumq = 0.
82 sumq = 0.
83
83
84 j = 0
84 j = 0
85 cont = 1
85 cont = 1
86
86
87 while((cont == 1)and(j < lenOfData)):
87 while((cont == 1)and(j < lenOfData)):
88
88
89 sump += sortdata[j]
89 sump += sortdata[j]
90 sumq += sortdata[j]**2
90 sumq += sortdata[j]**2
91
91
92 if j > nums_min:
92 if j > nums_min:
93 rtest = float(j)/(j-1) + 1.0/navg
93 rtest = float(j)/(j-1) + 1.0/navg
94 if ((sumq*j) > (rtest*sump**2)):
94 if ((sumq*j) > (rtest*sump**2)):
95 j = j - 1
95 j = j - 1
96 sump = sump - sortdata[j]
96 sump = sump - sortdata[j]
97 sumq = sumq - sortdata[j]**2
97 sumq = sumq - sortdata[j]**2
98 cont = 0
98 cont = 0
99
99
100 j += 1
100 j += 1
101
101
102 lnoise = sump / j
102 lnoise = sump / j
103 '''
103 '''
104 return _noise.hildebrand_sekhon(sortdata, navg)
104 return _noise.hildebrand_sekhon(sortdata, navg)
105
105
106
106
107 class Beam:
107 class Beam:
108
108
109 def __init__(self):
109 def __init__(self):
110 self.codeList = []
110 self.codeList = []
111 self.azimuthList = []
111 self.azimuthList = []
112 self.zenithList = []
112 self.zenithList = []
113
113
114
114
115 class GenericData(object):
115 class GenericData(object):
116
116
117 flagNoData = True
117 flagNoData = True
118
118
119 def copy(self, inputObj=None):
119 def copy(self, inputObj=None):
120
120
121 if inputObj == None:
121 if inputObj == None:
122 return copy.deepcopy(self)
122 return copy.deepcopy(self)
123
123
124 for key in list(inputObj.__dict__.keys()):
124 for key in list(inputObj.__dict__.keys()):
125
125
126 attribute = inputObj.__dict__[key]
126 attribute = inputObj.__dict__[key]
127
127
128 # If this attribute is a tuple or list
128 # If this attribute is a tuple or list
129 if type(inputObj.__dict__[key]) in (tuple, list):
129 if type(inputObj.__dict__[key]) in (tuple, list):
130 self.__dict__[key] = attribute[:]
130 self.__dict__[key] = attribute[:]
131 continue
131 continue
132
132
133 # If this attribute is another object or instance
133 # If this attribute is another object or instance
134 if hasattr(attribute, '__dict__'):
134 if hasattr(attribute, '__dict__'):
135 self.__dict__[key] = attribute.copy()
135 self.__dict__[key] = attribute.copy()
136 continue
136 continue
137
137
138 self.__dict__[key] = inputObj.__dict__[key]
138 self.__dict__[key] = inputObj.__dict__[key]
139
139
140 def deepcopy(self):
140 def deepcopy(self):
141
141
142 return copy.deepcopy(self)
142 return copy.deepcopy(self)
143
143
144 def isEmpty(self):
144 def isEmpty(self):
145
145
146 return self.flagNoData
146 return self.flagNoData
147
147
148 def isReady(self):
148 def isReady(self):
149
149
150 return not self.flagNoData
150 return not self.flagNoData
151
151
152
152
153 class JROData(GenericData):
153 class JROData(GenericData):
154
154
155 # m_BasicHeader = BasicHeader()
155 # m_BasicHeader = BasicHeader()
156 # m_ProcessingHeader = ProcessingHeader()
156 # m_ProcessingHeader = ProcessingHeader()
157
157
158 systemHeaderObj = SystemHeader()
158 systemHeaderObj = SystemHeader()
159 radarControllerHeaderObj = RadarControllerHeader()
159 radarControllerHeaderObj = RadarControllerHeader()
160 # data = None
160 # data = None
161 type = None
161 type = None
162 datatype = None # dtype but in string
162 datatype = None # dtype but in string
163 # dtype = None
163 # dtype = None
164 # nChannels = None
164 # nChannels = None
165 # nHeights = None
165 # nHeights = None
166 nProfiles = None
166 nProfiles = None
167 heightList = None
167 heightList = None
168 channelList = None
168 channelList = None
169 flagDiscontinuousBlock = False
169 flagDiscontinuousBlock = False
170 useLocalTime = False
170 useLocalTime = False
171 utctime = None
171 utctime = None
172 timeZone = None
172 timeZone = None
173 dstFlag = None
173 dstFlag = None
174 errorCount = None
174 errorCount = None
175 blocksize = None
175 blocksize = None
176 # nCode = None
176 # nCode = None
177 # nBaud = None
177 # nBaud = None
178 # code = None
178 # code = None
179 flagDecodeData = False # asumo q la data no esta decodificada
179 flagDecodeData = False # asumo q la data no esta decodificada
180 flagDeflipData = False # asumo q la data no esta sin flip
180 flagDeflipData = False # asumo q la data no esta sin flip
181 flagShiftFFT = False
181 flagShiftFFT = False
182 # ippSeconds = None
182 # ippSeconds = None
183 # timeInterval = None
183 # timeInterval = None
184 nCohInt = None
184 nCohInt = None
185 # noise = None
185 # noise = None
186 windowOfFilter = 1
186 windowOfFilter = 1
187 # Speed of ligth
187 # Speed of ligth
188 C = 3e8
188 C = 3e8
189 frequency = 49.92e6
189 frequency = 49.92e6
190 realtime = False
190 realtime = False
191 beacon_heiIndexList = None
191 beacon_heiIndexList = None
192 last_block = None
192 last_block = None
193 blocknow = None
193 blocknow = None
194 azimuth = None
194 azimuth = None
195 zenith = None
195 zenith = None
196 beam = Beam()
196 beam = Beam()
197 profileIndex = None
197 profileIndex = None
198 error = None
198 error = None
199 data = None
199 data = None
200 nmodes = None
200 nmodes = None
201
201
202 def __str__(self):
202 def __str__(self):
203
203
204 return '{} - {}'.format(self.type, self.getDatatime())
204 return '{} - {}'.format(self.type, self.getDatatime())
205
205
206 def getNoise(self):
206 def getNoise(self):
207
207
208 raise NotImplementedError
208 raise NotImplementedError
209
209
210 def getNChannels(self):
210 def getNChannels(self):
211
211
212 return len(self.channelList)
212 return len(self.channelList)
213
213
214 def getChannelIndexList(self):
214 def getChannelIndexList(self):
215
215
216 return list(range(self.nChannels))
216 return list(range(self.nChannels))
217
217
218 def getNHeights(self):
218 def getNHeights(self):
219
219
220 return len(self.heightList)
220 return len(self.heightList)
221
221
222 def getHeiRange(self, extrapoints=0):
222 def getHeiRange(self, extrapoints=0):
223
223
224 heis = self.heightList
224 heis = self.heightList
225 # deltah = self.heightList[1] - self.heightList[0]
225 # deltah = self.heightList[1] - self.heightList[0]
226 #
226 #
227 # heis.append(self.heightList[-1])
227 # heis.append(self.heightList[-1])
228
228
229 return heis
229 return heis
230
230
231 def getDeltaH(self):
231 def getDeltaH(self):
232
232
233 delta = self.heightList[1] - self.heightList[0]
233 delta = self.heightList[1] - self.heightList[0]
234
234
235 return delta
235 return delta
236
236
237 def getltctime(self):
237 def getltctime(self):
238
238
239 if self.useLocalTime:
239 if self.useLocalTime:
240 return self.utctime - self.timeZone * 60
240 return self.utctime - self.timeZone * 60
241
241
242 return self.utctime
242 return self.utctime
243
243
244 def getDatatime(self):
244 def getDatatime(self):
245
245
246 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
246 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
247 return datatimeValue
247 return datatimeValue
248
248
249 def getTimeRange(self):
249 def getTimeRange(self):
250
250
251 datatime = []
251 datatime = []
252
252
253 datatime.append(self.ltctime)
253 datatime.append(self.ltctime)
254 datatime.append(self.ltctime + self.timeInterval + 1)
254 datatime.append(self.ltctime + self.timeInterval + 1)
255
255
256 datatime = numpy.array(datatime)
256 datatime = numpy.array(datatime)
257
257
258 return datatime
258 return datatime
259
259
260 def getFmaxTimeResponse(self):
260 def getFmaxTimeResponse(self):
261
261
262 period = (10**-6) * self.getDeltaH() / (0.15)
262 period = (10**-6) * self.getDeltaH() / (0.15)
263
263
264 PRF = 1. / (period * self.nCohInt)
264 PRF = 1. / (period * self.nCohInt)
265
265
266 fmax = PRF
266 fmax = PRF
267
267
268 return fmax
268 return fmax
269
269
270 def getFmax(self):
270 def getFmax(self):
271 PRF = 1. / (self.ippSeconds * self.nCohInt)
271 PRF = 1. / (self.ippSeconds * self.nCohInt)
272
272
273 fmax = PRF
273 fmax = PRF
274 return fmax
274 return fmax
275
275
276 def getVmax(self):
276 def getVmax(self):
277
277
278 _lambda = self.C / self.frequency
278 _lambda = self.C / self.frequency
279
279
280 vmax = self.getFmax() * _lambda / 2
280 vmax = self.getFmax() * _lambda / 2
281
281
282 return vmax
282 return vmax
283
283
284 def get_ippSeconds(self):
284 def get_ippSeconds(self):
285 '''
285 '''
286 '''
286 '''
287 return self.radarControllerHeaderObj.ippSeconds
287 return self.radarControllerHeaderObj.ippSeconds
288
288
289 def set_ippSeconds(self, ippSeconds):
289 def set_ippSeconds(self, ippSeconds):
290 '''
290 '''
291 '''
291 '''
292
292
293 self.radarControllerHeaderObj.ippSeconds = ippSeconds
293 self.radarControllerHeaderObj.ippSeconds = ippSeconds
294
294
295 return
295 return
296
296
297 def get_dtype(self):
297 def get_dtype(self):
298 '''
298 '''
299 '''
299 '''
300 return getNumpyDtype(self.datatype)
300 return getNumpyDtype(self.datatype)
301
301
302 def set_dtype(self, numpyDtype):
302 def set_dtype(self, numpyDtype):
303 '''
303 '''
304 '''
304 '''
305
305
306 self.datatype = getDataTypeCode(numpyDtype)
306 self.datatype = getDataTypeCode(numpyDtype)
307
307
308 def get_code(self):
308 def get_code(self):
309 '''
309 '''
310 '''
310 '''
311 return self.radarControllerHeaderObj.code
311 return self.radarControllerHeaderObj.code
312
312
313 def set_code(self, code):
313 def set_code(self, code):
314 '''
314 '''
315 '''
315 '''
316 self.radarControllerHeaderObj.code = code
316 self.radarControllerHeaderObj.code = code
317
317
318 return
318 return
319
319
320 def get_ncode(self):
320 def get_ncode(self):
321 '''
321 '''
322 '''
322 '''
323 return self.radarControllerHeaderObj.nCode
323 return self.radarControllerHeaderObj.nCode
324
324
325 def set_ncode(self, nCode):
325 def set_ncode(self, nCode):
326 '''
326 '''
327 '''
327 '''
328 self.radarControllerHeaderObj.nCode = nCode
328 self.radarControllerHeaderObj.nCode = nCode
329
329
330 return
330 return
331
331
332 def get_nbaud(self):
332 def get_nbaud(self):
333 '''
333 '''
334 '''
334 '''
335 return self.radarControllerHeaderObj.nBaud
335 return self.radarControllerHeaderObj.nBaud
336
336
337 def set_nbaud(self, nBaud):
337 def set_nbaud(self, nBaud):
338 '''
338 '''
339 '''
339 '''
340 self.radarControllerHeaderObj.nBaud = nBaud
340 self.radarControllerHeaderObj.nBaud = nBaud
341
341
342 return
342 return
343
343
344 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
344 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
345 channelIndexList = property(
345 channelIndexList = property(
346 getChannelIndexList, "I'm the 'channelIndexList' property.")
346 getChannelIndexList, "I'm the 'channelIndexList' property.")
347 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
347 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
348 #noise = property(getNoise, "I'm the 'nHeights' property.")
348 #noise = property(getNoise, "I'm the 'nHeights' property.")
349 datatime = property(getDatatime, "I'm the 'datatime' property")
349 datatime = property(getDatatime, "I'm the 'datatime' property")
350 ltctime = property(getltctime, "I'm the 'ltctime' property")
350 ltctime = property(getltctime, "I'm the 'ltctime' property")
351 ippSeconds = property(get_ippSeconds, set_ippSeconds)
351 ippSeconds = property(get_ippSeconds, set_ippSeconds)
352 dtype = property(get_dtype, set_dtype)
352 dtype = property(get_dtype, set_dtype)
353 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
353 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
354 code = property(get_code, set_code)
354 code = property(get_code, set_code)
355 nCode = property(get_ncode, set_ncode)
355 nCode = property(get_ncode, set_ncode)
356 nBaud = property(get_nbaud, set_nbaud)
356 nBaud = property(get_nbaud, set_nbaud)
357
357
358
358
359 class Voltage(JROData):
359 class Voltage(JROData):
360
360
361 # data es un numpy array de 2 dmensiones (canales, alturas)
361 # data es un numpy array de 2 dmensiones (canales, alturas)
362 data = None
362 data = None
363 data_intensity = None
363 data_intensity = None
364 data_velocity = None
364 data_velocity = None
365 data_specwidth = None
365 def __init__(self):
366 def __init__(self):
366 '''
367 '''
367 Constructor
368 Constructor
368 '''
369 '''
369
370
370 self.useLocalTime = True
371 self.useLocalTime = True
371 self.radarControllerHeaderObj = RadarControllerHeader()
372 self.radarControllerHeaderObj = RadarControllerHeader()
372 self.systemHeaderObj = SystemHeader()
373 self.systemHeaderObj = SystemHeader()
373 self.type = "Voltage"
374 self.type = "Voltage"
374 self.data = None
375 self.data = None
375 # self.dtype = None
376 # self.dtype = None
376 # self.nChannels = 0
377 # self.nChannels = 0
377 # self.nHeights = 0
378 # self.nHeights = 0
378 self.nProfiles = None
379 self.nProfiles = None
379 self.heightList = None
380 self.heightList = None
380 self.channelList = None
381 self.channelList = None
381 # self.channelIndexList = None
382 # self.channelIndexList = None
382 self.flagNoData = True
383 self.flagNoData = True
383 self.flagDiscontinuousBlock = False
384 self.flagDiscontinuousBlock = False
384 self.utctime = None
385 self.utctime = None
385 self.timeZone = None
386 self.timeZone = None
386 self.dstFlag = None
387 self.dstFlag = None
387 self.errorCount = None
388 self.errorCount = None
388 self.nCohInt = None
389 self.nCohInt = None
389 self.blocksize = None
390 self.blocksize = None
390 self.flagDecodeData = False # asumo q la data no esta decodificada
391 self.flagDecodeData = False # asumo q la data no esta decodificada
391 self.flagDeflipData = False # asumo q la data no esta sin flip
392 self.flagDeflipData = False # asumo q la data no esta sin flip
392 self.flagShiftFFT = False
393 self.flagShiftFFT = False
393 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
394 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
394 self.profileIndex = 0
395 self.profileIndex = 0
395
396
396 def getNoisebyHildebrand(self, channel=None):
397 def getNoisebyHildebrand(self, channel=None):
397 """
398 """
398 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
399 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
399
400
400 Return:
401 Return:
401 noiselevel
402 noiselevel
402 """
403 """
403
404
404 if channel != None:
405 if channel != None:
405 data = self.data[channel]
406 data = self.data[channel]
406 nChannels = 1
407 nChannels = 1
407 else:
408 else:
408 data = self.data
409 data = self.data
409 nChannels = self.nChannels
410 nChannels = self.nChannels
410
411
411 noise = numpy.zeros(nChannels)
412 noise = numpy.zeros(nChannels)
412 power = data * numpy.conjugate(data)
413 power = data * numpy.conjugate(data)
413
414
414 for thisChannel in range(nChannels):
415 for thisChannel in range(nChannels):
415 if nChannels == 1:
416 if nChannels == 1:
416 daux = power[:].real
417 daux = power[:].real
417 else:
418 else:
418 daux = power[thisChannel, :].real
419 daux = power[thisChannel, :].real
419 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
420 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
420
421
421 return noise
422 return noise
422
423
423 def getNoise(self, type=1, channel=None):
424 def getNoise(self, type=1, channel=None):
424
425
425 if type == 1:
426 if type == 1:
426 noise = self.getNoisebyHildebrand(channel)
427 noise = self.getNoisebyHildebrand(channel)
427
428
428 return noise
429 return noise
429
430
430 def getPower(self, channel=None):
431 def getPower(self, channel=None):
431
432
432 if channel != None:
433 if channel != None:
433 data = self.data[channel]
434 data = self.data[channel]
434 else:
435 else:
435 data = self.data
436 data = self.data
436
437
437 power = data * numpy.conjugate(data)
438 power = data * numpy.conjugate(data)
438 powerdB = 10 * numpy.log10(power.real)
439 powerdB = 10 * numpy.log10(power.real)
439 powerdB = numpy.squeeze(powerdB)
440 powerdB = numpy.squeeze(powerdB)
440
441
441 return powerdB
442 return powerdB
442
443
443 def getTimeInterval(self):
444 def getTimeInterval(self):
444
445
445 timeInterval = self.ippSeconds * self.nCohInt
446 timeInterval = self.ippSeconds * self.nCohInt
446
447
447 return timeInterval
448 return timeInterval
448
449
449 noise = property(getNoise, "I'm the 'nHeights' property.")
450 noise = property(getNoise, "I'm the 'nHeights' property.")
450 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
451 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
451
452
452
453
453 class Spectra(JROData):
454 class Spectra(JROData):
454
455
455 # data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
456 # data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
456 data_spc = None
457 data_spc = None
457 # data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
458 # data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
458 data_cspc = None
459 data_cspc = None
459 # data dc es un numpy array de 2 dmensiones (canales, alturas)
460 # data dc es un numpy array de 2 dmensiones (canales, alturas)
460 data_dc = None
461 data_dc = None
461 # data power
462 # data power
462 data_pwr = None
463 data_pwr = None
463 nFFTPoints = None
464 nFFTPoints = None
464 # nPairs = None
465 # nPairs = None
465 pairsList = None
466 pairsList = None
466 nIncohInt = None
467 nIncohInt = None
467 wavelength = None # Necesario para cacular el rango de velocidad desde la frecuencia
468 wavelength = None # Necesario para cacular el rango de velocidad desde la frecuencia
468 nCohInt = None # se requiere para determinar el valor de timeInterval
469 nCohInt = None # se requiere para determinar el valor de timeInterval
469 ippFactor = None
470 ippFactor = None
470 profileIndex = 0
471 profileIndex = 0
471 plotting = "spectra"
472 plotting = "spectra"
472
473
473 def __init__(self):
474 def __init__(self):
474 '''
475 '''
475 Constructor
476 Constructor
476 '''
477 '''
477
478
478 self.useLocalTime = True
479 self.useLocalTime = True
479 self.radarControllerHeaderObj = RadarControllerHeader()
480 self.radarControllerHeaderObj = RadarControllerHeader()
480 self.systemHeaderObj = SystemHeader()
481 self.systemHeaderObj = SystemHeader()
481 self.type = "Spectra"
482 self.type = "Spectra"
482 # self.data = None
483 # self.data = None
483 # self.dtype = None
484 # self.dtype = None
484 # self.nChannels = 0
485 # self.nChannels = 0
485 # self.nHeights = 0
486 # self.nHeights = 0
486 self.nProfiles = None
487 self.nProfiles = None
487 self.heightList = None
488 self.heightList = None
488 self.channelList = None
489 self.channelList = None
489 # self.channelIndexList = None
490 # self.channelIndexList = None
490 self.pairsList = None
491 self.pairsList = None
491 self.flagNoData = True
492 self.flagNoData = True
492 self.flagDiscontinuousBlock = False
493 self.flagDiscontinuousBlock = False
493 self.utctime = None
494 self.utctime = None
494 self.nCohInt = None
495 self.nCohInt = None
495 self.nIncohInt = None
496 self.nIncohInt = None
496 self.blocksize = None
497 self.blocksize = None
497 self.nFFTPoints = None
498 self.nFFTPoints = None
498 self.wavelength = None
499 self.wavelength = None
499 self.flagDecodeData = False # asumo q la data no esta decodificada
500 self.flagDecodeData = False # asumo q la data no esta decodificada
500 self.flagDeflipData = False # asumo q la data no esta sin flip
501 self.flagDeflipData = False # asumo q la data no esta sin flip
501 self.flagShiftFFT = False
502 self.flagShiftFFT = False
502 self.ippFactor = 1
503 self.ippFactor = 1
503 #self.noise = None
504 #self.noise = None
504 self.beacon_heiIndexList = []
505 self.beacon_heiIndexList = []
505 self.noise_estimation = None
506 self.noise_estimation = None
506
507
507 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
508 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
508 """
509 """
509 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
510 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
510
511
511 Return:
512 Return:
512 noiselevel
513 noiselevel
513 """
514 """
514
515
515 noise = numpy.zeros(self.nChannels)
516 noise = numpy.zeros(self.nChannels)
516
517
517 for channel in range(self.nChannels):
518 for channel in range(self.nChannels):
518 daux = self.data_spc[channel,
519 daux = self.data_spc[channel,
519 xmin_index:xmax_index, ymin_index:ymax_index]
520 xmin_index:xmax_index, ymin_index:ymax_index]
520 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
521 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
521
522
522 return noise
523 return noise
523
524
524 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
525 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
525
526
526 if self.noise_estimation is not None:
527 if self.noise_estimation is not None:
527 # this was estimated by getNoise Operation defined in jroproc_spectra.py
528 # this was estimated by getNoise Operation defined in jroproc_spectra.py
528 return self.noise_estimation
529 return self.noise_estimation
529 else:
530 else:
530 noise = self.getNoisebyHildebrand(
531 noise = self.getNoisebyHildebrand(
531 xmin_index, xmax_index, ymin_index, ymax_index)
532 xmin_index, xmax_index, ymin_index, ymax_index)
532 return noise
533 return noise
533
534
534 def getFreqRangeTimeResponse(self, extrapoints=0):
535 def getFreqRangeTimeResponse(self, extrapoints=0):
535
536
536 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
537 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
537 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.) - deltafreq / 2
538 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.) - deltafreq / 2
538
539
539 return freqrange
540 return freqrange
540
541
541 def getAcfRange(self, extrapoints=0):
542 def getAcfRange(self, extrapoints=0):
542
543
543 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
544 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
544 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
545 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
545
546
546 return freqrange
547 return freqrange
547
548
548 def getFreqRange(self, extrapoints=0):
549 def getFreqRange(self, extrapoints=0):
549
550
550 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
551 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
551 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
552 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
552
553
553 return freqrange
554 return freqrange
554
555
555 def getVelRange(self, extrapoints=0):
556 def getVelRange(self, extrapoints=0):
556
557
557 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
558 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
558 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
559 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
559
560
560 if self.nmodes:
561 if self.nmodes:
561 return velrange/self.nmodes
562 return velrange/self.nmodes
562 else:
563 else:
563 return velrange
564 return velrange
564
565
565 def getNPairs(self):
566 def getNPairs(self):
566
567
567 return len(self.pairsList)
568 return len(self.pairsList)
568
569
569 def getPairsIndexList(self):
570 def getPairsIndexList(self):
570
571
571 return list(range(self.nPairs))
572 return list(range(self.nPairs))
572
573
573 def getNormFactor(self):
574 def getNormFactor(self):
574
575
575 pwcode = 1
576 pwcode = 1
576
577
577 if self.flagDecodeData:
578 if self.flagDecodeData:
578 pwcode = numpy.sum(self.code[0]**2)
579 pwcode = numpy.sum(self.code[0]**2)
579 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
580 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
580 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
581 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
581
582
582 return normFactor
583 return normFactor
583
584
584 def getFlagCspc(self):
585 def getFlagCspc(self):
585
586
586 if self.data_cspc is None:
587 if self.data_cspc is None:
587 return True
588 return True
588
589
589 return False
590 return False
590
591
591 def getFlagDc(self):
592 def getFlagDc(self):
592
593
593 if self.data_dc is None:
594 if self.data_dc is None:
594 return True
595 return True
595
596
596 return False
597 return False
597
598
598 def getTimeInterval(self):
599 def getTimeInterval(self):
599
600
600 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
601 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
601 if self.nmodes:
602 if self.nmodes:
602 return self.nmodes*timeInterval
603 return self.nmodes*timeInterval
603 else:
604 else:
604 return timeInterval
605 return timeInterval
605
606
606 def getPower(self):
607 def getPower(self):
607
608
608 factor = self.normFactor
609 factor = self.normFactor
609 z = self.data_spc / factor
610 z = self.data_spc / factor
610 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
611 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
611 avg = numpy.average(z, axis=1)
612 avg = numpy.average(z, axis=1)
612
613
613 return 10 * numpy.log10(avg)
614 return 10 * numpy.log10(avg)
614
615
615 def getCoherence(self, pairsList=None, phase=False):
616 def getCoherence(self, pairsList=None, phase=False):
616
617
617 z = []
618 z = []
618 if pairsList is None:
619 if pairsList is None:
619 pairsIndexList = self.pairsIndexList
620 pairsIndexList = self.pairsIndexList
620 else:
621 else:
621 pairsIndexList = []
622 pairsIndexList = []
622 for pair in pairsList:
623 for pair in pairsList:
623 if pair not in self.pairsList:
624 if pair not in self.pairsList:
624 raise ValueError("Pair %s is not in dataOut.pairsList" % (
625 raise ValueError("Pair %s is not in dataOut.pairsList" % (
625 pair))
626 pair))
626 pairsIndexList.append(self.pairsList.index(pair))
627 pairsIndexList.append(self.pairsList.index(pair))
627 for i in range(len(pairsIndexList)):
628 for i in range(len(pairsIndexList)):
628 pair = self.pairsList[pairsIndexList[i]]
629 pair = self.pairsList[pairsIndexList[i]]
629 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
630 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
630 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
631 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
631 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
632 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
632 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
633 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
633 if phase:
634 if phase:
634 data = numpy.arctan2(avgcoherenceComplex.imag,
635 data = numpy.arctan2(avgcoherenceComplex.imag,
635 avgcoherenceComplex.real) * 180 / numpy.pi
636 avgcoherenceComplex.real) * 180 / numpy.pi
636 else:
637 else:
637 data = numpy.abs(avgcoherenceComplex)
638 data = numpy.abs(avgcoherenceComplex)
638
639
639 z.append(data)
640 z.append(data)
640
641
641 return numpy.array(z)
642 return numpy.array(z)
642
643
643 def setValue(self, value):
644 def setValue(self, value):
644
645
645 print("This property should not be initialized")
646 print("This property should not be initialized")
646
647
647 return
648 return
648
649
649 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
650 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
650 pairsIndexList = property(
651 pairsIndexList = property(
651 getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
652 getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
652 normFactor = property(getNormFactor, setValue,
653 normFactor = property(getNormFactor, setValue,
653 "I'm the 'getNormFactor' property.")
654 "I'm the 'getNormFactor' property.")
654 flag_cspc = property(getFlagCspc, setValue)
655 flag_cspc = property(getFlagCspc, setValue)
655 flag_dc = property(getFlagDc, setValue)
656 flag_dc = property(getFlagDc, setValue)
656 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
657 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
657 timeInterval = property(getTimeInterval, setValue,
658 timeInterval = property(getTimeInterval, setValue,
658 "I'm the 'timeInterval' property")
659 "I'm the 'timeInterval' property")
659
660
660
661
661 class SpectraHeis(Spectra):
662 class SpectraHeis(Spectra):
662
663
663 data_spc = None
664 data_spc = None
664 data_cspc = None
665 data_cspc = None
665 data_dc = None
666 data_dc = None
666 nFFTPoints = None
667 nFFTPoints = None
667 # nPairs = None
668 # nPairs = None
668 pairsList = None
669 pairsList = None
669 nCohInt = None
670 nCohInt = None
670 nIncohInt = None
671 nIncohInt = None
671
672
672 def __init__(self):
673 def __init__(self):
673
674
674 self.radarControllerHeaderObj = RadarControllerHeader()
675 self.radarControllerHeaderObj = RadarControllerHeader()
675
676
676 self.systemHeaderObj = SystemHeader()
677 self.systemHeaderObj = SystemHeader()
677
678
678 self.type = "SpectraHeis"
679 self.type = "SpectraHeis"
679
680
680 # self.dtype = None
681 # self.dtype = None
681
682
682 # self.nChannels = 0
683 # self.nChannels = 0
683
684
684 # self.nHeights = 0
685 # self.nHeights = 0
685
686
686 self.nProfiles = None
687 self.nProfiles = None
687
688
688 self.heightList = None
689 self.heightList = None
689
690
690 self.channelList = None
691 self.channelList = None
691
692
692 # self.channelIndexList = None
693 # self.channelIndexList = None
693
694
694 self.flagNoData = True
695 self.flagNoData = True
695
696
696 self.flagDiscontinuousBlock = False
697 self.flagDiscontinuousBlock = False
697
698
698 # self.nPairs = 0
699 # self.nPairs = 0
699
700
700 self.utctime = None
701 self.utctime = None
701
702
702 self.blocksize = None
703 self.blocksize = None
703
704
704 self.profileIndex = 0
705 self.profileIndex = 0
705
706
706 self.nCohInt = 1
707 self.nCohInt = 1
707
708
708 self.nIncohInt = 1
709 self.nIncohInt = 1
709
710
710 def getNormFactor(self):
711 def getNormFactor(self):
711 pwcode = 1
712 pwcode = 1
712 if self.flagDecodeData:
713 if self.flagDecodeData:
713 pwcode = numpy.sum(self.code[0]**2)
714 pwcode = numpy.sum(self.code[0]**2)
714
715
715 normFactor = self.nIncohInt * self.nCohInt * pwcode
716 normFactor = self.nIncohInt * self.nCohInt * pwcode
716
717
717 return normFactor
718 return normFactor
718
719
719 def getTimeInterval(self):
720 def getTimeInterval(self):
720
721
721 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
722 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
722
723
723 return timeInterval
724 return timeInterval
724
725
725 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
726 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
726 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
727 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
727
728
728
729
729 class Fits(JROData):
730 class Fits(JROData):
730
731
731 heightList = None
732 heightList = None
732 channelList = None
733 channelList = None
733 flagNoData = True
734 flagNoData = True
734 flagDiscontinuousBlock = False
735 flagDiscontinuousBlock = False
735 useLocalTime = False
736 useLocalTime = False
736 utctime = None
737 utctime = None
737 timeZone = None
738 timeZone = None
738 # ippSeconds = None
739 # ippSeconds = None
739 # timeInterval = None
740 # timeInterval = None
740 nCohInt = None
741 nCohInt = None
741 nIncohInt = None
742 nIncohInt = None
742 noise = None
743 noise = None
743 windowOfFilter = 1
744 windowOfFilter = 1
744 # Speed of ligth
745 # Speed of ligth
745 C = 3e8
746 C = 3e8
746 frequency = 49.92e6
747 frequency = 49.92e6
747 realtime = False
748 realtime = False
748
749
749 def __init__(self):
750 def __init__(self):
750
751
751 self.type = "Fits"
752 self.type = "Fits"
752
753
753 self.nProfiles = None
754 self.nProfiles = None
754
755
755 self.heightList = None
756 self.heightList = None
756
757
757 self.channelList = None
758 self.channelList = None
758
759
759 # self.channelIndexList = None
760 # self.channelIndexList = None
760
761
761 self.flagNoData = True
762 self.flagNoData = True
762
763
763 self.utctime = None
764 self.utctime = None
764
765
765 self.nCohInt = 1
766 self.nCohInt = 1
766
767
767 self.nIncohInt = 1
768 self.nIncohInt = 1
768
769
769 self.useLocalTime = True
770 self.useLocalTime = True
770
771
771 self.profileIndex = 0
772 self.profileIndex = 0
772
773
773 # self.utctime = None
774 # self.utctime = None
774 # self.timeZone = None
775 # self.timeZone = None
775 # self.ltctime = None
776 # self.ltctime = None
776 # self.timeInterval = None
777 # self.timeInterval = None
777 # self.header = None
778 # self.header = None
778 # self.data_header = None
779 # self.data_header = None
779 # self.data = None
780 # self.data = None
780 # self.datatime = None
781 # self.datatime = None
781 # self.flagNoData = False
782 # self.flagNoData = False
782 # self.expName = ''
783 # self.expName = ''
783 # self.nChannels = None
784 # self.nChannels = None
784 # self.nSamples = None
785 # self.nSamples = None
785 # self.dataBlocksPerFile = None
786 # self.dataBlocksPerFile = None
786 # self.comments = ''
787 # self.comments = ''
787 #
788 #
788
789
789 def getltctime(self):
790 def getltctime(self):
790
791
791 if self.useLocalTime:
792 if self.useLocalTime:
792 return self.utctime - self.timeZone * 60
793 return self.utctime - self.timeZone * 60
793
794
794 return self.utctime
795 return self.utctime
795
796
796 def getDatatime(self):
797 def getDatatime(self):
797
798
798 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
799 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
799 return datatime
800 return datatime
800
801
801 def getTimeRange(self):
802 def getTimeRange(self):
802
803
803 datatime = []
804 datatime = []
804
805
805 datatime.append(self.ltctime)
806 datatime.append(self.ltctime)
806 datatime.append(self.ltctime + self.timeInterval)
807 datatime.append(self.ltctime + self.timeInterval)
807
808
808 datatime = numpy.array(datatime)
809 datatime = numpy.array(datatime)
809
810
810 return datatime
811 return datatime
811
812
812 def getHeiRange(self):
813 def getHeiRange(self):
813
814
814 heis = self.heightList
815 heis = self.heightList
815
816
816 return heis
817 return heis
817
818
818 def getNHeights(self):
819 def getNHeights(self):
819
820
820 return len(self.heightList)
821 return len(self.heightList)
821
822
822 def getNChannels(self):
823 def getNChannels(self):
823
824
824 return len(self.channelList)
825 return len(self.channelList)
825
826
826 def getChannelIndexList(self):
827 def getChannelIndexList(self):
827
828
828 return list(range(self.nChannels))
829 return list(range(self.nChannels))
829
830
830 def getNoise(self, type=1):
831 def getNoise(self, type=1):
831
832
832 #noise = numpy.zeros(self.nChannels)
833 #noise = numpy.zeros(self.nChannels)
833
834
834 if type == 1:
835 if type == 1:
835 noise = self.getNoisebyHildebrand()
836 noise = self.getNoisebyHildebrand()
836
837
837 if type == 2:
838 if type == 2:
838 noise = self.getNoisebySort()
839 noise = self.getNoisebySort()
839
840
840 if type == 3:
841 if type == 3:
841 noise = self.getNoisebyWindow()
842 noise = self.getNoisebyWindow()
842
843
843 return noise
844 return noise
844
845
845 def getTimeInterval(self):
846 def getTimeInterval(self):
846
847
847 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
848 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
848
849
849 return timeInterval
850 return timeInterval
850
851
851 def get_ippSeconds(self):
852 def get_ippSeconds(self):
852 '''
853 '''
853 '''
854 '''
854 return self.ipp_sec
855 return self.ipp_sec
855
856
856
857
857 datatime = property(getDatatime, "I'm the 'datatime' property")
858 datatime = property(getDatatime, "I'm the 'datatime' property")
858 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
859 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
859 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
860 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
860 channelIndexList = property(
861 channelIndexList = property(
861 getChannelIndexList, "I'm the 'channelIndexList' property.")
862 getChannelIndexList, "I'm the 'channelIndexList' property.")
862 noise = property(getNoise, "I'm the 'nHeights' property.")
863 noise = property(getNoise, "I'm the 'nHeights' property.")
863
864
864 ltctime = property(getltctime, "I'm the 'ltctime' property")
865 ltctime = property(getltctime, "I'm the 'ltctime' property")
865 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
866 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
866 ippSeconds = property(get_ippSeconds, '')
867 ippSeconds = property(get_ippSeconds, '')
867
868
868 class Correlation(JROData):
869 class Correlation(JROData):
869
870
870 noise = None
871 noise = None
871 SNR = None
872 SNR = None
872 #--------------------------------------------------
873 #--------------------------------------------------
873 mode = None
874 mode = None
874 split = False
875 split = False
875 data_cf = None
876 data_cf = None
876 lags = None
877 lags = None
877 lagRange = None
878 lagRange = None
878 pairsList = None
879 pairsList = None
879 normFactor = None
880 normFactor = None
880 #--------------------------------------------------
881 #--------------------------------------------------
881 # calculateVelocity = None
882 # calculateVelocity = None
882 nLags = None
883 nLags = None
883 nPairs = None
884 nPairs = None
884 nAvg = None
885 nAvg = None
885
886
886 def __init__(self):
887 def __init__(self):
887 '''
888 '''
888 Constructor
889 Constructor
889 '''
890 '''
890 self.radarControllerHeaderObj = RadarControllerHeader()
891 self.radarControllerHeaderObj = RadarControllerHeader()
891
892
892 self.systemHeaderObj = SystemHeader()
893 self.systemHeaderObj = SystemHeader()
893
894
894 self.type = "Correlation"
895 self.type = "Correlation"
895
896
896 self.data = None
897 self.data = None
897
898
898 self.dtype = None
899 self.dtype = None
899
900
900 self.nProfiles = None
901 self.nProfiles = None
901
902
902 self.heightList = None
903 self.heightList = None
903
904
904 self.channelList = None
905 self.channelList = None
905
906
906 self.flagNoData = True
907 self.flagNoData = True
907
908
908 self.flagDiscontinuousBlock = False
909 self.flagDiscontinuousBlock = False
909
910
910 self.utctime = None
911 self.utctime = None
911
912
912 self.timeZone = None
913 self.timeZone = None
913
914
914 self.dstFlag = None
915 self.dstFlag = None
915
916
916 self.errorCount = None
917 self.errorCount = None
917
918
918 self.blocksize = None
919 self.blocksize = None
919
920
920 self.flagDecodeData = False # asumo q la data no esta decodificada
921 self.flagDecodeData = False # asumo q la data no esta decodificada
921
922
922 self.flagDeflipData = False # asumo q la data no esta sin flip
923 self.flagDeflipData = False # asumo q la data no esta sin flip
923
924
924 self.pairsList = None
925 self.pairsList = None
925
926
926 self.nPoints = None
927 self.nPoints = None
927
928
928 def getPairsList(self):
929 def getPairsList(self):
929
930
930 return self.pairsList
931 return self.pairsList
931
932
932 def getNoise(self, mode=2):
933 def getNoise(self, mode=2):
933
934
934 indR = numpy.where(self.lagR == 0)[0][0]
935 indR = numpy.where(self.lagR == 0)[0][0]
935 indT = numpy.where(self.lagT == 0)[0][0]
936 indT = numpy.where(self.lagT == 0)[0][0]
936
937
937 jspectra0 = self.data_corr[:, :, indR, :]
938 jspectra0 = self.data_corr[:, :, indR, :]
938 jspectra = copy.copy(jspectra0)
939 jspectra = copy.copy(jspectra0)
939
940
940 num_chan = jspectra.shape[0]
941 num_chan = jspectra.shape[0]
941 num_hei = jspectra.shape[2]
942 num_hei = jspectra.shape[2]
942
943
943 freq_dc = jspectra.shape[1] / 2
944 freq_dc = jspectra.shape[1] / 2
944 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
945 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
945
946
946 if ind_vel[0] < 0:
947 if ind_vel[0] < 0:
947 ind_vel[list(range(0, 1))] = ind_vel[list(
948 ind_vel[list(range(0, 1))] = ind_vel[list(
948 range(0, 1))] + self.num_prof
949 range(0, 1))] + self.num_prof
949
950
950 if mode == 1:
951 if mode == 1:
951 jspectra[:, freq_dc, :] = (
952 jspectra[:, freq_dc, :] = (
952 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
953 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
953
954
954 if mode == 2:
955 if mode == 2:
955
956
956 vel = numpy.array([-2, -1, 1, 2])
957 vel = numpy.array([-2, -1, 1, 2])
957 xx = numpy.zeros([4, 4])
958 xx = numpy.zeros([4, 4])
958
959
959 for fil in range(4):
960 for fil in range(4):
960 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
961 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
961
962
962 xx_inv = numpy.linalg.inv(xx)
963 xx_inv = numpy.linalg.inv(xx)
963 xx_aux = xx_inv[0, :]
964 xx_aux = xx_inv[0, :]
964
965
965 for ich in range(num_chan):
966 for ich in range(num_chan):
966 yy = jspectra[ich, ind_vel, :]
967 yy = jspectra[ich, ind_vel, :]
967 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
968 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
968
969
969 junkid = jspectra[ich, freq_dc, :] <= 0
970 junkid = jspectra[ich, freq_dc, :] <= 0
970 cjunkid = sum(junkid)
971 cjunkid = sum(junkid)
971
972
972 if cjunkid.any():
973 if cjunkid.any():
973 jspectra[ich, freq_dc, junkid.nonzero()] = (
974 jspectra[ich, freq_dc, junkid.nonzero()] = (
974 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
975 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
975
976
976 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
977 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
977
978
978 return noise
979 return noise
979
980
980 def getTimeInterval(self):
981 def getTimeInterval(self):
981
982
982 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
983 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
983
984
984 return timeInterval
985 return timeInterval
985
986
986 def splitFunctions(self):
987 def splitFunctions(self):
987
988
988 pairsList = self.pairsList
989 pairsList = self.pairsList
989 ccf_pairs = []
990 ccf_pairs = []
990 acf_pairs = []
991 acf_pairs = []
991 ccf_ind = []
992 ccf_ind = []
992 acf_ind = []
993 acf_ind = []
993 for l in range(len(pairsList)):
994 for l in range(len(pairsList)):
994 chan0 = pairsList[l][0]
995 chan0 = pairsList[l][0]
995 chan1 = pairsList[l][1]
996 chan1 = pairsList[l][1]
996
997
997 # Obteniendo pares de Autocorrelacion
998 # Obteniendo pares de Autocorrelacion
998 if chan0 == chan1:
999 if chan0 == chan1:
999 acf_pairs.append(chan0)
1000 acf_pairs.append(chan0)
1000 acf_ind.append(l)
1001 acf_ind.append(l)
1001 else:
1002 else:
1002 ccf_pairs.append(pairsList[l])
1003 ccf_pairs.append(pairsList[l])
1003 ccf_ind.append(l)
1004 ccf_ind.append(l)
1004
1005
1005 data_acf = self.data_cf[acf_ind]
1006 data_acf = self.data_cf[acf_ind]
1006 data_ccf = self.data_cf[ccf_ind]
1007 data_ccf = self.data_cf[ccf_ind]
1007
1008
1008 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1009 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1009
1010
1010 def getNormFactor(self):
1011 def getNormFactor(self):
1011 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1012 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1012 acf_pairs = numpy.array(acf_pairs)
1013 acf_pairs = numpy.array(acf_pairs)
1013 normFactor = numpy.zeros((self.nPairs, self.nHeights))
1014 normFactor = numpy.zeros((self.nPairs, self.nHeights))
1014
1015
1015 for p in range(self.nPairs):
1016 for p in range(self.nPairs):
1016 pair = self.pairsList[p]
1017 pair = self.pairsList[p]
1017
1018
1018 ch0 = pair[0]
1019 ch0 = pair[0]
1019 ch1 = pair[1]
1020 ch1 = pair[1]
1020
1021
1021 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
1022 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
1022 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
1023 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
1023 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
1024 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
1024
1025
1025 return normFactor
1026 return normFactor
1026
1027
1027 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1028 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1028 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1029 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1029
1030
1030
1031
1031 class Parameters(Spectra):
1032 class Parameters(Spectra):
1032
1033
1033 experimentInfo = None # Information about the experiment
1034 experimentInfo = None # Information about the experiment
1034 # Information from previous data
1035 # Information from previous data
1035 inputUnit = None # Type of data to be processed
1036 inputUnit = None # Type of data to be processed
1036 operation = None # Type of operation to parametrize
1037 operation = None # Type of operation to parametrize
1037 # normFactor = None #Normalization Factor
1038 # normFactor = None #Normalization Factor
1038 groupList = None # List of Pairs, Groups, etc
1039 groupList = None # List of Pairs, Groups, etc
1039 # Parameters
1040 # Parameters
1040 data_param = None # Parameters obtained
1041 data_param = None # Parameters obtained
1041 data_pre = None # Data Pre Parametrization
1042 data_pre = None # Data Pre Parametrization
1042 data_SNR = None # Signal to Noise Ratio
1043 data_SNR = None # Signal to Noise Ratio
1043 # heightRange = None #Heights
1044 # heightRange = None #Heights
1044 abscissaList = None # Abscissa, can be velocities, lags or time
1045 abscissaList = None # Abscissa, can be velocities, lags or time
1045 # noise = None #Noise Potency
1046 # noise = None #Noise Potency
1046 utctimeInit = None # Initial UTC time
1047 utctimeInit = None # Initial UTC time
1047 paramInterval = None # Time interval to calculate Parameters in seconds
1048 paramInterval = None # Time interval to calculate Parameters in seconds
1048 useLocalTime = True
1049 useLocalTime = True
1049 # Fitting
1050 # Fitting
1050 data_error = None # Error of the estimation
1051 data_error = None # Error of the estimation
1051 constants = None
1052 constants = None
1052 library = None
1053 library = None
1053 # Output signal
1054 # Output signal
1054 outputInterval = None # Time interval to calculate output signal in seconds
1055 outputInterval = None # Time interval to calculate output signal in seconds
1055 data_output = None # Out signal
1056 data_output = None # Out signal
1056 nAvg = None
1057 nAvg = None
1057 noise_estimation = None
1058 noise_estimation = None
1058 GauSPC = None # Fit gaussian SPC
1059 GauSPC = None # Fit gaussian SPC
1059
1060
1060 def __init__(self):
1061 def __init__(self):
1061 '''
1062 '''
1062 Constructor
1063 Constructor
1063 '''
1064 '''
1064 self.radarControllerHeaderObj = RadarControllerHeader()
1065 self.radarControllerHeaderObj = RadarControllerHeader()
1065
1066
1066 self.systemHeaderObj = SystemHeader()
1067 self.systemHeaderObj = SystemHeader()
1067
1068
1068 self.type = "Parameters"
1069 self.type = "Parameters"
1069
1070
1070 def getTimeRange1(self, interval):
1071 def getTimeRange1(self, interval):
1071
1072
1072 datatime = []
1073 datatime = []
1073
1074
1074 if self.useLocalTime:
1075 if self.useLocalTime:
1075 time1 = self.utctimeInit - self.timeZone * 60
1076 time1 = self.utctimeInit - self.timeZone * 60
1076 else:
1077 else:
1077 time1 = self.utctimeInit
1078 time1 = self.utctimeInit
1078
1079
1079 datatime.append(time1)
1080 datatime.append(time1)
1080 datatime.append(time1 + interval)
1081 datatime.append(time1 + interval)
1081 datatime = numpy.array(datatime)
1082 datatime = numpy.array(datatime)
1082
1083
1083 return datatime
1084 return datatime
1084
1085
1085 def getTimeInterval(self):
1086 def getTimeInterval(self):
1086
1087
1087 if hasattr(self, 'timeInterval1'):
1088 if hasattr(self, 'timeInterval1'):
1088 return self.timeInterval1
1089 return self.timeInterval1
1089 else:
1090 else:
1090 return self.paramInterval
1091 return self.paramInterval
1091
1092
1092 def setValue(self, value):
1093 def setValue(self, value):
1093
1094
1094 print("This property should not be initialized")
1095 print("This property should not be initialized")
1095
1096
1096 return
1097 return
1097
1098
1098 def getNoise(self):
1099 def getNoise(self):
1099
1100
1100 return self.spc_noise
1101 return self.spc_noise
1101
1102
1102 timeInterval = property(getTimeInterval)
1103 timeInterval = property(getTimeInterval)
1103 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
1104 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
1104
1105
1105
1106
1106 class PlotterData(object):
1107 class PlotterData(object):
1107 '''
1108 '''
1108 Object to hold data to be plotted
1109 Object to hold data to be plotted
1109 '''
1110 '''
1110
1111
1111 MAXNUMX = 100
1112 MAXNUMX = 100
1112 MAXNUMY = 100
1113 MAXNUMY = 100
1113
1114
1114 def __init__(self, code, throttle_value, exp_code, buffering=True, snr=False):
1115 def __init__(self, code, throttle_value, exp_code, buffering=True, snr=False):
1115
1116
1116 self.key = code
1117 self.key = code
1117 self.throttle = throttle_value
1118 self.throttle = throttle_value
1118 self.exp_code = exp_code
1119 self.exp_code = exp_code
1119 self.buffering = buffering
1120 self.buffering = buffering
1120 self.ready = False
1121 self.ready = False
1121 self.flagNoData = False
1122 self.flagNoData = False
1122 self.localtime = False
1123 self.localtime = False
1123 self.data = {}
1124 self.data = {}
1124 self.meta = {}
1125 self.meta = {}
1125 self.__times = []
1126 self.__times = []
1126 self.__heights = []
1127 self.__heights = []
1127
1128
1128 if 'snr' in code:
1129 if 'snr' in code:
1129 self.plottypes = ['snr']
1130 self.plottypes = ['snr']
1130 elif code == 'spc':
1131 elif code == 'spc':
1131 self.plottypes = ['spc', 'noise', 'rti']
1132 self.plottypes = ['spc', 'noise', 'rti']
1132 elif code == 'rti':
1133 elif code == 'rti':
1133 self.plottypes = ['noise', 'rti']
1134 self.plottypes = ['noise', 'rti']
1134 else:
1135 else:
1135 self.plottypes = [code]
1136 self.plottypes = [code]
1136
1137
1137 if 'snr' not in self.plottypes and snr:
1138 if 'snr' not in self.plottypes and snr:
1138 self.plottypes.append('snr')
1139 self.plottypes.append('snr')
1139
1140
1140 for plot in self.plottypes:
1141 for plot in self.plottypes:
1141 self.data[plot] = {}
1142 self.data[plot] = {}
1142
1143
1143
1144
1144 def __str__(self):
1145 def __str__(self):
1145 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1146 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1146 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
1147 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
1147
1148
1148 def __len__(self):
1149 def __len__(self):
1149 return len(self.__times)
1150 return len(self.__times)
1150
1151
1151 def __getitem__(self, key):
1152 def __getitem__(self, key):
1152
1153
1153 if key not in self.data:
1154 if key not in self.data:
1154 raise KeyError(log.error('Missing key: {}'.format(key)))
1155 raise KeyError(log.error('Missing key: {}'.format(key)))
1155 if 'spc' in key or not self.buffering:
1156 if 'spc' in key or not self.buffering:
1156 ret = self.data[key]
1157 ret = self.data[key]
1157 elif 'scope' in key:
1158 elif 'scope' in key:
1158 ret = numpy.array(self.data[key][float(self.tm)])
1159 ret = numpy.array(self.data[key][float(self.tm)])
1159 else:
1160 else:
1160 ret = numpy.array([self.data[key][x] for x in self.times])
1161 ret = numpy.array([self.data[key][x] for x in self.times])
1161 if ret.ndim > 1:
1162 if ret.ndim > 1:
1162 ret = numpy.swapaxes(ret, 0, 1)
1163 ret = numpy.swapaxes(ret, 0, 1)
1163 return ret
1164 return ret
1164
1165
1165 def __contains__(self, key):
1166 def __contains__(self, key):
1166 return key in self.data
1167 return key in self.data
1167
1168
1168 def setup(self):
1169 def setup(self):
1169 '''
1170 '''
1170 Configure object
1171 Configure object
1171 '''
1172 '''
1172 self.type = ''
1173 self.type = ''
1173 self.ready = False
1174 self.ready = False
1174 self.data = {}
1175 self.data = {}
1175 self.__times = []
1176 self.__times = []
1176 self.__heights = []
1177 self.__heights = []
1177 self.__all_heights = set()
1178 self.__all_heights = set()
1178 for plot in self.plottypes:
1179 for plot in self.plottypes:
1179 if 'snr' in plot:
1180 if 'snr' in plot:
1180 plot = 'snr'
1181 plot = 'snr'
1181 elif 'spc_moments' == plot:
1182 elif 'spc_moments' == plot:
1182 plot = 'moments'
1183 plot = 'moments'
1183 self.data[plot] = {}
1184 self.data[plot] = {}
1184
1185
1185 if 'spc' in self.data or 'rti' in self.data or 'cspc' in self.data or 'moments' in self.data:
1186 if 'spc' in self.data or 'rti' in self.data or 'cspc' in self.data or 'moments' in self.data:
1186 self.data['noise'] = {}
1187 self.data['noise'] = {}
1187 self.data['rti'] = {}
1188 self.data['rti'] = {}
1188 if 'noise' not in self.plottypes:
1189 if 'noise' not in self.plottypes:
1189 self.plottypes.append('noise')
1190 self.plottypes.append('noise')
1190 if 'rti' not in self.plottypes:
1191 if 'rti' not in self.plottypes:
1191 self.plottypes.append('rti')
1192 self.plottypes.append('rti')
1192
1193
1193 def shape(self, key):
1194 def shape(self, key):
1194 '''
1195 '''
1195 Get the shape of the one-element data for the given key
1196 Get the shape of the one-element data for the given key
1196 '''
1197 '''
1197
1198
1198 if len(self.data[key]):
1199 if len(self.data[key]):
1199 if 'spc' in key or not self.buffering:
1200 if 'spc' in key or not self.buffering:
1200 return self.data[key].shape
1201 return self.data[key].shape
1201 return self.data[key][self.__times[0]].shape
1202 return self.data[key][self.__times[0]].shape
1202 return (0,)
1203 return (0,)
1203
1204
1204 def update(self, dataOut, tm):
1205 def update(self, dataOut, tm):
1205 '''
1206 '''
1206 Update data object with new dataOut
1207 Update data object with new dataOut
1207 '''
1208 '''
1208 if tm in self.__times:
1209 if tm in self.__times:
1209 return
1210 return
1210 self.profileIndex = dataOut.profileIndex
1211 self.profileIndex = dataOut.profileIndex
1211 self.tm = tm
1212 self.tm = tm
1212 self.type = dataOut.type
1213 self.type = dataOut.type
1213 self.parameters = getattr(dataOut, 'parameters', [])
1214 self.parameters = getattr(dataOut, 'parameters', [])
1214
1215
1215 if hasattr(dataOut, 'meta'):
1216 if hasattr(dataOut, 'meta'):
1216 self.meta.update(dataOut.meta)
1217 self.meta.update(dataOut.meta)
1217
1218
1218 if hasattr(dataOut, 'pairsList'):
1219 if hasattr(dataOut, 'pairsList'):
1219 self.pairs = dataOut.pairsList
1220 self.pairs = dataOut.pairsList
1220
1221
1221 self.interval = dataOut.getTimeInterval()
1222 self.interval = dataOut.getTimeInterval()
1222 self.localtime = dataOut.useLocalTime
1223 self.localtime = dataOut.useLocalTime
1223 if True in ['spc' in ptype for ptype in self.plottypes]:
1224 if True in ['spc' in ptype for ptype in self.plottypes]:
1224 self.xrange = (dataOut.getFreqRange(1)/1000.,
1225 self.xrange = (dataOut.getFreqRange(1)/1000.,
1225 dataOut.getAcfRange(1), dataOut.getVelRange(1))
1226 dataOut.getAcfRange(1), dataOut.getVelRange(1))
1226 self.factor = dataOut.normFactor
1227 self.factor = dataOut.normFactor
1227 self.__heights.append(dataOut.heightList)
1228 self.__heights.append(dataOut.heightList)
1228 self.__all_heights.update(dataOut.heightList)
1229 self.__all_heights.update(dataOut.heightList)
1229 self.__times.append(tm)
1230 self.__times.append(tm)
1230 for plot in self.plottypes:
1231 for plot in self.plottypes:
1231 if plot in ('spc', 'spc_moments', 'spc_cut'):
1232 if plot in ('spc', 'spc_moments', 'spc_cut'):
1232 z = dataOut.data_spc/dataOut.normFactor
1233 z = dataOut.data_spc/dataOut.normFactor
1233 buffer = 10*numpy.log10(z)
1234 buffer = 10*numpy.log10(z)
1234 if plot == 'cspc':
1235 if plot == 'cspc':
1235 z = dataOut.data_spc/dataOut.normFactor
1236 z = dataOut.data_spc/dataOut.normFactor
1236 buffer = (dataOut.data_spc, dataOut.data_cspc)
1237 buffer = (dataOut.data_spc, dataOut.data_cspc)
1237 if plot == 'noise':
1238 if plot == 'noise':
1238 buffer = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
1239 buffer = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
1239 if plot in ('rti', 'spcprofile'):
1240 if plot in ('rti', 'spcprofile'):
1240 buffer = dataOut.getPower()
1241 buffer = dataOut.getPower()
1241 if plot == 'snr_db':
1242 if plot == 'snr_db':
1242 buffer = dataOut.data_SNR
1243 buffer = dataOut.data_SNR
1243 if plot == 'snr':
1244 if plot == 'snr':
1244 buffer = 10*numpy.log10(dataOut.data_SNR)
1245 buffer = 10*numpy.log10(dataOut.data_SNR)
1245 if plot == 'dop':
1246 if plot == 'dop':
1246 buffer = dataOut.data_DOP
1247 buffer = dataOut.data_DOP
1247 if plot == 'pow':
1248 if plot == 'pow':
1248 buffer = 10*numpy.log10(dataOut.data_POW)
1249 buffer = 10*numpy.log10(dataOut.data_POW)
1249 if plot == 'width':
1250 if plot == 'width':
1250 buffer = dataOut.data_WIDTH
1251 buffer = dataOut.data_WIDTH
1251 if plot == 'coh':
1252 if plot == 'coh':
1252 buffer = dataOut.getCoherence()
1253 buffer = dataOut.getCoherence()
1253 if plot == 'phase':
1254 if plot == 'phase':
1254 buffer = dataOut.getCoherence(phase=True)
1255 buffer = dataOut.getCoherence(phase=True)
1255 if plot == 'output':
1256 if plot == 'output':
1256 buffer = dataOut.data_output
1257 buffer = dataOut.data_output
1257 if plot == 'param':
1258 if plot == 'param':
1258 buffer = dataOut.data_param
1259 buffer = dataOut.data_param
1259 if plot == 'scope':
1260 if plot == 'scope':
1260 buffer = dataOut.data
1261 buffer = dataOut.data
1261 self.flagDataAsBlock = dataOut.flagDataAsBlock
1262 self.flagDataAsBlock = dataOut.flagDataAsBlock
1262 self.nProfiles = dataOut.nProfiles
1263 self.nProfiles = dataOut.nProfiles
1263 if plot == 'pp_power':
1264 if plot == 'pp_power':
1264 buffer = dataOut.data_intensity
1265 buffer = dataOut.data_intensity
1265 self.flagDataAsBlock = dataOut.flagDataAsBlock
1266 self.flagDataAsBlock = dataOut.flagDataAsBlock
1266 self.nProfiles = dataOut.nProfiles
1267 self.nProfiles = dataOut.nProfiles
1267 if plot == 'pp_velocity':
1268 if plot == 'pp_velocity':
1268 buffer = dataOut.data_velocity
1269 buffer = dataOut.data_velocity
1269 self.flagDataAsBlock = dataOut.flagDataAsBlock
1270 self.flagDataAsBlock = dataOut.flagDataAsBlock
1270 self.nProfiles = dataOut.nProfiles
1271 self.nProfiles = dataOut.nProfiles
1272 if plot == 'pp_specwidth':
1273 buffer = dataOut.data_specwidth
1274 self.flagDataAsBlock = dataOut.flagDataAsBlock
1275 self.nProfiles = dataOut.nProfiles
1271
1276
1272 if plot == 'spc':
1277 if plot == 'spc':
1273 self.data['spc'] = buffer
1278 self.data['spc'] = buffer
1274 elif plot == 'cspc':
1279 elif plot == 'cspc':
1275 self.data['spc'] = buffer[0]
1280 self.data['spc'] = buffer[0]
1276 self.data['cspc'] = buffer[1]
1281 self.data['cspc'] = buffer[1]
1277 elif plot == 'spc_moments':
1282 elif plot == 'spc_moments':
1278 self.data['spc'] = buffer
1283 self.data['spc'] = buffer
1279 self.data['moments'][tm] = dataOut.moments
1284 self.data['moments'][tm] = dataOut.moments
1280 else:
1285 else:
1281 if self.buffering:
1286 if self.buffering:
1282 self.data[plot][tm] = buffer
1287 self.data[plot][tm] = buffer
1283 else:
1288 else:
1284 self.data[plot] = buffer
1289 self.data[plot] = buffer
1285
1290
1286 if dataOut.channelList is None:
1291 if dataOut.channelList is None:
1287 self.channels = range(buffer.shape[0])
1292 self.channels = range(buffer.shape[0])
1288 else:
1293 else:
1289 self.channels = dataOut.channelList
1294 self.channels = dataOut.channelList
1290
1295
1291 if buffer is None:
1296 if buffer is None:
1292 self.flagNoData = True
1297 self.flagNoData = True
1293 raise schainpy.admin.SchainWarning('Attribute data_{} is empty'.format(self.key))
1298 raise schainpy.admin.SchainWarning('Attribute data_{} is empty'.format(self.key))
1294
1299
1295 def normalize_heights(self):
1300 def normalize_heights(self):
1296 '''
1301 '''
1297 Ensure same-dimension of the data for different heighList
1302 Ensure same-dimension of the data for different heighList
1298 '''
1303 '''
1299
1304
1300 H = numpy.array(list(self.__all_heights))
1305 H = numpy.array(list(self.__all_heights))
1301 H.sort()
1306 H.sort()
1302 for key in self.data:
1307 for key in self.data:
1303 shape = self.shape(key)[:-1] + H.shape
1308 shape = self.shape(key)[:-1] + H.shape
1304 for tm, obj in list(self.data[key].items()):
1309 for tm, obj in list(self.data[key].items()):
1305 h = self.__heights[self.__times.index(tm)]
1310 h = self.__heights[self.__times.index(tm)]
1306 if H.size == h.size:
1311 if H.size == h.size:
1307 continue
1312 continue
1308 index = numpy.where(numpy.in1d(H, h))[0]
1313 index = numpy.where(numpy.in1d(H, h))[0]
1309 dummy = numpy.zeros(shape) + numpy.nan
1314 dummy = numpy.zeros(shape) + numpy.nan
1310 if len(shape) == 2:
1315 if len(shape) == 2:
1311 dummy[:, index] = obj
1316 dummy[:, index] = obj
1312 else:
1317 else:
1313 dummy[index] = obj
1318 dummy[index] = obj
1314 self.data[key][tm] = dummy
1319 self.data[key][tm] = dummy
1315
1320
1316 self.__heights = [H for tm in self.__times]
1321 self.__heights = [H for tm in self.__times]
1317
1322
1318 def jsonify(self, plot_name, plot_type, decimate=False):
1323 def jsonify(self, plot_name, plot_type, decimate=False):
1319 '''
1324 '''
1320 Convert data to json
1325 Convert data to json
1321 '''
1326 '''
1322
1327
1323 tm = self.times[-1]
1328 tm = self.times[-1]
1324 dy = int(self.heights.size/self.MAXNUMY) + 1
1329 dy = int(self.heights.size/self.MAXNUMY) + 1
1325 if self.key in ('spc', 'cspc') or not self.buffering:
1330 if self.key in ('spc', 'cspc') or not self.buffering:
1326 dx = int(self.data[self.key].shape[1]/self.MAXNUMX) + 1
1331 dx = int(self.data[self.key].shape[1]/self.MAXNUMX) + 1
1327 data = self.roundFloats(
1332 data = self.roundFloats(
1328 self.data[self.key][::, ::dx, ::dy].tolist())
1333 self.data[self.key][::, ::dx, ::dy].tolist())
1329 else:
1334 else:
1330 data = self.roundFloats(self.data[self.key][tm].tolist())
1335 data = self.roundFloats(self.data[self.key][tm].tolist())
1331 if self.key is 'noise':
1336 if self.key is 'noise':
1332 data = [[x] for x in data]
1337 data = [[x] for x in data]
1333
1338
1334 meta = {}
1339 meta = {}
1335 ret = {
1340 ret = {
1336 'plot': plot_name,
1341 'plot': plot_name,
1337 'code': self.exp_code,
1342 'code': self.exp_code,
1338 'time': float(tm),
1343 'time': float(tm),
1339 'data': data,
1344 'data': data,
1340 }
1345 }
1341 meta['type'] = plot_type
1346 meta['type'] = plot_type
1342 meta['interval'] = float(self.interval)
1347 meta['interval'] = float(self.interval)
1343 meta['localtime'] = self.localtime
1348 meta['localtime'] = self.localtime
1344 meta['yrange'] = self.roundFloats(self.heights[::dy].tolist())
1349 meta['yrange'] = self.roundFloats(self.heights[::dy].tolist())
1345 if 'spc' in self.data or 'cspc' in self.data:
1350 if 'spc' in self.data or 'cspc' in self.data:
1346 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1351 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1347 else:
1352 else:
1348 meta['xrange'] = []
1353 meta['xrange'] = []
1349
1354
1350 meta.update(self.meta)
1355 meta.update(self.meta)
1351 ret['metadata'] = meta
1356 ret['metadata'] = meta
1352 return json.dumps(ret)
1357 return json.dumps(ret)
1353
1358
1354 @property
1359 @property
1355 def times(self):
1360 def times(self):
1356 '''
1361 '''
1357 Return the list of times of the current data
1362 Return the list of times of the current data
1358 '''
1363 '''
1359
1364
1360 ret = numpy.array(self.__times)
1365 ret = numpy.array(self.__times)
1361 ret.sort()
1366 ret.sort()
1362 return ret
1367 return ret
1363
1368
1364 @property
1369 @property
1365 def min_time(self):
1370 def min_time(self):
1366 '''
1371 '''
1367 Return the minimun time value
1372 Return the minimun time value
1368 '''
1373 '''
1369
1374
1370 return self.times[0]
1375 return self.times[0]
1371
1376
1372 @property
1377 @property
1373 def max_time(self):
1378 def max_time(self):
1374 '''
1379 '''
1375 Return the maximun time value
1380 Return the maximun time value
1376 '''
1381 '''
1377
1382
1378 return self.times[-1]
1383 return self.times[-1]
1379
1384
1380 @property
1385 @property
1381 def heights(self):
1386 def heights(self):
1382 '''
1387 '''
1383 Return the list of heights of the current data
1388 Return the list of heights of the current data
1384 '''
1389 '''
1385
1390
1386 return numpy.array(self.__heights[-1])
1391 return numpy.array(self.__heights[-1])
1387
1392
1388 @staticmethod
1393 @staticmethod
1389 def roundFloats(obj):
1394 def roundFloats(obj):
1390 if isinstance(obj, list):
1395 if isinstance(obj, list):
1391 return list(map(PlotterData.roundFloats, obj))
1396 return list(map(PlotterData.roundFloats, obj))
1392 elif isinstance(obj, float):
1397 elif isinstance(obj, float):
1393 return round(obj, 2)
1398 return round(obj, 2)
@@ -1,473 +1,526
1 import numpy,math,random,time
1 import numpy,math,random,time
2 #---------------1 Heredamos JRODatareader
2 #---------------1 Heredamos JRODatareader
3 from schainpy.model.io.jroIO_base import *
3 from schainpy.model.io.jroIO_base import *
4 #---------------2 Heredamos las propiedades de ProcessingUnit
4 #---------------2 Heredamos las propiedades de ProcessingUnit
5 from schainpy.model.proc.jroproc_base import ProcessingUnit,Operation,MPDecorator
5 from schainpy.model.proc.jroproc_base import ProcessingUnit,Operation,MPDecorator
6 #---------------3 Importaremos las clases BascicHeader, SystemHeader, RadarControlHeader, ProcessingHeader
6 #---------------3 Importaremos las clases BascicHeader, SystemHeader, RadarControlHeader, ProcessingHeader
7 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader,SystemHeader,RadarControllerHeader, ProcessingHeader
7 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader,SystemHeader,RadarControllerHeader, ProcessingHeader
8 #---------------4 Importaremos el objeto Voltge
8 #---------------4 Importaremos el objeto Voltge
9 from schainpy.model.data.jrodata import Voltage
9 from schainpy.model.data.jrodata import Voltage
10
10
11 class SimulatorReader(JRODataReader, ProcessingUnit):
11 class SimulatorReader(JRODataReader, ProcessingUnit):
12 incIntFactor = 1
12 incIntFactor = 1
13 nFFTPoints = 0
13 nFFTPoints = 0
14 FixPP_IncInt = 1
14 FixPP_IncInt = 1
15 FixRCP_IPP = 1000
15 FixRCP_IPP = 1000
16 FixPP_CohInt = 1
16 FixPP_CohInt = 1
17 Tau_0 = 250
17 Tau_0 = 250
18 AcqH0_0 = 70
18 AcqH0_0 = 70
19 H0 = AcqH0_0
19 H0 = AcqH0_0
20 AcqDH_0 = 1.25
20 AcqDH_0 = 1.25
21 DH0 = AcqDH_0
21 DH0 = AcqDH_0
22 Bauds = 32
22 Bauds = 32
23 BaudWidth = None
23 BaudWidth = None
24 FixRCP_TXA = 40
24 FixRCP_TXA = 40
25 FixRCP_TXB = 70
25 FixRCP_TXB = 70
26 fAngle = 2.0*math.pi*(1/16)
26 fAngle = 2.0*math.pi*(1/16)
27 DC_level = 500
27 DC_level = 500
28 stdev = 8
28 stdev = 8
29 Num_Codes = 2
29 Num_Codes = 2
30 #code0 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1])
30 #code0 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1])
31 #code1 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0])
31 #code1 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0])
32 #Dyn_snCode = numpy.array([Num_Codes,Bauds])
32 #Dyn_snCode = numpy.array([Num_Codes,Bauds])
33 Dyn_snCode = None
33 Dyn_snCode = None
34 Samples = 200
34 Samples = 200
35 channels = 5
35 channels = 2
36 pulses = None
36 pulses = None
37 Reference = None
37 Reference = None
38 pulse_size = None
38 pulse_size = None
39 prof_gen = None
39 prof_gen = None
40 Fdoppler = 100
40 Fdoppler = 100
41 Hdoppler = 36
41 Hdoppler = 36
42 Adoppler = 300
42 Adoppler = 300
43 frequency = 9345
43 frequency = 9345
44 nTotalReadFiles = 1000
44 nTotalReadFiles = 1000
45
45
46 def __init__(self):
46 def __init__(self):
47 """
47 """
48 Inicializador de la clases SimulatorReader para
48 Inicializador de la clases SimulatorReader para
49 generar datos de voltage simulados.
49 generar datos de voltage simulados.
50 Input:
50 Input:
51 dataOut: Objeto de la clase Voltage.
51 dataOut: Objeto de la clase Voltage.
52 Este Objeto sera utilizado apra almacenar
52 Este Objeto sera utilizado apra almacenar
53 un perfil de datos cada vez qe se haga
53 un perfil de datos cada vez qe se haga
54 un requerimiento (getData)
54 un requerimiento (getData)
55 """
55 """
56 ProcessingUnit.__init__(self)
56 ProcessingUnit.__init__(self)
57 print(" [ START ] init - Metodo Simulator Reader")
57 print(" [ START ] init - Metodo Simulator Reader")
58
58
59 self.isConfig = False
59 self.isConfig = False
60 self.basicHeaderObj = BasicHeader(LOCALTIME)
60 self.basicHeaderObj = BasicHeader(LOCALTIME)
61 self.systemHeaderObj = SystemHeader()
61 self.systemHeaderObj = SystemHeader()
62 self.radarControllerHeaderObj = RadarControllerHeader()
62 self.radarControllerHeaderObj = RadarControllerHeader()
63 self.processingHeaderObj = ProcessingHeader()
63 self.processingHeaderObj = ProcessingHeader()
64 self.profileIndex = 2**32-1
64 self.profileIndex = 2**32-1
65 self.dataOut = Voltage()
65 self.dataOut = Voltage()
66 #code0 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1])
66 #code0 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1])
67 code0 = numpy.array([1,1,1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,1,-1,-1,-1,1,1,1,-1,1])
67 code0 = numpy.array([1,1,1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,1,-1,1,1,-1,1,-1,-1,-1,1,1,1,-1,1])
68 #code1 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0])
68 #code1 = numpy.array([1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0])
69 code1 = numpy.array([1,1,1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,1,1,-1,-1,-1,1,-1])
69 code1 = numpy.array([1,1,1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,1,1,-1,-1,-1,1,-1])
70 #self.Dyn_snCode = numpy.array([code0,code1])
70 #self.Dyn_snCode = numpy.array([code0,code1])
71 self.Dyn_snCode = None
71 self.Dyn_snCode = None
72
72
73 def set_kwargs(self, **kwargs):
73 def set_kwargs(self, **kwargs):
74 for key, value in kwargs.items():
74 for key, value in kwargs.items():
75 setattr(self, key, value)
75 setattr(self, key, value)
76
76
77 def __hasNotDataInBuffer(self):
77 def __hasNotDataInBuffer(self):
78
78
79 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock* self.nTxs:
79 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock* self.nTxs:
80 if self.nReadBlocks>0:
80 if self.nReadBlocks>0:
81 tmp = self.dataOut.utctime
81 tmp = self.dataOut.utctime
82 tmp_utc = int(self.dataOut.utctime)
82 tmp_utc = int(self.dataOut.utctime)
83 tmp_milisecond = int((tmp-tmp_utc)*1000)
83 tmp_milisecond = int((tmp-tmp_utc)*1000)
84 self.basicHeaderObj.utc = tmp_utc
84 self.basicHeaderObj.utc = tmp_utc
85 self.basicHeaderObj.miliSecond= tmp_milisecond
85 self.basicHeaderObj.miliSecond= tmp_milisecond
86 return 1
86 return 1
87 return 0
87 return 0
88
88
89 def setNextFile(self):
89 def setNextFile(self):
90 """Set the next file to be readed open it and parse de file header"""
90 """Set the next file to be readed open it and parse de file header"""
91
91
92 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
92 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
93 self.nReadFiles=self.nReadFiles+1
93 self.nReadFiles=self.nReadFiles+1
94 if self.nReadFiles ==self.nTotalReadFiles:
94 if self.nReadFiles > self.nTotalReadFiles:
95 self.flagNoMoreFiles=1
95 self.flagNoMoreFiles=1
96 raise schainpy.admin.SchainWarning('No more files to read')
96 raise schainpy.admin.SchainWarning('No more files to read')
97
97
98 print('------------------- [Opening file] ------------------------------',self.nReadFiles)
98 print('------------------- [Opening file] ------------------------------',self.nReadFiles)
99 self.nReadBlocks = 0
99 self.nReadBlocks = 0
100 #if self.nReadBlocks==0:
101 # self.readFirstHeader()
100
102
101 def __setNewBlock(self):
103 def __setNewBlock(self):
102 self.setNextFile()
104 self.setNextFile()
103 if self.flagIsNewFile:
105 if self.flagIsNewFile:
104 return 1
106 return 1
105
107
106 def readNextBlock(self):
108 def readNextBlock(self):
107 while True:
109 while True:
108 self.__setNewBlock()
110 self.__setNewBlock()
109 if not(self.readBlock()):
111 if not(self.readBlock()):
110 return 0
112 return 0
111 self.getBasicHeader()
113 self.getBasicHeader()
112 break
114 break
113 if self.verbose:
115 if self.verbose:
114 print("[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
116 print("[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
115 self.processingHeaderObj.dataBlocksPerFile,
117 self.processingHeaderObj.dataBlocksPerFile,
116 self.dataOut.datatime.ctime()) )
118 self.dataOut.datatime.ctime()) )
117 return 1
119 return 1
118
120
119 def getFirstHeader(self):
121 def getFirstHeader(self):
120 self.getBasicHeader()
122 self.getBasicHeader()
121 self.dataOut.processingHeaderObj = self.processingHeaderObj.copy()
123 self.dataOut.processingHeaderObj = self.processingHeaderObj.copy()
122 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
124 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
123 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
125 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
126 self.dataOut.dtype = self.dtype
124
127
125 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
128 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
126 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
129 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
127 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
130 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
128 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
131 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
129 # asumo q la data no esta decodificada
132 # asumo q la data no esta decodificada
130 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode
133 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode
131 # asumo q la data no esta sin flip
134 # asumo q la data no esta sin flip
132 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip
135 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip
133 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
136 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
134 self.dataOut.frequency = self.frequency
137 self.dataOut.frequency = self.frequency
135
138
136 def getBasicHeader(self):
139 def getBasicHeader(self):
137 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
140 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
138 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
141 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
139
142
140 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
143 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
141 self.dataOut.timeZone = self.basicHeaderObj.timeZone
144 self.dataOut.timeZone = self.basicHeaderObj.timeZone
142 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
145 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
143 self.dataOut.errorCount = self.basicHeaderObj.errorCount
146 self.dataOut.errorCount = self.basicHeaderObj.errorCount
144 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
147 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
145 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
148 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
146
149
150 def readFirstHeader(self):
151
152 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
153 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
154 if datatype == 0:
155 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
156 elif datatype == 1:
157 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
158 elif datatype == 2:
159 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
160 elif datatype == 3:
161 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
162 elif datatype == 4:
163 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
164 elif datatype == 5:
165 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
166 else:
167 raise ValueError('Data type was not defined')
168
169 self.dtype = datatype_str
170
171
147 def set_RCH(self, expType=2, nTx=1,ipp=None, txA=0, txB=0,
172 def set_RCH(self, expType=2, nTx=1,ipp=None, txA=0, txB=0,
148 nWindows=None, nHeights=None, firstHeight=None, deltaHeight=None,
173 nWindows=None, nHeights=None, firstHeight=None, deltaHeight=None,
149 numTaus=0, line6Function=0, line5Function=0, fClock=None,
174 numTaus=0, line6Function=0, line5Function=0, fClock=None,
150 prePulseBefore=0, prePulseAfter=0,
175 prePulseBefore=0, prePulseAfter=0,
151 codeType=0, nCode=0, nBaud=0, code=None,
176 codeType=0, nCode=0, nBaud=0, code=None,
152 flip1=0, flip2=0):
177 flip1=0, flip2=0,Taus=0):
153 self.radarControllerHeaderObj.expType = expType
178 self.radarControllerHeaderObj.expType = expType
154 self.radarControllerHeaderObj.nTx = nTx
179 self.radarControllerHeaderObj.nTx = nTx
155 self.radarControllerHeaderObj.ipp = float(ipp)
180 self.radarControllerHeaderObj.ipp = float(ipp)
156 self.radarControllerHeaderObj.txA = float(txA)
181 self.radarControllerHeaderObj.txA = float(txA)
157 self.radarControllerHeaderObj.txB = float(txB)
182 self.radarControllerHeaderObj.txB = float(txB)
158 self.radarControllerHeaderObj.rangeIPP = ipp
183 self.radarControllerHeaderObj.rangeIpp = b'A\n'#ipp
159 self.radarControllerHeaderObj.rangeTxA = txA
184 self.radarControllerHeaderObj.rangeTxA = b''
160 self.radarControllerHeaderObj.rangeTxB = txB
185 self.radarControllerHeaderObj.rangeTxB = b''
161
186
162 self.radarControllerHeaderObj.nHeights = int(nHeights)
187 self.radarControllerHeaderObj.nHeights = int(nHeights)
163 self.radarControllerHeaderObj.firstHeight = numpy.array([firstHeight])
188 self.radarControllerHeaderObj.firstHeight = numpy.array([firstHeight])
164 self.radarControllerHeaderObj.deltaHeight = numpy.array([deltaHeight])
189 self.radarControllerHeaderObj.deltaHeight = numpy.array([deltaHeight])
165 self.radarControllerHeaderObj.samplesWin = numpy.array([nHeights])
190 self.radarControllerHeaderObj.samplesWin = numpy.array([nHeights])
166
191
167
192
168 self.radarControllerHeaderObj.nWindows = nWindows
193 self.radarControllerHeaderObj.nWindows = nWindows
169 self.radarControllerHeaderObj.numTaus = numTaus
194 self.radarControllerHeaderObj.numTaus = numTaus
170 self.radarControllerHeaderObj.codeType = codeType
195 self.radarControllerHeaderObj.codeType = codeType
171 self.radarControllerHeaderObj.line6Function = line6Function
196 self.radarControllerHeaderObj.line6Function = line6Function
172 self.radarControllerHeaderObj.line5Function = line5Function
197 self.radarControllerHeaderObj.line5Function = line5Function
173 self.radarControllerHeaderObj.fclock = fClock
198 #self.radarControllerHeaderObj.fClock = fClock
174 self.radarControllerHeaderObj.prePulseBefore= prePulseBefore
199 self.radarControllerHeaderObj.prePulseBefore= prePulseBefore
175 self.radarControllerHeaderObj.prePulseAfter = prePulseAfter
200 self.radarControllerHeaderObj.prePulseAfter = prePulseAfter
176
201
177 self.radarControllerHeaderObj.nCode = nCode
178 self.radarControllerHeaderObj.nBaud = nBaud
179 self.radarControllerHeaderObj.code = code
180 self.radarControllerHeaderObj.flip1 = flip1
202 self.radarControllerHeaderObj.flip1 = flip1
181 self.radarControllerHeaderObj.flip2 = flip2
203 self.radarControllerHeaderObj.flip2 = flip2
182
204
183 self.radarControllerHeaderObj.code_size = int(numpy.ceil(nBaud / 32.)) * nCode * 4
205 self.radarControllerHeaderObj.code_size = 0
206 if self.radarControllerHeaderObj.codeType != 0:
207 self.radarControllerHeaderObj.nCode = nCode
208 self.radarControllerHeaderObj.nBaud = nBaud
209 self.radarControllerHeaderObj.code = code
210 self.radarControllerHeaderObj.code_size = int(numpy.ceil(nBaud / 32.)) * nCode * 4
184
211
185 if fClock is None and deltaHeight is not None:
212 if fClock is None and deltaHeight is not None:
186 self.fClock = 0.15 / (deltaHeight * 1e-6)
213 self.fClock = 0.15 / (deltaHeight * 1e-6)
214 self.radarControllerHeaderObj.fClock = self.fClock
215 if numTaus==0:
216 self.radarControllerHeaderObj.Taus = numpy.array(0,'<f4')
217 else:
218 self.radarControllerHeaderObj.Taus = numpy.array(Taus,'<f4')
187
219
188 def set_PH(self, dtype=0, blockSize=0, profilesPerBlock=0,
220 def set_PH(self, dtype=0, blockSize=0, profilesPerBlock=0,
189 dataBlocksPerFile=0, nWindows=0, processFlags=0, nCohInt=0,
221 dataBlocksPerFile=0, nWindows=0, processFlags=0, nCohInt=0,
190 nIncohInt=0, totalSpectra=0, nHeights=0, firstHeight=0,
222 nIncohInt=0, totalSpectra=0, nHeights=0, firstHeight=0,
191 deltaHeight=0, samplesWin=0, spectraComb=0, nCode=0,
223 deltaHeight=0, samplesWin=0, spectraComb=0, nCode=0,
192 code=0, nBaud=None, shif_fft=False, flag_dc=False,
224 code=0, nBaud=None, shif_fft=False, flag_dc=False,
193 flag_cspc=False, flag_decode=False, flag_deflip=False):
225 flag_cspc=False, flag_decode=False, flag_deflip=False):
194
226
227 self.processingHeaderObj.dtype = dtype
195 self.processingHeaderObj.profilesPerBlock = profilesPerBlock
228 self.processingHeaderObj.profilesPerBlock = profilesPerBlock
196 self.processingHeaderObj.dataBlocksPerFile = dataBlocksPerFile
229 self.processingHeaderObj.dataBlocksPerFile = dataBlocksPerFile
197 self.processingHeaderObj.nWindows = nWindows
230 self.processingHeaderObj.nWindows = nWindows
231 self.processingHeaderObj.processFlags = processFlags
198 self.processingHeaderObj.nCohInt = nCohInt
232 self.processingHeaderObj.nCohInt = nCohInt
199 self.processingHeaderObj.nIncohInt = nIncohInt
233 self.processingHeaderObj.nIncohInt = nIncohInt
200 self.processingHeaderObj.totalSpectra = totalSpectra
234 self.processingHeaderObj.totalSpectra = totalSpectra
235
201 self.processingHeaderObj.nHeights = int(nHeights)
236 self.processingHeaderObj.nHeights = int(nHeights)
202 self.processingHeaderObj.firstHeight = firstHeight
237 self.processingHeaderObj.firstHeight = firstHeight#numpy.array([firstHeight])#firstHeight
203 self.processingHeaderObj.deltaHeight = deltaHeight
238 self.processingHeaderObj.deltaHeight = deltaHeight#numpy.array([deltaHeight])#deltaHeight
204 self.processingHeaderObj.samplesWin = nHeights
239 self.processingHeaderObj.samplesWin = nHeights#numpy.array([nHeights])#nHeights
205
240
206 def set_BH(self, utc = 0, miliSecond = 0, timeZone = 0):
241 def set_BH(self, utc = 0, miliSecond = 0, timeZone = 0):
207 self.basicHeaderObj.utc = utc
242 self.basicHeaderObj.utc = utc
208 self.basicHeaderObj.miliSecond = miliSecond
243 self.basicHeaderObj.miliSecond = miliSecond
209 self.basicHeaderObj.timeZone = timeZone
244 self.basicHeaderObj.timeZone = timeZone
210
245
211 def set_SH(self, nSamples=0, nProfiles=0, nChannels=0, adcResolution=14, pciDioBusWidth=0):
246 def set_SH(self, nSamples=0, nProfiles=0, nChannels=0, adcResolution=14, pciDioBusWidth=32):
247 #self.systemHeaderObj.size = size
212 self.systemHeaderObj.nSamples = nSamples
248 self.systemHeaderObj.nSamples = nSamples
213 self.systemHeaderObj.nProfiles = nProfiles
249 self.systemHeaderObj.nProfiles = nProfiles
214 self.systemHeaderObj.nChannels = nChannels
250 self.systemHeaderObj.nChannels = nChannels
215 self.systemHeaderObj.adcResolution = adcResolution
251 self.systemHeaderObj.adcResolution = adcResolution
216 self.systemHeaderObj.pciDioBusWidth = pciDioBusWidth
252 self.systemHeaderObj.pciDioBusWidth = pciDioBusWidth
217
253
218 def init_acquisition(self):
254 def init_acquisition(self):
219
255
220 if self.nFFTPoints != 0:
256 if self.nFFTPoints != 0:
221 self.incIntFactor = m_nProfilesperBlock/self.nFFTPoints
257 self.incIntFactor = m_nProfilesperBlock/self.nFFTPoints
222 if (self.FixPP_IncInt > self.incIntFactor):
258 if (self.FixPP_IncInt > self.incIntFactor):
223 self.incIntFactor = self.FixPP_IncInt/ self.incIntFactor
259 self.incIntFactor = self.FixPP_IncInt/ self.incIntFactor
224 elif(self.FixPP_IncInt< self.incIntFactor):
260 elif(self.FixPP_IncInt< self.incIntFactor):
225 print("False alert...")
261 print("False alert...")
226
262
227 ProfilesperBlock = self.processingHeaderObj.profilesPerBlock
263 ProfilesperBlock = self.processingHeaderObj.profilesPerBlock
228
264
229 self.timeperblock =int(((self.FixRCP_IPP
265 self.timeperblock =int(((self.FixRCP_IPP
230 *ProfilesperBlock
266 *ProfilesperBlock
231 *self.FixPP_CohInt
267 *self.FixPP_CohInt
232 *self.incIntFactor)
268 *self.incIntFactor)
233 /150.0)
269 /150.0)
234 *0.9
270 *0.9
235 +0.5)
271 +0.5)
236 # para cada canal
272 # para cada canal
237 self.profiles = ProfilesperBlock*self.FixPP_CohInt
273 self.profiles = ProfilesperBlock*self.FixPP_CohInt
238 self.profiles = ProfilesperBlock
274 self.profiles = ProfilesperBlock
239 self.Reference = int((self.Tau_0-self.AcqH0_0)/(self.AcqDH_0)+0.5)
275 self.Reference = int((self.Tau_0-self.AcqH0_0)/(self.AcqDH_0)+0.5)
240 self.BaudWidth = int((self.FixRCP_TXA/self.AcqDH_0)/self.Bauds + 0.5 )
276 self.BaudWidth = int((self.FixRCP_TXA/self.AcqDH_0)/self.Bauds + 0.5 )
241
277
242 if (self.BaudWidth==0):
278 if (self.BaudWidth==0):
243 self.BaudWidth=1
279 self.BaudWidth=1
244
280
245 def init_pulse(self,Num_Codes=Num_Codes,Bauds=Bauds,BaudWidth=BaudWidth,Dyn_snCode=Dyn_snCode):
281 def init_pulse(self,Num_Codes=Num_Codes,Bauds=Bauds,BaudWidth=BaudWidth,Dyn_snCode=Dyn_snCode):
246
282
247 Num_Codes = Num_Codes
283 Num_Codes = Num_Codes
248 Bauds = Bauds
284 Bauds = Bauds
249 BaudWidth = BaudWidth
285 BaudWidth = BaudWidth
250 Dyn_snCode = Dyn_snCode
286 Dyn_snCode = Dyn_snCode
251
287
252 if Dyn_snCode:
288 if Dyn_snCode:
253 print("EXISTE")
289 print("EXISTE")
254 else:
290 else:
255 print("No existe")
291 print("No existe")
256
292
257 if Dyn_snCode: # if Bauds:
293 if Dyn_snCode: # if Bauds:
258 pulses = list(range(0,Num_Codes))
294 pulses = list(range(0,Num_Codes))
259 num_codes = Num_Codes
295 num_codes = Num_Codes
260 for i in range(num_codes):
296 for i in range(num_codes):
261 pulse_size = Bauds*BaudWidth
297 pulse_size = Bauds*BaudWidth
262 pulses[i] = numpy.zeros(pulse_size)
298 pulses[i] = numpy.zeros(pulse_size)
263 for j in range(Bauds):
299 for j in range(Bauds):
264 for k in range(BaudWidth):
300 for k in range(BaudWidth):
265 pulses[i][j*BaudWidth+k] = int(Dyn_snCode[i][j]*600)
301 pulses[i][j*BaudWidth+k] = int(Dyn_snCode[i][j]*600)
266 else:
302 else:
267 print("sin code")
303 print("sin code")
268 pulses = list(range(1))
304 pulses = list(range(1))
269 if self.AcqDH_0>0.149:
305 if self.AcqDH_0>0.149:
270 pulse_size = int(self.FixRCP_TXB/0.15+0.5)
306 pulse_size = int(self.FixRCP_TXB/0.15+0.5)
271 else:
307 else:
272 pulse_size = int((self.FixRCP_TXB/self.AcqDH_0)+0.5) #0.0375
308 pulse_size = int((self.FixRCP_TXB/self.AcqDH_0)+0.5) #0.0375
273 pulses[0] = numpy.ones(pulse_size)
309 pulses[0] = numpy.ones(pulse_size)
274 pulses = 600*pulses[0]
310 pulses = 600*pulses[0]
275
311
276 return pulses,pulse_size
312 return pulses,pulse_size
277
313
278 def jro_GenerateBlockOfData(self,Samples=Samples,DC_level= DC_level,stdev=stdev,
314 def jro_GenerateBlockOfData(self,Samples=Samples,DC_level= DC_level,stdev=stdev,
279 Reference= Reference,pulses= pulses,
315 Reference= Reference,pulses= pulses,
280 Num_Codes= Num_Codes,pulse_size=pulse_size,
316 Num_Codes= Num_Codes,pulse_size=pulse_size,
281 prof_gen= prof_gen,H0 = H0,DH0=DH0,
317 prof_gen= prof_gen,H0 = H0,DH0=DH0,
282 Adoppler=Adoppler,Fdoppler= Fdoppler,Hdoppler=Hdoppler):
318 Adoppler=Adoppler,Fdoppler= Fdoppler,Hdoppler=Hdoppler):
283 Samples = Samples
319 Samples = Samples
284 DC_level = DC_level
320 DC_level = DC_level
285 stdev = stdev
321 stdev = stdev
286 m_nR = Reference
322 m_nR = Reference
287 pulses = pulses
323 pulses = pulses
288 num_codes = Num_Codes
324 num_codes = Num_Codes
289 ps = pulse_size
325 ps = pulse_size
290 prof_gen = prof_gen
326 prof_gen = prof_gen
291 channels = self.channels
327 channels = self.channels
292 H0 = H0
328 H0 = H0
293 DH0 = DH0
329 DH0 = DH0
294 ippSec = self.radarControllerHeaderObj.ippSeconds
330 ippSec = self.radarControllerHeaderObj.ippSeconds
295 Fdoppler = self.Fdoppler
331 Fdoppler = self.Fdoppler
296 Hdoppler = self.Hdoppler
332 Hdoppler = self.Hdoppler
297 Adoppler = self.Adoppler
333 Adoppler = self.Adoppler
298
334
299 self.datablock = numpy.zeros([channels,prof_gen,Samples],dtype= numpy.complex64)
335 self.datablock = numpy.zeros([channels,prof_gen,Samples],dtype= numpy.complex64)
300 for i in range(channels):
336 for i in range(channels):
301 for k in range(prof_gen):
337 for k in range(prof_gen):
302 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·NOISEΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
338 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·NOISEΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
303 Noise_r = numpy.random.normal(DC_level,stdev,Samples)
339 Noise_r = numpy.random.normal(DC_level,stdev,Samples)
304 Noise_i = numpy.random.normal(DC_level,stdev,Samples)
340 Noise_i = numpy.random.normal(DC_level,stdev,Samples)
305 Noise = numpy.zeros(Samples,dtype=complex)
341 Noise = numpy.zeros(Samples,dtype=complex)
306 Noise.real = Noise_r
342 Noise.real = Noise_r
307 Noise.imag = Noise_i
343 Noise.imag = Noise_i
308 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·PULSOSΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
344 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·PULSOSΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
309 Pulso = numpy.zeros(pulse_size,dtype=complex)
345 Pulso = numpy.zeros(pulse_size,dtype=complex)
310 Pulso.real = pulses[k%num_codes]
346 Pulso.real = pulses[k%num_codes]
311 Pulso.imag = pulses[k%num_codes]
347 Pulso.imag = pulses[k%num_codes]
312 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· PULSES+NOISEΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·
348 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· PULSES+NOISEΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·
313 InBuffer = numpy.zeros(Samples,dtype=complex)
349 InBuffer = numpy.zeros(Samples,dtype=complex)
314 InBuffer[m_nR:m_nR+ps] = Pulso
350 InBuffer[m_nR:m_nR+ps] = Pulso
315 InBuffer = InBuffer+Noise
351 InBuffer = InBuffer+Noise
316 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· ANGLE Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
352 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· ANGLE Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
317 InBuffer.real[m_nR:m_nR+ps] = InBuffer.real[m_nR:m_nR+ps]*(math.cos( self.fAngle)*5)
353 InBuffer.real[m_nR:m_nR+ps] = InBuffer.real[m_nR:m_nR+ps]*(math.cos( self.fAngle)*5)
318 InBuffer.imag[m_nR:m_nR+ps] = InBuffer.imag[m_nR:m_nR+ps]*(math.sin( self.fAngle)*5)
354 InBuffer.imag[m_nR:m_nR+ps] = InBuffer.imag[m_nR:m_nR+ps]*(math.sin( self.fAngle)*5)
319 InBuffer=InBuffer
355 InBuffer=InBuffer
320 self.datablock[i][k]= InBuffer
356 self.datablock[i][k]= InBuffer
321 #plot_cts(InBuffer,H0=H0,DH0=DH0)
357 #plot_cts(InBuffer,H0=H0,DH0=DH0)
322 #wave_fft(x=InBuffer,plot_show=True)
358 #wave_fft(x=InBuffer,plot_show=True)
323 #time.sleep(1)
359 #time.sleep(1)
324 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·DOPPLER SIGNAL...............................................
360 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·DOPPLER SIGNAL...............................................
325 time_vec = numpy.linspace(0,(prof_gen-1)*ippSec,int(prof_gen))+self.nReadBlocks*ippSec*prof_gen+(self.nReadFiles-1)*ippSec*prof_gen
361 time_vec = numpy.linspace(0,(prof_gen-1)*ippSec,int(prof_gen))+self.nReadBlocks*ippSec*prof_gen+(self.nReadFiles-1)*ippSec*prof_gen
326 fd = Fdoppler #+(600.0/120)*self.nReadBlocks
362 fd = Fdoppler #+(600.0/120)*self.nReadBlocks
327 d_signal = Adoppler*numpy.array(numpy.exp(1.0j*2.0*math.pi*fd*time_vec),dtype=numpy.complex64)
363 d_signal = Adoppler*numpy.array(numpy.exp(1.0j*2.0*math.pi*fd*time_vec),dtype=numpy.complex64)
328 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· DATABLOCK + DOPPLERΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·...........................
364 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·SeΓ±al con ancho espectralΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
365 #specw_sig = numpy.zeros(int(prof_gen),dtype=complex)
366 #specw_sig.real[200:200+100] = 1*numpy.ones(100)
367 #specw_sig.imag[200:200+100] = 1*numpy.ones(100)
368 # w=2
369 specw_sig = numpy.linspace(-149,150,300)
370 w = 3
371 A = 10
372 specw_sig = specw_sig/w
373 specw_sig = numpy.sinc(specw_sig)
374 specw_sig = A*numpy.array(specw_sig,dtype=numpy.complex64)
375 #Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· DATABLOCK + DOPPLERΒ·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·Β·
329 HD=int(Hdoppler/self.AcqDH_0)
376 HD=int(Hdoppler/self.AcqDH_0)
330 for i in range(12):
377 for i in range(12):
331 self.datablock[:,:,HD+i]=self.datablock[:,:,HD+i]+ d_signal # RESULT
378 self.datablock[0,:,HD+i]=self.datablock[0,:,HD+i]+ d_signal# RESULT
379
380 HD=int(Hdoppler/self.AcqDH_0)
381 HD=int(HD/2)
382 for i in range(12):
383 self.datablock[0,:,HD+i]=self.datablock[0,:,HD+i]+ specw_sig*d_signal# RESULT
384
332 '''
385 '''
333 a= numpy.zeros(10)
386 a= numpy.zeros(10)
334 for i in range(10):
387 for i in range(10):
335 a[i]=i+self.nReadBlocks+20
388 a[i]=i+self.nReadBlocks+20
336 for i in a:
389 for i in a:
337 self.datablock[0,:,int(i)]=self.datablock[0,:,int(i)]+ d_signal # RESULT
390 self.datablock[0,:,int(i)]=self.datablock[0,:,int(i)]+ d_signal # RESULT
338 '''
391 '''
339
392
340 def readBlock(self):
393 def readBlock(self):
341
394
342 self.jro_GenerateBlockOfData(Samples= self.samples,DC_level=self.DC_level,
395 self.jro_GenerateBlockOfData(Samples= self.samples,DC_level=self.DC_level,
343 stdev=self.stdev,Reference= self.Reference,
396 stdev=self.stdev,Reference= self.Reference,
344 pulses = self.pulses,Num_Codes=self.Num_Codes,
397 pulses = self.pulses,Num_Codes=self.Num_Codes,
345 pulse_size=self.pulse_size,prof_gen=self.profiles,
398 pulse_size=self.pulse_size,prof_gen=self.profiles,
346 H0=self.H0,DH0=self.DH0)
399 H0=self.H0,DH0=self.DH0)
347
400
348 self.profileIndex = 0
401 self.profileIndex = 0
349 self.flagIsNewFile = 0
402 self.flagIsNewFile = 0
350 self.flagIsNewBlock = 1
403 self.flagIsNewBlock = 1
351 self.nTotalBlocks += 1
404 self.nTotalBlocks += 1
352 self.nReadBlocks += 1
405 self.nReadBlocks += 1
353
406
354 return 1
407 return 1
355
408
356
409
357 def getData(self):
410 def getData(self):
358 if self.flagNoMoreFiles:
411 if self.flagNoMoreFiles:
359 self.dataOut.flagNodata = True
412 self.dataOut.flagNodata = True
360 return 0
413 return 0
361 self.flagDiscontinuousBlock = 0
414 self.flagDiscontinuousBlock = 0
362 self.flagIsNewBlock = 0
415 self.flagIsNewBlock = 0
363 if self.__hasNotDataInBuffer(): # aqui es verdad
416 if self.__hasNotDataInBuffer(): # aqui es verdad
364 if not(self.readNextBlock()): # return 1 y por eso el if not salta a getBasic Header
417 if not(self.readNextBlock()): # return 1 y por eso el if not salta a getBasic Header
365 return 0
418 return 0
366 self.getFirstHeader() # atributo
419 self.getFirstHeader() # atributo
367
420
368 if not self.getByBlock:
421 if not self.getByBlock:
369 self.dataOut.flagDataAsBlock = False
422 self.dataOut.flagDataAsBlock = False
370 self.dataOut.data = self.datablock[:, self.profileIndex, :]
423 self.dataOut.data = self.datablock[:, self.profileIndex, :]
371 self.dataOut.profileIndex = self.profileIndex
424 self.dataOut.profileIndex = self.profileIndex
372 self.profileIndex += 1
425 self.profileIndex += 1
373 else:
426 else:
374 pass
427 pass
375 self.dataOut.flagNoData = False
428 self.dataOut.flagNoData = False
376 self.getBasicHeader()
429 self.getBasicHeader()
377 self.dataOut.realtime = self.online
430 self.dataOut.realtime = self.online
378 return self.dataOut.data
431 return self.dataOut.data
379
432
380
433
381 def setup(self,frequency=49.92e6,incIntFactor= 1, nFFTPoints = 0, FixPP_IncInt=1,FixRCP_IPP=1000,
434 def setup(self,frequency=49.92e6,incIntFactor= 1, nFFTPoints = 0, FixPP_IncInt=1,FixRCP_IPP=1000,
382 FixPP_CohInt= 1,Tau_0= 250,AcqH0_0 = 70 ,AcqDH_0=1.25, Bauds= 32,
435 FixPP_CohInt= 1,Tau_0= 250,AcqH0_0 = 70 ,AcqDH_0=1.25, Bauds= 32,
383 FixRCP_TXA = 40, FixRCP_TXB = 50, fAngle = 2.0*math.pi*(1/16),DC_level= 50,
436 FixRCP_TXA = 40, FixRCP_TXB = 50, fAngle = 2.0*math.pi*(1/16),DC_level= 50,
384 stdev= 8,Num_Codes = 1 , Dyn_snCode = None, samples=200,
437 stdev= 8,Num_Codes = 1 , Dyn_snCode = None, samples=200,
385 channels=2,Fdoppler=20,Hdoppler=36,Adoppler=500,nTotalReadFiles=10000,
438 channels=2,Fdoppler=20,Hdoppler=36,Adoppler=500,nTotalReadFiles=10000,
386 **kwargs):
439 **kwargs):
387
440
388 self.set_kwargs(**kwargs)
441 self.set_kwargs(**kwargs)
389 self.nReadBlocks = 0
442 self.nReadBlocks = 0
390 self.nReadFiles = 1
443 self.nReadFiles = 1
391 print('------------------- [Opening file: ] ------------------------------',self.nReadFiles)
444 print('------------------- [Opening file: ] ------------------------------',self.nReadFiles)
392
445
393 tmp = time.time()
446 tmp = time.time()
394 tmp_utc = int(tmp)
447 tmp_utc = int(tmp)
395 tmp_milisecond = int((tmp-tmp_utc)*1000)
448 tmp_milisecond = int((tmp-tmp_utc)*1000)
396 print(" SETUP -basicHeaderObj.utc",datetime.datetime.utcfromtimestamp(tmp))
449 print(" SETUP -basicHeaderObj.utc",datetime.datetime.utcfromtimestamp(tmp))
397 if Dyn_snCode is None:
450 if Dyn_snCode is None:
398 Num_Codes=1
451 Num_Codes=1
399 Bauds =1
452 Bauds =1
400
453
401
454
402
455
403 self.set_BH(utc= tmp_utc,miliSecond= tmp_milisecond,timeZone=300 )
456 self.set_BH(utc= tmp_utc,miliSecond= tmp_milisecond,timeZone=300 )
404
405 self.set_RCH( expType=0, nTx=150,ipp=FixRCP_IPP, txA=FixRCP_TXA, txB= FixRCP_TXB,
457 self.set_RCH( expType=0, nTx=150,ipp=FixRCP_IPP, txA=FixRCP_TXA, txB= FixRCP_TXB,
406 nWindows=1 , nHeights=samples, firstHeight=AcqH0_0, deltaHeight=AcqDH_0,
458 nWindows=1 , nHeights=samples, firstHeight=AcqH0_0, deltaHeight=AcqDH_0,
407 numTaus=1, line6Function=0, line5Function=0, fClock=None,
459 numTaus=1, line6Function=0, line5Function=0, fClock=None,
408 prePulseBefore=0, prePulseAfter=0,
460 prePulseBefore=0, prePulseAfter=0,
409 codeType=14, nCode=Num_Codes, nBaud=32, code=Dyn_snCode,
461 codeType=0, nCode=Num_Codes, nBaud=32, code=Dyn_snCode,
410 flip1=0, flip2=0)
462 flip1=0, flip2=0,Taus=Tau_0)
411
463
412 self.set_PH(dtype=0, blockSize=0, profilesPerBlock=300,
464 self.set_PH(dtype=0, blockSize=0, profilesPerBlock=300,
413 dataBlocksPerFile=120, nWindows=1, processFlags=0, nCohInt=1,
465 dataBlocksPerFile=120, nWindows=1, processFlags=numpy.array([1024]), nCohInt=1,
414 nIncohInt=1, totalSpectra=0, nHeights=samples, firstHeight=AcqH0_0,
466 nIncohInt=1, totalSpectra=0, nHeights=samples, firstHeight=AcqH0_0,
415 deltaHeight=AcqDH_0, samplesWin=samples, spectraComb=0, nCode=0,
467 deltaHeight=AcqDH_0, samplesWin=samples, spectraComb=0, nCode=0,
416 code=0, nBaud=None, shif_fft=False, flag_dc=False,
468 code=0, nBaud=None, shif_fft=False, flag_dc=False,
417 flag_cspc=False, flag_decode=False, flag_deflip=False)
469 flag_cspc=False, flag_decode=False, flag_deflip=False)
418
470
419 self.set_SH(nSamples=samples, nProfiles=300, nChannels=channels)
471 self.set_SH(nSamples=samples, nProfiles=300, nChannels=channels)
420
472
473 self.readFirstHeader()
421
474
422 self.frequency = frequency
475 self.frequency = frequency
423 self.incIntFactor = incIntFactor
476 self.incIntFactor = incIntFactor
424 self.nFFTPoints = nFFTPoints
477 self.nFFTPoints = nFFTPoints
425 self.FixPP_IncInt = FixPP_IncInt
478 self.FixPP_IncInt = FixPP_IncInt
426 self.FixRCP_IPP = FixRCP_IPP
479 self.FixRCP_IPP = FixRCP_IPP
427 self.FixPP_CohInt = FixPP_CohInt
480 self.FixPP_CohInt = FixPP_CohInt
428 self.Tau_0 = Tau_0
481 self.Tau_0 = Tau_0
429 self.AcqH0_0 = AcqH0_0
482 self.AcqH0_0 = AcqH0_0
430 self.H0 = AcqH0_0
483 self.H0 = AcqH0_0
431 self.AcqDH_0 = AcqDH_0
484 self.AcqDH_0 = AcqDH_0
432 self.DH0 = AcqDH_0
485 self.DH0 = AcqDH_0
433 self.Bauds = Bauds
486 self.Bauds = Bauds
434 self.FixRCP_TXA = FixRCP_TXA
487 self.FixRCP_TXA = FixRCP_TXA
435 self.FixRCP_TXB = FixRCP_TXB
488 self.FixRCP_TXB = FixRCP_TXB
436 self.fAngle = fAngle
489 self.fAngle = fAngle
437 self.DC_level = DC_level
490 self.DC_level = DC_level
438 self.stdev = stdev
491 self.stdev = stdev
439 self.Num_Codes = Num_Codes
492 self.Num_Codes = Num_Codes
440 self.Dyn_snCode = Dyn_snCode
493 self.Dyn_snCode = Dyn_snCode
441 self.samples = samples
494 self.samples = samples
442 self.channels = channels
495 self.channels = channels
443 self.profiles = None
496 self.profiles = None
444 self.m_nReference = None
497 self.m_nReference = None
445 self.Baudwidth = None
498 self.Baudwidth = None
446 self.Fdoppler = Fdoppler
499 self.Fdoppler = Fdoppler
447 self.Hdoppler = Hdoppler
500 self.Hdoppler = Hdoppler
448 self.Adoppler = Adoppler
501 self.Adoppler = Adoppler
449 self.nTotalReadFiles = int(nTotalReadFiles)
502 self.nTotalReadFiles = int(nTotalReadFiles)
450
503
451 print("IPP ", self.FixRCP_IPP)
504 print("IPP ", self.FixRCP_IPP)
452 print("Tau_0 ",self.Tau_0)
505 print("Tau_0 ",self.Tau_0)
453 print("AcqH0_0",self.AcqH0_0)
506 print("AcqH0_0",self.AcqH0_0)
454 print("samples,window ",self.samples)
507 print("samples,window ",self.samples)
455 print("AcqDH_0",AcqDH_0)
508 print("AcqDH_0",AcqDH_0)
456 print("FixRCP_TXA",self.FixRCP_TXA)
509 print("FixRCP_TXA",self.FixRCP_TXA)
457 print("FixRCP_TXB",self.FixRCP_TXB)
510 print("FixRCP_TXB",self.FixRCP_TXB)
458 print("Dyn_snCode",Dyn_snCode)
511 print("Dyn_snCode",Dyn_snCode)
459 print("Fdoppler", Fdoppler)
512 print("Fdoppler", Fdoppler)
460 print("Hdoppler",Hdoppler)
513 print("Hdoppler",Hdoppler)
461 print("Vdopplermax",Fdoppler*(3.0e8/self.frequency)/2.0)
514 print("Vdopplermax",Fdoppler*(3.0e8/self.frequency)/2.0)
462 print("nTotalReadFiles", nTotalReadFiles)
515 print("nTotalReadFiles", nTotalReadFiles)
463
516
464 self.init_acquisition()
517 self.init_acquisition()
465 self.pulses,self.pulse_size=self.init_pulse(Num_Codes=self.Num_Codes,Bauds=self.Bauds,BaudWidth=self.BaudWidth,Dyn_snCode=Dyn_snCode)
518 self.pulses,self.pulse_size=self.init_pulse(Num_Codes=self.Num_Codes,Bauds=self.Bauds,BaudWidth=self.BaudWidth,Dyn_snCode=Dyn_snCode)
466 print(" [ END ] - SETUP metodo")
519 print(" [ END ] - SETUP metodo")
467 return
520 return
468
521
469 def run(self,**kwargs): # metodo propio
522 def run(self,**kwargs): # metodo propio
470 if not(self.isConfig):
523 if not(self.isConfig):
471 self.setup(**kwargs)
524 self.setup(**kwargs)
472 self.isConfig = True
525 self.isConfig = True
473 self.getData()
526 self.getData()
@@ -1,1557 +1,1581
1 import sys
1 import sys
2 import numpy,math
2 import numpy,math
3 from scipy import interpolate
3 from scipy import interpolate
4 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
4 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
5 from schainpy.model.data.jrodata import Voltage
5 from schainpy.model.data.jrodata import Voltage
6 from schainpy.utils import log
6 from schainpy.utils import log
7 from time import time
7 from time import time
8
8
9
9
10
10
11 class VoltageProc(ProcessingUnit):
11 class VoltageProc(ProcessingUnit):
12
12
13 def __init__(self):
13 def __init__(self):
14
14
15 ProcessingUnit.__init__(self)
15 ProcessingUnit.__init__(self)
16
16
17 self.dataOut = Voltage()
17 self.dataOut = Voltage()
18 self.flip = 1
18 self.flip = 1
19 self.setupReq = False
19 self.setupReq = False
20
20
21 def run(self):
21 def run(self):
22
22
23 if self.dataIn.type == 'AMISR':
23 if self.dataIn.type == 'AMISR':
24 self.__updateObjFromAmisrInput()
24 self.__updateObjFromAmisrInput()
25
25
26 if self.dataIn.type == 'Voltage':
26 if self.dataIn.type == 'Voltage':
27 self.dataOut.copy(self.dataIn)
27 self.dataOut.copy(self.dataIn)
28
28
29 def __updateObjFromAmisrInput(self):
29 def __updateObjFromAmisrInput(self):
30
30
31 self.dataOut.timeZone = self.dataIn.timeZone
31 self.dataOut.timeZone = self.dataIn.timeZone
32 self.dataOut.dstFlag = self.dataIn.dstFlag
32 self.dataOut.dstFlag = self.dataIn.dstFlag
33 self.dataOut.errorCount = self.dataIn.errorCount
33 self.dataOut.errorCount = self.dataIn.errorCount
34 self.dataOut.useLocalTime = self.dataIn.useLocalTime
34 self.dataOut.useLocalTime = self.dataIn.useLocalTime
35
35
36 self.dataOut.flagNoData = self.dataIn.flagNoData
36 self.dataOut.flagNoData = self.dataIn.flagNoData
37 self.dataOut.data = self.dataIn.data
37 self.dataOut.data = self.dataIn.data
38 self.dataOut.utctime = self.dataIn.utctime
38 self.dataOut.utctime = self.dataIn.utctime
39 self.dataOut.channelList = self.dataIn.channelList
39 self.dataOut.channelList = self.dataIn.channelList
40 #self.dataOut.timeInterval = self.dataIn.timeInterval
40 #self.dataOut.timeInterval = self.dataIn.timeInterval
41 self.dataOut.heightList = self.dataIn.heightList
41 self.dataOut.heightList = self.dataIn.heightList
42 self.dataOut.nProfiles = self.dataIn.nProfiles
42 self.dataOut.nProfiles = self.dataIn.nProfiles
43
43
44 self.dataOut.nCohInt = self.dataIn.nCohInt
44 self.dataOut.nCohInt = self.dataIn.nCohInt
45 self.dataOut.ippSeconds = self.dataIn.ippSeconds
45 self.dataOut.ippSeconds = self.dataIn.ippSeconds
46 self.dataOut.frequency = self.dataIn.frequency
46 self.dataOut.frequency = self.dataIn.frequency
47
47
48 self.dataOut.azimuth = self.dataIn.azimuth
48 self.dataOut.azimuth = self.dataIn.azimuth
49 self.dataOut.zenith = self.dataIn.zenith
49 self.dataOut.zenith = self.dataIn.zenith
50
50
51 self.dataOut.beam.codeList = self.dataIn.beam.codeList
51 self.dataOut.beam.codeList = self.dataIn.beam.codeList
52 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
52 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
53 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
53 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
54
54
55
55
56 class selectChannels(Operation):
56 class selectChannels(Operation):
57
57
58 def run(self, dataOut, channelList):
58 def run(self, dataOut, channelList):
59
59
60 channelIndexList = []
60 channelIndexList = []
61 self.dataOut = dataOut
61 self.dataOut = dataOut
62 for channel in channelList:
62 for channel in channelList:
63 if channel not in self.dataOut.channelList:
63 if channel not in self.dataOut.channelList:
64 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
64 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
65
65
66 index = self.dataOut.channelList.index(channel)
66 index = self.dataOut.channelList.index(channel)
67 channelIndexList.append(index)
67 channelIndexList.append(index)
68 self.selectChannelsByIndex(channelIndexList)
68 self.selectChannelsByIndex(channelIndexList)
69 return self.dataOut
69 return self.dataOut
70
70
71 def selectChannelsByIndex(self, channelIndexList):
71 def selectChannelsByIndex(self, channelIndexList):
72 """
72 """
73 Selecciona un bloque de datos en base a canales segun el channelIndexList
73 Selecciona un bloque de datos en base a canales segun el channelIndexList
74
74
75 Input:
75 Input:
76 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
76 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
77
77
78 Affected:
78 Affected:
79 self.dataOut.data
79 self.dataOut.data
80 self.dataOut.channelIndexList
80 self.dataOut.channelIndexList
81 self.dataOut.nChannels
81 self.dataOut.nChannels
82 self.dataOut.m_ProcessingHeader.totalSpectra
82 self.dataOut.m_ProcessingHeader.totalSpectra
83 self.dataOut.systemHeaderObj.numChannels
83 self.dataOut.systemHeaderObj.numChannels
84 self.dataOut.m_ProcessingHeader.blockSize
84 self.dataOut.m_ProcessingHeader.blockSize
85
85
86 Return:
86 Return:
87 None
87 None
88 """
88 """
89
89
90 for channelIndex in channelIndexList:
90 for channelIndex in channelIndexList:
91 if channelIndex not in self.dataOut.channelIndexList:
91 if channelIndex not in self.dataOut.channelIndexList:
92 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
92 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
93
93
94 if self.dataOut.type == 'Voltage':
94 if self.dataOut.type == 'Voltage':
95 if self.dataOut.flagDataAsBlock:
95 if self.dataOut.flagDataAsBlock:
96 """
96 """
97 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
97 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
98 """
98 """
99 data = self.dataOut.data[channelIndexList,:,:]
99 data = self.dataOut.data[channelIndexList,:,:]
100 else:
100 else:
101 data = self.dataOut.data[channelIndexList,:]
101 data = self.dataOut.data[channelIndexList,:]
102
102
103 self.dataOut.data = data
103 self.dataOut.data = data
104 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
104 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
105 self.dataOut.channelList = range(len(channelIndexList))
105 self.dataOut.channelList = range(len(channelIndexList))
106
106
107 elif self.dataOut.type == 'Spectra':
107 elif self.dataOut.type == 'Spectra':
108 data_spc = self.dataOut.data_spc[channelIndexList, :]
108 data_spc = self.dataOut.data_spc[channelIndexList, :]
109 data_dc = self.dataOut.data_dc[channelIndexList, :]
109 data_dc = self.dataOut.data_dc[channelIndexList, :]
110
110
111 self.dataOut.data_spc = data_spc
111 self.dataOut.data_spc = data_spc
112 self.dataOut.data_dc = data_dc
112 self.dataOut.data_dc = data_dc
113
113
114 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
114 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
115 self.dataOut.channelList = range(len(channelIndexList))
115 self.dataOut.channelList = range(len(channelIndexList))
116 self.__selectPairsByChannel(channelIndexList)
116 self.__selectPairsByChannel(channelIndexList)
117
117
118 return 1
118 return 1
119
119
120 def __selectPairsByChannel(self, channelList=None):
120 def __selectPairsByChannel(self, channelList=None):
121
121
122 if channelList == None:
122 if channelList == None:
123 return
123 return
124
124
125 pairsIndexListSelected = []
125 pairsIndexListSelected = []
126 for pairIndex in self.dataOut.pairsIndexList:
126 for pairIndex in self.dataOut.pairsIndexList:
127 # First pair
127 # First pair
128 if self.dataOut.pairsList[pairIndex][0] not in channelList:
128 if self.dataOut.pairsList[pairIndex][0] not in channelList:
129 continue
129 continue
130 # Second pair
130 # Second pair
131 if self.dataOut.pairsList[pairIndex][1] not in channelList:
131 if self.dataOut.pairsList[pairIndex][1] not in channelList:
132 continue
132 continue
133
133
134 pairsIndexListSelected.append(pairIndex)
134 pairsIndexListSelected.append(pairIndex)
135
135
136 if not pairsIndexListSelected:
136 if not pairsIndexListSelected:
137 self.dataOut.data_cspc = None
137 self.dataOut.data_cspc = None
138 self.dataOut.pairsList = []
138 self.dataOut.pairsList = []
139 return
139 return
140
140
141 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
141 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
142 self.dataOut.pairsList = [self.dataOut.pairsList[i]
142 self.dataOut.pairsList = [self.dataOut.pairsList[i]
143 for i in pairsIndexListSelected]
143 for i in pairsIndexListSelected]
144
144
145 return
145 return
146
146
147 class selectHeights(Operation):
147 class selectHeights(Operation):
148
148
149 def run(self, dataOut, minHei=None, maxHei=None):
149 def run(self, dataOut, minHei=None, maxHei=None):
150 """
150 """
151 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
151 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
152 minHei <= height <= maxHei
152 minHei <= height <= maxHei
153
153
154 Input:
154 Input:
155 minHei : valor minimo de altura a considerar
155 minHei : valor minimo de altura a considerar
156 maxHei : valor maximo de altura a considerar
156 maxHei : valor maximo de altura a considerar
157
157
158 Affected:
158 Affected:
159 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
159 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
160
160
161 Return:
161 Return:
162 1 si el metodo se ejecuto con exito caso contrario devuelve 0
162 1 si el metodo se ejecuto con exito caso contrario devuelve 0
163 """
163 """
164
164
165 self.dataOut = dataOut
165 self.dataOut = dataOut
166
166
167 if minHei == None:
167 if minHei == None:
168 minHei = self.dataOut.heightList[0]
168 minHei = self.dataOut.heightList[0]
169
169
170 if maxHei == None:
170 if maxHei == None:
171 maxHei = self.dataOut.heightList[-1]
171 maxHei = self.dataOut.heightList[-1]
172
172
173 if (minHei < self.dataOut.heightList[0]):
173 if (minHei < self.dataOut.heightList[0]):
174 minHei = self.dataOut.heightList[0]
174 minHei = self.dataOut.heightList[0]
175
175
176 if (maxHei > self.dataOut.heightList[-1]):
176 if (maxHei > self.dataOut.heightList[-1]):
177 maxHei = self.dataOut.heightList[-1]
177 maxHei = self.dataOut.heightList[-1]
178
178
179 minIndex = 0
179 minIndex = 0
180 maxIndex = 0
180 maxIndex = 0
181 heights = self.dataOut.heightList
181 heights = self.dataOut.heightList
182
182
183 inda = numpy.where(heights >= minHei)
183 inda = numpy.where(heights >= minHei)
184 indb = numpy.where(heights <= maxHei)
184 indb = numpy.where(heights <= maxHei)
185
185
186 try:
186 try:
187 minIndex = inda[0][0]
187 minIndex = inda[0][0]
188 except:
188 except:
189 minIndex = 0
189 minIndex = 0
190
190
191 try:
191 try:
192 maxIndex = indb[0][-1]
192 maxIndex = indb[0][-1]
193 except:
193 except:
194 maxIndex = len(heights)
194 maxIndex = len(heights)
195
195
196 self.selectHeightsByIndex(minIndex, maxIndex)
196 self.selectHeightsByIndex(minIndex, maxIndex)
197
197
198 return self.dataOut
198 return self.dataOut
199
199
200 def selectHeightsByIndex(self, minIndex, maxIndex):
200 def selectHeightsByIndex(self, minIndex, maxIndex):
201 """
201 """
202 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
202 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
203 minIndex <= index <= maxIndex
203 minIndex <= index <= maxIndex
204
204
205 Input:
205 Input:
206 minIndex : valor de indice minimo de altura a considerar
206 minIndex : valor de indice minimo de altura a considerar
207 maxIndex : valor de indice maximo de altura a considerar
207 maxIndex : valor de indice maximo de altura a considerar
208
208
209 Affected:
209 Affected:
210 self.dataOut.data
210 self.dataOut.data
211 self.dataOut.heightList
211 self.dataOut.heightList
212
212
213 Return:
213 Return:
214 1 si el metodo se ejecuto con exito caso contrario devuelve 0
214 1 si el metodo se ejecuto con exito caso contrario devuelve 0
215 """
215 """
216
216
217 if self.dataOut.type == 'Voltage':
217 if self.dataOut.type == 'Voltage':
218 if (minIndex < 0) or (minIndex > maxIndex):
218 if (minIndex < 0) or (minIndex > maxIndex):
219 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
219 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
220
220
221 if (maxIndex >= self.dataOut.nHeights):
221 if (maxIndex >= self.dataOut.nHeights):
222 maxIndex = self.dataOut.nHeights
222 maxIndex = self.dataOut.nHeights
223
223
224 #voltage
224 #voltage
225 if self.dataOut.flagDataAsBlock:
225 if self.dataOut.flagDataAsBlock:
226 """
226 """
227 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
227 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
228 """
228 """
229 data = self.dataOut.data[:,:, minIndex:maxIndex]
229 data = self.dataOut.data[:,:, minIndex:maxIndex]
230 else:
230 else:
231 data = self.dataOut.data[:, minIndex:maxIndex]
231 data = self.dataOut.data[:, minIndex:maxIndex]
232
232
233 # firstHeight = self.dataOut.heightList[minIndex]
233 # firstHeight = self.dataOut.heightList[minIndex]
234
234
235 self.dataOut.data = data
235 self.dataOut.data = data
236 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
236 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
237
237
238 if self.dataOut.nHeights <= 1:
238 if self.dataOut.nHeights <= 1:
239 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
239 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
240 elif self.dataOut.type == 'Spectra':
240 elif self.dataOut.type == 'Spectra':
241 if (minIndex < 0) or (minIndex > maxIndex):
241 if (minIndex < 0) or (minIndex > maxIndex):
242 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
242 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
243 minIndex, maxIndex))
243 minIndex, maxIndex))
244
244
245 if (maxIndex >= self.dataOut.nHeights):
245 if (maxIndex >= self.dataOut.nHeights):
246 maxIndex = self.dataOut.nHeights - 1
246 maxIndex = self.dataOut.nHeights - 1
247
247
248 # Spectra
248 # Spectra
249 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
249 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
250
250
251 data_cspc = None
251 data_cspc = None
252 if self.dataOut.data_cspc is not None:
252 if self.dataOut.data_cspc is not None:
253 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
253 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
254
254
255 data_dc = None
255 data_dc = None
256 if self.dataOut.data_dc is not None:
256 if self.dataOut.data_dc is not None:
257 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
257 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
258
258
259 self.dataOut.data_spc = data_spc
259 self.dataOut.data_spc = data_spc
260 self.dataOut.data_cspc = data_cspc
260 self.dataOut.data_cspc = data_cspc
261 self.dataOut.data_dc = data_dc
261 self.dataOut.data_dc = data_dc
262
262
263 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
263 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
264
264
265 return 1
265 return 1
266
266
267
267
268 class filterByHeights(Operation):
268 class filterByHeights(Operation):
269
269
270 def run(self, dataOut, window):
270 def run(self, dataOut, window):
271
271
272 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
272 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
273
273
274 if window == None:
274 if window == None:
275 window = (dataOut.radarControllerHeaderObj.txA/dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
275 window = (dataOut.radarControllerHeaderObj.txA/dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
276
276
277 newdelta = deltaHeight * window
277 newdelta = deltaHeight * window
278 r = dataOut.nHeights % window
278 r = dataOut.nHeights % window
279 newheights = (dataOut.nHeights-r)/window
279 newheights = (dataOut.nHeights-r)/window
280
280
281 if newheights <= 1:
281 if newheights <= 1:
282 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(dataOut.nHeights, window))
282 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(dataOut.nHeights, window))
283
283
284 if dataOut.flagDataAsBlock:
284 if dataOut.flagDataAsBlock:
285 """
285 """
286 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
286 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
287 """
287 """
288 buffer = dataOut.data[:, :, 0:int(dataOut.nHeights-r)]
288 buffer = dataOut.data[:, :, 0:int(dataOut.nHeights-r)]
289 buffer = buffer.reshape(dataOut.nChannels, dataOut.nProfiles, int(dataOut.nHeights/window), window)
289 buffer = buffer.reshape(dataOut.nChannels, dataOut.nProfiles, int(dataOut.nHeights/window), window)
290 buffer = numpy.sum(buffer,3)
290 buffer = numpy.sum(buffer,3)
291
291
292 else:
292 else:
293 buffer = dataOut.data[:,0:int(dataOut.nHeights-r)]
293 buffer = dataOut.data[:,0:int(dataOut.nHeights-r)]
294 buffer = buffer.reshape(dataOut.nChannels,int(dataOut.nHeights/window),int(window))
294 buffer = buffer.reshape(dataOut.nChannels,int(dataOut.nHeights/window),int(window))
295 buffer = numpy.sum(buffer,2)
295 buffer = numpy.sum(buffer,2)
296
296
297 dataOut.data = buffer
297 dataOut.data = buffer
298 dataOut.heightList = dataOut.heightList[0] + numpy.arange( newheights )*newdelta
298 dataOut.heightList = dataOut.heightList[0] + numpy.arange( newheights )*newdelta
299 dataOut.windowOfFilter = window
299 dataOut.windowOfFilter = window
300
300
301 return dataOut
301 return dataOut
302
302
303
303
304 class setH0(Operation):
304 class setH0(Operation):
305
305
306 def run(self, dataOut, h0, deltaHeight = None):
306 def run(self, dataOut, h0, deltaHeight = None):
307
307
308 if not deltaHeight:
308 if not deltaHeight:
309 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
309 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
310
310
311 nHeights = dataOut.nHeights
311 nHeights = dataOut.nHeights
312
312
313 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
313 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
314
314
315 dataOut.heightList = newHeiRange
315 dataOut.heightList = newHeiRange
316
316
317 return dataOut
317 return dataOut
318
318
319
319
320 class deFlip(Operation):
320 class deFlip(Operation):
321
321
322 def run(self, dataOut, channelList = []):
322 def run(self, dataOut, channelList = []):
323
323
324 data = dataOut.data.copy()
324 data = dataOut.data.copy()
325
325
326 if dataOut.flagDataAsBlock:
326 if dataOut.flagDataAsBlock:
327 flip = self.flip
327 flip = self.flip
328 profileList = list(range(dataOut.nProfiles))
328 profileList = list(range(dataOut.nProfiles))
329
329
330 if not channelList:
330 if not channelList:
331 for thisProfile in profileList:
331 for thisProfile in profileList:
332 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
332 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
333 flip *= -1.0
333 flip *= -1.0
334 else:
334 else:
335 for thisChannel in channelList:
335 for thisChannel in channelList:
336 if thisChannel not in dataOut.channelList:
336 if thisChannel not in dataOut.channelList:
337 continue
337 continue
338
338
339 for thisProfile in profileList:
339 for thisProfile in profileList:
340 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
340 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
341 flip *= -1.0
341 flip *= -1.0
342
342
343 self.flip = flip
343 self.flip = flip
344
344
345 else:
345 else:
346 if not channelList:
346 if not channelList:
347 data[:,:] = data[:,:]*self.flip
347 data[:,:] = data[:,:]*self.flip
348 else:
348 else:
349 for thisChannel in channelList:
349 for thisChannel in channelList:
350 if thisChannel not in dataOut.channelList:
350 if thisChannel not in dataOut.channelList:
351 continue
351 continue
352
352
353 data[thisChannel,:] = data[thisChannel,:]*self.flip
353 data[thisChannel,:] = data[thisChannel,:]*self.flip
354
354
355 self.flip *= -1.
355 self.flip *= -1.
356
356
357 dataOut.data = data
357 dataOut.data = data
358
358
359 return dataOut
359 return dataOut
360
360
361
361
362 class setAttribute(Operation):
362 class setAttribute(Operation):
363 '''
363 '''
364 Set an arbitrary attribute(s) to dataOut
364 Set an arbitrary attribute(s) to dataOut
365 '''
365 '''
366
366
367 def __init__(self):
367 def __init__(self):
368
368
369 Operation.__init__(self)
369 Operation.__init__(self)
370 self._ready = False
370 self._ready = False
371
371
372 def run(self, dataOut, **kwargs):
372 def run(self, dataOut, **kwargs):
373
373
374 for key, value in kwargs.items():
374 for key, value in kwargs.items():
375 setattr(dataOut, key, value)
375 setattr(dataOut, key, value)
376
376
377 return dataOut
377 return dataOut
378
378
379
379
380 class interpolateHeights(Operation):
380 class interpolateHeights(Operation):
381
381
382 def run(self, dataOut, topLim, botLim):
382 def run(self, dataOut, topLim, botLim):
383 #69 al 72 para julia
383 #69 al 72 para julia
384 #82-84 para meteoros
384 #82-84 para meteoros
385 if len(numpy.shape(dataOut.data))==2:
385 if len(numpy.shape(dataOut.data))==2:
386 sampInterp = (dataOut.data[:,botLim-1] + dataOut.data[:,topLim+1])/2
386 sampInterp = (dataOut.data[:,botLim-1] + dataOut.data[:,topLim+1])/2
387 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
387 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
388 #dataOut.data[:,botLim:limSup+1] = sampInterp
388 #dataOut.data[:,botLim:limSup+1] = sampInterp
389 dataOut.data[:,botLim:topLim+1] = sampInterp
389 dataOut.data[:,botLim:topLim+1] = sampInterp
390 else:
390 else:
391 nHeights = dataOut.data.shape[2]
391 nHeights = dataOut.data.shape[2]
392 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
392 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
393 y = dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
393 y = dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
394 f = interpolate.interp1d(x, y, axis = 2)
394 f = interpolate.interp1d(x, y, axis = 2)
395 xnew = numpy.arange(botLim,topLim+1)
395 xnew = numpy.arange(botLim,topLim+1)
396 ynew = f(xnew)
396 ynew = f(xnew)
397 dataOut.data[:,:,botLim:topLim+1] = ynew
397 dataOut.data[:,:,botLim:topLim+1] = ynew
398
398
399 return dataOut
399 return dataOut
400
400
401
401
402 class CohInt(Operation):
402 class CohInt(Operation):
403
403
404 isConfig = False
404 isConfig = False
405 __profIndex = 0
405 __profIndex = 0
406 __byTime = False
406 __byTime = False
407 __initime = None
407 __initime = None
408 __lastdatatime = None
408 __lastdatatime = None
409 __integrationtime = None
409 __integrationtime = None
410 __buffer = None
410 __buffer = None
411 __bufferStride = []
411 __bufferStride = []
412 __dataReady = False
412 __dataReady = False
413 __profIndexStride = 0
413 __profIndexStride = 0
414 __dataToPutStride = False
414 __dataToPutStride = False
415 n = None
415 n = None
416
416
417 def __init__(self, **kwargs):
417 def __init__(self, **kwargs):
418
418
419 Operation.__init__(self, **kwargs)
419 Operation.__init__(self, **kwargs)
420
420
421 # self.isConfig = False
421 # self.isConfig = False
422
422
423 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
423 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
424 """
424 """
425 Set the parameters of the integration class.
425 Set the parameters of the integration class.
426
426
427 Inputs:
427 Inputs:
428
428
429 n : Number of coherent integrations
429 n : Number of coherent integrations
430 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
430 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
431 overlapping :
431 overlapping :
432 """
432 """
433
433
434 self.__initime = None
434 self.__initime = None
435 self.__lastdatatime = 0
435 self.__lastdatatime = 0
436 self.__buffer = None
436 self.__buffer = None
437 self.__dataReady = False
437 self.__dataReady = False
438 self.byblock = byblock
438 self.byblock = byblock
439 self.stride = stride
439 self.stride = stride
440
440
441 if n == None and timeInterval == None:
441 if n == None and timeInterval == None:
442 raise ValueError("n or timeInterval should be specified ...")
442 raise ValueError("n or timeInterval should be specified ...")
443
443
444 if n != None:
444 if n != None:
445 self.n = n
445 self.n = n
446 self.__byTime = False
446 self.__byTime = False
447 else:
447 else:
448 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
448 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
449 self.n = 9999
449 self.n = 9999
450 self.__byTime = True
450 self.__byTime = True
451
451
452 if overlapping:
452 if overlapping:
453 self.__withOverlapping = True
453 self.__withOverlapping = True
454 self.__buffer = None
454 self.__buffer = None
455 else:
455 else:
456 self.__withOverlapping = False
456 self.__withOverlapping = False
457 self.__buffer = 0
457 self.__buffer = 0
458
458
459 self.__profIndex = 0
459 self.__profIndex = 0
460
460
461 def putData(self, data):
461 def putData(self, data):
462
462
463 """
463 """
464 Add a profile to the __buffer and increase in one the __profileIndex
464 Add a profile to the __buffer and increase in one the __profileIndex
465
465
466 """
466 """
467
467
468 if not self.__withOverlapping:
468 if not self.__withOverlapping:
469 self.__buffer += data.copy()
469 self.__buffer += data.copy()
470 self.__profIndex += 1
470 self.__profIndex += 1
471 return
471 return
472
472
473 #Overlapping data
473 #Overlapping data
474 nChannels, nHeis = data.shape
474 nChannels, nHeis = data.shape
475 data = numpy.reshape(data, (1, nChannels, nHeis))
475 data = numpy.reshape(data, (1, nChannels, nHeis))
476
476
477 #If the buffer is empty then it takes the data value
477 #If the buffer is empty then it takes the data value
478 if self.__buffer is None:
478 if self.__buffer is None:
479 self.__buffer = data
479 self.__buffer = data
480 self.__profIndex += 1
480 self.__profIndex += 1
481 return
481 return
482
482
483 #If the buffer length is lower than n then stakcing the data value
483 #If the buffer length is lower than n then stakcing the data value
484 if self.__profIndex < self.n:
484 if self.__profIndex < self.n:
485 self.__buffer = numpy.vstack((self.__buffer, data))
485 self.__buffer = numpy.vstack((self.__buffer, data))
486 self.__profIndex += 1
486 self.__profIndex += 1
487 return
487 return
488
488
489 #If the buffer length is equal to n then replacing the last buffer value with the data value
489 #If the buffer length is equal to n then replacing the last buffer value with the data value
490 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
490 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
491 self.__buffer[self.n-1] = data
491 self.__buffer[self.n-1] = data
492 self.__profIndex = self.n
492 self.__profIndex = self.n
493 return
493 return
494
494
495
495
496 def pushData(self):
496 def pushData(self):
497 """
497 """
498 Return the sum of the last profiles and the profiles used in the sum.
498 Return the sum of the last profiles and the profiles used in the sum.
499
499
500 Affected:
500 Affected:
501
501
502 self.__profileIndex
502 self.__profileIndex
503
503
504 """
504 """
505
505
506 if not self.__withOverlapping:
506 if not self.__withOverlapping:
507 data = self.__buffer
507 data = self.__buffer
508 n = self.__profIndex
508 n = self.__profIndex
509
509
510 self.__buffer = 0
510 self.__buffer = 0
511 self.__profIndex = 0
511 self.__profIndex = 0
512
512
513 return data, n
513 return data, n
514
514
515 #Integration with Overlapping
515 #Integration with Overlapping
516 data = numpy.sum(self.__buffer, axis=0)
516 data = numpy.sum(self.__buffer, axis=0)
517 # print data
517 # print data
518 # raise
518 # raise
519 n = self.__profIndex
519 n = self.__profIndex
520
520
521 return data, n
521 return data, n
522
522
523 def byProfiles(self, data):
523 def byProfiles(self, data):
524
524
525 self.__dataReady = False
525 self.__dataReady = False
526 avgdata = None
526 avgdata = None
527 # n = None
527 # n = None
528 # print data
528 # print data
529 # raise
529 # raise
530 self.putData(data)
530 self.putData(data)
531
531
532 if self.__profIndex == self.n:
532 if self.__profIndex == self.n:
533 avgdata, n = self.pushData()
533 avgdata, n = self.pushData()
534 self.__dataReady = True
534 self.__dataReady = True
535
535
536 return avgdata
536 return avgdata
537
537
538 def byTime(self, data, datatime):
538 def byTime(self, data, datatime):
539
539
540 self.__dataReady = False
540 self.__dataReady = False
541 avgdata = None
541 avgdata = None
542 n = None
542 n = None
543
543
544 self.putData(data)
544 self.putData(data)
545
545
546 if (datatime - self.__initime) >= self.__integrationtime:
546 if (datatime - self.__initime) >= self.__integrationtime:
547 avgdata, n = self.pushData()
547 avgdata, n = self.pushData()
548 self.n = n
548 self.n = n
549 self.__dataReady = True
549 self.__dataReady = True
550
550
551 return avgdata
551 return avgdata
552
552
553 def integrateByStride(self, data, datatime):
553 def integrateByStride(self, data, datatime):
554 # print data
554 # print data
555 if self.__profIndex == 0:
555 if self.__profIndex == 0:
556 self.__buffer = [[data.copy(), datatime]]
556 self.__buffer = [[data.copy(), datatime]]
557 else:
557 else:
558 self.__buffer.append([data.copy(),datatime])
558 self.__buffer.append([data.copy(),datatime])
559 self.__profIndex += 1
559 self.__profIndex += 1
560 self.__dataReady = False
560 self.__dataReady = False
561
561
562 if self.__profIndex == self.n * self.stride :
562 if self.__profIndex == self.n * self.stride :
563 self.__dataToPutStride = True
563 self.__dataToPutStride = True
564 self.__profIndexStride = 0
564 self.__profIndexStride = 0
565 self.__profIndex = 0
565 self.__profIndex = 0
566 self.__bufferStride = []
566 self.__bufferStride = []
567 for i in range(self.stride):
567 for i in range(self.stride):
568 current = self.__buffer[i::self.stride]
568 current = self.__buffer[i::self.stride]
569 data = numpy.sum([t[0] for t in current], axis=0)
569 data = numpy.sum([t[0] for t in current], axis=0)
570 avgdatatime = numpy.average([t[1] for t in current])
570 avgdatatime = numpy.average([t[1] for t in current])
571 # print data
571 # print data
572 self.__bufferStride.append((data, avgdatatime))
572 self.__bufferStride.append((data, avgdatatime))
573
573
574 if self.__dataToPutStride:
574 if self.__dataToPutStride:
575 self.__dataReady = True
575 self.__dataReady = True
576 self.__profIndexStride += 1
576 self.__profIndexStride += 1
577 if self.__profIndexStride == self.stride:
577 if self.__profIndexStride == self.stride:
578 self.__dataToPutStride = False
578 self.__dataToPutStride = False
579 # print self.__bufferStride[self.__profIndexStride - 1]
579 # print self.__bufferStride[self.__profIndexStride - 1]
580 # raise
580 # raise
581 return self.__bufferStride[self.__profIndexStride - 1]
581 return self.__bufferStride[self.__profIndexStride - 1]
582
582
583
583
584 return None, None
584 return None, None
585
585
586 def integrate(self, data, datatime=None):
586 def integrate(self, data, datatime=None):
587
587
588 if self.__initime == None:
588 if self.__initime == None:
589 self.__initime = datatime
589 self.__initime = datatime
590
590
591 if self.__byTime:
591 if self.__byTime:
592 avgdata = self.byTime(data, datatime)
592 avgdata = self.byTime(data, datatime)
593 else:
593 else:
594 avgdata = self.byProfiles(data)
594 avgdata = self.byProfiles(data)
595
595
596
596
597 self.__lastdatatime = datatime
597 self.__lastdatatime = datatime
598
598
599 if avgdata is None:
599 if avgdata is None:
600 return None, None
600 return None, None
601
601
602 avgdatatime = self.__initime
602 avgdatatime = self.__initime
603
603
604 deltatime = datatime - self.__lastdatatime
604 deltatime = datatime - self.__lastdatatime
605
605
606 if not self.__withOverlapping:
606 if not self.__withOverlapping:
607 self.__initime = datatime
607 self.__initime = datatime
608 else:
608 else:
609 self.__initime += deltatime
609 self.__initime += deltatime
610
610
611 return avgdata, avgdatatime
611 return avgdata, avgdatatime
612
612
613 def integrateByBlock(self, dataOut):
613 def integrateByBlock(self, dataOut):
614
614
615 times = int(dataOut.data.shape[1]/self.n)
615 times = int(dataOut.data.shape[1]/self.n)
616 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
616 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
617
617
618 id_min = 0
618 id_min = 0
619 id_max = self.n
619 id_max = self.n
620
620
621 for i in range(times):
621 for i in range(times):
622 junk = dataOut.data[:,id_min:id_max,:]
622 junk = dataOut.data[:,id_min:id_max,:]
623 avgdata[:,i,:] = junk.sum(axis=1)
623 avgdata[:,i,:] = junk.sum(axis=1)
624 id_min += self.n
624 id_min += self.n
625 id_max += self.n
625 id_max += self.n
626
626
627 timeInterval = dataOut.ippSeconds*self.n
627 timeInterval = dataOut.ippSeconds*self.n
628 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
628 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
629 self.__dataReady = True
629 self.__dataReady = True
630 return avgdata, avgdatatime
630 return avgdata, avgdatatime
631
631
632 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
632 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
633
633
634 if not self.isConfig:
634 if not self.isConfig:
635 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
635 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
636 self.isConfig = True
636 self.isConfig = True
637
637
638 if dataOut.flagDataAsBlock:
638 if dataOut.flagDataAsBlock:
639 """
639 """
640 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
640 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
641 """
641 """
642 avgdata, avgdatatime = self.integrateByBlock(dataOut)
642 avgdata, avgdatatime = self.integrateByBlock(dataOut)
643 dataOut.nProfiles /= self.n
643 dataOut.nProfiles /= self.n
644 else:
644 else:
645 if stride is None:
645 if stride is None:
646 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
646 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
647 else:
647 else:
648 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
648 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
649
649
650
650
651 # dataOut.timeInterval *= n
651 # dataOut.timeInterval *= n
652 dataOut.flagNoData = True
652 dataOut.flagNoData = True
653
653
654 if self.__dataReady:
654 if self.__dataReady:
655 dataOut.data = avgdata
655 dataOut.data = avgdata
656 dataOut.nCohInt *= self.n
656 dataOut.nCohInt *= self.n
657 dataOut.utctime = avgdatatime
657 dataOut.utctime = avgdatatime
658 # print avgdata, avgdatatime
658 # print avgdata, avgdatatime
659 # raise
659 # raise
660 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
660 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
661 dataOut.flagNoData = False
661 dataOut.flagNoData = False
662 return dataOut
662 return dataOut
663
663
664 class Decoder(Operation):
664 class Decoder(Operation):
665
665
666 isConfig = False
666 isConfig = False
667 __profIndex = 0
667 __profIndex = 0
668
668
669 code = None
669 code = None
670
670
671 nCode = None
671 nCode = None
672 nBaud = None
672 nBaud = None
673
673
674 def __init__(self, **kwargs):
674 def __init__(self, **kwargs):
675
675
676 Operation.__init__(self, **kwargs)
676 Operation.__init__(self, **kwargs)
677
677
678 self.times = None
678 self.times = None
679 self.osamp = None
679 self.osamp = None
680 # self.__setValues = False
680 # self.__setValues = False
681 self.isConfig = False
681 self.isConfig = False
682 self.setupReq = False
682 self.setupReq = False
683 def setup(self, code, osamp, dataOut):
683 def setup(self, code, osamp, dataOut):
684
684
685 self.__profIndex = 0
685 self.__profIndex = 0
686
686
687 self.code = code
687 self.code = code
688
688
689 self.nCode = len(code)
689 self.nCode = len(code)
690 self.nBaud = len(code[0])
690 self.nBaud = len(code[0])
691
691
692 if (osamp != None) and (osamp >1):
692 if (osamp != None) and (osamp >1):
693 self.osamp = osamp
693 self.osamp = osamp
694 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
694 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
695 self.nBaud = self.nBaud*self.osamp
695 self.nBaud = self.nBaud*self.osamp
696
696
697 self.__nChannels = dataOut.nChannels
697 self.__nChannels = dataOut.nChannels
698 self.__nProfiles = dataOut.nProfiles
698 self.__nProfiles = dataOut.nProfiles
699 self.__nHeis = dataOut.nHeights
699 self.__nHeis = dataOut.nHeights
700
700
701 if self.__nHeis < self.nBaud:
701 if self.__nHeis < self.nBaud:
702 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
702 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
703
703
704 #Frequency
704 #Frequency
705 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
705 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
706
706
707 __codeBuffer[:,0:self.nBaud] = self.code
707 __codeBuffer[:,0:self.nBaud] = self.code
708
708
709 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
709 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
710
710
711 if dataOut.flagDataAsBlock:
711 if dataOut.flagDataAsBlock:
712
712
713 self.ndatadec = self.__nHeis #- self.nBaud + 1
713 self.ndatadec = self.__nHeis #- self.nBaud + 1
714
714
715 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
715 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
716
716
717 else:
717 else:
718
718
719 #Time
719 #Time
720 self.ndatadec = self.__nHeis #- self.nBaud + 1
720 self.ndatadec = self.__nHeis #- self.nBaud + 1
721
721
722 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
722 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
723
723
724 def __convolutionInFreq(self, data):
724 def __convolutionInFreq(self, data):
725
725
726 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
726 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
727
727
728 fft_data = numpy.fft.fft(data, axis=1)
728 fft_data = numpy.fft.fft(data, axis=1)
729
729
730 conv = fft_data*fft_code
730 conv = fft_data*fft_code
731
731
732 data = numpy.fft.ifft(conv,axis=1)
732 data = numpy.fft.ifft(conv,axis=1)
733
733
734 return data
734 return data
735
735
736 def __convolutionInFreqOpt(self, data):
736 def __convolutionInFreqOpt(self, data):
737
737
738 raise NotImplementedError
738 raise NotImplementedError
739
739
740 def __convolutionInTime(self, data):
740 def __convolutionInTime(self, data):
741
741
742 code = self.code[self.__profIndex]
742 code = self.code[self.__profIndex]
743 for i in range(self.__nChannels):
743 for i in range(self.__nChannels):
744 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
744 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
745
745
746 return self.datadecTime
746 return self.datadecTime
747
747
748 def __convolutionByBlockInTime(self, data):
748 def __convolutionByBlockInTime(self, data):
749
749
750 repetitions = int(self.__nProfiles / self.nCode)
750 repetitions = int(self.__nProfiles / self.nCode)
751 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
751 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
752 junk = junk.flatten()
752 junk = junk.flatten()
753 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
753 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
754 profilesList = range(self.__nProfiles)
754 profilesList = range(self.__nProfiles)
755
755
756 for i in range(self.__nChannels):
756 for i in range(self.__nChannels):
757 for j in profilesList:
757 for j in profilesList:
758 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
758 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
759 return self.datadecTime
759 return self.datadecTime
760
760
761 def __convolutionByBlockInFreq(self, data):
761 def __convolutionByBlockInFreq(self, data):
762
762
763 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
763 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
764
764
765
765
766 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
766 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
767
767
768 fft_data = numpy.fft.fft(data, axis=2)
768 fft_data = numpy.fft.fft(data, axis=2)
769
769
770 conv = fft_data*fft_code
770 conv = fft_data*fft_code
771
771
772 data = numpy.fft.ifft(conv,axis=2)
772 data = numpy.fft.ifft(conv,axis=2)
773
773
774 return data
774 return data
775
775
776
776
777 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
777 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
778
778
779 if dataOut.flagDecodeData:
779 if dataOut.flagDecodeData:
780 print("This data is already decoded, recoding again ...")
780 print("This data is already decoded, recoding again ...")
781
781
782 if not self.isConfig:
782 if not self.isConfig:
783
783
784 if code is None:
784 if code is None:
785 if dataOut.code is None:
785 if dataOut.code is None:
786 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
786 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
787
787
788 code = dataOut.code
788 code = dataOut.code
789 else:
789 else:
790 code = numpy.array(code).reshape(nCode,nBaud)
790 code = numpy.array(code).reshape(nCode,nBaud)
791 self.setup(code, osamp, dataOut)
791 self.setup(code, osamp, dataOut)
792
792
793 self.isConfig = True
793 self.isConfig = True
794
794
795 if mode == 3:
795 if mode == 3:
796 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
796 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
797
797
798 if times != None:
798 if times != None:
799 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
799 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
800
800
801 if self.code is None:
801 if self.code is None:
802 print("Fail decoding: Code is not defined.")
802 print("Fail decoding: Code is not defined.")
803 return
803 return
804
804
805 self.__nProfiles = dataOut.nProfiles
805 self.__nProfiles = dataOut.nProfiles
806 datadec = None
806 datadec = None
807
807
808 if mode == 3:
808 if mode == 3:
809 mode = 0
809 mode = 0
810
810
811 if dataOut.flagDataAsBlock:
811 if dataOut.flagDataAsBlock:
812 """
812 """
813 Decoding when data have been read as block,
813 Decoding when data have been read as block,
814 """
814 """
815
815
816 if mode == 0:
816 if mode == 0:
817 datadec = self.__convolutionByBlockInTime(dataOut.data)
817 datadec = self.__convolutionByBlockInTime(dataOut.data)
818 if mode == 1:
818 if mode == 1:
819 datadec = self.__convolutionByBlockInFreq(dataOut.data)
819 datadec = self.__convolutionByBlockInFreq(dataOut.data)
820 else:
820 else:
821 """
821 """
822 Decoding when data have been read profile by profile
822 Decoding when data have been read profile by profile
823 """
823 """
824 if mode == 0:
824 if mode == 0:
825 datadec = self.__convolutionInTime(dataOut.data)
825 datadec = self.__convolutionInTime(dataOut.data)
826
826
827 if mode == 1:
827 if mode == 1:
828 datadec = self.__convolutionInFreq(dataOut.data)
828 datadec = self.__convolutionInFreq(dataOut.data)
829
829
830 if mode == 2:
830 if mode == 2:
831 datadec = self.__convolutionInFreqOpt(dataOut.data)
831 datadec = self.__convolutionInFreqOpt(dataOut.data)
832
832
833 if datadec is None:
833 if datadec is None:
834 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
834 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
835
835
836 dataOut.code = self.code
836 dataOut.code = self.code
837 dataOut.nCode = self.nCode
837 dataOut.nCode = self.nCode
838 dataOut.nBaud = self.nBaud
838 dataOut.nBaud = self.nBaud
839
839
840 dataOut.data = datadec
840 dataOut.data = datadec
841
841
842 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
842 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
843
843
844 dataOut.flagDecodeData = True #asumo q la data esta decodificada
844 dataOut.flagDecodeData = True #asumo q la data esta decodificada
845
845
846 if self.__profIndex == self.nCode-1:
846 if self.__profIndex == self.nCode-1:
847 self.__profIndex = 0
847 self.__profIndex = 0
848 return dataOut
848 return dataOut
849
849
850 self.__profIndex += 1
850 self.__profIndex += 1
851
851
852 return dataOut
852 return dataOut
853 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
853 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
854
854
855
855
856 class ProfileConcat(Operation):
856 class ProfileConcat(Operation):
857
857
858 isConfig = False
858 isConfig = False
859 buffer = None
859 buffer = None
860
860
861 def __init__(self, **kwargs):
861 def __init__(self, **kwargs):
862
862
863 Operation.__init__(self, **kwargs)
863 Operation.__init__(self, **kwargs)
864 self.profileIndex = 0
864 self.profileIndex = 0
865
865
866 def reset(self):
866 def reset(self):
867 self.buffer = numpy.zeros_like(self.buffer)
867 self.buffer = numpy.zeros_like(self.buffer)
868 self.start_index = 0
868 self.start_index = 0
869 self.times = 1
869 self.times = 1
870
870
871 def setup(self, data, m, n=1):
871 def setup(self, data, m, n=1):
872 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
872 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
873 self.nHeights = data.shape[1]#.nHeights
873 self.nHeights = data.shape[1]#.nHeights
874 self.start_index = 0
874 self.start_index = 0
875 self.times = 1
875 self.times = 1
876
876
877 def concat(self, data):
877 def concat(self, data):
878
878
879 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
879 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
880 self.start_index = self.start_index + self.nHeights
880 self.start_index = self.start_index + self.nHeights
881
881
882 def run(self, dataOut, m):
882 def run(self, dataOut, m):
883 dataOut.flagNoData = True
883 dataOut.flagNoData = True
884
884
885 if not self.isConfig:
885 if not self.isConfig:
886 self.setup(dataOut.data, m, 1)
886 self.setup(dataOut.data, m, 1)
887 self.isConfig = True
887 self.isConfig = True
888
888
889 if dataOut.flagDataAsBlock:
889 if dataOut.flagDataAsBlock:
890 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
890 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
891
891
892 else:
892 else:
893 self.concat(dataOut.data)
893 self.concat(dataOut.data)
894 self.times += 1
894 self.times += 1
895 if self.times > m:
895 if self.times > m:
896 dataOut.data = self.buffer
896 dataOut.data = self.buffer
897 self.reset()
897 self.reset()
898 dataOut.flagNoData = False
898 dataOut.flagNoData = False
899 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
899 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
900 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
900 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
901 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
901 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
902 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
902 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
903 dataOut.ippSeconds *= m
903 dataOut.ippSeconds *= m
904 return dataOut
904 return dataOut
905
905
906 class ProfileSelector(Operation):
906 class ProfileSelector(Operation):
907
907
908 profileIndex = None
908 profileIndex = None
909 # Tamanho total de los perfiles
909 # Tamanho total de los perfiles
910 nProfiles = None
910 nProfiles = None
911
911
912 def __init__(self, **kwargs):
912 def __init__(self, **kwargs):
913
913
914 Operation.__init__(self, **kwargs)
914 Operation.__init__(self, **kwargs)
915 self.profileIndex = 0
915 self.profileIndex = 0
916
916
917 def incProfileIndex(self):
917 def incProfileIndex(self):
918
918
919 self.profileIndex += 1
919 self.profileIndex += 1
920
920
921 if self.profileIndex >= self.nProfiles:
921 if self.profileIndex >= self.nProfiles:
922 self.profileIndex = 0
922 self.profileIndex = 0
923
923
924 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
924 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
925
925
926 if profileIndex < minIndex:
926 if profileIndex < minIndex:
927 return False
927 return False
928
928
929 if profileIndex > maxIndex:
929 if profileIndex > maxIndex:
930 return False
930 return False
931
931
932 return True
932 return True
933
933
934 def isThisProfileInList(self, profileIndex, profileList):
934 def isThisProfileInList(self, profileIndex, profileList):
935
935
936 if profileIndex not in profileList:
936 if profileIndex not in profileList:
937 return False
937 return False
938
938
939 return True
939 return True
940
940
941 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
941 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
942
942
943 """
943 """
944 ProfileSelector:
944 ProfileSelector:
945
945
946 Inputs:
946 Inputs:
947 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
947 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
948
948
949 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
949 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
950
950
951 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
951 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
952
952
953 """
953 """
954
954
955 if rangeList is not None:
955 if rangeList is not None:
956 if type(rangeList[0]) not in (tuple, list):
956 if type(rangeList[0]) not in (tuple, list):
957 rangeList = [rangeList]
957 rangeList = [rangeList]
958
958
959 dataOut.flagNoData = True
959 dataOut.flagNoData = True
960
960
961 if dataOut.flagDataAsBlock:
961 if dataOut.flagDataAsBlock:
962 """
962 """
963 data dimension = [nChannels, nProfiles, nHeis]
963 data dimension = [nChannels, nProfiles, nHeis]
964 """
964 """
965 if profileList != None:
965 if profileList != None:
966 dataOut.data = dataOut.data[:,profileList,:]
966 dataOut.data = dataOut.data[:,profileList,:]
967
967
968 if profileRangeList != None:
968 if profileRangeList != None:
969 minIndex = profileRangeList[0]
969 minIndex = profileRangeList[0]
970 maxIndex = profileRangeList[1]
970 maxIndex = profileRangeList[1]
971 profileList = list(range(minIndex, maxIndex+1))
971 profileList = list(range(minIndex, maxIndex+1))
972
972
973 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
973 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
974
974
975 if rangeList != None:
975 if rangeList != None:
976
976
977 profileList = []
977 profileList = []
978
978
979 for thisRange in rangeList:
979 for thisRange in rangeList:
980 minIndex = thisRange[0]
980 minIndex = thisRange[0]
981 maxIndex = thisRange[1]
981 maxIndex = thisRange[1]
982
982
983 profileList.extend(list(range(minIndex, maxIndex+1)))
983 profileList.extend(list(range(minIndex, maxIndex+1)))
984
984
985 dataOut.data = dataOut.data[:,profileList,:]
985 dataOut.data = dataOut.data[:,profileList,:]
986
986
987 dataOut.nProfiles = len(profileList)
987 dataOut.nProfiles = len(profileList)
988 dataOut.profileIndex = dataOut.nProfiles - 1
988 dataOut.profileIndex = dataOut.nProfiles - 1
989 dataOut.flagNoData = False
989 dataOut.flagNoData = False
990
990
991 return dataOut
991 return dataOut
992
992
993 """
993 """
994 data dimension = [nChannels, nHeis]
994 data dimension = [nChannels, nHeis]
995 """
995 """
996
996
997 if profileList != None:
997 if profileList != None:
998
998
999 if self.isThisProfileInList(dataOut.profileIndex, profileList):
999 if self.isThisProfileInList(dataOut.profileIndex, profileList):
1000
1000
1001 self.nProfiles = len(profileList)
1001 self.nProfiles = len(profileList)
1002 dataOut.nProfiles = self.nProfiles
1002 dataOut.nProfiles = self.nProfiles
1003 dataOut.profileIndex = self.profileIndex
1003 dataOut.profileIndex = self.profileIndex
1004 dataOut.flagNoData = False
1004 dataOut.flagNoData = False
1005
1005
1006 self.incProfileIndex()
1006 self.incProfileIndex()
1007 return dataOut
1007 return dataOut
1008
1008
1009 if profileRangeList != None:
1009 if profileRangeList != None:
1010
1010
1011 minIndex = profileRangeList[0]
1011 minIndex = profileRangeList[0]
1012 maxIndex = profileRangeList[1]
1012 maxIndex = profileRangeList[1]
1013
1013
1014 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1014 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1015
1015
1016 self.nProfiles = maxIndex - minIndex + 1
1016 self.nProfiles = maxIndex - minIndex + 1
1017 dataOut.nProfiles = self.nProfiles
1017 dataOut.nProfiles = self.nProfiles
1018 dataOut.profileIndex = self.profileIndex
1018 dataOut.profileIndex = self.profileIndex
1019 dataOut.flagNoData = False
1019 dataOut.flagNoData = False
1020
1020
1021 self.incProfileIndex()
1021 self.incProfileIndex()
1022 return dataOut
1022 return dataOut
1023
1023
1024 if rangeList != None:
1024 if rangeList != None:
1025
1025
1026 nProfiles = 0
1026 nProfiles = 0
1027
1027
1028 for thisRange in rangeList:
1028 for thisRange in rangeList:
1029 minIndex = thisRange[0]
1029 minIndex = thisRange[0]
1030 maxIndex = thisRange[1]
1030 maxIndex = thisRange[1]
1031
1031
1032 nProfiles += maxIndex - minIndex + 1
1032 nProfiles += maxIndex - minIndex + 1
1033
1033
1034 for thisRange in rangeList:
1034 for thisRange in rangeList:
1035
1035
1036 minIndex = thisRange[0]
1036 minIndex = thisRange[0]
1037 maxIndex = thisRange[1]
1037 maxIndex = thisRange[1]
1038
1038
1039 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1039 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
1040
1040
1041 self.nProfiles = nProfiles
1041 self.nProfiles = nProfiles
1042 dataOut.nProfiles = self.nProfiles
1042 dataOut.nProfiles = self.nProfiles
1043 dataOut.profileIndex = self.profileIndex
1043 dataOut.profileIndex = self.profileIndex
1044 dataOut.flagNoData = False
1044 dataOut.flagNoData = False
1045
1045
1046 self.incProfileIndex()
1046 self.incProfileIndex()
1047
1047
1048 break
1048 break
1049
1049
1050 return dataOut
1050 return dataOut
1051
1051
1052
1052
1053 if beam != None: #beam is only for AMISR data
1053 if beam != None: #beam is only for AMISR data
1054 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
1054 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
1055 dataOut.flagNoData = False
1055 dataOut.flagNoData = False
1056 dataOut.profileIndex = self.profileIndex
1056 dataOut.profileIndex = self.profileIndex
1057
1057
1058 self.incProfileIndex()
1058 self.incProfileIndex()
1059
1059
1060 return dataOut
1060 return dataOut
1061
1061
1062 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
1062 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
1063
1063
1064
1064
1065 class Reshaper(Operation):
1065 class Reshaper(Operation):
1066
1066
1067 def __init__(self, **kwargs):
1067 def __init__(self, **kwargs):
1068
1068
1069 Operation.__init__(self, **kwargs)
1069 Operation.__init__(self, **kwargs)
1070
1070
1071 self.__buffer = None
1071 self.__buffer = None
1072 self.__nitems = 0
1072 self.__nitems = 0
1073
1073
1074 def __appendProfile(self, dataOut, nTxs):
1074 def __appendProfile(self, dataOut, nTxs):
1075
1075
1076 if self.__buffer is None:
1076 if self.__buffer is None:
1077 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
1077 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
1078 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
1078 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
1079
1079
1080 ini = dataOut.nHeights * self.__nitems
1080 ini = dataOut.nHeights * self.__nitems
1081 end = ini + dataOut.nHeights
1081 end = ini + dataOut.nHeights
1082
1082
1083 self.__buffer[:, ini:end] = dataOut.data
1083 self.__buffer[:, ini:end] = dataOut.data
1084
1084
1085 self.__nitems += 1
1085 self.__nitems += 1
1086
1086
1087 return int(self.__nitems*nTxs)
1087 return int(self.__nitems*nTxs)
1088
1088
1089 def __getBuffer(self):
1089 def __getBuffer(self):
1090
1090
1091 if self.__nitems == int(1./self.__nTxs):
1091 if self.__nitems == int(1./self.__nTxs):
1092
1092
1093 self.__nitems = 0
1093 self.__nitems = 0
1094
1094
1095 return self.__buffer.copy()
1095 return self.__buffer.copy()
1096
1096
1097 return None
1097 return None
1098
1098
1099 def __checkInputs(self, dataOut, shape, nTxs):
1099 def __checkInputs(self, dataOut, shape, nTxs):
1100
1100
1101 if shape is None and nTxs is None:
1101 if shape is None and nTxs is None:
1102 raise ValueError("Reshaper: shape of factor should be defined")
1102 raise ValueError("Reshaper: shape of factor should be defined")
1103
1103
1104 if nTxs:
1104 if nTxs:
1105 if nTxs < 0:
1105 if nTxs < 0:
1106 raise ValueError("nTxs should be greater than 0")
1106 raise ValueError("nTxs should be greater than 0")
1107
1107
1108 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1108 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1109 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1109 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1110
1110
1111 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1111 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1112
1112
1113 return shape, nTxs
1113 return shape, nTxs
1114
1114
1115 if len(shape) != 2 and len(shape) != 3:
1115 if len(shape) != 2 and len(shape) != 3:
1116 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
1116 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
1117
1117
1118 if len(shape) == 2:
1118 if len(shape) == 2:
1119 shape_tuple = [dataOut.nChannels]
1119 shape_tuple = [dataOut.nChannels]
1120 shape_tuple.extend(shape)
1120 shape_tuple.extend(shape)
1121 else:
1121 else:
1122 shape_tuple = list(shape)
1122 shape_tuple = list(shape)
1123
1123
1124 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1124 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1125
1125
1126 return shape_tuple, nTxs
1126 return shape_tuple, nTxs
1127
1127
1128 def run(self, dataOut, shape=None, nTxs=None):
1128 def run(self, dataOut, shape=None, nTxs=None):
1129
1129
1130 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1130 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1131
1131
1132 dataOut.flagNoData = True
1132 dataOut.flagNoData = True
1133 profileIndex = None
1133 profileIndex = None
1134
1134
1135 if dataOut.flagDataAsBlock:
1135 if dataOut.flagDataAsBlock:
1136
1136
1137 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1137 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1138 dataOut.flagNoData = False
1138 dataOut.flagNoData = False
1139
1139
1140 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1140 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1141
1141
1142 else:
1142 else:
1143
1143
1144 if self.__nTxs < 1:
1144 if self.__nTxs < 1:
1145
1145
1146 self.__appendProfile(dataOut, self.__nTxs)
1146 self.__appendProfile(dataOut, self.__nTxs)
1147 new_data = self.__getBuffer()
1147 new_data = self.__getBuffer()
1148
1148
1149 if new_data is not None:
1149 if new_data is not None:
1150 dataOut.data = new_data
1150 dataOut.data = new_data
1151 dataOut.flagNoData = False
1151 dataOut.flagNoData = False
1152
1152
1153 profileIndex = dataOut.profileIndex*nTxs
1153 profileIndex = dataOut.profileIndex*nTxs
1154
1154
1155 else:
1155 else:
1156 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1156 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1157
1157
1158 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1158 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1159
1159
1160 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1160 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1161
1161
1162 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1162 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1163
1163
1164 dataOut.profileIndex = profileIndex
1164 dataOut.profileIndex = profileIndex
1165
1165
1166 dataOut.ippSeconds /= self.__nTxs
1166 dataOut.ippSeconds /= self.__nTxs
1167
1167
1168 return dataOut
1168 return dataOut
1169
1169
1170 class SplitProfiles(Operation):
1170 class SplitProfiles(Operation):
1171
1171
1172 def __init__(self, **kwargs):
1172 def __init__(self, **kwargs):
1173
1173
1174 Operation.__init__(self, **kwargs)
1174 Operation.__init__(self, **kwargs)
1175
1175
1176 def run(self, dataOut, n):
1176 def run(self, dataOut, n):
1177
1177
1178 dataOut.flagNoData = True
1178 dataOut.flagNoData = True
1179 profileIndex = None
1179 profileIndex = None
1180
1180
1181 if dataOut.flagDataAsBlock:
1181 if dataOut.flagDataAsBlock:
1182
1182
1183 #nchannels, nprofiles, nsamples
1183 #nchannels, nprofiles, nsamples
1184 shape = dataOut.data.shape
1184 shape = dataOut.data.shape
1185
1185
1186 if shape[2] % n != 0:
1186 if shape[2] % n != 0:
1187 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1187 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1188
1188
1189 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1189 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1190
1190
1191 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1191 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1192 dataOut.flagNoData = False
1192 dataOut.flagNoData = False
1193
1193
1194 profileIndex = int(dataOut.nProfiles/n) - 1
1194 profileIndex = int(dataOut.nProfiles/n) - 1
1195
1195
1196 else:
1196 else:
1197
1197
1198 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1198 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1199
1199
1200 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1200 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1201
1201
1202 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1202 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1203
1203
1204 dataOut.nProfiles = int(dataOut.nProfiles*n)
1204 dataOut.nProfiles = int(dataOut.nProfiles*n)
1205
1205
1206 dataOut.profileIndex = profileIndex
1206 dataOut.profileIndex = profileIndex
1207
1207
1208 dataOut.ippSeconds /= n
1208 dataOut.ippSeconds /= n
1209
1209
1210 return dataOut
1210 return dataOut
1211
1211
1212 class CombineProfiles(Operation):
1212 class CombineProfiles(Operation):
1213 def __init__(self, **kwargs):
1213 def __init__(self, **kwargs):
1214
1214
1215 Operation.__init__(self, **kwargs)
1215 Operation.__init__(self, **kwargs)
1216
1216
1217 self.__remData = None
1217 self.__remData = None
1218 self.__profileIndex = 0
1218 self.__profileIndex = 0
1219
1219
1220 def run(self, dataOut, n):
1220 def run(self, dataOut, n):
1221
1221
1222 dataOut.flagNoData = True
1222 dataOut.flagNoData = True
1223 profileIndex = None
1223 profileIndex = None
1224
1224
1225 if dataOut.flagDataAsBlock:
1225 if dataOut.flagDataAsBlock:
1226
1226
1227 #nchannels, nprofiles, nsamples
1227 #nchannels, nprofiles, nsamples
1228 shape = dataOut.data.shape
1228 shape = dataOut.data.shape
1229 new_shape = shape[0], shape[1]/n, shape[2]*n
1229 new_shape = shape[0], shape[1]/n, shape[2]*n
1230
1230
1231 if shape[1] % n != 0:
1231 if shape[1] % n != 0:
1232 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1232 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1233
1233
1234 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1234 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1235 dataOut.flagNoData = False
1235 dataOut.flagNoData = False
1236
1236
1237 profileIndex = int(dataOut.nProfiles*n) - 1
1237 profileIndex = int(dataOut.nProfiles*n) - 1
1238
1238
1239 else:
1239 else:
1240
1240
1241 #nchannels, nsamples
1241 #nchannels, nsamples
1242 if self.__remData is None:
1242 if self.__remData is None:
1243 newData = dataOut.data
1243 newData = dataOut.data
1244 else:
1244 else:
1245 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1245 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1246
1246
1247 self.__profileIndex += 1
1247 self.__profileIndex += 1
1248
1248
1249 if self.__profileIndex < n:
1249 if self.__profileIndex < n:
1250 self.__remData = newData
1250 self.__remData = newData
1251 #continue
1251 #continue
1252 return
1252 return
1253
1253
1254 self.__profileIndex = 0
1254 self.__profileIndex = 0
1255 self.__remData = None
1255 self.__remData = None
1256
1256
1257 dataOut.data = newData
1257 dataOut.data = newData
1258 dataOut.flagNoData = False
1258 dataOut.flagNoData = False
1259
1259
1260 profileIndex = dataOut.profileIndex/n
1260 profileIndex = dataOut.profileIndex/n
1261
1261
1262
1262
1263 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1263 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1264
1264
1265 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1265 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1266
1266
1267 dataOut.nProfiles = int(dataOut.nProfiles/n)
1267 dataOut.nProfiles = int(dataOut.nProfiles/n)
1268
1268
1269 dataOut.profileIndex = profileIndex
1269 dataOut.profileIndex = profileIndex
1270
1270
1271 dataOut.ippSeconds *= n
1271 dataOut.ippSeconds *= n
1272
1272
1273 return dataOut
1273 return dataOut
1274
1274
1275 class PulsePairVoltage(Operation):
1275 class PulsePairVoltage(Operation):
1276 '''
1276 '''
1277 Function PulsePair(Signal Power, Velocity)
1277 Function PulsePair(Signal Power, Velocity)
1278 The real component of Lag[0] provides Intensity Information
1278 The real component of Lag[0] provides Intensity Information
1279 The imag component of Lag[1] Phase provides Velocity Information
1279 The imag component of Lag[1] Phase provides Velocity Information
1280
1280
1281 Configuration Parameters:
1281 Configuration Parameters:
1282 nPRF = Number of Several PRF
1282 nPRF = Number of Several PRF
1283 theta = Degree Azimuth angel Boundaries
1283 theta = Degree Azimuth angel Boundaries
1284
1284
1285 Input:
1285 Input:
1286 self.dataOut
1286 self.dataOut
1287 lag[N]
1287 lag[N]
1288 Affected:
1288 Affected:
1289 self.dataOut.spc
1289 self.dataOut.spc
1290 '''
1290 '''
1291 isConfig = False
1291 isConfig = False
1292 __profIndex = 0
1292 __profIndex = 0
1293 __initime = None
1293 __initime = None
1294 __lastdatatime = None
1294 __lastdatatime = None
1295 __buffer = None
1295 __buffer = None
1296 __buffer2 = []
1296 noise = None
1297 __buffer3 = None
1298 __dataReady = False
1297 __dataReady = False
1299 n = None
1298 n = None
1300 __nch = 0
1299 __nch = 0
1301 __nHeis = 0
1300 __nHeis = 0
1302 removeDC = False
1301 removeDC = False
1303 ipp = None
1302 ipp = None
1304 lambda_ = 0
1303 lambda_ = 0
1305
1304
1306 def __init__(self,**kwargs):
1305 def __init__(self,**kwargs):
1307 Operation.__init__(self,**kwargs)
1306 Operation.__init__(self,**kwargs)
1308
1307
1309 def setup(self, dataOut, n = None, removeDC=False):
1308 def setup(self, dataOut, n = None, removeDC=False):
1310 '''
1309 '''
1311 n= Numero de PRF's de entrada
1310 n= Numero de PRF's de entrada
1312 '''
1311 '''
1313 self.__initime = None
1312 self.__initime = None
1314 self.__lastdatatime = 0
1313 self.__lastdatatime = 0
1315 self.__dataReady = False
1314 self.__dataReady = False
1316 self.__buffer = 0
1315 self.__buffer = 0
1317 self.__buffer2 = []
1318 self.__buffer3 = 0
1319 self.__profIndex = 0
1316 self.__profIndex = 0
1320
1317 self.noise = None
1321 self.__nch = dataOut.nChannels
1318 self.__nch = dataOut.nChannels
1322 self.__nHeis = dataOut.nHeights
1319 self.__nHeis = dataOut.nHeights
1323 self.removeDC = removeDC
1320 self.removeDC = removeDC
1324 self.lambda_ = 3.0e8/(9345.0e6)
1321 self.lambda_ = 3.0e8/(9345.0e6)
1325 self.ippSec = dataOut.ippSeconds
1322 self.ippSec = dataOut.ippSeconds
1326 self.nCohInt = dataOut.nCohInt
1323 self.nCohInt = dataOut.nCohInt
1327 print("IPPseconds",dataOut.ippSeconds)
1324 print("IPPseconds",dataOut.ippSeconds)
1328
1325
1329 print("ELVALOR DE n es:", n)
1326 print("ELVALOR DE n es:", n)
1330 if n == None:
1327 if n == None:
1331 raise ValueError("n should be specified.")
1328 raise ValueError("n should be specified.")
1332
1329
1333 if n != None:
1330 if n != None:
1334 if n<2:
1331 if n<2:
1335 raise ValueError("n should be greater than 2")
1332 raise ValueError("n should be greater than 2")
1336
1333
1337 self.n = n
1334 self.n = n
1338 self.__nProf = n
1335 self.__nProf = n
1339
1336
1340 self.__buffer = numpy.zeros((dataOut.nChannels,
1337 self.__buffer = numpy.zeros((dataOut.nChannels,
1341 n,
1338 n,
1342 dataOut.nHeights),
1339 dataOut.nHeights),
1343 dtype='complex')
1340 dtype='complex')
1341 self.noise = numpy.zeros([self.__nch,self.__nHeis])
1342 for i in range(self.__nch):
1343 self.noise[i]=dataOut.getNoise(channel=i)
1344
1344
1345 def putData(self,data):
1345 def putData(self,data):
1346 '''
1346 '''
1347 Add a profile to he __buffer and increase in one the __profiel Index
1347 Add a profile to he __buffer and increase in one the __profiel Index
1348 '''
1348 '''
1349 self.__buffer[:,self.__profIndex,:]= data
1349 self.__buffer[:,self.__profIndex,:]= data
1350 self.__profIndex += 1
1350 self.__profIndex += 1
1351 return
1351 return
1352
1352
1353 def pushData(self):
1353 def pushData(self):
1354 '''
1354 '''
1355 Return the PULSEPAIR and the profiles used in the operation
1355 Return the PULSEPAIR and the profiles used in the operation
1356 Affected : self.__profileIndex
1356 Affected : self.__profileIndex
1357 '''
1357 '''
1358
1358
1359 if self.removeDC==True:
1359 if self.removeDC==True:
1360 mean = numpy.mean(self.__buffer,1)
1360 mean = numpy.mean(self.__buffer,1)
1361 tmp = mean.reshape(self.__nch,1,self.__nHeis)
1361 tmp = mean.reshape(self.__nch,1,self.__nHeis)
1362 dc= numpy.tile(tmp,[1,self.__nProf,1])
1362 dc= numpy.tile(tmp,[1,self.__nProf,1])
1363 self.__buffer = self.__buffer - dc
1363 self.__buffer = self.__buffer - dc
1364
1364
1365 data_intensity = numpy.sum(self.__buffer*numpy.conj(self.__buffer),1)/(self.n*self.nCohInt)#*self.nCohInt)
1365 lag_0 = numpy.sum(self.__buffer*numpy.conj(self.__buffer),1)
1366 pair1 = self.__buffer[:,1:,:]*numpy.conjugate(self.__buffer[:,:-1,:])
1366 data_intensity = lag_0/(self.n*self.nCohInt)#*self.nCohInt)
1367 angle = numpy.angle(numpy.sum(pair1,1))*180/(math.pi)
1367
1368 #print(angle.shape)#print("__ANGLE__") #print("angle",angle[:,:10])
1368 pair1 = self.__buffer[:,:-1,:]*numpy.conjugate(self.__buffer[:,1:,:])
1369 data_velocity = (self.lambda_/(4*math.pi*self.ippSec))*numpy.angle(numpy.sum(pair1,1))#self.ippSec*self.nCohInt
1369 lag_1 = numpy.sum(pair1,1)
1370 #angle = numpy.angle(numpy.sum(pair1,1))*180/(math.pi)
1371 data_velocity = (-1.0*self.lambda_/(4*math.pi*self.ippSec))*numpy.angle(lag_1)#self.ippSec*self.nCohInt
1372
1373 lag_0 = lag_0.real/(self.n)
1374 lag_1 = lag_1/(self.n-1)
1375 R1 = numpy.abs(lag_1)
1376 S = (lag_0-self.noise)
1377 #k = R1/S
1378 #k = 1-k
1379 #k =numpy.absolute(k)
1380 #k =numpy.sqrt(k)
1381 L = S/R1
1382 #print("L",L[0])
1383 L = numpy.where(L<0,1,L)
1384 L = numpy.log(L)
1385 tmp = numpy.sqrt(numpy.absolute(L))
1386 data_specwidth = (self.lambda_/(2*math.sqrt(2)*math.pi*self.ippSec))*tmp*numpy.sign(L)
1387 #data_specwidth = (self.lambda_/(2*math.sqrt(2)*math.pi*self.ippSec))*k
1370 n = self.__profIndex
1388 n = self.__profIndex
1371
1389
1372 self.__buffer = numpy.zeros((self.__nch, self.__nProf,self.__nHeis), dtype='complex')
1390 self.__buffer = numpy.zeros((self.__nch, self.__nProf,self.__nHeis), dtype='complex')
1373 self.__profIndex = 0
1391 self.__profIndex = 0
1374 return data_intensity,data_velocity,n
1392 return data_intensity,data_velocity,data_specwidth,n
1375
1393
1376 def pulsePairbyProfiles(self,data):
1394 def pulsePairbyProfiles(self,data):
1377
1395
1378 self.__dataReady = False
1396 self.__dataReady = False
1379 data_intensity = None
1397 data_intensity = None
1380 data_velocity = None
1398 data_velocity = None
1399 data_specwidth = None
1381 self.putData(data)
1400 self.putData(data)
1382 if self.__profIndex == self.n:
1401 if self.__profIndex == self.n:
1383 data_intensity, data_velocity, n = self.pushData()
1402 #self.noise = numpy.zeros([self.__nch,self.__nHeis])
1403 #for i in range(self.__nch):
1404 # self.noise[i]=data.getNoise(channel=i)
1405 #print(self.noise.shape)
1406 data_intensity, data_velocity,data_specwidth, n = self.pushData()
1384 self.__dataReady = True
1407 self.__dataReady = True
1385
1408
1386 return data_intensity, data_velocity
1409 return data_intensity, data_velocity,data_specwidth
1387
1410
1388 def pulsePairOp(self, data, datatime= None):
1411 def pulsePairOp(self, data, datatime= None):
1389
1412
1390 if self.__initime == None:
1413 if self.__initime == None:
1391 self.__initime = datatime
1414 self.__initime = datatime
1392
1415
1393 data_intensity, data_velocity = self.pulsePairbyProfiles(data)
1416 data_intensity, data_velocity,data_specwidth = self.pulsePairbyProfiles(data)
1394 self.__lastdatatime = datatime
1417 self.__lastdatatime = datatime
1395
1418
1396 if data_intensity is None:
1419 if data_intensity is None:
1397 return None, None, None
1420 return None, None,None, None
1398
1421
1399 avgdatatime = self.__initime
1422 avgdatatime = self.__initime
1400 deltatime = datatime - self.__lastdatatime
1423 deltatime = datatime - self.__lastdatatime
1401 self.__initime = datatime
1424 self.__initime = datatime
1402
1425
1403 return data_intensity, data_velocity, avgdatatime
1426 return data_intensity, data_velocity,data_specwidth,avgdatatime
1404
1427
1405 def run(self, dataOut,n = None,removeDC= False, overlapping= False,**kwargs):
1428 def run(self, dataOut,n = None,removeDC= False, overlapping= False,**kwargs):
1406
1429
1407 if not self.isConfig:
1430 if not self.isConfig:
1408 self.setup(dataOut = dataOut, n = n , removeDC=removeDC , **kwargs)
1431 self.setup(dataOut = dataOut, n = n , removeDC=removeDC , **kwargs)
1409 self.isConfig = True
1432 self.isConfig = True
1410 data_intensity, data_velocity, avgdatatime = self.pulsePairOp(dataOut.data, dataOut.utctime)
1433 data_intensity, data_velocity,data_specwidth, avgdatatime = self.pulsePairOp(dataOut.data, dataOut.utctime)
1411 dataOut.flagNoData = True
1434 dataOut.flagNoData = True
1412
1435
1413 if self.__dataReady:
1436 if self.__dataReady:
1414 dataOut.nCohInt *= self.n
1437 dataOut.nCohInt *= self.n
1415 dataOut.data_intensity = data_intensity #valor para intensidad
1438 dataOut.data_intensity = data_intensity #valor para intensidad
1416 dataOut.data_velocity = data_velocity #valor para velocidad
1439 dataOut.data_velocity = data_velocity #valor para velocidad
1440 dataOut.data_specwidth = data_specwidth
1417 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1441 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1418 dataOut.utctime = avgdatatime
1442 dataOut.utctime = avgdatatime
1419 dataOut.flagNoData = False
1443 dataOut.flagNoData = False
1420 return dataOut
1444 return dataOut
1421
1445
1422
1446
1423 # import collections
1447 # import collections
1424 # from scipy.stats import mode
1448 # from scipy.stats import mode
1425 #
1449 #
1426 # class Synchronize(Operation):
1450 # class Synchronize(Operation):
1427 #
1451 #
1428 # isConfig = False
1452 # isConfig = False
1429 # __profIndex = 0
1453 # __profIndex = 0
1430 #
1454 #
1431 # def __init__(self, **kwargs):
1455 # def __init__(self, **kwargs):
1432 #
1456 #
1433 # Operation.__init__(self, **kwargs)
1457 # Operation.__init__(self, **kwargs)
1434 # # self.isConfig = False
1458 # # self.isConfig = False
1435 # self.__powBuffer = None
1459 # self.__powBuffer = None
1436 # self.__startIndex = 0
1460 # self.__startIndex = 0
1437 # self.__pulseFound = False
1461 # self.__pulseFound = False
1438 #
1462 #
1439 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1463 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1440 #
1464 #
1441 # #Read data
1465 # #Read data
1442 #
1466 #
1443 # powerdB = dataOut.getPower(channel = channel)
1467 # powerdB = dataOut.getPower(channel = channel)
1444 # noisedB = dataOut.getNoise(channel = channel)[0]
1468 # noisedB = dataOut.getNoise(channel = channel)[0]
1445 #
1469 #
1446 # self.__powBuffer.extend(powerdB.flatten())
1470 # self.__powBuffer.extend(powerdB.flatten())
1447 #
1471 #
1448 # dataArray = numpy.array(self.__powBuffer)
1472 # dataArray = numpy.array(self.__powBuffer)
1449 #
1473 #
1450 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1474 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1451 #
1475 #
1452 # maxValue = numpy.nanmax(filteredPower)
1476 # maxValue = numpy.nanmax(filteredPower)
1453 #
1477 #
1454 # if maxValue < noisedB + 10:
1478 # if maxValue < noisedB + 10:
1455 # #No se encuentra ningun pulso de transmision
1479 # #No se encuentra ningun pulso de transmision
1456 # return None
1480 # return None
1457 #
1481 #
1458 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1482 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1459 #
1483 #
1460 # if len(maxValuesIndex) < 2:
1484 # if len(maxValuesIndex) < 2:
1461 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1485 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1462 # return None
1486 # return None
1463 #
1487 #
1464 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1488 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1465 #
1489 #
1466 # #Seleccionar solo valores con un espaciamiento de nSamples
1490 # #Seleccionar solo valores con un espaciamiento de nSamples
1467 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1491 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1468 #
1492 #
1469 # if len(pulseIndex) < 2:
1493 # if len(pulseIndex) < 2:
1470 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1494 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1471 # return None
1495 # return None
1472 #
1496 #
1473 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1497 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1474 #
1498 #
1475 # #remover senales que se distancien menos de 10 unidades o muestras
1499 # #remover senales que se distancien menos de 10 unidades o muestras
1476 # #(No deberian existir IPP menor a 10 unidades)
1500 # #(No deberian existir IPP menor a 10 unidades)
1477 #
1501 #
1478 # realIndex = numpy.where(spacing > 10 )[0]
1502 # realIndex = numpy.where(spacing > 10 )[0]
1479 #
1503 #
1480 # if len(realIndex) < 2:
1504 # if len(realIndex) < 2:
1481 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1505 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1482 # return None
1506 # return None
1483 #
1507 #
1484 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1508 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1485 # realPulseIndex = pulseIndex[realIndex]
1509 # realPulseIndex = pulseIndex[realIndex]
1486 #
1510 #
1487 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1511 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1488 #
1512 #
1489 # print "IPP = %d samples" %period
1513 # print "IPP = %d samples" %period
1490 #
1514 #
1491 # self.__newNSamples = dataOut.nHeights #int(period)
1515 # self.__newNSamples = dataOut.nHeights #int(period)
1492 # self.__startIndex = int(realPulseIndex[0])
1516 # self.__startIndex = int(realPulseIndex[0])
1493 #
1517 #
1494 # return 1
1518 # return 1
1495 #
1519 #
1496 #
1520 #
1497 # def setup(self, nSamples, nChannels, buffer_size = 4):
1521 # def setup(self, nSamples, nChannels, buffer_size = 4):
1498 #
1522 #
1499 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1523 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1500 # maxlen = buffer_size*nSamples)
1524 # maxlen = buffer_size*nSamples)
1501 #
1525 #
1502 # bufferList = []
1526 # bufferList = []
1503 #
1527 #
1504 # for i in range(nChannels):
1528 # for i in range(nChannels):
1505 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1529 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1506 # maxlen = buffer_size*nSamples)
1530 # maxlen = buffer_size*nSamples)
1507 #
1531 #
1508 # bufferList.append(bufferByChannel)
1532 # bufferList.append(bufferByChannel)
1509 #
1533 #
1510 # self.__nSamples = nSamples
1534 # self.__nSamples = nSamples
1511 # self.__nChannels = nChannels
1535 # self.__nChannels = nChannels
1512 # self.__bufferList = bufferList
1536 # self.__bufferList = bufferList
1513 #
1537 #
1514 # def run(self, dataOut, channel = 0):
1538 # def run(self, dataOut, channel = 0):
1515 #
1539 #
1516 # if not self.isConfig:
1540 # if not self.isConfig:
1517 # nSamples = dataOut.nHeights
1541 # nSamples = dataOut.nHeights
1518 # nChannels = dataOut.nChannels
1542 # nChannels = dataOut.nChannels
1519 # self.setup(nSamples, nChannels)
1543 # self.setup(nSamples, nChannels)
1520 # self.isConfig = True
1544 # self.isConfig = True
1521 #
1545 #
1522 # #Append new data to internal buffer
1546 # #Append new data to internal buffer
1523 # for thisChannel in range(self.__nChannels):
1547 # for thisChannel in range(self.__nChannels):
1524 # bufferByChannel = self.__bufferList[thisChannel]
1548 # bufferByChannel = self.__bufferList[thisChannel]
1525 # bufferByChannel.extend(dataOut.data[thisChannel])
1549 # bufferByChannel.extend(dataOut.data[thisChannel])
1526 #
1550 #
1527 # if self.__pulseFound:
1551 # if self.__pulseFound:
1528 # self.__startIndex -= self.__nSamples
1552 # self.__startIndex -= self.__nSamples
1529 #
1553 #
1530 # #Finding Tx Pulse
1554 # #Finding Tx Pulse
1531 # if not self.__pulseFound:
1555 # if not self.__pulseFound:
1532 # indexFound = self.__findTxPulse(dataOut, channel)
1556 # indexFound = self.__findTxPulse(dataOut, channel)
1533 #
1557 #
1534 # if indexFound == None:
1558 # if indexFound == None:
1535 # dataOut.flagNoData = True
1559 # dataOut.flagNoData = True
1536 # return
1560 # return
1537 #
1561 #
1538 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1562 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1539 # self.__pulseFound = True
1563 # self.__pulseFound = True
1540 # self.__startIndex = indexFound
1564 # self.__startIndex = indexFound
1541 #
1565 #
1542 # #If pulse was found ...
1566 # #If pulse was found ...
1543 # for thisChannel in range(self.__nChannels):
1567 # for thisChannel in range(self.__nChannels):
1544 # bufferByChannel = self.__bufferList[thisChannel]
1568 # bufferByChannel = self.__bufferList[thisChannel]
1545 # #print self.__startIndex
1569 # #print self.__startIndex
1546 # x = numpy.array(bufferByChannel)
1570 # x = numpy.array(bufferByChannel)
1547 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1571 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1548 #
1572 #
1549 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1573 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1550 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1574 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1551 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1575 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1552 #
1576 #
1553 # dataOut.data = self.__arrayBuffer
1577 # dataOut.data = self.__arrayBuffer
1554 #
1578 #
1555 # self.__startIndex += self.__newNSamples
1579 # self.__startIndex += self.__newNSamples
1556 #
1580 #
1557 # return
1581 # return
General Comments 0
You need to be logged in to leave comments. Login now