##// END OF EJS Templates
Update de WR-Project
avaldez -
r1282:f590e95f1fbc
parent child
Show More

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

@@ -1,1372 +1,1372
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 from schainpy.utils import log
12 from schainpy.utils import log
13 from .jroheaderIO import SystemHeader, RadarControllerHeader
13 from .jroheaderIO import SystemHeader, RadarControllerHeader
14
14
15
15
16 def getNumpyDtype(dataTypeCode):
16 def getNumpyDtype(dataTypeCode):
17
17
18 if dataTypeCode == 0:
18 if dataTypeCode == 0:
19 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
19 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
20 elif dataTypeCode == 1:
20 elif dataTypeCode == 1:
21 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
21 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
22 elif dataTypeCode == 2:
22 elif dataTypeCode == 2:
23 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
23 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
24 elif dataTypeCode == 3:
24 elif dataTypeCode == 3:
25 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
25 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
26 elif dataTypeCode == 4:
26 elif dataTypeCode == 4:
27 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
27 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
28 elif dataTypeCode == 5:
28 elif dataTypeCode == 5:
29 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
29 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
30 else:
30 else:
31 raise ValueError('dataTypeCode was not defined')
31 raise ValueError('dataTypeCode was not defined')
32
32
33 return numpyDtype
33 return numpyDtype
34
34
35
35
36 def getDataTypeCode(numpyDtype):
36 def getDataTypeCode(numpyDtype):
37
37
38 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
38 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
39 datatype = 0
39 datatype = 0
40 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
40 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
41 datatype = 1
41 datatype = 1
42 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
42 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
43 datatype = 2
43 datatype = 2
44 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
44 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
45 datatype = 3
45 datatype = 3
46 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
46 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
47 datatype = 4
47 datatype = 4
48 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
48 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
49 datatype = 5
49 datatype = 5
50 else:
50 else:
51 datatype = None
51 datatype = None
52
52
53 return datatype
53 return datatype
54
54
55
55
56 def hildebrand_sekhon(data, navg):
56 def hildebrand_sekhon(data, navg):
57 """
57 """
58 This method is for the objective determination of the noise level in Doppler spectra. This
58 This method is for the objective determination of the noise level in Doppler spectra. This
59 implementation technique is based on the fact that the standard deviation of the spectral
59 implementation technique is based on the fact that the standard deviation of the spectral
60 densities is equal to the mean spectral density for white Gaussian noise
60 densities is equal to the mean spectral density for white Gaussian noise
61
61
62 Inputs:
62 Inputs:
63 Data : heights
63 Data : heights
64 navg : numbers of averages
64 navg : numbers of averages
65
65
66 Return:
66 Return:
67 mean : noise's level
67 mean : noise's level
68 """
68 """
69
69
70 sortdata = numpy.sort(data, axis=None)
70 sortdata = numpy.sort(data, axis=None)
71 lenOfData = len(sortdata)
71 lenOfData = len(sortdata)
72 nums_min = lenOfData*0.2
72 nums_min = lenOfData*0.2
73
73
74 if nums_min <= 5:
74 if nums_min <= 5:
75
75
76 nums_min = 5
76 nums_min = 5
77
77
78 sump = 0.
78 sump = 0.
79 sumq = 0.
79 sumq = 0.
80
80
81 j = 0
81 j = 0
82 cont = 1
82 cont = 1
83
83
84 while((cont == 1)and(j < lenOfData)):
84 while((cont == 1)and(j < lenOfData)):
85
85
86 sump += sortdata[j]
86 sump += sortdata[j]
87 sumq += sortdata[j]**2
87 sumq += sortdata[j]**2
88
88
89 if j > nums_min:
89 if j > nums_min:
90 rtest = float(j)/(j-1) + 1.0/navg
90 rtest = float(j)/(j-1) + 1.0/navg
91 if ((sumq*j) > (rtest*sump**2)):
91 if ((sumq*j) > (rtest*sump**2)):
92 j = j - 1
92 j = j - 1
93 sump = sump - sortdata[j]
93 sump = sump - sortdata[j]
94 sumq = sumq - sortdata[j]**2
94 sumq = sumq - sortdata[j]**2
95 cont = 0
95 cont = 0
96
96
97 j += 1
97 j += 1
98
98
99 lnoise = sump / j
99 lnoise = sump / j
100
100
101 return lnoise
101 return lnoise
102
102
103
103
104 class Beam:
104 class Beam:
105
105
106 def __init__(self):
106 def __init__(self):
107 self.codeList = []
107 self.codeList = []
108 self.azimuthList = []
108 self.azimuthList = []
109 self.zenithList = []
109 self.zenithList = []
110
110
111
111
112 class GenericData(object):
112 class GenericData(object):
113
113
114 flagNoData = True
114 flagNoData = True
115
115
116 def copy(self, inputObj=None):
116 def copy(self, inputObj=None):
117
117
118 if inputObj == None:
118 if inputObj == None:
119 return copy.deepcopy(self)
119 return copy.deepcopy(self)
120
120
121 for key in list(inputObj.__dict__.keys()):
121 for key in list(inputObj.__dict__.keys()):
122
122
123 attribute = inputObj.__dict__[key]
123 attribute = inputObj.__dict__[key]
124
124
125 # If this attribute is a tuple or list
125 # If this attribute is a tuple or list
126 if type(inputObj.__dict__[key]) in (tuple, list):
126 if type(inputObj.__dict__[key]) in (tuple, list):
127 self.__dict__[key] = attribute[:]
127 self.__dict__[key] = attribute[:]
128 continue
128 continue
129
129
130 # If this attribute is another object or instance
130 # If this attribute is another object or instance
131 if hasattr(attribute, '__dict__'):
131 if hasattr(attribute, '__dict__'):
132 self.__dict__[key] = attribute.copy()
132 self.__dict__[key] = attribute.copy()
133 continue
133 continue
134
134
135 self.__dict__[key] = inputObj.__dict__[key]
135 self.__dict__[key] = inputObj.__dict__[key]
136
136
137 def deepcopy(self):
137 def deepcopy(self):
138
138
139 return copy.deepcopy(self)
139 return copy.deepcopy(self)
140
140
141 def isEmpty(self):
141 def isEmpty(self):
142
142
143 return self.flagNoData
143 return self.flagNoData
144
144
145
145
146 class JROData(GenericData):
146 class JROData(GenericData):
147
147
148 # m_BasicHeader = BasicHeader()
148 # m_BasicHeader = BasicHeader()
149 # m_ProcessingHeader = ProcessingHeader()
149 # m_ProcessingHeader = ProcessingHeader()
150
150
151 systemHeaderObj = SystemHeader()
151 systemHeaderObj = SystemHeader()
152 radarControllerHeaderObj = RadarControllerHeader()
152 radarControllerHeaderObj = RadarControllerHeader()
153 # data = None
153 # data = None
154 type = None
154 type = None
155 datatype = None # dtype but in string
155 datatype = None # dtype but in string
156 # dtype = None
156 # dtype = None
157 # nChannels = None
157 # nChannels = None
158 # nHeights = None
158 # nHeights = None
159 nProfiles = None
159 nProfiles = None
160 heightList = None
160 heightList = None
161 channelList = None
161 channelList = None
162 flagDiscontinuousBlock = False
162 flagDiscontinuousBlock = False
163 useLocalTime = False
163 useLocalTime = False
164 utctime = None
164 utctime = None
165 timeZone = None
165 timeZone = None
166 dstFlag = None
166 dstFlag = None
167 errorCount = None
167 errorCount = None
168 blocksize = None
168 blocksize = None
169 # nCode = None
169 # nCode = None
170 # nBaud = None
170 # nBaud = None
171 # code = None
171 # code = None
172 flagDecodeData = False # asumo q la data no esta decodificada
172 flagDecodeData = False # asumo q la data no esta decodificada
173 flagDeflipData = False # asumo q la data no esta sin flip
173 flagDeflipData = False # asumo q la data no esta sin flip
174 flagShiftFFT = False
174 flagShiftFFT = False
175 # ippSeconds = None
175 # ippSeconds = None
176 # timeInterval = None
176 # timeInterval = None
177 nCohInt = None
177 nCohInt = None
178 # noise = None
178 # noise = None
179 windowOfFilter = 1
179 windowOfFilter = 1
180 # Speed of ligth
180 # Speed of ligth
181 C = 3e8
181 C = 3e8
182 frequency = 49.92e6
182 frequency = 49.92e6
183 realtime = False
183 realtime = False
184 beacon_heiIndexList = None
184 beacon_heiIndexList = None
185 last_block = None
185 last_block = None
186 blocknow = None
186 blocknow = None
187 azimuth = None
187 azimuth = None
188 zenith = None
188 zenith = None
189 beam = Beam()
189 beam = Beam()
190 profileIndex = None
190 profileIndex = None
191 error = None
191 error = None
192 data = None
192 data = None
193 nmodes = None
193 nmodes = None
194
194
195 def __str__(self):
195 def __str__(self):
196
196
197 return '{} - {}'.format(self.type, self.getDatatime())
197 return '{} - {}'.format(self.type, self.getDatatime())
198
198
199 def getNoise(self):
199 def getNoise(self):
200
200
201 raise NotImplementedError
201 raise NotImplementedError
202
202
203 def getNChannels(self):
203 def getNChannels(self):
204
204
205 return len(self.channelList)
205 return len(self.channelList)
206
206
207 def getChannelIndexList(self):
207 def getChannelIndexList(self):
208
208
209 return list(range(self.nChannels))
209 return list(range(self.nChannels))
210
210
211 def getNHeights(self):
211 def getNHeights(self):
212
212
213 return len(self.heightList)
213 return len(self.heightList)
214
214
215 def getHeiRange(self, extrapoints=0):
215 def getHeiRange(self, extrapoints=0):
216
216
217 heis = self.heightList
217 heis = self.heightList
218 # deltah = self.heightList[1] - self.heightList[0]
218 # deltah = self.heightList[1] - self.heightList[0]
219 #
219 #
220 # heis.append(self.heightList[-1])
220 # heis.append(self.heightList[-1])
221
221
222 return heis
222 return heis
223
223
224 def getDeltaH(self):
224 def getDeltaH(self):
225
225
226 delta = self.heightList[1] - self.heightList[0]
226 delta = self.heightList[1] - self.heightList[0]
227
227
228 return delta
228 return delta
229
229
230 def getltctime(self):
230 def getltctime(self):
231
231
232 if self.useLocalTime:
232 if self.useLocalTime:
233 return self.utctime - self.timeZone * 60
233 return self.utctime - self.timeZone * 60
234
234
235 return self.utctime
235 return self.utctime
236
236
237 def getDatatime(self):
237 def getDatatime(self):
238
238
239 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
239 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
240 return datatimeValue
240 return datatimeValue
241
241
242 def getTimeRange(self):
242 def getTimeRange(self):
243
243
244 datatime = []
244 datatime = []
245
245
246 datatime.append(self.ltctime)
246 datatime.append(self.ltctime)
247 datatime.append(self.ltctime + self.timeInterval + 1)
247 datatime.append(self.ltctime + self.timeInterval + 1)
248
248
249 datatime = numpy.array(datatime)
249 datatime = numpy.array(datatime)
250
250
251 return datatime
251 return datatime
252
252
253 def getFmaxTimeResponse(self):
253 def getFmaxTimeResponse(self):
254
254
255 period = (10**-6) * self.getDeltaH() / (0.15)
255 period = (10**-6) * self.getDeltaH() / (0.15)
256
256
257 PRF = 1. / (period * self.nCohInt)
257 PRF = 1. / (period * self.nCohInt)
258
258
259 fmax = PRF
259 fmax = PRF
260
260
261 return fmax
261 return fmax
262
262
263 def getFmax(self):
263 def getFmax(self):
264 PRF = 1. / (self.ippSeconds * self.nCohInt)
264 PRF = 1. / (self.ippSeconds * self.nCohInt)
265
265
266 fmax = PRF
266 fmax = PRF
267 return fmax
267 return fmax
268
268
269 def getVmax(self):
269 def getVmax(self):
270
270
271 _lambda = self.C / self.frequency
271 _lambda = self.C / self.frequency
272
272
273 vmax = self.getFmax() * _lambda / 2
273 vmax = self.getFmax() * _lambda / 2
274
274
275 return vmax
275 return vmax
276
276
277 def get_ippSeconds(self):
277 def get_ippSeconds(self):
278 '''
278 '''
279 '''
279 '''
280 return self.radarControllerHeaderObj.ippSeconds
280 return self.radarControllerHeaderObj.ippSeconds
281
281
282 def set_ippSeconds(self, ippSeconds):
282 def set_ippSeconds(self, ippSeconds):
283 '''
283 '''
284 '''
284 '''
285
285
286 self.radarControllerHeaderObj.ippSeconds = ippSeconds
286 self.radarControllerHeaderObj.ippSeconds = ippSeconds
287
287
288 return
288 return
289
289
290 def get_dtype(self):
290 def get_dtype(self):
291 '''
291 '''
292 '''
292 '''
293 return getNumpyDtype(self.datatype)
293 return getNumpyDtype(self.datatype)
294
294
295 def set_dtype(self, numpyDtype):
295 def set_dtype(self, numpyDtype):
296 '''
296 '''
297 '''
297 '''
298
298
299 self.datatype = getDataTypeCode(numpyDtype)
299 self.datatype = getDataTypeCode(numpyDtype)
300
300
301 def get_code(self):
301 def get_code(self):
302 '''
302 '''
303 '''
303 '''
304 return self.radarControllerHeaderObj.code
304 return self.radarControllerHeaderObj.code
305
305
306 def set_code(self, code):
306 def set_code(self, code):
307 '''
307 '''
308 '''
308 '''
309 self.radarControllerHeaderObj.code = code
309 self.radarControllerHeaderObj.code = code
310
310
311 return
311 return
312
312
313 def get_ncode(self):
313 def get_ncode(self):
314 '''
314 '''
315 '''
315 '''
316 return self.radarControllerHeaderObj.nCode
316 return self.radarControllerHeaderObj.nCode
317
317
318 def set_ncode(self, nCode):
318 def set_ncode(self, nCode):
319 '''
319 '''
320 '''
320 '''
321 self.radarControllerHeaderObj.nCode = nCode
321 self.radarControllerHeaderObj.nCode = nCode
322
322
323 return
323 return
324
324
325 def get_nbaud(self):
325 def get_nbaud(self):
326 '''
326 '''
327 '''
327 '''
328 return self.radarControllerHeaderObj.nBaud
328 return self.radarControllerHeaderObj.nBaud
329
329
330 def set_nbaud(self, nBaud):
330 def set_nbaud(self, nBaud):
331 '''
331 '''
332 '''
332 '''
333 self.radarControllerHeaderObj.nBaud = nBaud
333 self.radarControllerHeaderObj.nBaud = nBaud
334
334
335 return
335 return
336
336
337 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
337 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
338 channelIndexList = property(
338 channelIndexList = property(
339 getChannelIndexList, "I'm the 'channelIndexList' property.")
339 getChannelIndexList, "I'm the 'channelIndexList' property.")
340 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
340 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
341 #noise = property(getNoise, "I'm the 'nHeights' property.")
341 #noise = property(getNoise, "I'm the 'nHeights' property.")
342 datatime = property(getDatatime, "I'm the 'datatime' property")
342 datatime = property(getDatatime, "I'm the 'datatime' property")
343 ltctime = property(getltctime, "I'm the 'ltctime' property")
343 ltctime = property(getltctime, "I'm the 'ltctime' property")
344 ippSeconds = property(get_ippSeconds, set_ippSeconds)
344 ippSeconds = property(get_ippSeconds, set_ippSeconds)
345 dtype = property(get_dtype, set_dtype)
345 dtype = property(get_dtype, set_dtype)
346 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
346 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
347 code = property(get_code, set_code)
347 code = property(get_code, set_code)
348 nCode = property(get_ncode, set_ncode)
348 nCode = property(get_ncode, set_ncode)
349 nBaud = property(get_nbaud, set_nbaud)
349 nBaud = property(get_nbaud, set_nbaud)
350
350
351
351
352 class Voltage(JROData):
352 class Voltage(JROData):
353
353
354 # data es un numpy array de 2 dmensiones (canales, alturas)
354 # data es un numpy array de 2 dmensiones (canales, alturas)
355 data = None
355 data = None
356
356
357 def __init__(self):
357 def __init__(self):
358 '''
358 '''
359 Constructor
359 Constructor
360 '''
360 '''
361
361
362 self.useLocalTime = True
362 self.useLocalTime = True
363 self.radarControllerHeaderObj = RadarControllerHeader()
363 self.radarControllerHeaderObj = RadarControllerHeader()
364 self.systemHeaderObj = SystemHeader()
364 self.systemHeaderObj = SystemHeader()
365 self.type = "Voltage"
365 self.type = "Voltage"
366 self.data = None
366 self.data = None
367 # self.dtype = None
367 # self.dtype = None
368 # self.nChannels = 0
368 # self.nChannels = 0
369 # self.nHeights = 0
369 # self.nHeights = 0
370 self.nProfiles = None
370 self.nProfiles = None
371 self.heightList = None
371 self.heightList = None
372 self.channelList = None
372 self.channelList = None
373 # self.channelIndexList = None
373 # self.channelIndexList = None
374 self.flagNoData = True
374 self.flagNoData = True
375 self.flagDiscontinuousBlock = False
375 self.flagDiscontinuousBlock = False
376 self.utctime = None
376 self.utctime = None
377 self.timeZone = None
377 self.timeZone = None
378 self.dstFlag = None
378 self.dstFlag = None
379 self.errorCount = None
379 self.errorCount = None
380 self.nCohInt = None
380 self.nCohInt = None
381 self.blocksize = None
381 self.blocksize = None
382 self.flagDecodeData = False # asumo q la data no esta decodificada
382 self.flagDecodeData = False # asumo q la data no esta decodificada
383 self.flagDeflipData = False # asumo q la data no esta sin flip
383 self.flagDeflipData = False # asumo q la data no esta sin flip
384 self.flagShiftFFT = False
384 self.flagShiftFFT = False
385 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
385 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
386 self.profileIndex = 0
386 self.profileIndex = 0
387
387
388 def getNoisebyHildebrand(self, channel=None):
388 def getNoisebyHildebrand(self, channel=None):
389 """
389 """
390 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
390 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
391
391
392 Return:
392 Return:
393 noiselevel
393 noiselevel
394 """
394 """
395
395
396 if channel != None:
396 if channel != None:
397 data = self.data[channel]
397 data = self.data[channel]
398 nChannels = 1
398 nChannels = 1
399 else:
399 else:
400 data = self.data
400 data = self.data
401 nChannels = self.nChannels
401 nChannels = self.nChannels
402
402
403 noise = numpy.zeros(nChannels)
403 noise = numpy.zeros(nChannels)
404 power = data * numpy.conjugate(data)
404 power = data * numpy.conjugate(data)
405
405
406 for thisChannel in range(nChannels):
406 for thisChannel in range(nChannels):
407 if nChannels == 1:
407 if nChannels == 1:
408 daux = power[:].real
408 daux = power[:].real
409 else:
409 else:
410 daux = power[thisChannel, :].real
410 daux = power[thisChannel, :].real
411 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
411 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
412
412
413 return noise
413 return noise
414
414
415 def getNoise(self, type=1, channel=None):
415 def getNoise(self, type=1, channel=None):
416
416
417 if type == 1:
417 if type == 1:
418 noise = self.getNoisebyHildebrand(channel)
418 noise = self.getNoisebyHildebrand(channel)
419
419
420 return noise
420 return noise
421
421
422 def getPower(self, channel=None):
422 def getPower(self, channel=None):
423
423
424 if channel != None:
424 if channel != None:
425 data = self.data[channel]
425 data = self.data[channel]
426 else:
426 else:
427 data = self.data
427 data = self.data
428
428
429 power = data * numpy.conjugate(data)
429 power = data * numpy.conjugate(data)
430 powerdB = 10 * numpy.log10(power.real)
430 powerdB = 10 * numpy.log10(power.real)
431 powerdB = numpy.squeeze(powerdB)
431 powerdB = numpy.squeeze(powerdB)
432
432
433 return powerdB
433 return powerdB
434
434
435 def getTimeInterval(self):
435 def getTimeInterval(self):
436
436
437 timeInterval = self.ippSeconds * self.nCohInt
437 timeInterval = self.ippSeconds * self.nCohInt
438
438
439 return timeInterval
439 return timeInterval
440
440
441 noise = property(getNoise, "I'm the 'nHeights' property.")
441 noise = property(getNoise, "I'm the 'nHeights' property.")
442 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
442 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
443
443
444
444
445 class Spectra(JROData):
445 class Spectra(JROData):
446
446
447 # data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
447 # data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
448 data_spc = None
448 data_spc = None
449 # data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
449 # data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
450 data_cspc = None
450 data_cspc = None
451 # data dc es un numpy array de 2 dmensiones (canales, alturas)
451 # data dc es un numpy array de 2 dmensiones (canales, alturas)
452 data_dc = None
452 data_dc = None
453 # data power
453 # data power
454 data_pwr = None
454 data_pwr = None
455 nFFTPoints = None
455 nFFTPoints = None
456 # nPairs = None
456 # nPairs = None
457 pairsList = None
457 pairsList = None
458 nIncohInt = None
458 nIncohInt = None
459 wavelength = None # Necesario para cacular el rango de velocidad desde la frecuencia
459 wavelength = None # Necesario para cacular el rango de velocidad desde la frecuencia
460 nCohInt = None # se requiere para determinar el valor de timeInterval
460 nCohInt = None # se requiere para determinar el valor de timeInterval
461 ippFactor = None
461 ippFactor = None
462 profileIndex = 0
462 profileIndex = 0
463 plotting = "spectra"
463 plotting = "spectra"
464
464
465 def __init__(self):
465 def __init__(self):
466 '''
466 '''
467 Constructor
467 Constructor
468 '''
468 '''
469
469
470 self.useLocalTime = True
470 self.useLocalTime = True
471 self.radarControllerHeaderObj = RadarControllerHeader()
471 self.radarControllerHeaderObj = RadarControllerHeader()
472 self.systemHeaderObj = SystemHeader()
472 self.systemHeaderObj = SystemHeader()
473 self.type = "Spectra"
473 self.type = "Spectra"
474 # self.data = None
474 # self.data = None
475 # self.dtype = None
475 # self.dtype = None
476 # self.nChannels = 0
476 # self.nChannels = 0
477 # self.nHeights = 0
477 # self.nHeights = 0
478 self.nProfiles = None
478 self.nProfiles = None
479 self.heightList = None
479 self.heightList = None
480 self.channelList = None
480 self.channelList = None
481 # self.channelIndexList = None
481 # self.channelIndexList = None
482 self.pairsList = None
482 self.pairsList = None
483 self.flagNoData = True
483 self.flagNoData = True
484 self.flagDiscontinuousBlock = False
484 self.flagDiscontinuousBlock = False
485 self.utctime = None
485 self.utctime = None
486 self.nCohInt = None
486 self.nCohInt = None
487 self.nIncohInt = None
487 self.nIncohInt = None
488 self.blocksize = None
488 self.blocksize = None
489 self.nFFTPoints = None
489 self.nFFTPoints = None
490 self.wavelength = None
490 self.wavelength = None
491 self.flagDecodeData = False # asumo q la data no esta decodificada
491 self.flagDecodeData = False # asumo q la data no esta decodificada
492 self.flagDeflipData = False # asumo q la data no esta sin flip
492 self.flagDeflipData = False # asumo q la data no esta sin flip
493 self.flagShiftFFT = False
493 self.flagShiftFFT = False
494 self.ippFactor = 1
494 self.ippFactor = 1
495 #self.noise = None
495 #self.noise = None
496 self.beacon_heiIndexList = []
496 self.beacon_heiIndexList = []
497 self.noise_estimation = None
497 self.noise_estimation = None
498
498
499 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
499 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
500 """
500 """
501 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
501 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
502
502
503 Return:
503 Return:
504 noiselevel
504 noiselevel
505 """
505 """
506
506
507 noise = numpy.zeros(self.nChannels)
507 noise = numpy.zeros(self.nChannels)
508
508
509 for channel in range(self.nChannels):
509 for channel in range(self.nChannels):
510 daux = self.data_spc[channel,
510 daux = self.data_spc[channel,
511 xmin_index:xmax_index, ymin_index:ymax_index]
511 xmin_index:xmax_index, ymin_index:ymax_index]
512 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
512 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
513
513
514 return noise
514 return noise
515
515
516 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
516 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
517
517
518 if self.noise_estimation is not None:
518 if self.noise_estimation is not None:
519 # this was estimated by getNoise Operation defined in jroproc_spectra.py
519 # this was estimated by getNoise Operation defined in jroproc_spectra.py
520 return self.noise_estimation
520 return self.noise_estimation
521 else:
521 else:
522 noise = self.getNoisebyHildebrand(
522 noise = self.getNoisebyHildebrand(
523 xmin_index, xmax_index, ymin_index, ymax_index)
523 xmin_index, xmax_index, ymin_index, ymax_index)
524 return noise
524 return noise
525
525
526 def getFreqRangeTimeResponse(self, extrapoints=0):
526 def getFreqRangeTimeResponse(self, extrapoints=0):
527
527
528 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
528 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
529 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
529 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
530
530
531 return freqrange
531 return freqrange
532
532
533 def getAcfRange(self, extrapoints=0):
533 def getAcfRange(self, extrapoints=0):
534
534
535 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
535 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
536 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
536 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
537
537
538 return freqrange
538 return freqrange
539
539
540 def getFreqRange(self, extrapoints=0):
540 def getFreqRange(self, extrapoints=0):
541
541
542 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
542 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
543 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
543 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
544
544
545 return freqrange
545 return freqrange
546
546
547 def getVelRange(self, extrapoints=0):
547 def getVelRange(self, extrapoints=0):
548
548
549 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
549 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
550 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
550 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
551
551
552 if self.nmodes:
552 if self.nmodes:
553 return velrange/self.nmodes
553 return velrange/self.nmodes
554 else:
554 else:
555 return velrange
555 return velrange
556
556
557 def getNPairs(self):
557 def getNPairs(self):
558
558
559 return len(self.pairsList)
559 return len(self.pairsList)
560
560
561 def getPairsIndexList(self):
561 def getPairsIndexList(self):
562
562
563 return list(range(self.nPairs))
563 return list(range(self.nPairs))
564
564
565 def getNormFactor(self):
565 def getNormFactor(self):
566
566
567 pwcode = 1
567 pwcode = 1
568
568
569 if self.flagDecodeData:
569 if self.flagDecodeData:
570 pwcode = numpy.sum(self.code[0]**2)
570 pwcode = numpy.sum(self.code[0]**2)
571 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
571 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
572 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
572 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
573
573
574 return normFactor
574 return normFactor
575
575
576 def getFlagCspc(self):
576 def getFlagCspc(self):
577
577
578 if self.data_cspc is None:
578 if self.data_cspc is None:
579 return True
579 return True
580
580
581 return False
581 return False
582
582
583 def getFlagDc(self):
583 def getFlagDc(self):
584
584
585 if self.data_dc is None:
585 if self.data_dc is None:
586 return True
586 return True
587
587
588 return False
588 return False
589
589
590 def getTimeInterval(self):
590 def getTimeInterval(self):
591
591
592 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
592 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
593 if self.nmodes:
593 if self.nmodes:
594 return self.nmodes*timeInterval
594 return self.nmodes*timeInterval
595 else:
595 else:
596 return timeInterval
596 return timeInterval
597
597
598 def getPower(self):
598 def getPower(self):
599
599
600 factor = self.normFactor
600 factor = self.normFactor
601 z = self.data_spc / factor
601 z = self.data_spc / factor
602 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
602 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
603 avg = numpy.average(z, axis=1)
603 avg = numpy.average(z, axis=1)
604
604
605 return 10 * numpy.log10(avg)
605 return 10 * numpy.log10(avg)
606
606
607 def getCoherence(self, pairsList=None, phase=False):
607 def getCoherence(self, pairsList=None, phase=False):
608
608
609 z = []
609 z = []
610 if pairsList is None:
610 if pairsList is None:
611 pairsIndexList = self.pairsIndexList
611 pairsIndexList = self.pairsIndexList
612 else:
612 else:
613 pairsIndexList = []
613 pairsIndexList = []
614 for pair in pairsList:
614 for pair in pairsList:
615 if pair not in self.pairsList:
615 if pair not in self.pairsList:
616 raise ValueError("Pair %s is not in dataOut.pairsList" % (
616 raise ValueError("Pair %s is not in dataOut.pairsList" % (
617 pair))
617 pair))
618 pairsIndexList.append(self.pairsList.index(pair))
618 pairsIndexList.append(self.pairsList.index(pair))
619 for i in range(len(pairsIndexList)):
619 for i in range(len(pairsIndexList)):
620 pair = self.pairsList[pairsIndexList[i]]
620 pair = self.pairsList[pairsIndexList[i]]
621 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
621 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
622 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
622 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
623 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
623 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
624 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
624 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
625 if phase:
625 if phase:
626 data = numpy.arctan2(avgcoherenceComplex.imag,
626 data = numpy.arctan2(avgcoherenceComplex.imag,
627 avgcoherenceComplex.real) * 180 / numpy.pi
627 avgcoherenceComplex.real) * 180 / numpy.pi
628 else:
628 else:
629 data = numpy.abs(avgcoherenceComplex)
629 data = numpy.abs(avgcoherenceComplex)
630
630
631 z.append(data)
631 z.append(data)
632
632
633 return numpy.array(z)
633 return numpy.array(z)
634
634
635 def setValue(self, value):
635 def setValue(self, value):
636
636
637 print("This property should not be initialized")
637 print("This property should not be initialized")
638
638
639 return
639 return
640
640
641 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
641 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
642 pairsIndexList = property(
642 pairsIndexList = property(
643 getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
643 getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
644 normFactor = property(getNormFactor, setValue,
644 normFactor = property(getNormFactor, setValue,
645 "I'm the 'getNormFactor' property.")
645 "I'm the 'getNormFactor' property.")
646 flag_cspc = property(getFlagCspc, setValue)
646 flag_cspc = property(getFlagCspc, setValue)
647 flag_dc = property(getFlagDc, setValue)
647 flag_dc = property(getFlagDc, setValue)
648 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
648 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
649 timeInterval = property(getTimeInterval, setValue,
649 timeInterval = property(getTimeInterval, setValue,
650 "I'm the 'timeInterval' property")
650 "I'm the 'timeInterval' property")
651
651
652
652
653 class SpectraHeis(Spectra):
653 class SpectraHeis(Spectra):
654
654
655 data_spc = None
655 data_spc = None
656 data_cspc = None
656 data_cspc = None
657 data_dc = None
657 data_dc = None
658 nFFTPoints = None
658 nFFTPoints = None
659 # nPairs = None
659 # nPairs = None
660 pairsList = None
660 pairsList = None
661 nCohInt = None
661 nCohInt = None
662 nIncohInt = None
662 nIncohInt = None
663
663
664 def __init__(self):
664 def __init__(self):
665
665
666 self.radarControllerHeaderObj = RadarControllerHeader()
666 self.radarControllerHeaderObj = RadarControllerHeader()
667
667
668 self.systemHeaderObj = SystemHeader()
668 self.systemHeaderObj = SystemHeader()
669
669
670 self.type = "SpectraHeis"
670 self.type = "SpectraHeis"
671
671
672 # self.dtype = None
672 # self.dtype = None
673
673
674 # self.nChannels = 0
674 # self.nChannels = 0
675
675
676 # self.nHeights = 0
676 # self.nHeights = 0
677
677
678 self.nProfiles = None
678 self.nProfiles = None
679
679
680 self.heightList = None
680 self.heightList = None
681
681
682 self.channelList = None
682 self.channelList = None
683
683
684 # self.channelIndexList = None
684 # self.channelIndexList = None
685
685
686 self.flagNoData = True
686 self.flagNoData = True
687
687
688 self.flagDiscontinuousBlock = False
688 self.flagDiscontinuousBlock = False
689
689
690 # self.nPairs = 0
690 # self.nPairs = 0
691
691
692 self.utctime = None
692 self.utctime = None
693
693
694 self.blocksize = None
694 self.blocksize = None
695
695
696 self.profileIndex = 0
696 self.profileIndex = 0
697
697
698 self.nCohInt = 1
698 self.nCohInt = 1
699
699
700 self.nIncohInt = 1
700 self.nIncohInt = 1
701
701
702 def getNormFactor(self):
702 def getNormFactor(self):
703 pwcode = 1
703 pwcode = 1
704 if self.flagDecodeData:
704 if self.flagDecodeData:
705 pwcode = numpy.sum(self.code[0]**2)
705 pwcode = numpy.sum(self.code[0]**2)
706
706
707 normFactor = self.nIncohInt * self.nCohInt * pwcode
707 normFactor = self.nIncohInt * self.nCohInt * pwcode
708
708
709 return normFactor
709 return normFactor
710
710
711 def getTimeInterval(self):
711 def getTimeInterval(self):
712
712
713 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
713 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
714
714
715 return timeInterval
715 return timeInterval
716
716
717 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
717 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
718 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
718 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
719
719
720
720
721 class Fits(JROData):
721 class Fits(JROData):
722
722
723 heightList = None
723 heightList = None
724 channelList = None
724 channelList = None
725 flagNoData = True
725 flagNoData = True
726 flagDiscontinuousBlock = False
726 flagDiscontinuousBlock = False
727 useLocalTime = False
727 useLocalTime = False
728 utctime = None
728 utctime = None
729 timeZone = None
729 timeZone = None
730 # ippSeconds = None
730 # ippSeconds = None
731 # timeInterval = None
731 # timeInterval = None
732 nCohInt = None
732 nCohInt = None
733 nIncohInt = None
733 nIncohInt = None
734 noise = None
734 noise = None
735 windowOfFilter = 1
735 windowOfFilter = 1
736 # Speed of ligth
736 # Speed of ligth
737 C = 3e8
737 C = 3e8
738 frequency = 49.92e6
738 frequency = 49.92e6
739 realtime = False
739 realtime = False
740
740
741 def __init__(self):
741 def __init__(self):
742
742
743 self.type = "Fits"
743 self.type = "Fits"
744
744
745 self.nProfiles = None
745 self.nProfiles = None
746
746
747 self.heightList = None
747 self.heightList = None
748
748
749 self.channelList = None
749 self.channelList = None
750
750
751 # self.channelIndexList = None
751 # self.channelIndexList = None
752
752
753 self.flagNoData = True
753 self.flagNoData = True
754
754
755 self.utctime = None
755 self.utctime = None
756
756
757 self.nCohInt = 1
757 self.nCohInt = 1
758
758
759 self.nIncohInt = 1
759 self.nIncohInt = 1
760
760
761 self.useLocalTime = True
761 self.useLocalTime = True
762
762
763 self.profileIndex = 0
763 self.profileIndex = 0
764
764
765 # self.utctime = None
765 # self.utctime = None
766 # self.timeZone = None
766 # self.timeZone = None
767 # self.ltctime = None
767 # self.ltctime = None
768 # self.timeInterval = None
768 # self.timeInterval = None
769 # self.header = None
769 # self.header = None
770 # self.data_header = None
770 # self.data_header = None
771 # self.data = None
771 # self.data = None
772 # self.datatime = None
772 # self.datatime = None
773 # self.flagNoData = False
773 # self.flagNoData = False
774 # self.expName = ''
774 # self.expName = ''
775 # self.nChannels = None
775 # self.nChannels = None
776 # self.nSamples = None
776 # self.nSamples = None
777 # self.dataBlocksPerFile = None
777 # self.dataBlocksPerFile = None
778 # self.comments = ''
778 # self.comments = ''
779 #
779 #
780
780
781 def getltctime(self):
781 def getltctime(self):
782
782
783 if self.useLocalTime:
783 if self.useLocalTime:
784 return self.utctime - self.timeZone * 60
784 return self.utctime - self.timeZone * 60
785
785
786 return self.utctime
786 return self.utctime
787
787
788 def getDatatime(self):
788 def getDatatime(self):
789
789
790 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
790 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
791 return datatime
791 return datatime
792
792
793 def getTimeRange(self):
793 def getTimeRange(self):
794
794
795 datatime = []
795 datatime = []
796
796
797 datatime.append(self.ltctime)
797 datatime.append(self.ltctime)
798 datatime.append(self.ltctime + self.timeInterval)
798 datatime.append(self.ltctime + self.timeInterval)
799
799
800 datatime = numpy.array(datatime)
800 datatime = numpy.array(datatime)
801
801
802 return datatime
802 return datatime
803
803
804 def getHeiRange(self):
804 def getHeiRange(self):
805
805
806 heis = self.heightList
806 heis = self.heightList
807
807
808 return heis
808 return heis
809
809
810 def getNHeights(self):
810 def getNHeights(self):
811
811
812 return len(self.heightList)
812 return len(self.heightList)
813
813
814 def getNChannels(self):
814 def getNChannels(self):
815
815
816 return len(self.channelList)
816 return len(self.channelList)
817
817
818 def getChannelIndexList(self):
818 def getChannelIndexList(self):
819
819
820 return list(range(self.nChannels))
820 return list(range(self.nChannels))
821
821
822 def getNoise(self, type=1):
822 def getNoise(self, type=1):
823
823
824 #noise = numpy.zeros(self.nChannels)
824 #noise = numpy.zeros(self.nChannels)
825
825
826 if type == 1:
826 if type == 1:
827 noise = self.getNoisebyHildebrand()
827 noise = self.getNoisebyHildebrand()
828
828
829 if type == 2:
829 if type == 2:
830 noise = self.getNoisebySort()
830 noise = self.getNoisebySort()
831
831
832 if type == 3:
832 if type == 3:
833 noise = self.getNoisebyWindow()
833 noise = self.getNoisebyWindow()
834
834
835 return noise
835 return noise
836
836
837 def getTimeInterval(self):
837 def getTimeInterval(self):
838
838
839 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
839 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
840
840
841 return timeInterval
841 return timeInterval
842
842
843 def get_ippSeconds(self):
843 def get_ippSeconds(self):
844 '''
844 '''
845 '''
845 '''
846 return self.ipp_sec
846 return self.ipp_sec
847
847
848
848
849 datatime = property(getDatatime, "I'm the 'datatime' property")
849 datatime = property(getDatatime, "I'm the 'datatime' property")
850 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
850 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
851 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
851 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
852 channelIndexList = property(
852 channelIndexList = property(
853 getChannelIndexList, "I'm the 'channelIndexList' property.")
853 getChannelIndexList, "I'm the 'channelIndexList' property.")
854 noise = property(getNoise, "I'm the 'nHeights' property.")
854 noise = property(getNoise, "I'm the 'nHeights' property.")
855
855
856 ltctime = property(getltctime, "I'm the 'ltctime' property")
856 ltctime = property(getltctime, "I'm the 'ltctime' property")
857 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
857 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
858 ippSeconds = property(get_ippSeconds, '')
858 ippSeconds = property(get_ippSeconds, '')
859
859
860 class Correlation(JROData):
860 class Correlation(JROData):
861
861
862 noise = None
862 noise = None
863 SNR = None
863 SNR = None
864 #--------------------------------------------------
864 #--------------------------------------------------
865 mode = None
865 mode = None
866 split = False
866 split = False
867 data_cf = None
867 data_cf = None
868 lags = None
868 lags = None
869 lagRange = None
869 lagRange = None
870 pairsList = None
870 pairsList = None
871 normFactor = None
871 normFactor = None
872 #--------------------------------------------------
872 #--------------------------------------------------
873 # calculateVelocity = None
873 # calculateVelocity = None
874 nLags = None
874 nLags = None
875 nPairs = None
875 nPairs = None
876 nAvg = None
876 nAvg = None
877
877
878 def __init__(self):
878 def __init__(self):
879 '''
879 '''
880 Constructor
880 Constructor
881 '''
881 '''
882 self.radarControllerHeaderObj = RadarControllerHeader()
882 self.radarControllerHeaderObj = RadarControllerHeader()
883
883
884 self.systemHeaderObj = SystemHeader()
884 self.systemHeaderObj = SystemHeader()
885
885
886 self.type = "Correlation"
886 self.type = "Correlation"
887
887
888 self.data = None
888 self.data = None
889
889
890 self.dtype = None
890 self.dtype = None
891
891
892 self.nProfiles = None
892 self.nProfiles = None
893
893
894 self.heightList = None
894 self.heightList = None
895
895
896 self.channelList = None
896 self.channelList = None
897
897
898 self.flagNoData = True
898 self.flagNoData = True
899
899
900 self.flagDiscontinuousBlock = False
900 self.flagDiscontinuousBlock = False
901
901
902 self.utctime = None
902 self.utctime = None
903
903
904 self.timeZone = None
904 self.timeZone = None
905
905
906 self.dstFlag = None
906 self.dstFlag = None
907
907
908 self.errorCount = None
908 self.errorCount = None
909
909
910 self.blocksize = None
910 self.blocksize = None
911
911
912 self.flagDecodeData = False # asumo q la data no esta decodificada
912 self.flagDecodeData = False # asumo q la data no esta decodificada
913
913
914 self.flagDeflipData = False # asumo q la data no esta sin flip
914 self.flagDeflipData = False # asumo q la data no esta sin flip
915
915
916 self.pairsList = None
916 self.pairsList = None
917
917
918 self.nPoints = None
918 self.nPoints = None
919
919
920 def getPairsList(self):
920 def getPairsList(self):
921
921
922 return self.pairsList
922 return self.pairsList
923
923
924 def getNoise(self, mode=2):
924 def getNoise(self, mode=2):
925
925
926 indR = numpy.where(self.lagR == 0)[0][0]
926 indR = numpy.where(self.lagR == 0)[0][0]
927 indT = numpy.where(self.lagT == 0)[0][0]
927 indT = numpy.where(self.lagT == 0)[0][0]
928
928
929 jspectra0 = self.data_corr[:, :, indR, :]
929 jspectra0 = self.data_corr[:, :, indR, :]
930 jspectra = copy.copy(jspectra0)
930 jspectra = copy.copy(jspectra0)
931
931
932 num_chan = jspectra.shape[0]
932 num_chan = jspectra.shape[0]
933 num_hei = jspectra.shape[2]
933 num_hei = jspectra.shape[2]
934
934
935 freq_dc = jspectra.shape[1] / 2
935 freq_dc = jspectra.shape[1] / 2
936 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
936 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
937
937
938 if ind_vel[0] < 0:
938 if ind_vel[0] < 0:
939 ind_vel[list(range(0, 1))] = ind_vel[list(
939 ind_vel[list(range(0, 1))] = ind_vel[list(
940 range(0, 1))] + self.num_prof
940 range(0, 1))] + self.num_prof
941
941
942 if mode == 1:
942 if mode == 1:
943 jspectra[:, freq_dc, :] = (
943 jspectra[:, freq_dc, :] = (
944 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
944 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
945
945
946 if mode == 2:
946 if mode == 2:
947
947
948 vel = numpy.array([-2, -1, 1, 2])
948 vel = numpy.array([-2, -1, 1, 2])
949 xx = numpy.zeros([4, 4])
949 xx = numpy.zeros([4, 4])
950
950
951 for fil in range(4):
951 for fil in range(4):
952 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
952 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
953
953
954 xx_inv = numpy.linalg.inv(xx)
954 xx_inv = numpy.linalg.inv(xx)
955 xx_aux = xx_inv[0, :]
955 xx_aux = xx_inv[0, :]
956
956
957 for ich in range(num_chan):
957 for ich in range(num_chan):
958 yy = jspectra[ich, ind_vel, :]
958 yy = jspectra[ich, ind_vel, :]
959 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
959 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
960
960
961 junkid = jspectra[ich, freq_dc, :] <= 0
961 junkid = jspectra[ich, freq_dc, :] <= 0
962 cjunkid = sum(junkid)
962 cjunkid = sum(junkid)
963
963
964 if cjunkid.any():
964 if cjunkid.any():
965 jspectra[ich, freq_dc, junkid.nonzero()] = (
965 jspectra[ich, freq_dc, junkid.nonzero()] = (
966 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
966 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
967
967
968 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
968 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
969
969
970 return noise
970 return noise
971
971
972 def getTimeInterval(self):
972 def getTimeInterval(self):
973
973
974 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
974 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
975
975
976 return timeInterval
976 return timeInterval
977
977
978 def splitFunctions(self):
978 def splitFunctions(self):
979
979
980 pairsList = self.pairsList
980 pairsList = self.pairsList
981 ccf_pairs = []
981 ccf_pairs = []
982 acf_pairs = []
982 acf_pairs = []
983 ccf_ind = []
983 ccf_ind = []
984 acf_ind = []
984 acf_ind = []
985 for l in range(len(pairsList)):
985 for l in range(len(pairsList)):
986 chan0 = pairsList[l][0]
986 chan0 = pairsList[l][0]
987 chan1 = pairsList[l][1]
987 chan1 = pairsList[l][1]
988
988
989 # Obteniendo pares de Autocorrelacion
989 # Obteniendo pares de Autocorrelacion
990 if chan0 == chan1:
990 if chan0 == chan1:
991 acf_pairs.append(chan0)
991 acf_pairs.append(chan0)
992 acf_ind.append(l)
992 acf_ind.append(l)
993 else:
993 else:
994 ccf_pairs.append(pairsList[l])
994 ccf_pairs.append(pairsList[l])
995 ccf_ind.append(l)
995 ccf_ind.append(l)
996
996
997 data_acf = self.data_cf[acf_ind]
997 data_acf = self.data_cf[acf_ind]
998 data_ccf = self.data_cf[ccf_ind]
998 data_ccf = self.data_cf[ccf_ind]
999
999
1000 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1000 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1001
1001
1002 def getNormFactor(self):
1002 def getNormFactor(self):
1003 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1003 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1004 acf_pairs = numpy.array(acf_pairs)
1004 acf_pairs = numpy.array(acf_pairs)
1005 normFactor = numpy.zeros((self.nPairs, self.nHeights))
1005 normFactor = numpy.zeros((self.nPairs, self.nHeights))
1006
1006
1007 for p in range(self.nPairs):
1007 for p in range(self.nPairs):
1008 pair = self.pairsList[p]
1008 pair = self.pairsList[p]
1009
1009
1010 ch0 = pair[0]
1010 ch0 = pair[0]
1011 ch1 = pair[1]
1011 ch1 = pair[1]
1012
1012
1013 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
1013 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
1014 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
1014 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
1015 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
1015 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
1016
1016
1017 return normFactor
1017 return normFactor
1018
1018
1019 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1019 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1020 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1020 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1021
1021
1022
1022
1023 class Parameters(Spectra):
1023 class Parameters(Spectra):
1024
1024
1025 experimentInfo = None # Information about the experiment
1025 experimentInfo = None # Information about the experiment
1026 # Information from previous data
1026 # Information from previous data
1027 inputUnit = None # Type of data to be processed
1027 inputUnit = None # Type of data to be processed
1028 operation = None # Type of operation to parametrize
1028 operation = None # Type of operation to parametrize
1029 # normFactor = None #Normalization Factor
1029 # normFactor = None #Normalization Factor
1030 groupList = None # List of Pairs, Groups, etc
1030 groupList = None # List of Pairs, Groups, etc
1031 # Parameters
1031 # Parameters
1032 data_param = None # Parameters obtained
1032 data_param = None # Parameters obtained
1033 data_pre = None # Data Pre Parametrization
1033 data_pre = None # Data Pre Parametrization
1034 data_SNR = None # Signal to Noise Ratio
1034 data_SNR = None # Signal to Noise Ratio
1035 # heightRange = None #Heights
1035 # heightRange = None #Heights
1036 abscissaList = None # Abscissa, can be velocities, lags or time
1036 abscissaList = None # Abscissa, can be velocities, lags or time
1037 # noise = None #Noise Potency
1037 # noise = None #Noise Potency
1038 utctimeInit = None # Initial UTC time
1038 utctimeInit = None # Initial UTC time
1039 paramInterval = None # Time interval to calculate Parameters in seconds
1039 paramInterval = None # Time interval to calculate Parameters in seconds
1040 useLocalTime = True
1040 useLocalTime = True
1041 # Fitting
1041 # Fitting
1042 data_error = None # Error of the estimation
1042 data_error = None # Error of the estimation
1043 constants = None
1043 constants = None
1044 library = None
1044 library = None
1045 # Output signal
1045 # Output signal
1046 outputInterval = None # Time interval to calculate output signal in seconds
1046 outputInterval = None # Time interval to calculate output signal in seconds
1047 data_output = None # Out signal
1047 data_output = None # Out signal
1048 nAvg = None
1048 nAvg = None
1049 noise_estimation = None
1049 noise_estimation = None
1050 GauSPC = None # Fit gaussian SPC
1050 GauSPC = None # Fit gaussian SPC
1051
1051
1052 def __init__(self):
1052 def __init__(self):
1053 '''
1053 '''
1054 Constructor
1054 Constructor
1055 '''
1055 '''
1056 self.radarControllerHeaderObj = RadarControllerHeader()
1056 self.radarControllerHeaderObj = RadarControllerHeader()
1057
1057
1058 self.systemHeaderObj = SystemHeader()
1058 self.systemHeaderObj = SystemHeader()
1059
1059
1060 self.type = "Parameters"
1060 self.type = "Parameters"
1061
1061
1062 def getTimeRange1(self, interval):
1062 def getTimeRange1(self, interval):
1063
1063
1064 datatime = []
1064 datatime = []
1065
1065
1066 if self.useLocalTime:
1066 if self.useLocalTime:
1067 time1 = self.utctimeInit - self.timeZone * 60
1067 time1 = self.utctimeInit - self.timeZone * 60
1068 else:
1068 else:
1069 time1 = self.utctimeInit
1069 time1 = self.utctimeInit
1070
1070
1071 datatime.append(time1)
1071 datatime.append(time1)
1072 datatime.append(time1 + interval)
1072 datatime.append(time1 + interval)
1073 datatime = numpy.array(datatime)
1073 datatime = numpy.array(datatime)
1074
1074
1075 return datatime
1075 return datatime
1076
1076
1077 def getTimeInterval(self):
1077 def getTimeInterval(self):
1078
1078
1079 if hasattr(self, 'timeInterval1'):
1079 if hasattr(self, 'timeInterval1'):
1080 return self.timeInterval1
1080 return self.timeInterval1
1081 else:
1081 else:
1082 return self.paramInterval
1082 return self.paramInterval
1083
1083
1084 def setValue(self, value):
1084 def setValue(self, value):
1085
1085
1086 print("This property should not be initialized")
1086 print("This property should not be initialized")
1087
1087
1088 return
1088 return
1089
1089
1090 def getNoise(self):
1090 def getNoise(self):
1091
1091
1092 return self.spc_noise
1092 return self.spc_noise
1093
1093
1094 timeInterval = property(getTimeInterval)
1094 timeInterval = property(getTimeInterval)
1095 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
1095 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
1096
1096
1097
1097
1098 class PlotterData(object):
1098 class PlotterData(object):
1099 '''
1099 '''
1100 Object to hold data to be plotted
1100 Object to hold data to be plotted
1101 '''
1101 '''
1102
1102
1103 MAXNUMX = 100
1103 MAXNUMX = 100
1104 MAXNUMY = 100
1104 MAXNUMY = 100
1105
1105
1106 def __init__(self, code, throttle_value, exp_code, buffering=True, snr=False):
1106 def __init__(self, code, throttle_value, exp_code, buffering=True, snr=False):
1107
1107
1108 self.key = code
1108 self.key = code
1109 self.throttle = throttle_value
1109 self.throttle = throttle_value
1110 self.exp_code = exp_code
1110 self.exp_code = exp_code
1111 self.buffering = buffering
1111 self.buffering = buffering
1112 self.ready = False
1112 self.ready = False
1113 self.localtime = False
1113 self.localtime = False
1114 self.data = {}
1114 self.data = {}
1115 self.meta = {}
1115 self.meta = {}
1116 self.__times = []
1116 self.__times = []
1117 self.__heights = []
1117 self.__heights = []
1118
1118
1119 if 'snr' in code:
1119 if 'snr' in code:
1120 self.plottypes = ['snr']
1120 self.plottypes = ['snr']
1121 elif code == 'spc':
1121 elif code == 'spc':
1122 self.plottypes = ['spc', 'noise', 'rti']
1122 self.plottypes = ['spc', 'noise', 'rti']
1123 elif code == 'rti':
1123 elif code == 'rti':
1124 self.plottypes = ['noise', 'rti']
1124 self.plottypes = ['noise', 'rti']
1125 else:
1125 else:
1126 self.plottypes = [code]
1126 self.plottypes = [code]
1127
1127
1128 if 'snr' not in self.plottypes and snr:
1128 if 'snr' not in self.plottypes and snr:
1129 self.plottypes.append('snr')
1129 self.plottypes.append('snr')
1130
1130
1131 for plot in self.plottypes:
1131 for plot in self.plottypes:
1132 self.data[plot] = {}
1132 self.data[plot] = {}
1133
1133
1134 def __str__(self):
1134 def __str__(self):
1135 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1135 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1136 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
1136 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
1137
1137
1138 def __len__(self):
1138 def __len__(self):
1139 return len(self.__times)
1139 return len(self.__times)
1140
1140
1141 def __getitem__(self, key):
1141 def __getitem__(self, key):
1142
1142
1143 if key not in self.data:
1143 if key not in self.data:
1144 raise KeyError(log.error('Missing key: {}'.format(key)))
1144 raise KeyError(log.error('Missing key: {}'.format(key)))
1145 if 'spc' in key or not self.buffering:
1145 if 'spc' in key or not self.buffering:
1146 ret = self.data[key]
1146 ret = self.data[key]
1147 elif 'scope' in key:
1147 elif 'scope' in key:
1148 ret = numpy.array(self.data[key][float(self.tm)])
1148 ret = numpy.array(self.data[key][float(self.tm)])
1149 else:
1149 else:
1150 ret = numpy.array([self.data[key][x] for x in self.times])
1150 ret = numpy.array([self.data[key][x] for x in self.times])
1151 if ret.ndim > 1:
1151 if ret.ndim > 1:
1152 ret = numpy.swapaxes(ret, 0, 1)
1152 ret = numpy.swapaxes(ret, 0, 1)
1153 return ret
1153 return ret
1154
1154
1155 def __contains__(self, key):
1155 def __contains__(self, key):
1156 return key in self.data
1156 return key in self.data
1157
1157
1158 def setup(self):
1158 def setup(self):
1159 '''
1159 '''
1160 Configure object
1160 Configure object
1161 '''
1161 '''
1162
1162
1163 self.type = ''
1163 self.type = ''
1164 self.ready = False
1164 self.ready = False
1165 self.data = {}
1165 self.data = {}
1166 self.__times = []
1166 self.__times = []
1167 self.__heights = []
1167 self.__heights = []
1168 self.__all_heights = set()
1168 self.__all_heights = set()
1169 for plot in self.plottypes:
1169 for plot in self.plottypes:
1170 if 'snr' in plot:
1170 if 'snr' in plot:
1171 plot = 'snr'
1171 plot = 'snr'
1172 elif 'spc_moments' == plot:
1172 elif 'spc_moments' == plot:
1173 plot = 'moments'
1173 plot = 'moments'
1174 self.data[plot] = {}
1174 self.data[plot] = {}
1175
1175
1176 if 'spc' in self.data or 'rti' in self.data or 'cspc' in self.data or 'moments' in self.data:
1176 if 'spc' in self.data or 'rti' in self.data or 'cspc' in self.data or 'moments' in self.data:
1177 self.data['noise'] = {}
1177 self.data['noise'] = {}
1178 self.data['rti'] = {}
1178 self.data['rti'] = {}
1179 if 'noise' not in self.plottypes:
1179 if 'noise' not in self.plottypes:
1180 self.plottypes.append('noise')
1180 self.plottypes.append('noise')
1181 if 'rti' not in self.plottypes:
1181 if 'rti' not in self.plottypes:
1182 self.plottypes.append('rti')
1182 self.plottypes.append('rti')
1183
1183
1184 def shape(self, key):
1184 def shape(self, key):
1185 '''
1185 '''
1186 Get the shape of the one-element data for the given key
1186 Get the shape of the one-element data for the given key
1187 '''
1187 '''
1188
1188
1189 if len(self.data[key]):
1189 if len(self.data[key]):
1190 if 'spc' in key or not self.buffering:
1190 if 'spc' in key or not self.buffering:
1191 return self.data[key].shape
1191 return self.data[key].shape
1192 return self.data[key][self.__times[0]].shape
1192 return self.data[key][self.__times[0]].shape
1193 return (0,)
1193 return (0,)
1194
1194
1195 def update(self, dataOut, tm):
1195 def update(self, dataOut, tm):
1196 '''
1196 '''
1197 Update data object with new dataOut
1197 Update data object with new dataOut
1198 '''
1198 '''
1199
1199
1200 if tm in self.__times:
1200 if tm in self.__times:
1201 return
1201 return
1202 self.profileIndex = dataOut.profileIndex
1202 self.profileIndex = dataOut.profileIndex
1203 self.tm = tm
1203 self.tm = tm
1204 self.type = dataOut.type
1204 self.type = dataOut.type
1205 self.parameters = getattr(dataOut, 'parameters', [])
1205 self.parameters = getattr(dataOut, 'parameters', [])
1206
1206
1207 if hasattr(dataOut, 'meta'):
1207 if hasattr(dataOut, 'meta'):
1208 self.meta.update(dataOut.meta)
1208 self.meta.update(dataOut.meta)
1209
1209
1210 self.pairs = dataOut.pairsList
1210 self.pairs = dataOut.pairsList
1211 self.interval = dataOut.getTimeInterval()
1211 self.interval = dataOut.getTimeInterval()
1212 self.localtime = dataOut.useLocalTime
1212 self.localtime = dataOut.useLocalTime
1213 if 'spc' in self.plottypes or 'cspc' in self.plottypes or 'spc_moments' in self.plottypes:
1213 if 'spc' in self.plottypes or 'cspc' in self.plottypes or 'spc_moments' in self.plottypes:
1214 self.xrange = (dataOut.getFreqRange(1)/1000.,
1214 self.xrange = (dataOut.getFreqRange(1)/1000.,
1215 dataOut.getAcfRange(1), dataOut.getVelRange(1))
1215 dataOut.getAcfRange(1), dataOut.getVelRange(1))
1216 self.factor = dataOut.normFactor
1216 self.factor = dataOut.normFactor
1217 self.__heights.append(dataOut.heightList)
1217 self.__heights.append(dataOut.heightList)
1218 self.__all_heights.update(dataOut.heightList)
1218 self.__all_heights.update(dataOut.heightList)
1219 self.__times.append(tm)
1219 self.__times.append(tm)
1220
1220
1221 for plot in self.plottypes:
1221 for plot in self.plottypes:
1222 if plot in ('spc', 'spc_moments'):
1222 if plot in ('spc', 'spc_moments'):
1223 z = dataOut.data_spc/dataOut.normFactor
1223 z = dataOut.data_spc/dataOut.normFactor
1224 buffer = 10*numpy.log10(z)
1224 buffer = 10*numpy.log10(z)
1225 if plot == 'cspc':
1225 if plot == 'cspc':
1226 z = dataOut.data_spc/dataOut.normFactor
1226 z = dataOut.data_spc/dataOut.normFactor
1227 buffer = (dataOut.data_spc, dataOut.data_cspc)
1227 buffer = (dataOut.data_spc, dataOut.data_cspc)
1228 if plot == 'noise':
1228 if plot == 'noise':
1229 buffer = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
1229 buffer = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
1230 if plot == 'rti':
1230 if plot == 'rti':
1231 buffer = dataOut.getPower()
1231 buffer = dataOut.getPower()
1232 if plot == 'snr_db':
1232 if plot == 'snr_db':
1233 buffer = dataOut.data_SNR
1233 buffer = dataOut.data_SNR
1234 if plot == 'snr':
1234 if plot == 'snr':
1235 buffer = 10*numpy.log10(dataOut.data_SNR)
1235 buffer = 10*numpy.log10(dataOut.data_SNR)
1236 if plot == 'dop':
1236 if plot == 'dop':
1237 buffer = dataOut.data_DOP
1237 buffer = dataOut.data_DOP
1238 if plot == 'pow':
1238 if plot == 'pow':
1239 buffer = 10*numpy.log10(dataOut.data_POW)
1239 buffer = 10*numpy.log10(dataOut.data_POW)
1240 if plot == 'width':
1240 if plot == 'width':
1241 buffer = dataOut.data_WIDTH
1241 buffer = dataOut.data_WIDTH
1242 if plot == 'coh':
1242 if plot == 'coh':
1243 buffer = dataOut.getCoherence()
1243 buffer = dataOut.getCoherence()
1244 if plot == 'phase':
1244 if plot == 'phase':
1245 buffer = dataOut.getCoherence(phase=True)
1245 buffer = dataOut.getCoherence(phase=True)
1246 if plot == 'output':
1246 if plot == 'output':
1247 buffer = dataOut.data_output
1247 buffer = dataOut.data_output
1248 if plot == 'param':
1248 if plot == 'param':
1249 buffer = dataOut.data_param
1249 buffer = dataOut.data_param
1250 if plot == 'scope':
1250 if plot == 'scope':
1251 buffer = dataOut.data
1251 buffer = dataOut.data
1252 self.flagDataAsBlock = dataOut.flagDataAsBlock
1252 self.flagDataAsBlock = dataOut.flagDataAsBlock
1253 self.nProfiles = dataOut.nProfiles
1253 self.nProfiles = dataOut.nProfiles
1254
1254
1255 if plot == 'spc':
1255 if plot == 'spc':
1256 self.data['spc'] = buffer
1256 self.data['spc'] = buffer
1257 elif plot == 'cspc':
1257 elif plot == 'cspc':
1258 self.data['spc'] = buffer[0]
1258 self.data['spc'] = buffer[0]
1259 self.data['cspc'] = buffer[1]
1259 self.data['cspc'] = buffer[1]
1260 elif plot == 'spc_moments':
1260 elif plot == 'spc_moments':
1261 self.data['spc'] = buffer
1261 self.data['spc'] = buffer
1262 self.data['moments'][tm] = dataOut.moments
1262 self.data['moments'][tm] = dataOut.moments
1263 else:
1263 else:
1264 if self.buffering:
1264 if self.buffering:
1265 self.data[plot][tm] = buffer
1265 self.data[plot][tm] = buffer
1266 else:
1266 else:
1267 self.data[plot] = buffer
1267 self.data[plot] = buffer
1268
1268
1269 if dataOut.channelList is None:
1269 if dataOut.channelList is None:
1270 self.channels = range(buffer.shape[0])
1270 self.channels = range(buffer.shape[0])
1271 else:
1271 else:
1272 self.channels = dataOut.channelList
1272 self.channels = dataOut.channelList
1273
1273
1274 def normalize_heights(self):
1274 def normalize_heights(self):
1275 '''
1275 '''
1276 Ensure same-dimension of the data for different heighList
1276 Ensure same-dimension of the data for different heighList
1277 '''
1277 '''
1278
1278
1279 H = numpy.array(list(self.__all_heights))
1279 H = numpy.array(list(self.__all_heights))
1280 H.sort()
1280 H.sort()
1281 for key in self.data:
1281 for key in self.data:
1282 shape = self.shape(key)[:-1] + H.shape
1282 shape = self.shape(key)[:-1] + H.shape
1283 for tm, obj in list(self.data[key].items()):
1283 for tm, obj in list(self.data[key].items()):
1284 h = self.__heights[self.__times.index(tm)]
1284 h = self.__heights[self.__times.index(tm)]
1285 if H.size == h.size:
1285 if H.size == h.size:
1286 continue
1286 continue
1287 index = numpy.where(numpy.in1d(H, h))[0]
1287 index = numpy.where(numpy.in1d(H, h))[0]
1288 dummy = numpy.zeros(shape) + numpy.nan
1288 dummy = numpy.zeros(shape) + numpy.nan
1289 if len(shape) == 2:
1289 if len(shape) == 2:
1290 dummy[:, index] = obj
1290 dummy[:, index] = obj
1291 else:
1291 else:
1292 dummy[index] = obj
1292 dummy[index] = obj
1293 self.data[key][tm] = dummy
1293 self.data[key][tm] = dummy
1294
1294
1295 self.__heights = [H for tm in self.__times]
1295 self.__heights = [H for tm in self.__times]
1296
1296
1297 def jsonify(self, plot_name, plot_type, decimate=False):
1297 def jsonify(self, plot_name, plot_type, decimate=False):
1298 '''
1298 '''
1299 Convert data to json
1299 Convert data to json
1300 '''
1300 '''
1301
1301
1302 tm = self.times[-1]
1302 tm = self.times[-1]
1303 dy = int(self.heights.size/self.MAXNUMY) + 1
1303 dy = int(self.heights.size/self.MAXNUMY) + 1
1304 if self.key in ('spc', 'cspc') or not self.buffering:
1304 if self.key in ('spc', 'cspc') or not self.buffering:
1305 dx = int(self.data[self.key].shape[1]/self.MAXNUMX) + 1
1305 dx = int(self.data[self.key].shape[1]/self.MAXNUMX) + 1
1306 data = self.roundFloats(
1306 data = self.roundFloats(
1307 self.data[self.key][::, ::dx, ::dy].tolist())
1307 self.data[self.key][::, ::dx, ::dy].tolist())
1308 else:
1308 else:
1309 data = self.roundFloats(self.data[self.key][tm].tolist())
1309 data = self.roundFloats(self.data[self.key][tm].tolist())
1310 if self.key is 'noise':
1310 if self.key is 'noise':
1311 data = [[x] for x in data]
1311 data = [[x] for x in data]
1312
1312
1313 meta = {}
1313 meta = {}
1314 ret = {
1314 ret = {
1315 'plot': plot_name,
1315 'plot': plot_name,
1316 'code': self.exp_code,
1316 'code': self.exp_code,
1317 'time': float(tm),
1317 'time': float(tm),
1318 'data': data,
1318 'data': data,
1319 }
1319 }
1320 meta['type'] = plot_type
1320 meta['type'] = plot_type
1321 meta['interval'] = float(self.interval)
1321 meta['interval'] = float(self.interval)
1322 meta['localtime'] = self.localtime
1322 meta['localtime'] = self.localtime
1323 meta['yrange'] = self.roundFloats(self.heights[::dy].tolist())
1323 meta['yrange'] = self.roundFloats(self.heights[::dy].tolist())
1324 if 'spc' in self.data or 'cspc' in self.data:
1324 if 'spc' in self.data or 'cspc' in self.data:
1325 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1325 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1326 else:
1326 else:
1327 meta['xrange'] = []
1327 meta['xrange'] = []
1328
1328
1329 meta.update(self.meta)
1329 meta.update(self.meta)
1330 ret['metadata'] = meta
1330 ret['metadata'] = meta
1331 return json.dumps(ret)
1331 return json.dumps(ret)
1332
1332
1333 @property
1333 @property
1334 def times(self):
1334 def times(self):
1335 '''
1335 '''
1336 Return the list of times of the current data
1336 Return the list of times of the current data
1337 '''
1337 '''
1338
1338
1339 ret = numpy.array(self.__times)
1339 ret = numpy.array(self.__times)
1340 ret.sort()
1340 ret.sort()
1341 return ret
1341 return ret
1342
1342
1343 @property
1343 @property
1344 def min_time(self):
1344 def min_time(self):
1345 '''
1345 '''
1346 Return the minimun time value
1346 Return the minimun time value
1347 '''
1347 '''
1348
1348
1349 return self.times[0]
1349 return self.times[0]
1350
1350
1351 @property
1351 @property
1352 def max_time(self):
1352 def max_time(self):
1353 '''
1353 '''
1354 Return the maximun time value
1354 Return the maximun time value
1355 '''
1355 '''
1356
1356
1357 return self.times[-1]
1357 return self.times[-1]
1358
1358
1359 @property
1359 @property
1360 def heights(self):
1360 def heights(self):
1361 '''
1361 '''
1362 Return the list of heights of the current data
1362 Return the list of heights of the current data
1363 '''
1363 '''
1364
1364
1365 return numpy.array(self.__heights[-1])
1365 return numpy.array(self.__heights[-1])
1366
1366
1367 @staticmethod
1367 @staticmethod
1368 def roundFloats(obj):
1368 def roundFloats(obj):
1369 if isinstance(obj, list):
1369 if isinstance(obj, list):
1370 return list(map(PlotterData.roundFloats, obj))
1370 return list(map(PlotterData.roundFloats, obj))
1371 elif isinstance(obj, float):
1371 elif isinstance(obj, float):
1372 return round(obj, 2)
1372 return round(obj, 2)
@@ -1,1589 +1,1809
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from .figure import Figure, isRealtime, isTimeInHourRange
10 from .figure import Figure, isRealtime, isTimeInHourRange
11 from .plotting_codes import *
11 from .plotting_codes import *
12 from schainpy.model.proc.jroproc_base import MPDecorator
12 from schainpy.model.proc.jroproc_base import MPDecorator
13
13
14 from schainpy.utils import log
14 from schainpy.utils import log
15
15
16 @MPDecorator
16 @MPDecorator
17 class SpectraPlot_(Figure):
17 class SpectraPlot_(Figure):
18
18
19 isConfig = None
19 isConfig = None
20 __nsubplots = None
20 __nsubplots = None
21
21
22 WIDTHPROF = None
22 WIDTHPROF = None
23 HEIGHTPROF = None
23 HEIGHTPROF = None
24 PREFIX = 'spc'
24 PREFIX = 'spc'
25
25
26 def __init__(self):
26 def __init__(self):
27 Figure.__init__(self)
27 Figure.__init__(self)
28 self.isConfig = False
28 self.isConfig = False
29 self.__nsubplots = 1
29 self.__nsubplots = 1
30 self.WIDTH = 250
30 self.WIDTH = 250
31 self.HEIGHT = 250
31 self.HEIGHT = 250
32 self.WIDTHPROF = 120
32 self.WIDTHPROF = 120
33 self.HEIGHTPROF = 0
33 self.HEIGHTPROF = 0
34 self.counter_imagwr = 0
34 self.counter_imagwr = 0
35
35
36 self.PLOT_CODE = SPEC_CODE
36 self.PLOT_CODE = SPEC_CODE
37
37
38 self.FTP_WEI = None
38 self.FTP_WEI = None
39 self.EXP_CODE = None
39 self.EXP_CODE = None
40 self.SUB_EXP_CODE = None
40 self.SUB_EXP_CODE = None
41 self.PLOT_POS = None
41 self.PLOT_POS = None
42
42
43 self.__xfilter_ena = False
43 self.__xfilter_ena = False
44 self.__yfilter_ena = False
44 self.__yfilter_ena = False
45
45
46 self.indice=1
46 self.indice=1
47
47
48 def getSubplots(self):
48 def getSubplots(self):
49
49
50 ncol = int(numpy.sqrt(self.nplots)+0.9)
50 ncol = int(numpy.sqrt(self.nplots)+0.9)
51 nrow = int(self.nplots*1./ncol + 0.9)
51 nrow = int(self.nplots*1./ncol + 0.9)
52
52
53 return nrow, ncol
53 return nrow, ncol
54
54
55 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
55 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
56
56
57 self.__showprofile = showprofile
57 self.__showprofile = showprofile
58 self.nplots = nplots
58 self.nplots = nplots
59
59
60 ncolspan = 1
60 ncolspan = 1
61 colspan = 1
61 colspan = 1
62 if showprofile:
62 if showprofile:
63 ncolspan = 3
63 ncolspan = 3
64 colspan = 2
64 colspan = 2
65 self.__nsubplots = 2
65 self.__nsubplots = 2
66
66
67 self.createFigure(id = id,
67 self.createFigure(id = id,
68 wintitle = wintitle,
68 wintitle = wintitle,
69 widthplot = self.WIDTH + self.WIDTHPROF,
69 widthplot = self.WIDTH + self.WIDTHPROF,
70 heightplot = self.HEIGHT + self.HEIGHTPROF,
70 heightplot = self.HEIGHT + self.HEIGHTPROF,
71 show=show)
71 show=show)
72
72
73 nrow, ncol = self.getSubplots()
73 nrow, ncol = self.getSubplots()
74
74
75 counter = 0
75 counter = 0
76 for y in range(nrow):
76 for y in range(nrow):
77 for x in range(ncol):
77 for x in range(ncol):
78
78
79 if counter >= self.nplots:
79 if counter >= self.nplots:
80 break
80 break
81
81
82 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
82 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
83
83
84 if showprofile:
84 if showprofile:
85 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
85 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
86
86
87 counter += 1
87 counter += 1
88
88
89 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
89 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
90 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
90 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
91 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
91 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
92 server=None, folder=None, username=None, password=None,
92 server=None, folder=None, username=None, password=None,
93 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
93 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
94 xaxis="frequency", colormap='jet', normFactor=None):
94 xaxis="frequency", colormap='jet', normFactor=None):
95
95
96 """
96 """
97
97
98 Input:
98 Input:
99 dataOut :
99 dataOut :
100 id :
100 id :
101 wintitle :
101 wintitle :
102 channelList :
102 channelList :
103 showProfile :
103 showProfile :
104 xmin : None,
104 xmin : None,
105 xmax : None,
105 xmax : None,
106 ymin : None,
106 ymin : None,
107 ymax : None,
107 ymax : None,
108 zmin : None,
108 zmin : None,
109 zmax : None
109 zmax : None
110 """
110 """
111 if dataOut.flagNoData:
111 if dataOut.flagNoData:
112 return dataOut
112 return dataOut
113
113
114 if realtime:
114 if realtime:
115 if not(isRealtime(utcdatatime = dataOut.utctime)):
115 if not(isRealtime(utcdatatime = dataOut.utctime)):
116 print('Skipping this plot function')
116 print('Skipping this plot function')
117 return
117 return
118
118
119 if channelList == None:
119 if channelList == None:
120 channelIndexList = dataOut.channelIndexList
120 channelIndexList = dataOut.channelIndexList
121 else:
121 else:
122 channelIndexList = []
122 channelIndexList = []
123 for channel in channelList:
123 for channel in channelList:
124 if channel not in dataOut.channelList:
124 if channel not in dataOut.channelList:
125 raise ValueError("Channel %d is not in dataOut.channelList" %channel)
125 raise ValueError("Channel %d is not in dataOut.channelList" %channel)
126 channelIndexList.append(dataOut.channelList.index(channel))
126 channelIndexList.append(dataOut.channelList.index(channel))
127
127
128 if normFactor is None:
128 if normFactor is None:
129 factor = dataOut.normFactor
129 factor = dataOut.normFactor
130 else:
130 else:
131 factor = normFactor
131 factor = normFactor
132 if xaxis == "frequency":
132 if xaxis == "frequency":
133 x = dataOut.getFreqRange(1)/1000.
133 x = dataOut.getFreqRange(1)/1000.
134 xlabel = "Frequency (kHz)"
134 xlabel = "Frequency (kHz)"
135
135
136 elif xaxis == "time":
136 elif xaxis == "time":
137 x = dataOut.getAcfRange(1)
137 x = dataOut.getAcfRange(1)
138 xlabel = "Time (ms)"
138 xlabel = "Time (ms)"
139
139
140 else:
140 else:
141 x = dataOut.getVelRange(1)
141 x = dataOut.getVelRange(1)
142 xlabel = "Velocity (m/s)"
142 xlabel = "Velocity (m/s)"
143
143
144 ylabel = "Range (km)"
144 ylabel = "Range (km)"
145
145
146 y = dataOut.getHeiRange()
146 y = dataOut.getHeiRange()
147 z = dataOut.data_spc/factor
147 z = dataOut.data_spc/factor
148 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
148 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
149 zdB = 10*numpy.log10(z)
149 zdB = 10*numpy.log10(z)
150
150
151 avg = numpy.average(z, axis=1)
151 avg = numpy.average(z, axis=1)
152 avgdB = 10*numpy.log10(avg)
152 avgdB = 10*numpy.log10(avg)
153
153
154 noise = dataOut.getNoise()/factor
154 noise = dataOut.getNoise()/factor
155 noisedB = 10*numpy.log10(noise)
155 noisedB = 10*numpy.log10(noise)
156
156
157 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
157 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
158 title = wintitle + " Spectra"
158 title = wintitle + " Spectra"
159
159
160 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
160 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
161 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
161 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
162
162
163 if not self.isConfig:
163 if not self.isConfig:
164
164
165 nplots = len(channelIndexList)
165 nplots = len(channelIndexList)
166
166
167 self.setup(id=id,
167 self.setup(id=id,
168 nplots=nplots,
168 nplots=nplots,
169 wintitle=wintitle,
169 wintitle=wintitle,
170 showprofile=showprofile,
170 showprofile=showprofile,
171 show=show)
171 show=show)
172
172
173 if xmin == None: xmin = numpy.nanmin(x)
173 if xmin == None: xmin = numpy.nanmin(x)
174 if xmax == None: xmax = numpy.nanmax(x)
174 if xmax == None: xmax = numpy.nanmax(x)
175 if ymin == None: ymin = numpy.nanmin(y)
175 if ymin == None: ymin = numpy.nanmin(y)
176 if ymax == None: ymax = numpy.nanmax(y)
176 if ymax == None: ymax = numpy.nanmax(y)
177 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
177 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
178 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
178 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
179
179
180 self.FTP_WEI = ftp_wei
180 self.FTP_WEI = ftp_wei
181 self.EXP_CODE = exp_code
181 self.EXP_CODE = exp_code
182 self.SUB_EXP_CODE = sub_exp_code
182 self.SUB_EXP_CODE = sub_exp_code
183 self.PLOT_POS = plot_pos
183 self.PLOT_POS = plot_pos
184
184
185 self.isConfig = True
185 self.isConfig = True
186
186
187 self.setWinTitle(title)
187 self.setWinTitle(title)
188
188
189 for i in range(self.nplots):
189 for i in range(self.nplots):
190 index = channelIndexList[i]
190 index = channelIndexList[i]
191 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
191 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
192 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
192 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
193 if len(dataOut.beam.codeList) != 0:
193 if len(dataOut.beam.codeList) != 0:
194 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
194 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
195
195
196 axes = self.axesList[i*self.__nsubplots]
196 axes = self.axesList[i*self.__nsubplots]
197 axes.pcolor(x, y, zdB[index,:,:],
197 axes.pcolor(x, y, zdB[index,:,:],
198 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
198 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
199 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
199 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
200 ticksize=9, cblabel='')
200 ticksize=9, cblabel='')
201
201
202 if self.__showprofile:
202 if self.__showprofile:
203 axes = self.axesList[i*self.__nsubplots +1]
203 axes = self.axesList[i*self.__nsubplots +1]
204 axes.pline(avgdB[index,:], y,
204 axes.pline(avgdB[index,:], y,
205 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
205 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
206 xlabel='dB', ylabel='', title='',
206 xlabel='dB', ylabel='', title='',
207 ytick_visible=False,
207 ytick_visible=False,
208 grid='x')
208 grid='x')
209
209
210 noiseline = numpy.repeat(noisedB[index], len(y))
210 noiseline = numpy.repeat(noisedB[index], len(y))
211 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
211 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
212
212
213 self.draw()
213 self.draw()
214
214
215 if figfile == None:
215 if figfile == None:
216 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
216 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
217 name = str_datetime
217 name = str_datetime
218 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
218 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
219 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
219 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
220 figfile = self.getFilename(name)
220 figfile = self.getFilename(name)
221
221
222 self.save(figpath=figpath,
222 self.save(figpath=figpath,
223 figfile=figfile,
223 figfile=figfile,
224 save=save,
224 save=save,
225 ftp=ftp,
225 ftp=ftp,
226 wr_period=wr_period,
226 wr_period=wr_period,
227 thisDatetime=thisDatetime)
227 thisDatetime=thisDatetime)
228
228
229
229
230 return dataOut
230 return dataOut
231
231
232 @MPDecorator
232 @MPDecorator
233 class WpowerPlot_(Figure):
234
235 isConfig = None
236 __nsubplots = None
237
238 WIDTHPROF = None
239 HEIGHTPROF = None
240 PREFIX = 'wpo'
241
242 def __init__(self):
243 Figure.__init__(self)
244 self.isConfig = False
245 self.__nsubplots = 1
246 self.WIDTH = 250
247 self.HEIGHT = 250
248 self.WIDTHPROF = 120
249 self.HEIGHTPROF = 0
250 self.counter_imagwr = 0
251
252 self.PLOT_CODE = WPO_CODE
253
254 self.FTP_WEI = None
255 self.EXP_CODE = None
256 self.SUB_EXP_CODE = None
257 self.PLOT_POS = None
258
259 self.__xfilter_ena = False
260 self.__yfilter_ena = False
261
262 self.indice=1
263
264 def getSubplots(self):
265
266 ncol = int(numpy.sqrt(self.nplots)+0.9)
267 nrow = int(self.nplots*1./ncol + 0.9)
268
269 return nrow, ncol
270
271 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
272
273 self.__showprofile = showprofile
274 self.nplots = nplots
275
276 ncolspan = 1
277 colspan = 1
278 if showprofile:
279 ncolspan = 3
280 colspan = 2
281 self.__nsubplots = 2
282
283 self.createFigure(id = id,
284 wintitle = wintitle,
285 widthplot = self.WIDTH + self.WIDTHPROF,
286 heightplot = self.HEIGHT + self.HEIGHTPROF,
287 show=show)
288
289 nrow, ncol = self.getSubplots()
290
291 counter = 0
292 for y in range(nrow):
293 for x in range(ncol):
294
295 if counter >= self.nplots:
296 break
297
298 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
299
300 if showprofile:
301 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
302
303 counter += 1
304
305 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
306 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
307 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
308 server=None, folder=None, username=None, password=None,
309 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
310 xaxis="frequency", colormap='jet', normFactor=None):
311
312 """
313
314 Input:
315 dataOut :
316 id :
317 wintitle :
318 channelList :
319 showProfile :
320 xmin : None,
321 xmax : None,
322 ymin : None,
323 ymax : None,
324 zmin : None,
325 zmax : None
326 """
327 print("***************PLOTEO******************")
328 print("DATAOUT SHAPE : ",dataOut.data.shape)
329 if dataOut.flagNoData:
330 return dataOut
331
332 if realtime:
333 if not(isRealtime(utcdatatime = dataOut.utctime)):
334 print('Skipping this plot function')
335 return
336
337 if channelList == None:
338 channelIndexList = dataOut.channelIndexList
339 else:
340 channelIndexList = []
341 for channel in channelList:
342 if channel not in dataOut.channelList:
343 raise ValueError("Channel %d is not in dataOut.channelList" %channel)
344 channelIndexList.append(dataOut.channelList.index(channel))
345
346
347 print("channelIndexList",channelIndexList)
348 if normFactor is None:
349 factor = dataOut.normFactor
350 else:
351 factor = normFactor
352 if xaxis == "frequency":
353 x = dataOut.getFreqRange(1)/1000.
354 xlabel = "Frequency (kHz)"
355
356 elif xaxis == "time":
357 x = dataOut.getAcfRange(1)
358 xlabel = "Time (ms)"
359
360 else:
361 x = dataOut.getVelRange(1)
362 xlabel = "Velocity (m/s)"
363
364 ylabel = "Range (km)"
365
366 y = dataOut.getHeiRange()
367 print("factor",factor)
368
369 z = dataOut.data/factor # dividido /factor
370 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
371 zdB = 10*numpy.log10(z)
372
373 avg = numpy.average(z, axis=1)
374 avgdB = 10*numpy.log10(avg)
375
376 noise = dataOut.getNoise()/factor
377 noisedB = 10*numpy.log10(noise)
378
379 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
380 title = wintitle + "Weather Power"
381
382 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
383 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
384
385 if not self.isConfig:
386
387 nplots = len(channelIndexList)
388
389 self.setup(id=id,
390 nplots=nplots,
391 wintitle=wintitle,
392 showprofile=showprofile,
393 show=show)
394
395 if xmin == None: xmin = numpy.nanmin(x)
396 if xmax == None: xmax = numpy.nanmax(x)
397 if ymin == None: ymin = numpy.nanmin(y)
398 if ymax == None: ymax = numpy.nanmax(y)
399 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
400 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
401
402 self.FTP_WEI = ftp_wei
403 self.EXP_CODE = exp_code
404 self.SUB_EXP_CODE = sub_exp_code
405 self.PLOT_POS = plot_pos
406
407 self.isConfig = True
408
409 self.setWinTitle(title)
410
411 for i in range(self.nplots):
412 index = channelIndexList[i]
413 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
414 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
415 if len(dataOut.beam.codeList) != 0:
416 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
417
418 axes = self.axesList[i*self.__nsubplots]
419 axes.pcolor(x, y, zdB[index,:,:],
420 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
421 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
422 ticksize=9, cblabel='')
423
424 if self.__showprofile:
425 axes = self.axesList[i*self.__nsubplots +1]
426 axes.pline(avgdB[index,:], y,
427 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
428 xlabel='dB', ylabel='', title='',
429 ytick_visible=False,
430 grid='x')
431
432 noiseline = numpy.repeat(noisedB[index], len(y))
433 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
434
435 self.draw()
436
437 if figfile == None:
438 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
439 name = str_datetime
440 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
441 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
442 figfile = self.getFilename(name)
443
444 self.save(figpath=figpath,
445 figfile=figfile,
446 save=save,
447 ftp=ftp,
448 wr_period=wr_period,
449 thisDatetime=thisDatetime)
450 return dataOut
451
452 @MPDecorator
233 class CrossSpectraPlot_(Figure):
453 class CrossSpectraPlot_(Figure):
234
454
235 isConfig = None
455 isConfig = None
236 __nsubplots = None
456 __nsubplots = None
237
457
238 WIDTH = None
458 WIDTH = None
239 HEIGHT = None
459 HEIGHT = None
240 WIDTHPROF = None
460 WIDTHPROF = None
241 HEIGHTPROF = None
461 HEIGHTPROF = None
242 PREFIX = 'cspc'
462 PREFIX = 'cspc'
243
463
244 def __init__(self):
464 def __init__(self):
245 Figure.__init__(self)
465 Figure.__init__(self)
246 self.isConfig = False
466 self.isConfig = False
247 self.__nsubplots = 4
467 self.__nsubplots = 4
248 self.counter_imagwr = 0
468 self.counter_imagwr = 0
249 self.WIDTH = 250
469 self.WIDTH = 250
250 self.HEIGHT = 250
470 self.HEIGHT = 250
251 self.WIDTHPROF = 0
471 self.WIDTHPROF = 0
252 self.HEIGHTPROF = 0
472 self.HEIGHTPROF = 0
253
473
254 self.PLOT_CODE = CROSS_CODE
474 self.PLOT_CODE = CROSS_CODE
255 self.FTP_WEI = None
475 self.FTP_WEI = None
256 self.EXP_CODE = None
476 self.EXP_CODE = None
257 self.SUB_EXP_CODE = None
477 self.SUB_EXP_CODE = None
258 self.PLOT_POS = None
478 self.PLOT_POS = None
259
479
260 self.indice=0
480 self.indice=0
261
481
262 def getSubplots(self):
482 def getSubplots(self):
263
483
264 ncol = 4
484 ncol = 4
265 nrow = self.nplots
485 nrow = self.nplots
266
486
267 return nrow, ncol
487 return nrow, ncol
268
488
269 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
489 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
270
490
271 self.__showprofile = showprofile
491 self.__showprofile = showprofile
272 self.nplots = nplots
492 self.nplots = nplots
273
493
274 ncolspan = 1
494 ncolspan = 1
275 colspan = 1
495 colspan = 1
276
496
277 self.createFigure(id = id,
497 self.createFigure(id = id,
278 wintitle = wintitle,
498 wintitle = wintitle,
279 widthplot = self.WIDTH + self.WIDTHPROF,
499 widthplot = self.WIDTH + self.WIDTHPROF,
280 heightplot = self.HEIGHT + self.HEIGHTPROF,
500 heightplot = self.HEIGHT + self.HEIGHTPROF,
281 show=True)
501 show=True)
282
502
283 nrow, ncol = self.getSubplots()
503 nrow, ncol = self.getSubplots()
284
504
285 counter = 0
505 counter = 0
286 for y in range(nrow):
506 for y in range(nrow):
287 for x in range(ncol):
507 for x in range(ncol):
288 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
508 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
289
509
290 counter += 1
510 counter += 1
291
511
292 def run(self, dataOut, id, wintitle="", pairsList=None,
512 def run(self, dataOut, id, wintitle="", pairsList=None,
293 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
513 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
294 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
514 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
295 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
515 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
296 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
516 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
297 server=None, folder=None, username=None, password=None,
517 server=None, folder=None, username=None, password=None,
298 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
518 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
299 xaxis='frequency'):
519 xaxis='frequency'):
300
520
301 """
521 """
302
522
303 Input:
523 Input:
304 dataOut :
524 dataOut :
305 id :
525 id :
306 wintitle :
526 wintitle :
307 channelList :
527 channelList :
308 showProfile :
528 showProfile :
309 xmin : None,
529 xmin : None,
310 xmax : None,
530 xmax : None,
311 ymin : None,
531 ymin : None,
312 ymax : None,
532 ymax : None,
313 zmin : None,
533 zmin : None,
314 zmax : None
534 zmax : None
315 """
535 """
316
536
317 if dataOut.flagNoData:
537 if dataOut.flagNoData:
318 return dataOut
538 return dataOut
319
539
320 if pairsList == None:
540 if pairsList == None:
321 pairsIndexList = dataOut.pairsIndexList
541 pairsIndexList = dataOut.pairsIndexList
322 else:
542 else:
323 pairsIndexList = []
543 pairsIndexList = []
324 for pair in pairsList:
544 for pair in pairsList:
325 if pair not in dataOut.pairsList:
545 if pair not in dataOut.pairsList:
326 raise ValueError("Pair %s is not in dataOut.pairsList" %str(pair))
546 raise ValueError("Pair %s is not in dataOut.pairsList" %str(pair))
327 pairsIndexList.append(dataOut.pairsList.index(pair))
547 pairsIndexList.append(dataOut.pairsList.index(pair))
328
548
329 if not pairsIndexList:
549 if not pairsIndexList:
330 return
550 return
331
551
332 if len(pairsIndexList) > 4:
552 if len(pairsIndexList) > 4:
333 pairsIndexList = pairsIndexList[0:4]
553 pairsIndexList = pairsIndexList[0:4]
334
554
335 if normFactor is None:
555 if normFactor is None:
336 factor = dataOut.normFactor
556 factor = dataOut.normFactor
337 else:
557 else:
338 factor = normFactor
558 factor = normFactor
339 x = dataOut.getVelRange(1)
559 x = dataOut.getVelRange(1)
340 y = dataOut.getHeiRange()
560 y = dataOut.getHeiRange()
341 z = dataOut.data_spc[:,:,:]/factor
561 z = dataOut.data_spc[:,:,:]/factor
342 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
562 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
343
563
344 noise = dataOut.noise/factor
564 noise = dataOut.noise/factor
345
565
346 zdB = 10*numpy.log10(z)
566 zdB = 10*numpy.log10(z)
347 noisedB = 10*numpy.log10(noise)
567 noisedB = 10*numpy.log10(noise)
348
568
349 if coh_min == None:
569 if coh_min == None:
350 coh_min = 0.0
570 coh_min = 0.0
351 if coh_max == None:
571 if coh_max == None:
352 coh_max = 1.0
572 coh_max = 1.0
353
573
354 if phase_min == None:
574 if phase_min == None:
355 phase_min = -180
575 phase_min = -180
356 if phase_max == None:
576 if phase_max == None:
357 phase_max = 180
577 phase_max = 180
358
578
359 #thisDatetime = dataOut.datatime
579 #thisDatetime = dataOut.datatime
360 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
580 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
361 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
581 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
362 # xlabel = "Velocity (m/s)"
582 # xlabel = "Velocity (m/s)"
363 ylabel = "Range (Km)"
583 ylabel = "Range (Km)"
364
584
365 if xaxis == "frequency":
585 if xaxis == "frequency":
366 x = dataOut.getFreqRange(1)/1000.
586 x = dataOut.getFreqRange(1)/1000.
367 xlabel = "Frequency (kHz)"
587 xlabel = "Frequency (kHz)"
368
588
369 elif xaxis == "time":
589 elif xaxis == "time":
370 x = dataOut.getAcfRange(1)
590 x = dataOut.getAcfRange(1)
371 xlabel = "Time (ms)"
591 xlabel = "Time (ms)"
372
592
373 else:
593 else:
374 x = dataOut.getVelRange(1)
594 x = dataOut.getVelRange(1)
375 xlabel = "Velocity (m/s)"
595 xlabel = "Velocity (m/s)"
376
596
377 if not self.isConfig:
597 if not self.isConfig:
378
598
379 nplots = len(pairsIndexList)
599 nplots = len(pairsIndexList)
380
600
381 self.setup(id=id,
601 self.setup(id=id,
382 nplots=nplots,
602 nplots=nplots,
383 wintitle=wintitle,
603 wintitle=wintitle,
384 showprofile=False,
604 showprofile=False,
385 show=show)
605 show=show)
386
606
387 avg = numpy.abs(numpy.average(z, axis=1))
607 avg = numpy.abs(numpy.average(z, axis=1))
388 avgdB = 10*numpy.log10(avg)
608 avgdB = 10*numpy.log10(avg)
389
609
390 if xmin == None: xmin = numpy.nanmin(x)
610 if xmin == None: xmin = numpy.nanmin(x)
391 if xmax == None: xmax = numpy.nanmax(x)
611 if xmax == None: xmax = numpy.nanmax(x)
392 if ymin == None: ymin = numpy.nanmin(y)
612 if ymin == None: ymin = numpy.nanmin(y)
393 if ymax == None: ymax = numpy.nanmax(y)
613 if ymax == None: ymax = numpy.nanmax(y)
394 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
614 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
395 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
615 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
396
616
397 self.FTP_WEI = ftp_wei
617 self.FTP_WEI = ftp_wei
398 self.EXP_CODE = exp_code
618 self.EXP_CODE = exp_code
399 self.SUB_EXP_CODE = sub_exp_code
619 self.SUB_EXP_CODE = sub_exp_code
400 self.PLOT_POS = plot_pos
620 self.PLOT_POS = plot_pos
401
621
402 self.isConfig = True
622 self.isConfig = True
403
623
404 self.setWinTitle(title)
624 self.setWinTitle(title)
405
625
406
626
407 for i in range(self.nplots):
627 for i in range(self.nplots):
408 pair = dataOut.pairsList[pairsIndexList[i]]
628 pair = dataOut.pairsList[pairsIndexList[i]]
409
629
410 chan_index0 = dataOut.channelList.index(pair[0])
630 chan_index0 = dataOut.channelList.index(pair[0])
411 chan_index1 = dataOut.channelList.index(pair[1])
631 chan_index1 = dataOut.channelList.index(pair[1])
412
632
413 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
633 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
414 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
634 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
415 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
635 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
416 axes0 = self.axesList[i*self.__nsubplots]
636 axes0 = self.axesList[i*self.__nsubplots]
417 axes0.pcolor(x, y, zdB,
637 axes0.pcolor(x, y, zdB,
418 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
638 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
419 xlabel=xlabel, ylabel=ylabel, title=title,
639 xlabel=xlabel, ylabel=ylabel, title=title,
420 ticksize=9, colormap=power_cmap, cblabel='')
640 ticksize=9, colormap=power_cmap, cblabel='')
421
641
422 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
642 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
423 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
643 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
424 axes0 = self.axesList[i*self.__nsubplots+1]
644 axes0 = self.axesList[i*self.__nsubplots+1]
425 axes0.pcolor(x, y, zdB,
645 axes0.pcolor(x, y, zdB,
426 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
646 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
427 xlabel=xlabel, ylabel=ylabel, title=title,
647 xlabel=xlabel, ylabel=ylabel, title=title,
428 ticksize=9, colormap=power_cmap, cblabel='')
648 ticksize=9, colormap=power_cmap, cblabel='')
429
649
430 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:] / numpy.sqrt( dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:] )
650 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:] / numpy.sqrt( dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:] )
431 coherence = numpy.abs(coherenceComplex)
651 coherence = numpy.abs(coherenceComplex)
432 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
652 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
433 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
653 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
434
654
435 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
655 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
436 axes0 = self.axesList[i*self.__nsubplots+2]
656 axes0 = self.axesList[i*self.__nsubplots+2]
437 axes0.pcolor(x, y, coherence,
657 axes0.pcolor(x, y, coherence,
438 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
658 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
439 xlabel=xlabel, ylabel=ylabel, title=title,
659 xlabel=xlabel, ylabel=ylabel, title=title,
440 ticksize=9, colormap=coherence_cmap, cblabel='')
660 ticksize=9, colormap=coherence_cmap, cblabel='')
441
661
442 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
662 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
443 axes0 = self.axesList[i*self.__nsubplots+3]
663 axes0 = self.axesList[i*self.__nsubplots+3]
444 axes0.pcolor(x, y, phase,
664 axes0.pcolor(x, y, phase,
445 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
665 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
446 xlabel=xlabel, ylabel=ylabel, title=title,
666 xlabel=xlabel, ylabel=ylabel, title=title,
447 ticksize=9, colormap=phase_cmap, cblabel='')
667 ticksize=9, colormap=phase_cmap, cblabel='')
448
668
449 self.draw()
669 self.draw()
450
670
451 self.save(figpath=figpath,
671 self.save(figpath=figpath,
452 figfile=figfile,
672 figfile=figfile,
453 save=save,
673 save=save,
454 ftp=ftp,
674 ftp=ftp,
455 wr_period=wr_period,
675 wr_period=wr_period,
456 thisDatetime=thisDatetime)
676 thisDatetime=thisDatetime)
457
677
458 return dataOut
678 return dataOut
459
679
460 @MPDecorator
680 @MPDecorator
461 class RTIPlot_(Figure):
681 class RTIPlot_(Figure):
462
682
463 __isConfig = None
683 __isConfig = None
464 __nsubplots = None
684 __nsubplots = None
465
685
466 WIDTHPROF = None
686 WIDTHPROF = None
467 HEIGHTPROF = None
687 HEIGHTPROF = None
468 PREFIX = 'rti'
688 PREFIX = 'rti'
469
689
470 def __init__(self):
690 def __init__(self):
471
691
472 Figure.__init__(self)
692 Figure.__init__(self)
473 self.timerange = None
693 self.timerange = None
474 self.isConfig = False
694 self.isConfig = False
475 self.__nsubplots = 1
695 self.__nsubplots = 1
476
696
477 self.WIDTH = 800
697 self.WIDTH = 800
478 self.HEIGHT = 250
698 self.HEIGHT = 250
479 self.WIDTHPROF = 120
699 self.WIDTHPROF = 120
480 self.HEIGHTPROF = 0
700 self.HEIGHTPROF = 0
481 self.counter_imagwr = 0
701 self.counter_imagwr = 0
482
702
483 self.PLOT_CODE = RTI_CODE
703 self.PLOT_CODE = RTI_CODE
484
704
485 self.FTP_WEI = None
705 self.FTP_WEI = None
486 self.EXP_CODE = None
706 self.EXP_CODE = None
487 self.SUB_EXP_CODE = None
707 self.SUB_EXP_CODE = None
488 self.PLOT_POS = None
708 self.PLOT_POS = None
489 self.tmin = None
709 self.tmin = None
490 self.tmax = None
710 self.tmax = None
491
711
492 self.xmin = None
712 self.xmin = None
493 self.xmax = None
713 self.xmax = None
494
714
495 self.figfile = None
715 self.figfile = None
496
716
497 def getSubplots(self):
717 def getSubplots(self):
498
718
499 ncol = 1
719 ncol = 1
500 nrow = self.nplots
720 nrow = self.nplots
501
721
502 return nrow, ncol
722 return nrow, ncol
503
723
504 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
724 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
505
725
506 self.__showprofile = showprofile
726 self.__showprofile = showprofile
507 self.nplots = nplots
727 self.nplots = nplots
508
728
509 ncolspan = 1
729 ncolspan = 1
510 colspan = 1
730 colspan = 1
511 if showprofile:
731 if showprofile:
512 ncolspan = 7
732 ncolspan = 7
513 colspan = 6
733 colspan = 6
514 self.__nsubplots = 2
734 self.__nsubplots = 2
515
735
516 self.createFigure(id = id,
736 self.createFigure(id = id,
517 wintitle = wintitle,
737 wintitle = wintitle,
518 widthplot = self.WIDTH + self.WIDTHPROF,
738 widthplot = self.WIDTH + self.WIDTHPROF,
519 heightplot = self.HEIGHT + self.HEIGHTPROF,
739 heightplot = self.HEIGHT + self.HEIGHTPROF,
520 show=show)
740 show=show)
521
741
522 nrow, ncol = self.getSubplots()
742 nrow, ncol = self.getSubplots()
523
743
524 counter = 0
744 counter = 0
525 for y in range(nrow):
745 for y in range(nrow):
526 for x in range(ncol):
746 for x in range(ncol):
527
747
528 if counter >= self.nplots:
748 if counter >= self.nplots:
529 break
749 break
530
750
531 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
751 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
532
752
533 if showprofile:
753 if showprofile:
534 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
754 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
535
755
536 counter += 1
756 counter += 1
537
757
538 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
758 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
539 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
759 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
540 timerange=None, colormap='jet',
760 timerange=None, colormap='jet',
541 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
761 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
542 server=None, folder=None, username=None, password=None,
762 server=None, folder=None, username=None, password=None,
543 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
763 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
544
764
545 """
765 """
546
766
547 Input:
767 Input:
548 dataOut :
768 dataOut :
549 id :
769 id :
550 wintitle :
770 wintitle :
551 channelList :
771 channelList :
552 showProfile :
772 showProfile :
553 xmin : None,
773 xmin : None,
554 xmax : None,
774 xmax : None,
555 ymin : None,
775 ymin : None,
556 ymax : None,
776 ymax : None,
557 zmin : None,
777 zmin : None,
558 zmax : None
778 zmax : None
559 """
779 """
560 if dataOut.flagNoData:
780 if dataOut.flagNoData:
561 return dataOut
781 return dataOut
562
782
563 #colormap = kwargs.get('colormap', 'jet')
783 #colormap = kwargs.get('colormap', 'jet')
564 if HEIGHT is not None:
784 if HEIGHT is not None:
565 self.HEIGHT = HEIGHT
785 self.HEIGHT = HEIGHT
566
786
567 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
787 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
568 return
788 return
569
789
570 if channelList == None:
790 if channelList == None:
571 channelIndexList = dataOut.channelIndexList
791 channelIndexList = dataOut.channelIndexList
572 else:
792 else:
573 channelIndexList = []
793 channelIndexList = []
574 for channel in channelList:
794 for channel in channelList:
575 if channel not in dataOut.channelList:
795 if channel not in dataOut.channelList:
576 raise ValueError("Channel %d is not in dataOut.channelList")
796 raise ValueError("Channel %d is not in dataOut.channelList")
577 channelIndexList.append(dataOut.channelList.index(channel))
797 channelIndexList.append(dataOut.channelList.index(channel))
578
798
579 if normFactor is None:
799 if normFactor is None:
580 factor = dataOut.normFactor
800 factor = dataOut.normFactor
581 else:
801 else:
582 factor = normFactor
802 factor = normFactor
583
803
584 #factor = dataOut.normFactor
804 #factor = dataOut.normFactor
585 x = dataOut.getTimeRange()
805 x = dataOut.getTimeRange()
586 y = dataOut.getHeiRange()
806 y = dataOut.getHeiRange()
587
807
588 z = dataOut.data_spc/factor
808 z = dataOut.data_spc/factor
589 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
809 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
590 avg = numpy.average(z, axis=1)
810 avg = numpy.average(z, axis=1)
591 avgdB = 10.*numpy.log10(avg)
811 avgdB = 10.*numpy.log10(avg)
592 # avgdB = dataOut.getPower()
812 # avgdB = dataOut.getPower()
593
813
594
814
595 thisDatetime = dataOut.datatime
815 thisDatetime = dataOut.datatime
596 #thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
816 #thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
597 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
817 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
598 xlabel = ""
818 xlabel = ""
599 ylabel = "Range (Km)"
819 ylabel = "Range (Km)"
600
820
601 update_figfile = False
821 update_figfile = False
602
822
603 if self.xmax is not None and dataOut.ltctime >= self.xmax: #yong
823 if self.xmax is not None and dataOut.ltctime >= self.xmax: #yong
604 self.counter_imagwr = wr_period
824 self.counter_imagwr = wr_period
605 self.isConfig = False
825 self.isConfig = False
606 update_figfile = True
826 update_figfile = True
607
827
608 if not self.isConfig:
828 if not self.isConfig:
609
829
610 nplots = len(channelIndexList)
830 nplots = len(channelIndexList)
611
831
612 self.setup(id=id,
832 self.setup(id=id,
613 nplots=nplots,
833 nplots=nplots,
614 wintitle=wintitle,
834 wintitle=wintitle,
615 showprofile=showprofile,
835 showprofile=showprofile,
616 show=show)
836 show=show)
617
837
618 if timerange != None:
838 if timerange != None:
619 self.timerange = timerange
839 self.timerange = timerange
620
840
621 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
841 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
622
842
623 noise = dataOut.noise/factor
843 noise = dataOut.noise/factor
624 noisedB = 10*numpy.log10(noise)
844 noisedB = 10*numpy.log10(noise)
625
845
626 if ymin == None: ymin = numpy.nanmin(y)
846 if ymin == None: ymin = numpy.nanmin(y)
627 if ymax == None: ymax = numpy.nanmax(y)
847 if ymax == None: ymax = numpy.nanmax(y)
628 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
848 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
629 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
849 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
630
850
631 self.FTP_WEI = ftp_wei
851 self.FTP_WEI = ftp_wei
632 self.EXP_CODE = exp_code
852 self.EXP_CODE = exp_code
633 self.SUB_EXP_CODE = sub_exp_code
853 self.SUB_EXP_CODE = sub_exp_code
634 self.PLOT_POS = plot_pos
854 self.PLOT_POS = plot_pos
635
855
636 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
856 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
637 self.isConfig = True
857 self.isConfig = True
638 self.figfile = figfile
858 self.figfile = figfile
639 update_figfile = True
859 update_figfile = True
640
860
641 self.setWinTitle(title)
861 self.setWinTitle(title)
642
862
643 for i in range(self.nplots):
863 for i in range(self.nplots):
644 index = channelIndexList[i]
864 index = channelIndexList[i]
645 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
865 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
646 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
866 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
647 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
867 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
648 axes = self.axesList[i*self.__nsubplots]
868 axes = self.axesList[i*self.__nsubplots]
649 zdB = avgdB[index].reshape((1,-1))
869 zdB = avgdB[index].reshape((1,-1))
650 axes.pcolorbuffer(x, y, zdB,
870 axes.pcolorbuffer(x, y, zdB,
651 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
871 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
652 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
872 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
653 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
873 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
654
874
655 if self.__showprofile:
875 if self.__showprofile:
656 axes = self.axesList[i*self.__nsubplots +1]
876 axes = self.axesList[i*self.__nsubplots +1]
657 axes.pline(avgdB[index], y,
877 axes.pline(avgdB[index], y,
658 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
878 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
659 xlabel='dB', ylabel='', title='',
879 xlabel='dB', ylabel='', title='',
660 ytick_visible=False,
880 ytick_visible=False,
661 grid='x')
881 grid='x')
662
882
663 self.draw()
883 self.draw()
664
884
665 self.save(figpath=figpath,
885 self.save(figpath=figpath,
666 figfile=figfile,
886 figfile=figfile,
667 save=save,
887 save=save,
668 ftp=ftp,
888 ftp=ftp,
669 wr_period=wr_period,
889 wr_period=wr_period,
670 thisDatetime=thisDatetime,
890 thisDatetime=thisDatetime,
671 update_figfile=update_figfile)
891 update_figfile=update_figfile)
672 return dataOut
892 return dataOut
673
893
674 @MPDecorator
894 @MPDecorator
675 class CoherenceMap_(Figure):
895 class CoherenceMap_(Figure):
676 isConfig = None
896 isConfig = None
677 __nsubplots = None
897 __nsubplots = None
678
898
679 WIDTHPROF = None
899 WIDTHPROF = None
680 HEIGHTPROF = None
900 HEIGHTPROF = None
681 PREFIX = 'cmap'
901 PREFIX = 'cmap'
682
902
683 def __init__(self):
903 def __init__(self):
684 Figure.__init__(self)
904 Figure.__init__(self)
685 self.timerange = 2*60*60
905 self.timerange = 2*60*60
686 self.isConfig = False
906 self.isConfig = False
687 self.__nsubplots = 1
907 self.__nsubplots = 1
688
908
689 self.WIDTH = 800
909 self.WIDTH = 800
690 self.HEIGHT = 180
910 self.HEIGHT = 180
691 self.WIDTHPROF = 120
911 self.WIDTHPROF = 120
692 self.HEIGHTPROF = 0
912 self.HEIGHTPROF = 0
693 self.counter_imagwr = 0
913 self.counter_imagwr = 0
694
914
695 self.PLOT_CODE = COH_CODE
915 self.PLOT_CODE = COH_CODE
696
916
697 self.FTP_WEI = None
917 self.FTP_WEI = None
698 self.EXP_CODE = None
918 self.EXP_CODE = None
699 self.SUB_EXP_CODE = None
919 self.SUB_EXP_CODE = None
700 self.PLOT_POS = None
920 self.PLOT_POS = None
701 self.counter_imagwr = 0
921 self.counter_imagwr = 0
702
922
703 self.xmin = None
923 self.xmin = None
704 self.xmax = None
924 self.xmax = None
705
925
706 def getSubplots(self):
926 def getSubplots(self):
707 ncol = 1
927 ncol = 1
708 nrow = self.nplots*2
928 nrow = self.nplots*2
709
929
710 return nrow, ncol
930 return nrow, ncol
711
931
712 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
932 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
713 self.__showprofile = showprofile
933 self.__showprofile = showprofile
714 self.nplots = nplots
934 self.nplots = nplots
715
935
716 ncolspan = 1
936 ncolspan = 1
717 colspan = 1
937 colspan = 1
718 if showprofile:
938 if showprofile:
719 ncolspan = 7
939 ncolspan = 7
720 colspan = 6
940 colspan = 6
721 self.__nsubplots = 2
941 self.__nsubplots = 2
722
942
723 self.createFigure(id = id,
943 self.createFigure(id = id,
724 wintitle = wintitle,
944 wintitle = wintitle,
725 widthplot = self.WIDTH + self.WIDTHPROF,
945 widthplot = self.WIDTH + self.WIDTHPROF,
726 heightplot = self.HEIGHT + self.HEIGHTPROF,
946 heightplot = self.HEIGHT + self.HEIGHTPROF,
727 show=True)
947 show=True)
728
948
729 nrow, ncol = self.getSubplots()
949 nrow, ncol = self.getSubplots()
730
950
731 for y in range(nrow):
951 for y in range(nrow):
732 for x in range(ncol):
952 for x in range(ncol):
733
953
734 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
954 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
735
955
736 if showprofile:
956 if showprofile:
737 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
957 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
738
958
739 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
959 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
740 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
960 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
741 timerange=None, phase_min=None, phase_max=None,
961 timerange=None, phase_min=None, phase_max=None,
742 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
962 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
743 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
963 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
744 server=None, folder=None, username=None, password=None,
964 server=None, folder=None, username=None, password=None,
745 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
965 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
746
966
747
967
748 if dataOut.flagNoData:
968 if dataOut.flagNoData:
749 return dataOut
969 return dataOut
750
970
751 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
971 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
752 return
972 return
753
973
754 if pairsList == None:
974 if pairsList == None:
755 pairsIndexList = dataOut.pairsIndexList
975 pairsIndexList = dataOut.pairsIndexList
756 else:
976 else:
757 pairsIndexList = []
977 pairsIndexList = []
758 for pair in pairsList:
978 for pair in pairsList:
759 if pair not in dataOut.pairsList:
979 if pair not in dataOut.pairsList:
760 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
980 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
761 pairsIndexList.append(dataOut.pairsList.index(pair))
981 pairsIndexList.append(dataOut.pairsList.index(pair))
762
982
763 if pairsIndexList == []:
983 if pairsIndexList == []:
764 return
984 return
765
985
766 if len(pairsIndexList) > 4:
986 if len(pairsIndexList) > 4:
767 pairsIndexList = pairsIndexList[0:4]
987 pairsIndexList = pairsIndexList[0:4]
768
988
769 if phase_min == None:
989 if phase_min == None:
770 phase_min = -180
990 phase_min = -180
771 if phase_max == None:
991 if phase_max == None:
772 phase_max = 180
992 phase_max = 180
773
993
774 x = dataOut.getTimeRange()
994 x = dataOut.getTimeRange()
775 y = dataOut.getHeiRange()
995 y = dataOut.getHeiRange()
776
996
777 thisDatetime = dataOut.datatime
997 thisDatetime = dataOut.datatime
778
998
779 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
999 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
780 xlabel = ""
1000 xlabel = ""
781 ylabel = "Range (Km)"
1001 ylabel = "Range (Km)"
782 update_figfile = False
1002 update_figfile = False
783
1003
784 if not self.isConfig:
1004 if not self.isConfig:
785 nplots = len(pairsIndexList)
1005 nplots = len(pairsIndexList)
786 self.setup(id=id,
1006 self.setup(id=id,
787 nplots=nplots,
1007 nplots=nplots,
788 wintitle=wintitle,
1008 wintitle=wintitle,
789 showprofile=showprofile,
1009 showprofile=showprofile,
790 show=show)
1010 show=show)
791
1011
792 if timerange != None:
1012 if timerange != None:
793 self.timerange = timerange
1013 self.timerange = timerange
794
1014
795 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1015 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
796
1016
797 if ymin == None: ymin = numpy.nanmin(y)
1017 if ymin == None: ymin = numpy.nanmin(y)
798 if ymax == None: ymax = numpy.nanmax(y)
1018 if ymax == None: ymax = numpy.nanmax(y)
799 if zmin == None: zmin = 0.
1019 if zmin == None: zmin = 0.
800 if zmax == None: zmax = 1.
1020 if zmax == None: zmax = 1.
801
1021
802 self.FTP_WEI = ftp_wei
1022 self.FTP_WEI = ftp_wei
803 self.EXP_CODE = exp_code
1023 self.EXP_CODE = exp_code
804 self.SUB_EXP_CODE = sub_exp_code
1024 self.SUB_EXP_CODE = sub_exp_code
805 self.PLOT_POS = plot_pos
1025 self.PLOT_POS = plot_pos
806
1026
807 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1027 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
808
1028
809 self.isConfig = True
1029 self.isConfig = True
810 update_figfile = True
1030 update_figfile = True
811
1031
812 self.setWinTitle(title)
1032 self.setWinTitle(title)
813
1033
814 for i in range(self.nplots):
1034 for i in range(self.nplots):
815
1035
816 pair = dataOut.pairsList[pairsIndexList[i]]
1036 pair = dataOut.pairsList[pairsIndexList[i]]
817
1037
818 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
1038 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
819 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
1039 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
820 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
1040 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
821
1041
822
1042
823 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1043 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
824 coherence = numpy.abs(avgcoherenceComplex)
1044 coherence = numpy.abs(avgcoherenceComplex)
825
1045
826 z = coherence.reshape((1,-1))
1046 z = coherence.reshape((1,-1))
827
1047
828 counter = 0
1048 counter = 0
829
1049
830 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1050 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
831 axes = self.axesList[i*self.__nsubplots*2]
1051 axes = self.axesList[i*self.__nsubplots*2]
832 axes.pcolorbuffer(x, y, z,
1052 axes.pcolorbuffer(x, y, z,
833 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1053 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
834 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1054 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
835 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
1055 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
836
1056
837 if self.__showprofile:
1057 if self.__showprofile:
838 counter += 1
1058 counter += 1
839 axes = self.axesList[i*self.__nsubplots*2 + counter]
1059 axes = self.axesList[i*self.__nsubplots*2 + counter]
840 axes.pline(coherence, y,
1060 axes.pline(coherence, y,
841 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
1061 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
842 xlabel='', ylabel='', title='', ticksize=7,
1062 xlabel='', ylabel='', title='', ticksize=7,
843 ytick_visible=False, nxticks=5,
1063 ytick_visible=False, nxticks=5,
844 grid='x')
1064 grid='x')
845
1065
846 counter += 1
1066 counter += 1
847
1067
848 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1068 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
849
1069
850 z = phase.reshape((1,-1))
1070 z = phase.reshape((1,-1))
851
1071
852 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1072 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
853 axes = self.axesList[i*self.__nsubplots*2 + counter]
1073 axes = self.axesList[i*self.__nsubplots*2 + counter]
854 axes.pcolorbuffer(x, y, z,
1074 axes.pcolorbuffer(x, y, z,
855 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
1075 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
856 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1076 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
857 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
1077 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
858
1078
859 if self.__showprofile:
1079 if self.__showprofile:
860 counter += 1
1080 counter += 1
861 axes = self.axesList[i*self.__nsubplots*2 + counter]
1081 axes = self.axesList[i*self.__nsubplots*2 + counter]
862 axes.pline(phase, y,
1082 axes.pline(phase, y,
863 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
1083 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
864 xlabel='', ylabel='', title='', ticksize=7,
1084 xlabel='', ylabel='', title='', ticksize=7,
865 ytick_visible=False, nxticks=4,
1085 ytick_visible=False, nxticks=4,
866 grid='x')
1086 grid='x')
867
1087
868 self.draw()
1088 self.draw()
869
1089
870 if dataOut.ltctime >= self.xmax:
1090 if dataOut.ltctime >= self.xmax:
871 self.counter_imagwr = wr_period
1091 self.counter_imagwr = wr_period
872 self.isConfig = False
1092 self.isConfig = False
873 update_figfile = True
1093 update_figfile = True
874
1094
875 self.save(figpath=figpath,
1095 self.save(figpath=figpath,
876 figfile=figfile,
1096 figfile=figfile,
877 save=save,
1097 save=save,
878 ftp=ftp,
1098 ftp=ftp,
879 wr_period=wr_period,
1099 wr_period=wr_period,
880 thisDatetime=thisDatetime,
1100 thisDatetime=thisDatetime,
881 update_figfile=update_figfile)
1101 update_figfile=update_figfile)
882
1102
883 return dataOut
1103 return dataOut
884
1104
885 @MPDecorator
1105 @MPDecorator
886 class PowerProfilePlot_(Figure):
1106 class PowerProfilePlot_(Figure):
887
1107
888 isConfig = None
1108 isConfig = None
889 __nsubplots = None
1109 __nsubplots = None
890
1110
891 WIDTHPROF = None
1111 WIDTHPROF = None
892 HEIGHTPROF = None
1112 HEIGHTPROF = None
893 PREFIX = 'spcprofile'
1113 PREFIX = 'spcprofile'
894
1114
895 def __init__(self):
1115 def __init__(self):
896 Figure.__init__(self)
1116 Figure.__init__(self)
897 self.isConfig = False
1117 self.isConfig = False
898 self.__nsubplots = 1
1118 self.__nsubplots = 1
899
1119
900 self.PLOT_CODE = POWER_CODE
1120 self.PLOT_CODE = POWER_CODE
901
1121
902 self.WIDTH = 300
1122 self.WIDTH = 300
903 self.HEIGHT = 500
1123 self.HEIGHT = 500
904 self.counter_imagwr = 0
1124 self.counter_imagwr = 0
905
1125
906 def getSubplots(self):
1126 def getSubplots(self):
907 ncol = 1
1127 ncol = 1
908 nrow = 1
1128 nrow = 1
909
1129
910 return nrow, ncol
1130 return nrow, ncol
911
1131
912 def setup(self, id, nplots, wintitle, show):
1132 def setup(self, id, nplots, wintitle, show):
913
1133
914 self.nplots = nplots
1134 self.nplots = nplots
915
1135
916 ncolspan = 1
1136 ncolspan = 1
917 colspan = 1
1137 colspan = 1
918
1138
919 self.createFigure(id = id,
1139 self.createFigure(id = id,
920 wintitle = wintitle,
1140 wintitle = wintitle,
921 widthplot = self.WIDTH,
1141 widthplot = self.WIDTH,
922 heightplot = self.HEIGHT,
1142 heightplot = self.HEIGHT,
923 show=show)
1143 show=show)
924
1144
925 nrow, ncol = self.getSubplots()
1145 nrow, ncol = self.getSubplots()
926
1146
927 counter = 0
1147 counter = 0
928 for y in range(nrow):
1148 for y in range(nrow):
929 for x in range(ncol):
1149 for x in range(ncol):
930 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1150 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
931
1151
932 def run(self, dataOut, id, wintitle="", channelList=None,
1152 def run(self, dataOut, id, wintitle="", channelList=None,
933 xmin=None, xmax=None, ymin=None, ymax=None,
1153 xmin=None, xmax=None, ymin=None, ymax=None,
934 save=False, figpath='./', figfile=None, show=True,
1154 save=False, figpath='./', figfile=None, show=True,
935 ftp=False, wr_period=1, server=None,
1155 ftp=False, wr_period=1, server=None,
936 folder=None, username=None, password=None):
1156 folder=None, username=None, password=None):
937
1157
938 if dataOut.flagNoData:
1158 if dataOut.flagNoData:
939 return dataOut
1159 return dataOut
940
1160
941
1161
942 if channelList == None:
1162 if channelList == None:
943 channelIndexList = dataOut.channelIndexList
1163 channelIndexList = dataOut.channelIndexList
944 channelList = dataOut.channelList
1164 channelList = dataOut.channelList
945 else:
1165 else:
946 channelIndexList = []
1166 channelIndexList = []
947 for channel in channelList:
1167 for channel in channelList:
948 if channel not in dataOut.channelList:
1168 if channel not in dataOut.channelList:
949 raise ValueError("Channel %d is not in dataOut.channelList")
1169 raise ValueError("Channel %d is not in dataOut.channelList")
950 channelIndexList.append(dataOut.channelList.index(channel))
1170 channelIndexList.append(dataOut.channelList.index(channel))
951
1171
952 factor = dataOut.normFactor
1172 factor = dataOut.normFactor
953
1173
954 y = dataOut.getHeiRange()
1174 y = dataOut.getHeiRange()
955
1175
956 #for voltage
1176 #for voltage
957 if dataOut.type == 'Voltage':
1177 if dataOut.type == 'Voltage':
958 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
1178 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
959 x = x.real
1179 x = x.real
960 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
1180 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
961
1181
962 #for spectra
1182 #for spectra
963 if dataOut.type == 'Spectra':
1183 if dataOut.type == 'Spectra':
964 x = dataOut.data_spc[channelIndexList,:,:]/factor
1184 x = dataOut.data_spc[channelIndexList,:,:]/factor
965 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
1185 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
966 x = numpy.average(x, axis=1)
1186 x = numpy.average(x, axis=1)
967
1187
968
1188
969 xdB = 10*numpy.log10(x)
1189 xdB = 10*numpy.log10(x)
970
1190
971 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1191 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
972 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
1192 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
973 xlabel = "dB"
1193 xlabel = "dB"
974 ylabel = "Range (Km)"
1194 ylabel = "Range (Km)"
975
1195
976 if not self.isConfig:
1196 if not self.isConfig:
977
1197
978 nplots = 1
1198 nplots = 1
979
1199
980 self.setup(id=id,
1200 self.setup(id=id,
981 nplots=nplots,
1201 nplots=nplots,
982 wintitle=wintitle,
1202 wintitle=wintitle,
983 show=show)
1203 show=show)
984
1204
985 if ymin == None: ymin = numpy.nanmin(y)
1205 if ymin == None: ymin = numpy.nanmin(y)
986 if ymax == None: ymax = numpy.nanmax(y)
1206 if ymax == None: ymax = numpy.nanmax(y)
987 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
1207 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
988 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
1208 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
989
1209
990 self.isConfig = True
1210 self.isConfig = True
991
1211
992 self.setWinTitle(title)
1212 self.setWinTitle(title)
993
1213
994 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1214 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
995 axes = self.axesList[0]
1215 axes = self.axesList[0]
996
1216
997 legendlabels = ["channel %d"%x for x in channelList]
1217 legendlabels = ["channel %d"%x for x in channelList]
998 axes.pmultiline(xdB, y,
1218 axes.pmultiline(xdB, y,
999 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1219 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1000 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1220 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1001 ytick_visible=True, nxticks=5,
1221 ytick_visible=True, nxticks=5,
1002 grid='x')
1222 grid='x')
1003
1223
1004 self.draw()
1224 self.draw()
1005
1225
1006 self.save(figpath=figpath,
1226 self.save(figpath=figpath,
1007 figfile=figfile,
1227 figfile=figfile,
1008 save=save,
1228 save=save,
1009 ftp=ftp,
1229 ftp=ftp,
1010 wr_period=wr_period,
1230 wr_period=wr_period,
1011 thisDatetime=thisDatetime)
1231 thisDatetime=thisDatetime)
1012
1232
1013 return dataOut
1233 return dataOut
1014
1234
1015 @MPDecorator
1235 @MPDecorator
1016 class SpectraCutPlot_(Figure):
1236 class SpectraCutPlot_(Figure):
1017
1237
1018 isConfig = None
1238 isConfig = None
1019 __nsubplots = None
1239 __nsubplots = None
1020
1240
1021 WIDTHPROF = None
1241 WIDTHPROF = None
1022 HEIGHTPROF = None
1242 HEIGHTPROF = None
1023 PREFIX = 'spc_cut'
1243 PREFIX = 'spc_cut'
1024
1244
1025 def __init__(self):
1245 def __init__(self):
1026 Figure.__init__(self)
1246 Figure.__init__(self)
1027 self.isConfig = False
1247 self.isConfig = False
1028 self.__nsubplots = 1
1248 self.__nsubplots = 1
1029
1249
1030 self.PLOT_CODE = POWER_CODE
1250 self.PLOT_CODE = POWER_CODE
1031
1251
1032 self.WIDTH = 700
1252 self.WIDTH = 700
1033 self.HEIGHT = 500
1253 self.HEIGHT = 500
1034 self.counter_imagwr = 0
1254 self.counter_imagwr = 0
1035
1255
1036 def getSubplots(self):
1256 def getSubplots(self):
1037 ncol = 1
1257 ncol = 1
1038 nrow = 1
1258 nrow = 1
1039
1259
1040 return nrow, ncol
1260 return nrow, ncol
1041
1261
1042 def setup(self, id, nplots, wintitle, show):
1262 def setup(self, id, nplots, wintitle, show):
1043
1263
1044 self.nplots = nplots
1264 self.nplots = nplots
1045
1265
1046 ncolspan = 1
1266 ncolspan = 1
1047 colspan = 1
1267 colspan = 1
1048
1268
1049 self.createFigure(id = id,
1269 self.createFigure(id = id,
1050 wintitle = wintitle,
1270 wintitle = wintitle,
1051 widthplot = self.WIDTH,
1271 widthplot = self.WIDTH,
1052 heightplot = self.HEIGHT,
1272 heightplot = self.HEIGHT,
1053 show=show)
1273 show=show)
1054
1274
1055 nrow, ncol = self.getSubplots()
1275 nrow, ncol = self.getSubplots()
1056
1276
1057 counter = 0
1277 counter = 0
1058 for y in range(nrow):
1278 for y in range(nrow):
1059 for x in range(ncol):
1279 for x in range(ncol):
1060 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1280 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1061
1281
1062 def run(self, dataOut, id, wintitle="", channelList=None,
1282 def run(self, dataOut, id, wintitle="", channelList=None,
1063 xmin=None, xmax=None, ymin=None, ymax=None,
1283 xmin=None, xmax=None, ymin=None, ymax=None,
1064 save=False, figpath='./', figfile=None, show=True,
1284 save=False, figpath='./', figfile=None, show=True,
1065 ftp=False, wr_period=1, server=None,
1285 ftp=False, wr_period=1, server=None,
1066 folder=None, username=None, password=None,
1286 folder=None, username=None, password=None,
1067 xaxis="frequency"):
1287 xaxis="frequency"):
1068
1288
1069 if dataOut.flagNoData:
1289 if dataOut.flagNoData:
1070 return dataOut
1290 return dataOut
1071
1291
1072 if channelList == None:
1292 if channelList == None:
1073 channelIndexList = dataOut.channelIndexList
1293 channelIndexList = dataOut.channelIndexList
1074 channelList = dataOut.channelList
1294 channelList = dataOut.channelList
1075 else:
1295 else:
1076 channelIndexList = []
1296 channelIndexList = []
1077 for channel in channelList:
1297 for channel in channelList:
1078 if channel not in dataOut.channelList:
1298 if channel not in dataOut.channelList:
1079 raise ValueError("Channel %d is not in dataOut.channelList")
1299 raise ValueError("Channel %d is not in dataOut.channelList")
1080 channelIndexList.append(dataOut.channelList.index(channel))
1300 channelIndexList.append(dataOut.channelList.index(channel))
1081
1301
1082 factor = dataOut.normFactor
1302 factor = dataOut.normFactor
1083
1303
1084 y = dataOut.getHeiRange()
1304 y = dataOut.getHeiRange()
1085
1305
1086 z = dataOut.data_spc/factor
1306 z = dataOut.data_spc/factor
1087 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1307 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1088
1308
1089 hei_index = numpy.arange(25)*3 + 20
1309 hei_index = numpy.arange(25)*3 + 20
1090
1310
1091 if xaxis == "frequency":
1311 if xaxis == "frequency":
1092 x = dataOut.getFreqRange()/1000.
1312 x = dataOut.getFreqRange()/1000.
1093 zdB = 10*numpy.log10(z[0,:,hei_index])
1313 zdB = 10*numpy.log10(z[0,:,hei_index])
1094 xlabel = "Frequency (kHz)"
1314 xlabel = "Frequency (kHz)"
1095 ylabel = "Power (dB)"
1315 ylabel = "Power (dB)"
1096
1316
1097 elif xaxis == "time":
1317 elif xaxis == "time":
1098 x = dataOut.getAcfRange()
1318 x = dataOut.getAcfRange()
1099 zdB = z[0,:,hei_index]
1319 zdB = z[0,:,hei_index]
1100 xlabel = "Time (ms)"
1320 xlabel = "Time (ms)"
1101 ylabel = "ACF"
1321 ylabel = "ACF"
1102
1322
1103 else:
1323 else:
1104 x = dataOut.getVelRange()
1324 x = dataOut.getVelRange()
1105 zdB = 10*numpy.log10(z[0,:,hei_index])
1325 zdB = 10*numpy.log10(z[0,:,hei_index])
1106 xlabel = "Velocity (m/s)"
1326 xlabel = "Velocity (m/s)"
1107 ylabel = "Power (dB)"
1327 ylabel = "Power (dB)"
1108
1328
1109 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1329 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1110 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1330 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1111
1331
1112 if not self.isConfig:
1332 if not self.isConfig:
1113
1333
1114 nplots = 1
1334 nplots = 1
1115
1335
1116 self.setup(id=id,
1336 self.setup(id=id,
1117 nplots=nplots,
1337 nplots=nplots,
1118 wintitle=wintitle,
1338 wintitle=wintitle,
1119 show=show)
1339 show=show)
1120
1340
1121 if xmin == None: xmin = numpy.nanmin(x)*0.9
1341 if xmin == None: xmin = numpy.nanmin(x)*0.9
1122 if xmax == None: xmax = numpy.nanmax(x)*1.1
1342 if xmax == None: xmax = numpy.nanmax(x)*1.1
1123 if ymin == None: ymin = numpy.nanmin(zdB)
1343 if ymin == None: ymin = numpy.nanmin(zdB)
1124 if ymax == None: ymax = numpy.nanmax(zdB)
1344 if ymax == None: ymax = numpy.nanmax(zdB)
1125
1345
1126 self.isConfig = True
1346 self.isConfig = True
1127
1347
1128 self.setWinTitle(title)
1348 self.setWinTitle(title)
1129
1349
1130 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1350 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1131 axes = self.axesList[0]
1351 axes = self.axesList[0]
1132
1352
1133 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1353 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1134
1354
1135 axes.pmultilineyaxis( x, zdB,
1355 axes.pmultilineyaxis( x, zdB,
1136 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1356 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1137 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1357 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1138 ytick_visible=True, nxticks=5,
1358 ytick_visible=True, nxticks=5,
1139 grid='x')
1359 grid='x')
1140
1360
1141 self.draw()
1361 self.draw()
1142
1362
1143 self.save(figpath=figpath,
1363 self.save(figpath=figpath,
1144 figfile=figfile,
1364 figfile=figfile,
1145 save=save,
1365 save=save,
1146 ftp=ftp,
1366 ftp=ftp,
1147 wr_period=wr_period,
1367 wr_period=wr_period,
1148 thisDatetime=thisDatetime)
1368 thisDatetime=thisDatetime)
1149
1369
1150 return dataOut
1370 return dataOut
1151
1371
1152 @MPDecorator
1372 @MPDecorator
1153 class Noise_(Figure):
1373 class Noise_(Figure):
1154
1374
1155 isConfig = None
1375 isConfig = None
1156 __nsubplots = None
1376 __nsubplots = None
1157
1377
1158 PREFIX = 'noise'
1378 PREFIX = 'noise'
1159
1379
1160
1380
1161 def __init__(self):
1381 def __init__(self):
1162 Figure.__init__(self)
1382 Figure.__init__(self)
1163 self.timerange = 24*60*60
1383 self.timerange = 24*60*60
1164 self.isConfig = False
1384 self.isConfig = False
1165 self.__nsubplots = 1
1385 self.__nsubplots = 1
1166 self.counter_imagwr = 0
1386 self.counter_imagwr = 0
1167 self.WIDTH = 800
1387 self.WIDTH = 800
1168 self.HEIGHT = 400
1388 self.HEIGHT = 400
1169 self.WIDTHPROF = 120
1389 self.WIDTHPROF = 120
1170 self.HEIGHTPROF = 0
1390 self.HEIGHTPROF = 0
1171 self.xdata = None
1391 self.xdata = None
1172 self.ydata = None
1392 self.ydata = None
1173
1393
1174 self.PLOT_CODE = NOISE_CODE
1394 self.PLOT_CODE = NOISE_CODE
1175
1395
1176 self.FTP_WEI = None
1396 self.FTP_WEI = None
1177 self.EXP_CODE = None
1397 self.EXP_CODE = None
1178 self.SUB_EXP_CODE = None
1398 self.SUB_EXP_CODE = None
1179 self.PLOT_POS = None
1399 self.PLOT_POS = None
1180 self.figfile = None
1400 self.figfile = None
1181
1401
1182 self.xmin = None
1402 self.xmin = None
1183 self.xmax = None
1403 self.xmax = None
1184
1404
1185 def getSubplots(self):
1405 def getSubplots(self):
1186
1406
1187 ncol = 1
1407 ncol = 1
1188 nrow = 1
1408 nrow = 1
1189
1409
1190 return nrow, ncol
1410 return nrow, ncol
1191
1411
1192 def openfile(self, filename):
1412 def openfile(self, filename):
1193 dirname = os.path.dirname(filename)
1413 dirname = os.path.dirname(filename)
1194
1414
1195 if not os.path.exists(dirname):
1415 if not os.path.exists(dirname):
1196 os.mkdir(dirname)
1416 os.mkdir(dirname)
1197
1417
1198 f = open(filename,'w+')
1418 f = open(filename,'w+')
1199 f.write('\n\n')
1419 f.write('\n\n')
1200 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1420 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1201 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1421 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1202 f.close()
1422 f.close()
1203
1423
1204 def save_data(self, filename_phase, data, data_datetime):
1424 def save_data(self, filename_phase, data, data_datetime):
1205
1425
1206 f=open(filename_phase,'a')
1426 f=open(filename_phase,'a')
1207
1427
1208 timetuple_data = data_datetime.timetuple()
1428 timetuple_data = data_datetime.timetuple()
1209 day = str(timetuple_data.tm_mday)
1429 day = str(timetuple_data.tm_mday)
1210 month = str(timetuple_data.tm_mon)
1430 month = str(timetuple_data.tm_mon)
1211 year = str(timetuple_data.tm_year)
1431 year = str(timetuple_data.tm_year)
1212 hour = str(timetuple_data.tm_hour)
1432 hour = str(timetuple_data.tm_hour)
1213 minute = str(timetuple_data.tm_min)
1433 minute = str(timetuple_data.tm_min)
1214 second = str(timetuple_data.tm_sec)
1434 second = str(timetuple_data.tm_sec)
1215
1435
1216 data_msg = ''
1436 data_msg = ''
1217 for i in range(len(data)):
1437 for i in range(len(data)):
1218 data_msg += str(data[i]) + ' '
1438 data_msg += str(data[i]) + ' '
1219
1439
1220 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1440 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1221 f.close()
1441 f.close()
1222
1442
1223
1443
1224 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1444 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1225
1445
1226 self.__showprofile = showprofile
1446 self.__showprofile = showprofile
1227 self.nplots = nplots
1447 self.nplots = nplots
1228
1448
1229 ncolspan = 7
1449 ncolspan = 7
1230 colspan = 6
1450 colspan = 6
1231 self.__nsubplots = 2
1451 self.__nsubplots = 2
1232
1452
1233 self.createFigure(id = id,
1453 self.createFigure(id = id,
1234 wintitle = wintitle,
1454 wintitle = wintitle,
1235 widthplot = self.WIDTH+self.WIDTHPROF,
1455 widthplot = self.WIDTH+self.WIDTHPROF,
1236 heightplot = self.HEIGHT+self.HEIGHTPROF,
1456 heightplot = self.HEIGHT+self.HEIGHTPROF,
1237 show=show)
1457 show=show)
1238
1458
1239 nrow, ncol = self.getSubplots()
1459 nrow, ncol = self.getSubplots()
1240
1460
1241 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1461 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1242
1462
1243
1463
1244 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1464 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1245 xmin=None, xmax=None, ymin=None, ymax=None,
1465 xmin=None, xmax=None, ymin=None, ymax=None,
1246 timerange=None,
1466 timerange=None,
1247 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1467 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1248 server=None, folder=None, username=None, password=None,
1468 server=None, folder=None, username=None, password=None,
1249 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1469 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1250
1470
1251 if dataOut.flagNoData:
1471 if dataOut.flagNoData:
1252 return dataOut
1472 return dataOut
1253
1473
1254 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1474 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1255 return
1475 return
1256
1476
1257 if channelList == None:
1477 if channelList == None:
1258 channelIndexList = dataOut.channelIndexList
1478 channelIndexList = dataOut.channelIndexList
1259 channelList = dataOut.channelList
1479 channelList = dataOut.channelList
1260 else:
1480 else:
1261 channelIndexList = []
1481 channelIndexList = []
1262 for channel in channelList:
1482 for channel in channelList:
1263 if channel not in dataOut.channelList:
1483 if channel not in dataOut.channelList:
1264 raise ValueError("Channel %d is not in dataOut.channelList")
1484 raise ValueError("Channel %d is not in dataOut.channelList")
1265 channelIndexList.append(dataOut.channelList.index(channel))
1485 channelIndexList.append(dataOut.channelList.index(channel))
1266
1486
1267 x = dataOut.getTimeRange()
1487 x = dataOut.getTimeRange()
1268 #y = dataOut.getHeiRange()
1488 #y = dataOut.getHeiRange()
1269 factor = dataOut.normFactor
1489 factor = dataOut.normFactor
1270 noise = dataOut.noise[channelIndexList]/factor
1490 noise = dataOut.noise[channelIndexList]/factor
1271 noisedB = 10*numpy.log10(noise)
1491 noisedB = 10*numpy.log10(noise)
1272
1492
1273 thisDatetime = dataOut.datatime
1493 thisDatetime = dataOut.datatime
1274
1494
1275 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1495 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1276 xlabel = ""
1496 xlabel = ""
1277 ylabel = "Intensity (dB)"
1497 ylabel = "Intensity (dB)"
1278 update_figfile = False
1498 update_figfile = False
1279
1499
1280 if not self.isConfig:
1500 if not self.isConfig:
1281
1501
1282 nplots = 1
1502 nplots = 1
1283
1503
1284 self.setup(id=id,
1504 self.setup(id=id,
1285 nplots=nplots,
1505 nplots=nplots,
1286 wintitle=wintitle,
1506 wintitle=wintitle,
1287 showprofile=showprofile,
1507 showprofile=showprofile,
1288 show=show)
1508 show=show)
1289
1509
1290 if timerange != None:
1510 if timerange != None:
1291 self.timerange = timerange
1511 self.timerange = timerange
1292
1512
1293 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1513 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1294
1514
1295 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1515 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1296 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1516 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1297
1517
1298 self.FTP_WEI = ftp_wei
1518 self.FTP_WEI = ftp_wei
1299 self.EXP_CODE = exp_code
1519 self.EXP_CODE = exp_code
1300 self.SUB_EXP_CODE = sub_exp_code
1520 self.SUB_EXP_CODE = sub_exp_code
1301 self.PLOT_POS = plot_pos
1521 self.PLOT_POS = plot_pos
1302
1522
1303
1523
1304 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1524 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1305 self.isConfig = True
1525 self.isConfig = True
1306 self.figfile = figfile
1526 self.figfile = figfile
1307 self.xdata = numpy.array([])
1527 self.xdata = numpy.array([])
1308 self.ydata = numpy.array([])
1528 self.ydata = numpy.array([])
1309
1529
1310 update_figfile = True
1530 update_figfile = True
1311
1531
1312 #open file beacon phase
1532 #open file beacon phase
1313 path = '%s%03d' %(self.PREFIX, self.id)
1533 path = '%s%03d' %(self.PREFIX, self.id)
1314 noise_file = os.path.join(path,'%s.txt'%self.name)
1534 noise_file = os.path.join(path,'%s.txt'%self.name)
1315 self.filename_noise = os.path.join(figpath,noise_file)
1535 self.filename_noise = os.path.join(figpath,noise_file)
1316
1536
1317 self.setWinTitle(title)
1537 self.setWinTitle(title)
1318
1538
1319 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1539 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1320
1540
1321 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1541 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1322 axes = self.axesList[0]
1542 axes = self.axesList[0]
1323
1543
1324 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1544 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1325
1545
1326 if len(self.ydata)==0:
1546 if len(self.ydata)==0:
1327 self.ydata = noisedB.reshape(-1,1)
1547 self.ydata = noisedB.reshape(-1,1)
1328 else:
1548 else:
1329 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1549 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1330
1550
1331
1551
1332 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1552 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1333 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1553 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1334 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1554 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1335 XAxisAsTime=True, grid='both'
1555 XAxisAsTime=True, grid='both'
1336 )
1556 )
1337
1557
1338 self.draw()
1558 self.draw()
1339
1559
1340 if dataOut.ltctime >= self.xmax:
1560 if dataOut.ltctime >= self.xmax:
1341 self.counter_imagwr = wr_period
1561 self.counter_imagwr = wr_period
1342 self.isConfig = False
1562 self.isConfig = False
1343 update_figfile = True
1563 update_figfile = True
1344
1564
1345 self.save(figpath=figpath,
1565 self.save(figpath=figpath,
1346 figfile=figfile,
1566 figfile=figfile,
1347 save=save,
1567 save=save,
1348 ftp=ftp,
1568 ftp=ftp,
1349 wr_period=wr_period,
1569 wr_period=wr_period,
1350 thisDatetime=thisDatetime,
1570 thisDatetime=thisDatetime,
1351 update_figfile=update_figfile)
1571 update_figfile=update_figfile)
1352
1572
1353 #store data beacon phase
1573 #store data beacon phase
1354 if save:
1574 if save:
1355 self.save_data(self.filename_noise, noisedB, thisDatetime)
1575 self.save_data(self.filename_noise, noisedB, thisDatetime)
1356
1576
1357 return dataOut
1577 return dataOut
1358
1578
1359 @MPDecorator
1579 @MPDecorator
1360 class BeaconPhase_(Figure):
1580 class BeaconPhase_(Figure):
1361
1581
1362 __isConfig = None
1582 __isConfig = None
1363 __nsubplots = None
1583 __nsubplots = None
1364
1584
1365 PREFIX = 'beacon_phase'
1585 PREFIX = 'beacon_phase'
1366
1586
1367 def __init__(self):
1587 def __init__(self):
1368 Figure.__init__(self)
1588 Figure.__init__(self)
1369 self.timerange = 24*60*60
1589 self.timerange = 24*60*60
1370 self.isConfig = False
1590 self.isConfig = False
1371 self.__nsubplots = 1
1591 self.__nsubplots = 1
1372 self.counter_imagwr = 0
1592 self.counter_imagwr = 0
1373 self.WIDTH = 800
1593 self.WIDTH = 800
1374 self.HEIGHT = 400
1594 self.HEIGHT = 400
1375 self.WIDTHPROF = 120
1595 self.WIDTHPROF = 120
1376 self.HEIGHTPROF = 0
1596 self.HEIGHTPROF = 0
1377 self.xdata = None
1597 self.xdata = None
1378 self.ydata = None
1598 self.ydata = None
1379
1599
1380 self.PLOT_CODE = BEACON_CODE
1600 self.PLOT_CODE = BEACON_CODE
1381
1601
1382 self.FTP_WEI = None
1602 self.FTP_WEI = None
1383 self.EXP_CODE = None
1603 self.EXP_CODE = None
1384 self.SUB_EXP_CODE = None
1604 self.SUB_EXP_CODE = None
1385 self.PLOT_POS = None
1605 self.PLOT_POS = None
1386
1606
1387 self.filename_phase = None
1607 self.filename_phase = None
1388
1608
1389 self.figfile = None
1609 self.figfile = None
1390
1610
1391 self.xmin = None
1611 self.xmin = None
1392 self.xmax = None
1612 self.xmax = None
1393
1613
1394 def getSubplots(self):
1614 def getSubplots(self):
1395
1615
1396 ncol = 1
1616 ncol = 1
1397 nrow = 1
1617 nrow = 1
1398
1618
1399 return nrow, ncol
1619 return nrow, ncol
1400
1620
1401 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1621 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1402
1622
1403 self.__showprofile = showprofile
1623 self.__showprofile = showprofile
1404 self.nplots = nplots
1624 self.nplots = nplots
1405
1625
1406 ncolspan = 7
1626 ncolspan = 7
1407 colspan = 6
1627 colspan = 6
1408 self.__nsubplots = 2
1628 self.__nsubplots = 2
1409
1629
1410 self.createFigure(id = id,
1630 self.createFigure(id = id,
1411 wintitle = wintitle,
1631 wintitle = wintitle,
1412 widthplot = self.WIDTH+self.WIDTHPROF,
1632 widthplot = self.WIDTH+self.WIDTHPROF,
1413 heightplot = self.HEIGHT+self.HEIGHTPROF,
1633 heightplot = self.HEIGHT+self.HEIGHTPROF,
1414 show=show)
1634 show=show)
1415
1635
1416 nrow, ncol = self.getSubplots()
1636 nrow, ncol = self.getSubplots()
1417
1637
1418 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1638 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1419
1639
1420 def save_phase(self, filename_phase):
1640 def save_phase(self, filename_phase):
1421 f = open(filename_phase,'w+')
1641 f = open(filename_phase,'w+')
1422 f.write('\n\n')
1642 f.write('\n\n')
1423 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1643 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1424 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1644 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1425 f.close()
1645 f.close()
1426
1646
1427 def save_data(self, filename_phase, data, data_datetime):
1647 def save_data(self, filename_phase, data, data_datetime):
1428 f=open(filename_phase,'a')
1648 f=open(filename_phase,'a')
1429 timetuple_data = data_datetime.timetuple()
1649 timetuple_data = data_datetime.timetuple()
1430 day = str(timetuple_data.tm_mday)
1650 day = str(timetuple_data.tm_mday)
1431 month = str(timetuple_data.tm_mon)
1651 month = str(timetuple_data.tm_mon)
1432 year = str(timetuple_data.tm_year)
1652 year = str(timetuple_data.tm_year)
1433 hour = str(timetuple_data.tm_hour)
1653 hour = str(timetuple_data.tm_hour)
1434 minute = str(timetuple_data.tm_min)
1654 minute = str(timetuple_data.tm_min)
1435 second = str(timetuple_data.tm_sec)
1655 second = str(timetuple_data.tm_sec)
1436 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1656 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1437 f.close()
1657 f.close()
1438
1658
1439
1659
1440 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1660 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1441 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1661 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1442 timerange=None,
1662 timerange=None,
1443 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1663 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1444 server=None, folder=None, username=None, password=None,
1664 server=None, folder=None, username=None, password=None,
1445 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1665 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1446
1666
1447 if dataOut.flagNoData:
1667 if dataOut.flagNoData:
1448 return dataOut
1668 return dataOut
1449
1669
1450 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1670 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1451 return
1671 return
1452
1672
1453 if pairsList == None:
1673 if pairsList == None:
1454 pairsIndexList = dataOut.pairsIndexList[:10]
1674 pairsIndexList = dataOut.pairsIndexList[:10]
1455 else:
1675 else:
1456 pairsIndexList = []
1676 pairsIndexList = []
1457 for pair in pairsList:
1677 for pair in pairsList:
1458 if pair not in dataOut.pairsList:
1678 if pair not in dataOut.pairsList:
1459 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
1679 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
1460 pairsIndexList.append(dataOut.pairsList.index(pair))
1680 pairsIndexList.append(dataOut.pairsList.index(pair))
1461
1681
1462 if pairsIndexList == []:
1682 if pairsIndexList == []:
1463 return
1683 return
1464
1684
1465 # if len(pairsIndexList) > 4:
1685 # if len(pairsIndexList) > 4:
1466 # pairsIndexList = pairsIndexList[0:4]
1686 # pairsIndexList = pairsIndexList[0:4]
1467
1687
1468 hmin_index = None
1688 hmin_index = None
1469 hmax_index = None
1689 hmax_index = None
1470
1690
1471 if hmin != None and hmax != None:
1691 if hmin != None and hmax != None:
1472 indexes = numpy.arange(dataOut.nHeights)
1692 indexes = numpy.arange(dataOut.nHeights)
1473 hmin_list = indexes[dataOut.heightList >= hmin]
1693 hmin_list = indexes[dataOut.heightList >= hmin]
1474 hmax_list = indexes[dataOut.heightList <= hmax]
1694 hmax_list = indexes[dataOut.heightList <= hmax]
1475
1695
1476 if hmin_list.any():
1696 if hmin_list.any():
1477 hmin_index = hmin_list[0]
1697 hmin_index = hmin_list[0]
1478
1698
1479 if hmax_list.any():
1699 if hmax_list.any():
1480 hmax_index = hmax_list[-1]+1
1700 hmax_index = hmax_list[-1]+1
1481
1701
1482 x = dataOut.getTimeRange()
1702 x = dataOut.getTimeRange()
1483 #y = dataOut.getHeiRange()
1703 #y = dataOut.getHeiRange()
1484
1704
1485
1705
1486 thisDatetime = dataOut.datatime
1706 thisDatetime = dataOut.datatime
1487
1707
1488 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1708 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 xlabel = "Local Time"
1709 xlabel = "Local Time"
1490 ylabel = "Phase (degrees)"
1710 ylabel = "Phase (degrees)"
1491
1711
1492 update_figfile = False
1712 update_figfile = False
1493
1713
1494 nplots = len(pairsIndexList)
1714 nplots = len(pairsIndexList)
1495 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1715 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1496 phase_beacon = numpy.zeros(len(pairsIndexList))
1716 phase_beacon = numpy.zeros(len(pairsIndexList))
1497 for i in range(nplots):
1717 for i in range(nplots):
1498 pair = dataOut.pairsList[pairsIndexList[i]]
1718 pair = dataOut.pairsList[pairsIndexList[i]]
1499 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1719 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1500 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1720 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1501 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1721 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1502 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1722 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1503 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1723 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1504
1724
1505 if dataOut.beacon_heiIndexList:
1725 if dataOut.beacon_heiIndexList:
1506 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1726 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1507 else:
1727 else:
1508 phase_beacon[i] = numpy.average(phase)
1728 phase_beacon[i] = numpy.average(phase)
1509
1729
1510 if not self.isConfig:
1730 if not self.isConfig:
1511
1731
1512 nplots = len(pairsIndexList)
1732 nplots = len(pairsIndexList)
1513
1733
1514 self.setup(id=id,
1734 self.setup(id=id,
1515 nplots=nplots,
1735 nplots=nplots,
1516 wintitle=wintitle,
1736 wintitle=wintitle,
1517 showprofile=showprofile,
1737 showprofile=showprofile,
1518 show=show)
1738 show=show)
1519
1739
1520 if timerange != None:
1740 if timerange != None:
1521 self.timerange = timerange
1741 self.timerange = timerange
1522
1742
1523 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1743 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1524
1744
1525 if ymin == None: ymin = 0
1745 if ymin == None: ymin = 0
1526 if ymax == None: ymax = 360
1746 if ymax == None: ymax = 360
1527
1747
1528 self.FTP_WEI = ftp_wei
1748 self.FTP_WEI = ftp_wei
1529 self.EXP_CODE = exp_code
1749 self.EXP_CODE = exp_code
1530 self.SUB_EXP_CODE = sub_exp_code
1750 self.SUB_EXP_CODE = sub_exp_code
1531 self.PLOT_POS = plot_pos
1751 self.PLOT_POS = plot_pos
1532
1752
1533 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1753 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1534 self.isConfig = True
1754 self.isConfig = True
1535 self.figfile = figfile
1755 self.figfile = figfile
1536 self.xdata = numpy.array([])
1756 self.xdata = numpy.array([])
1537 self.ydata = numpy.array([])
1757 self.ydata = numpy.array([])
1538
1758
1539 update_figfile = True
1759 update_figfile = True
1540
1760
1541 #open file beacon phase
1761 #open file beacon phase
1542 path = '%s%03d' %(self.PREFIX, self.id)
1762 path = '%s%03d' %(self.PREFIX, self.id)
1543 beacon_file = os.path.join(path,'%s.txt'%self.name)
1763 beacon_file = os.path.join(path,'%s.txt'%self.name)
1544 self.filename_phase = os.path.join(figpath,beacon_file)
1764 self.filename_phase = os.path.join(figpath,beacon_file)
1545 #self.save_phase(self.filename_phase)
1765 #self.save_phase(self.filename_phase)
1546
1766
1547
1767
1548 #store data beacon phase
1768 #store data beacon phase
1549 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1769 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1550
1770
1551 self.setWinTitle(title)
1771 self.setWinTitle(title)
1552
1772
1553
1773
1554 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1774 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1555
1775
1556 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1776 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1557
1777
1558 axes = self.axesList[0]
1778 axes = self.axesList[0]
1559
1779
1560 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1780 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1561
1781
1562 if len(self.ydata)==0:
1782 if len(self.ydata)==0:
1563 self.ydata = phase_beacon.reshape(-1,1)
1783 self.ydata = phase_beacon.reshape(-1,1)
1564 else:
1784 else:
1565 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1785 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1566
1786
1567
1787
1568 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1788 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1569 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1789 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1570 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1790 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1571 XAxisAsTime=True, grid='both'
1791 XAxisAsTime=True, grid='both'
1572 )
1792 )
1573
1793
1574 self.draw()
1794 self.draw()
1575
1795
1576 if dataOut.ltctime >= self.xmax:
1796 if dataOut.ltctime >= self.xmax:
1577 self.counter_imagwr = wr_period
1797 self.counter_imagwr = wr_period
1578 self.isConfig = False
1798 self.isConfig = False
1579 update_figfile = True
1799 update_figfile = True
1580
1800
1581 self.save(figpath=figpath,
1801 self.save(figpath=figpath,
1582 figfile=figfile,
1802 figfile=figfile,
1583 save=save,
1803 save=save,
1584 ftp=ftp,
1804 ftp=ftp,
1585 wr_period=wr_period,
1805 wr_period=wr_period,
1586 thisDatetime=thisDatetime,
1806 thisDatetime=thisDatetime,
1587 update_figfile=update_figfile)
1807 update_figfile=update_figfile)
1588
1808
1589 return dataOut No newline at end of file
1809 return dataOut
@@ -1,232 +1,294
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator #YONG
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator #YONG
10 from schainpy.utils import log
10 from schainpy.utils import log
11 from .figure import Figure
11 from .figure import Figure
12
12
13
13
14 @MPDecorator
14 @MPDecorator
15 class Scope_(Figure):
15 class Scope_(Figure):
16
16
17 isConfig = None
17 isConfig = None
18
18
19 def __init__(self):#, **kwargs): #YONG
19 def __init__(self):#, **kwargs): #YONG
20 Figure.__init__(self)#, **kwargs)
20 Figure.__init__(self)#, **kwargs)
21 self.isConfig = False
21 self.isConfig = False
22 self.WIDTH = 300
22 self.WIDTH = 300
23 self.HEIGHT = 200
23 self.HEIGHT = 200
24 self.counter_imagwr = 0
24 self.counter_imagwr = 0
25
25
26 def getSubplots(self):
26 def getSubplots(self):
27
27
28 nrow = self.nplots
28 nrow = self.nplots
29 ncol = 3
29 ncol = 3
30 return nrow, ncol
30 return nrow, ncol
31
31
32 def setup(self, id, nplots, wintitle, show):
32 def setup(self, id, nplots, wintitle, show):
33
33
34 self.nplots = nplots
34 self.nplots = nplots
35
35
36 self.createFigure(id=id,
36 self.createFigure(id=id,
37 wintitle=wintitle,
37 wintitle=wintitle,
38 show=show)
38 show=show)
39
39
40 nrow,ncol = self.getSubplots()
40 nrow,ncol = self.getSubplots()
41 colspan = 3
41 colspan = 3
42 rowspan = 1
42 rowspan = 1
43
43
44 for i in range(nplots):
44 for i in range(nplots):
45 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
45 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
46
46
47 def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
47 def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
48 yreal = y[channelIndexList,:].real
48 yreal = y[channelIndexList,:].real
49 yimag = y[channelIndexList,:].imag
49 yimag = y[channelIndexList,:].imag
50
50
51 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
51 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
52 xlabel = "Range (Km)"
52 xlabel = "Range (Km)"
53 ylabel = "Intensity - IQ"
53 ylabel = "Intensity - IQ"
54
54
55 if not self.isConfig:
55 if not self.isConfig:
56 nplots = len(channelIndexList)
56 nplots = len(channelIndexList)
57
57
58 self.setup(id=id,
58 self.setup(id=id,
59 nplots=nplots,
59 nplots=nplots,
60 wintitle='',
60 wintitle='',
61 show=show)
61 show=show)
62
62
63 if xmin == None: xmin = numpy.nanmin(x)
63 if xmin == None: xmin = numpy.nanmin(x)
64 if xmax == None: xmax = numpy.nanmax(x)
64 if xmax == None: xmax = numpy.nanmax(x)
65 if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag))
65 if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag))
66 if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag))
66 if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag))
67
67
68 self.isConfig = True
68 self.isConfig = True
69
69
70 self.setWinTitle(title)
70 self.setWinTitle(title)
71
71
72 for i in range(len(self.axesList)):
72 for i in range(len(self.axesList)):
73 title = "Channel %d" %(i)
73 title = "Channel %d" %(i)
74 axes = self.axesList[i]
74 axes = self.axesList[i]
75
75
76 axes.pline(x, yreal[i,:],
76 axes.pline(x, yreal[i,:],
77 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
77 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
78 xlabel=xlabel, ylabel=ylabel, title=title)
78 xlabel=xlabel, ylabel=ylabel, title=title)
79
79
80 axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2)
80 axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2)
81
81
82 def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
82 def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
83 y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:])
83 y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:])
84 yreal = y.real
84 yreal = y.real
85
85
86 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
86 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
87 xlabel = "Range (Km)"
87 xlabel = "Range (Km)"
88 ylabel = "Intensity"
88 ylabel = "Intensity"
89
89
90 if not self.isConfig:
90 if not self.isConfig:
91 nplots = len(channelIndexList)
91 nplots = len(channelIndexList)
92
92
93 self.setup(id=id,
93 self.setup(id=id,
94 nplots=nplots,
94 nplots=nplots,
95 wintitle='',
95 wintitle='',
96 show=show)
96 show=show)
97
97
98 if xmin == None: xmin = numpy.nanmin(x)
98 if xmin == None: xmin = numpy.nanmin(x)
99 if xmax == None: xmax = numpy.nanmax(x)
99 if xmax == None: xmax = numpy.nanmax(x)
100 if ymin == None: ymin = numpy.nanmin(yreal)
100 if ymin == None: ymin = numpy.nanmin(yreal)
101 if ymax == None: ymax = numpy.nanmax(yreal)
101 if ymax == None: ymax = numpy.nanmax(yreal)
102
102
103 self.isConfig = True
103 self.isConfig = True
104
104
105 self.setWinTitle(title)
105 self.setWinTitle(title)
106
106
107 for i in range(len(self.axesList)):
107 for i in range(len(self.axesList)):
108 title = "Channel %d" %(i)
108 title = "Channel %d" %(i)
109 axes = self.axesList[i]
109 axes = self.axesList[i]
110 ychannel = yreal[i,:]
110 ychannel = yreal[i,:]
111 axes.pline(x, ychannel,
111 axes.pline(x, ychannel,
112 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
112 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
113 xlabel=xlabel, ylabel=ylabel, title=title)
113 xlabel=xlabel, ylabel=ylabel, title=title)
114
114
115
115 def plot_weatherpower(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
116 y = y[channelIndexList,:]
117 yreal = y
118
119 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
120 xlabel = "Range (Km)"
121 ylabel = "Intensity"
122
123 if not self.isConfig:
124 nplots = len(channelIndexList)
125
126 self.setup(id=id,
127 nplots=nplots,
128 wintitle='',
129 show=show)
130
131 if xmin == None: xmin = numpy.nanmin(x)
132 if xmax == None: xmax = numpy.nanmax(x)
133 if ymin == None: ymin = numpy.nanmin(yreal)
134 if ymax == None: ymax = numpy.nanmax(yreal)
135
136 self.isConfig = True
137
138 self.setWinTitle(title)
139
140 for i in range(len(self.axesList)):
141 title = "Channel %d" %(i)
142 axes = self.axesList[i]
143 ychannel = yreal[i,:]
144 axes.pline(x, ychannel,
145 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
146 xlabel=xlabel, ylabel=ylabel, title=title)
147
148
149
116 def run(self, dataOut, id, wintitle="", channelList=None,
150 def run(self, dataOut, id, wintitle="", channelList=None,
117 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
151 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
118 figpath='./', figfile=None, show=True, wr_period=1,
152 figpath='./', figfile=None, show=True, wr_period=1,
119 ftp=False, server=None, folder=None, username=None, password=None, type='power', **kwargs):
153 ftp=False, server=None, folder=None, username=None, password=None, type='power', **kwargs):
120
154
121 """
155 """
122
156
123 Input:
157 Input:
124 dataOut :
158 dataOut :
125 id :
159 id :
126 wintitle :
160 wintitle :
127 channelList :
161 channelList :
128 xmin : None,
162 xmin : None,
129 xmax : None,
163 xmax : None,
130 ymin : None,
164 ymin : None,
131 ymax : None,
165 ymax : None,
132 """
166 """
133 if dataOut.flagNoData:
167 if dataOut.flagNoData:
134 return dataOut
168 return dataOut
135
169
136 if channelList == None:
170 if channelList == None:
137 channelIndexList = dataOut.channelIndexList
171 channelIndexList = dataOut.channelIndexList
138 else:
172 else:
139 channelIndexList = []
173 channelIndexList = []
140 for channel in channelList:
174 for channel in channelList:
141 if channel not in dataOut.channelList:
175 if channel not in dataOut.channelList:
142 raise ValueError("Channel %d is not in dataOut.channelList")
176 raise ValueError("Channel %d is not in dataOut.channelList")
143 channelIndexList.append(dataOut.channelList.index(channel))
177 channelIndexList.append(dataOut.channelList.index(channel))
144
178
145 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
179 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
146
180 ### print("***************** PLOTEO **************************")
181 ### print(dataOut.nProfiles)
182 ### print(dataOut.heightList.shape)
147 if dataOut.flagDataAsBlock:
183 if dataOut.flagDataAsBlock:
148
184
149 for i in range(dataOut.nProfiles):
185 for i in range(dataOut.nProfiles):
150
186
151 wintitle1 = wintitle + " [Profile = %d] " %i
187 wintitle1 = wintitle + " [Profile = %d] " %i
152
188
153 if type == "power":
189 if type == "power":
154 self.plot_power(dataOut.heightList,
190 self.plot_power(dataOut.heightList,
155 dataOut.data[:,i,:],
191 dataOut.data[:,i,:],
156 id,
192 id,
157 channelIndexList,
193 channelIndexList,
158 thisDatetime,
194 thisDatetime,
159 wintitle1,
195 wintitle1,
160 show,
196 show,
161 xmin,
197 xmin,
162 xmax,
198 xmax,
163 ymin,
199 ymin,
164 ymax)
200 ymax)
165
201
202 if type == "weatherpower":
203 self.plot_weatherpower(dataOut.heightList,
204 dataOut.data[:,i,:],
205 id,
206 channelIndexList,
207 thisDatetime,
208 wintitle1,
209 show,
210 xmin,
211 xmax,
212 ymin,
213 ymax)
214
215 if type == "weathervelocity":
216 self.plot_weatherpower(dataOut.heightList,
217 dataOut.data_velocity[:,i,:],
218 id,
219 channelIndexList,
220 thisDatetime,
221 wintitle1,
222 show,
223 xmin,
224 xmax,
225 ymin,
226 ymax)
227
166 if type == "iq":
228 if type == "iq":
167 self.plot_iq(dataOut.heightList,
229 self.plot_iq(dataOut.heightList,
168 dataOut.data[:,i,:],
230 dataOut.data[:,i,:],
169 id,
231 id,
170 channelIndexList,
232 channelIndexList,
171 thisDatetime,
233 thisDatetime,
172 wintitle1,
234 wintitle1,
173 show,
235 show,
174 xmin,
236 xmin,
175 xmax,
237 xmax,
176 ymin,
238 ymin,
177 ymax)
239 ymax)
178
240
179 self.draw()
241 self.draw()
180
242
181 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
243 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
182 figfile = self.getFilename(name = str_datetime) + "_" + str(i)
244 figfile = self.getFilename(name = str_datetime) + "_" + str(i)
183
245
184 self.save(figpath=figpath,
246 self.save(figpath=figpath,
185 figfile=figfile,
247 figfile=figfile,
186 save=save,
248 save=save,
187 ftp=ftp,
249 ftp=ftp,
188 wr_period=wr_period,
250 wr_period=wr_period,
189 thisDatetime=thisDatetime)
251 thisDatetime=thisDatetime)
190
252
191 else:
253 else:
192 wintitle += " [Profile = %d] " %dataOut.profileIndex
254 wintitle += " [Profile = %d] " %dataOut.profileIndex
193
255
194 if type == "power":
256 if type == "power":
195 self.plot_power(dataOut.heightList,
257 self.plot_power(dataOut.heightList,
196 dataOut.data,
258 dataOut.data,
197 id,
259 id,
198 channelIndexList,
260 channelIndexList,
199 thisDatetime,
261 thisDatetime,
200 wintitle,
262 wintitle,
201 show,
263 show,
202 xmin,
264 xmin,
203 xmax,
265 xmax,
204 ymin,
266 ymin,
205 ymax)
267 ymax)
206
268
207 if type == "iq":
269 if type == "iq":
208 self.plot_iq(dataOut.heightList,
270 self.plot_iq(dataOut.heightList,
209 dataOut.data,
271 dataOut.data,
210 id,
272 id,
211 channelIndexList,
273 channelIndexList,
212 thisDatetime,
274 thisDatetime,
213 wintitle,
275 wintitle,
214 show,
276 show,
215 xmin,
277 xmin,
216 xmax,
278 xmax,
217 ymin,
279 ymin,
218 ymax)
280 ymax)
219
281
220 self.draw()
282 self.draw()
221
283
222 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") + "_" + str(dataOut.profileIndex)
284 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") + "_" + str(dataOut.profileIndex)
223 figfile = self.getFilename(name = str_datetime)
285 figfile = self.getFilename(name = str_datetime)
224
286
225 self.save(figpath=figpath,
287 self.save(figpath=figpath,
226 figfile=figfile,
288 figfile=figfile,
227 save=save,
289 save=save,
228 ftp=ftp,
290 ftp=ftp,
229 wr_period=wr_period,
291 wr_period=wr_period,
230 thisDatetime=thisDatetime)
292 thisDatetime=thisDatetime)
231
293
232 return dataOut No newline at end of file
294 return dataOut
@@ -1,28 +1,30
1 '''
1 '''
2 @author: roj-idl71
2 @author: roj-idl71
3 '''
3 '''
4 #USED IN jroplot_spectra.py
4 #USED IN jroplot_spectra.py
5 RTI_CODE = 0 #Range time intensity (RTI).
5 RTI_CODE = 0 #Range time intensity (RTI).
6 SPEC_CODE = 1 #Spectra (and Cross-spectra) information.
6 SPEC_CODE = 1 #Spectra (and Cross-spectra) information.
7 CROSS_CODE = 2 #Cross-Correlation information.
7 CROSS_CODE = 2 #Cross-Correlation information.
8 COH_CODE = 3 #Coherence map.
8 COH_CODE = 3 #Coherence map.
9 BASE_CODE = 4 #Base lines graphic.
9 BASE_CODE = 4 #Base lines graphic.
10 ROW_CODE = 5 #Row Spectra.
10 ROW_CODE = 5 #Row Spectra.
11 TOTAL_CODE = 6 #Total Power.
11 TOTAL_CODE = 6 #Total Power.
12 DRIFT_CODE = 7 #Drifts graphics.
12 DRIFT_CODE = 7 #Drifts graphics.
13 HEIGHT_CODE = 8 #Height profile.
13 HEIGHT_CODE = 8 #Height profile.
14 PHASE_CODE = 9 #Signal Phase.
14 PHASE_CODE = 9 #Signal Phase.
15
15
16 POWER_CODE = 16
16 POWER_CODE = 16
17 NOISE_CODE = 17
17 NOISE_CODE = 17
18 BEACON_CODE = 18
18 BEACON_CODE = 18
19
19
20 #USED IN jroplot_parameters.py
20 #USED IN jroplot_parameters.py
21 WIND_CODE = 22
21 WIND_CODE = 22
22 MSKYMAP_CODE = 23
22 MSKYMAP_CODE = 23
23 MPHASE_CODE = 24
23 MPHASE_CODE = 24
24
24
25 MOMENTS_CODE = 25
25 MOMENTS_CODE = 25
26 PARMS_CODE = 26
26 PARMS_CODE = 26
27 SPECFIT_CODE = 27
27 SPECFIT_CODE = 27
28 EWDRIFT_CODE = 28
28 EWDRIFT_CODE = 28
29
30 WPO_CODE = 29 #Weather Intensity - Power
@@ -1,1435 +1,1458
1 import numpy
1 import numpy
2 import time
2 import time
3 import os
3 import os
4 import h5py
4 import h5py
5 import re
5 import re
6 import datetime
6 import datetime
7
7
8 import schainpy.admin
8 import schainpy.admin
9 from schainpy.model.data.jrodata import *
9 from schainpy.model.data.jrodata import *
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
11 from schainpy.model.io.jroIO_base import *
11 from schainpy.model.io.jroIO_base import *
12 from schainpy.utils import log
12 from schainpy.utils import log
13
13
14 @MPDecorator
14 @MPDecorator
15 class ParamReader(JRODataReader,ProcessingUnit):
15 class ParamReader(JRODataReader,ProcessingUnit):
16 '''
16 '''
17 Reads HDF5 format files
17 Reads HDF5 format files
18 path
18 path
19 startDate
19 startDate
20 endDate
20 endDate
21 startTime
21 startTime
22 endTime
22 endTime
23 '''
23 '''
24
24
25 ext = ".hdf5"
25 ext = ".hdf5"
26 optchar = "D"
26 optchar = "D"
27 timezone = None
27 timezone = None
28 startTime = None
28 startTime = None
29 endTime = None
29 endTime = None
30 fileIndex = None
30 fileIndex = None
31 utcList = None #To select data in the utctime list
31 utcList = None #To select data in the utctime list
32 blockList = None #List to blocks to be read from the file
32 blockList = None #List to blocks to be read from the file
33 blocksPerFile = None #Number of blocks to be read
33 blocksPerFile = None #Number of blocks to be read
34 blockIndex = None
34 blockIndex = None
35 path = None
35 path = None
36 #List of Files
36 #List of Files
37 filenameList = None
37 filenameList = None
38 datetimeList = None
38 datetimeList = None
39 #Hdf5 File
39 #Hdf5 File
40 listMetaname = None
40 listMetaname = None
41 listMeta = None
41 listMeta = None
42 listDataname = None
42 listDataname = None
43 listData = None
43 listData = None
44 listShapes = None
44 listShapes = None
45 fp = None
45 fp = None
46 #dataOut reconstruction
46 #dataOut reconstruction
47 dataOut = None
47 dataOut = None
48
48
49 def __init__(self):#, **kwargs):
49 def __init__(self):#, **kwargs):
50 ProcessingUnit.__init__(self) #, **kwargs)
50 ProcessingUnit.__init__(self) #, **kwargs)
51 self.dataOut = Parameters()
51 self.dataOut = Parameters()
52 return
52 return
53
53
54 def setup(self, **kwargs):
54 def setup(self, **kwargs):
55
55
56 path = kwargs['path']
56 path = kwargs['path']
57 startDate = kwargs['startDate']
57 startDate = kwargs['startDate']
58 endDate = kwargs['endDate']
58 endDate = kwargs['endDate']
59 startTime = kwargs['startTime']
59 startTime = kwargs['startTime']
60 endTime = kwargs['endTime']
60 endTime = kwargs['endTime']
61 walk = kwargs['walk']
61 walk = kwargs['walk']
62 if 'ext' in kwargs:
62 if 'ext' in kwargs:
63 ext = kwargs['ext']
63 ext = kwargs['ext']
64 else:
64 else:
65 ext = '.hdf5'
65 ext = '.hdf5'
66 if 'timezone' in kwargs:
66 if 'timezone' in kwargs:
67 self.timezone = kwargs['timezone']
67 self.timezone = kwargs['timezone']
68 else:
68 else:
69 self.timezone = 'lt'
69 self.timezone = 'lt'
70
70
71 print("[Reading] Searching files in offline mode ...")
71 print("[Reading] Searching files in offline mode ...")
72 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
72 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
73 startTime=startTime, endTime=endTime,
73 startTime=startTime, endTime=endTime,
74 ext=ext, walk=walk)
74 ext=ext, walk=walk)
75
75
76 if not(filenameList):
76 if not(filenameList):
77 print("There is no files into the folder: %s"%(path))
77 print("There is no files into the folder: %s"%(path))
78 sys.exit(-1)
78 sys.exit(-1)
79
79
80 self.fileIndex = -1
80 self.fileIndex = -1
81 self.startTime = startTime
81 self.startTime = startTime
82 self.endTime = endTime
82 self.endTime = endTime
83
83
84 self.__readMetadata()
84 self.__readMetadata()
85
85
86 self.__setNextFileOffline()
86 self.__setNextFileOffline()
87
87
88 return
88 return
89
89
90 def searchFilesOffLine(self,
90 def searchFilesOffLine(self,
91 path,
91 path,
92 startDate=None,
92 startDate=None,
93 endDate=None,
93 endDate=None,
94 startTime=datetime.time(0,0,0),
94 startTime=datetime.time(0,0,0),
95 endTime=datetime.time(23,59,59),
95 endTime=datetime.time(23,59,59),
96 ext='.hdf5',
96 ext='.hdf5',
97 walk=True):
97 walk=True):
98
98
99 expLabel = ''
99 expLabel = ''
100 self.filenameList = []
100 self.filenameList = []
101 self.datetimeList = []
101 self.datetimeList = []
102
102
103 pathList = []
103 pathList = []
104
104
105 JRODataObj = JRODataReader()
105 JRODataObj = JRODataReader()
106 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
106 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
107
107
108 if dateList == []:
108 if dateList == []:
109 print("[Reading] No *%s files in %s from %s to %s)"%(ext, path,
109 print("[Reading] No *%s files in %s from %s to %s)"%(ext, path,
110 datetime.datetime.combine(startDate,startTime).ctime(),
110 datetime.datetime.combine(startDate,startTime).ctime(),
111 datetime.datetime.combine(endDate,endTime).ctime()))
111 datetime.datetime.combine(endDate,endTime).ctime()))
112
112
113 return None, None
113 return None, None
114
114
115 if len(dateList) > 1:
115 if len(dateList) > 1:
116 print("[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate))
116 print("[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate))
117 else:
117 else:
118 print("[Reading] data was found for the date %s" %(dateList[0]))
118 print("[Reading] data was found for the date %s" %(dateList[0]))
119
119
120 filenameList = []
120 filenameList = []
121 datetimeList = []
121 datetimeList = []
122
122
123 #----------------------------------------------------------------------------------
123 #----------------------------------------------------------------------------------
124
124
125 for thisPath in pathList:
125 for thisPath in pathList:
126
126
127 fileList = glob.glob1(thisPath, "*%s" %ext)
127 fileList = glob.glob1(thisPath, "*%s" %ext)
128 fileList.sort()
128 fileList.sort()
129
129
130 for file in fileList:
130 for file in fileList:
131
131
132 filename = os.path.join(thisPath,file)
132 filename = os.path.join(thisPath,file)
133
133
134 if not isFileInDateRange(filename, startDate, endDate):
134 if not isFileInDateRange(filename, startDate, endDate):
135 continue
135 continue
136
136
137 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
137 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
138
138
139 if not(thisDatetime):
139 if not(thisDatetime):
140 continue
140 continue
141
141
142 filenameList.append(filename)
142 filenameList.append(filename)
143 datetimeList.append(thisDatetime)
143 datetimeList.append(thisDatetime)
144
144
145 if not(filenameList):
145 if not(filenameList):
146 print("[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()))
146 print("[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()))
147 return None, None
147 return None, None
148
148
149 print("[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime))
149 print("[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime))
150 print()
150 print()
151
151
152 self.filenameList = filenameList
152 self.filenameList = filenameList
153 self.datetimeList = datetimeList
153 self.datetimeList = datetimeList
154
154
155 return pathList, filenameList
155 return pathList, filenameList
156
156
157 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
157 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
158
158
159 """
159 """
160 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
160 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
161
161
162 Inputs:
162 Inputs:
163 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
163 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
164 startDate : fecha inicial del rango seleccionado en formato datetime.date
164 startDate : fecha inicial del rango seleccionado en formato datetime.date
165 endDate : fecha final del rango seleccionado en formato datetime.date
165 endDate : fecha final del rango seleccionado en formato datetime.date
166 startTime : tiempo inicial del rango seleccionado en formato datetime.time
166 startTime : tiempo inicial del rango seleccionado en formato datetime.time
167 endTime : tiempo final del rango seleccionado en formato datetime.time
167 endTime : tiempo final del rango seleccionado en formato datetime.time
168
168
169 Return:
169 Return:
170 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
170 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
171 fecha especificado, de lo contrario retorna False.
171 fecha especificado, de lo contrario retorna False.
172
172
173 Excepciones:
173 Excepciones:
174 Si el archivo no existe o no puede ser abierto
174 Si el archivo no existe o no puede ser abierto
175 Si la cabecera no puede ser leida.
175 Si la cabecera no puede ser leida.
176
176
177 """
177 """
178
178
179 try:
179 try:
180 fp = h5py.File(filename,'r')
180 fp = h5py.File(filename,'r')
181 grp1 = fp['Data']
181 grp1 = fp['Data']
182
182
183 except IOError:
183 except IOError:
184 traceback.print_exc()
184 traceback.print_exc()
185 raise IOError("The file %s can't be opened" %(filename))
185 raise IOError("The file %s can't be opened" %(filename))
186
186
187 #In case has utctime attribute
187 #In case has utctime attribute
188 grp2 = grp1['utctime']
188 grp2 = grp1['utctime']
189 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
189 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
190 thisUtcTime = grp2.value[0]
190 thisUtcTime = grp2.value[0]
191
191
192 fp.close()
192 fp.close()
193
193
194 if self.timezone == 'lt':
194 if self.timezone == 'lt':
195 thisUtcTime -= 5*3600
195 thisUtcTime -= 5*3600
196
196
197 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
197 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
198 thisDate = thisDatetime.date()
198 thisDate = thisDatetime.date()
199 thisTime = thisDatetime.time()
199 thisTime = thisDatetime.time()
200
200
201 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
201 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
202 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
202 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
203
203
204 #General case
204 #General case
205 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
205 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
206 #-----------o----------------------------o-----------
206 #-----------o----------------------------o-----------
207 # startTime endTime
207 # startTime endTime
208
208
209 if endTime >= startTime:
209 if endTime >= startTime:
210 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
210 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
211 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
211 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
212 return thisDatetime
212 return thisDatetime
213 return None
213 return None
214
214
215 #If endTime < startTime then endTime belongs to the next day
215 #If endTime < startTime then endTime belongs to the next day
216 #<<<<<<<<<<<o o>>>>>>>>>>>
216 #<<<<<<<<<<<o o>>>>>>>>>>>
217 #-----------o----------------------------o-----------
217 #-----------o----------------------------o-----------
218 # endTime startTime
218 # endTime startTime
219
219
220 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
220 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
221 return None
221 return None
222
222
223 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
223 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
224 return None
224 return None
225
225
226 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
226 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
227 return None
227 return None
228
228
229 return thisDatetime
229 return thisDatetime
230
230
231 def __setNextFileOffline(self):
231 def __setNextFileOffline(self):
232
232
233 self.fileIndex += 1
233 self.fileIndex += 1
234 idFile = self.fileIndex
234 idFile = self.fileIndex
235
235
236 if not(idFile < len(self.filenameList)):
236 if not(idFile < len(self.filenameList)):
237 raise schainpy.admin.SchainError("No more Files")
237 raise schainpy.admin.SchainError("No more Files")
238 return 0
238 return 0
239
239
240 filename = self.filenameList[idFile]
240 filename = self.filenameList[idFile]
241 filePointer = h5py.File(filename,'r')
241 filePointer = h5py.File(filename,'r')
242 self.filename = filename
242 self.filename = filename
243 self.fp = filePointer
243 self.fp = filePointer
244
244
245 print("Setting the file: %s"%self.filename)
245 print("Setting the file: %s"%self.filename)
246
246
247 self.__setBlockList()
247 self.__setBlockList()
248 self.__readData()
248 self.__readData()
249 self.blockIndex = 0
249 self.blockIndex = 0
250 return 1
250 return 1
251
251
252 def __setBlockList(self):
252 def __setBlockList(self):
253 '''
253 '''
254 Selects the data within the times defined
254 Selects the data within the times defined
255
255
256 self.fp
256 self.fp
257 self.startTime
257 self.startTime
258 self.endTime
258 self.endTime
259
259
260 self.blockList
260 self.blockList
261 self.blocksPerFile
261 self.blocksPerFile
262
262
263 '''
263 '''
264 fp = self.fp
264 fp = self.fp
265 startTime = self.startTime
265 startTime = self.startTime
266 endTime = self.endTime
266 endTime = self.endTime
267
267
268 grp = fp['Data']
268 grp = fp['Data']
269 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
269 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
270
270
271 #ERROOOOR
271 #ERROOOOR
272 if self.timezone == 'lt':
272 if self.timezone == 'lt':
273 thisUtcTime -= 5*3600
273 thisUtcTime -= 5*3600
274
274
275 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
275 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
276
276
277 thisDate = thisDatetime.date()
277 thisDate = thisDatetime.date()
278 thisTime = thisDatetime.time()
278 thisTime = thisDatetime.time()
279
279
280 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
280 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
281 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
281 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
282
282
283 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
283 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
284
284
285 self.blockList = ind
285 self.blockList = ind
286 self.blocksPerFile = len(ind)
286 self.blocksPerFile = len(ind)
287
287
288 return
288 return
289
289
290 def __readMetadata(self):
290 def __readMetadata(self):
291 '''
291 '''
292 Reads Metadata
292 Reads Metadata
293
293
294 self.pathMeta
294 self.pathMeta
295 self.listShapes
295 self.listShapes
296 self.listMetaname
296 self.listMetaname
297 self.listMeta
297 self.listMeta
298
298
299 '''
299 '''
300
300
301 filename = self.filenameList[0]
301 filename = self.filenameList[0]
302 fp = h5py.File(filename,'r')
302 fp = h5py.File(filename,'r')
303 gp = fp['Metadata']
303 gp = fp['Metadata']
304
304
305 listMetaname = []
305 listMetaname = []
306 listMetadata = []
306 listMetadata = []
307 for item in list(gp.items()):
307 for item in list(gp.items()):
308 name = item[0]
308 name = item[0]
309
309
310 if name=='array dimensions':
310 if name=='array dimensions':
311 table = gp[name][:]
311 table = gp[name][:]
312 listShapes = {}
312 listShapes = {}
313 for shapes in table:
313 for shapes in table:
314 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
314 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
315 else:
315 else:
316 data = gp[name].value
316 data = gp[name].value
317 listMetaname.append(name)
317 listMetaname.append(name)
318 listMetadata.append(data)
318 listMetadata.append(data)
319
319
320 self.listShapes = listShapes
320 self.listShapes = listShapes
321 self.listMetaname = listMetaname
321 self.listMetaname = listMetaname
322 self.listMeta = listMetadata
322 self.listMeta = listMetadata
323
323
324 fp.close()
324 fp.close()
325 return
325 return
326
326
327 def __readData(self):
327 def __readData(self):
328 grp = self.fp['Data']
328 grp = self.fp['Data']
329 listdataname = []
329 listdataname = []
330 listdata = []
330 listdata = []
331
331
332 for item in list(grp.items()):
332 for item in list(grp.items()):
333 name = item[0]
333 name = item[0]
334 listdataname.append(name)
334 listdataname.append(name)
335
335
336 array = self.__setDataArray(grp[name],self.listShapes[name])
336 array = self.__setDataArray(grp[name],self.listShapes[name])
337 listdata.append(array)
337 listdata.append(array)
338
338
339 self.listDataname = listdataname
339 self.listDataname = listdataname
340 self.listData = listdata
340 self.listData = listdata
341 return
341 return
342
342
343 def __setDataArray(self, dataset, shapes):
343 def __setDataArray(self, dataset, shapes):
344
344
345 nDims = shapes[0]
345 nDims = shapes[0]
346 nDim2 = shapes[1] #Dimension 0
346 nDim2 = shapes[1] #Dimension 0
347 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
347 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
348 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
348 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
349 mode = shapes[4] #Mode of storing
349 mode = shapes[4] #Mode of storing
350 blockList = self.blockList
350 blockList = self.blockList
351 blocksPerFile = self.blocksPerFile
351 blocksPerFile = self.blocksPerFile
352
352
353 #Depending on what mode the data was stored
353 #Depending on what mode the data was stored
354 if mode == 0: #Divided in channels
354 if mode == 0: #Divided in channels
355 arrayData = dataset.value.astype(numpy.float)[0][blockList]
355 arrayData = dataset.value.astype(numpy.float)[0][blockList]
356 if mode == 1: #Divided in parameter
356 if mode == 1: #Divided in parameter
357 strds = 'table'
357 strds = 'table'
358 nDatas = nDim1
358 nDatas = nDim1
359 newShapes = (blocksPerFile,nDim2,nDim0)
359 newShapes = (blocksPerFile,nDim2,nDim0)
360 elif mode==2: #Concatenated in a table
360 elif mode==2: #Concatenated in a table
361 strds = 'table0'
361 strds = 'table0'
362 arrayData = dataset[strds].value
362 arrayData = dataset[strds].value
363 #Selecting part of the dataset
363 #Selecting part of the dataset
364 utctime = arrayData[:,0]
364 utctime = arrayData[:,0]
365 u, indices = numpy.unique(utctime, return_index=True)
365 u, indices = numpy.unique(utctime, return_index=True)
366
366
367 if blockList.size != indices.size:
367 if blockList.size != indices.size:
368 indMin = indices[blockList[0]]
368 indMin = indices[blockList[0]]
369 if blockList[1] + 1 >= indices.size:
369 if blockList[1] + 1 >= indices.size:
370 arrayData = arrayData[indMin:,:]
370 arrayData = arrayData[indMin:,:]
371 else:
371 else:
372 indMax = indices[blockList[1] + 1]
372 indMax = indices[blockList[1] + 1]
373 arrayData = arrayData[indMin:indMax,:]
373 arrayData = arrayData[indMin:indMax,:]
374 return arrayData
374 return arrayData
375
375
376 # One dimension
376 # One dimension
377 if nDims == 0:
377 if nDims == 0:
378 arrayData = dataset.value.astype(numpy.float)[0][blockList]
378 arrayData = dataset.value.astype(numpy.float)[0][blockList]
379
379
380 # Two dimensions
380 # Two dimensions
381 elif nDims == 2:
381 elif nDims == 2:
382 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
382 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
383 newShapes = (blocksPerFile,nDim0)
383 newShapes = (blocksPerFile,nDim0)
384 nDatas = nDim1
384 nDatas = nDim1
385
385
386 for i in range(nDatas):
386 for i in range(nDatas):
387 data = dataset[strds + str(i)].value
387 data = dataset[strds + str(i)].value
388 arrayData[:,i,:] = data[blockList,:]
388 arrayData[:,i,:] = data[blockList,:]
389
389
390 # Three dimensions
390 # Three dimensions
391 else:
391 else:
392 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
392 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
393 for i in range(nDatas):
393 for i in range(nDatas):
394
394
395 data = dataset[strds + str(i)].value
395 data = dataset[strds + str(i)].value
396
396
397 for b in range(blockList.size):
397 for b in range(blockList.size):
398 arrayData[b,:,i,:] = data[:,:,blockList[b]]
398 arrayData[b,:,i,:] = data[:,:,blockList[b]]
399
399
400 return arrayData
400 return arrayData
401
401
402 def __setDataOut(self):
402 def __setDataOut(self):
403 listMeta = self.listMeta
403 listMeta = self.listMeta
404 listMetaname = self.listMetaname
404 listMetaname = self.listMetaname
405 listDataname = self.listDataname
405 listDataname = self.listDataname
406 listData = self.listData
406 listData = self.listData
407 listShapes = self.listShapes
407 listShapes = self.listShapes
408
408
409 blockIndex = self.blockIndex
409 blockIndex = self.blockIndex
410 # blockList = self.blockList
410 # blockList = self.blockList
411
411
412 for i in range(len(listMeta)):
412 for i in range(len(listMeta)):
413 setattr(self.dataOut,listMetaname[i],listMeta[i])
413 setattr(self.dataOut,listMetaname[i],listMeta[i])
414
414
415 for j in range(len(listData)):
415 for j in range(len(listData)):
416 nShapes = listShapes[listDataname[j]][0]
416 nShapes = listShapes[listDataname[j]][0]
417 mode = listShapes[listDataname[j]][4]
417 mode = listShapes[listDataname[j]][4]
418 if nShapes == 1:
418 if nShapes == 1:
419 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
419 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
420 elif nShapes > 1:
420 elif nShapes > 1:
421 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
421 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
422 elif mode==0:
422 elif mode==0:
423 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
423 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
424 #Mode Meteors
424 #Mode Meteors
425 elif mode ==2:
425 elif mode ==2:
426 selectedData = self.__selectDataMode2(listData[j], blockIndex)
426 selectedData = self.__selectDataMode2(listData[j], blockIndex)
427 setattr(self.dataOut, listDataname[j], selectedData)
427 setattr(self.dataOut, listDataname[j], selectedData)
428 return
428 return
429
429
430 def __selectDataMode2(self, data, blockIndex):
430 def __selectDataMode2(self, data, blockIndex):
431 utctime = data[:,0]
431 utctime = data[:,0]
432 aux, indices = numpy.unique(utctime, return_inverse=True)
432 aux, indices = numpy.unique(utctime, return_inverse=True)
433 selInd = numpy.where(indices == blockIndex)[0]
433 selInd = numpy.where(indices == blockIndex)[0]
434 selData = data[selInd,:]
434 selData = data[selInd,:]
435
435
436 return selData
436 return selData
437
437
438 def getData(self):
438 def getData(self):
439
439
440 if self.blockIndex==self.blocksPerFile:
440 if self.blockIndex==self.blocksPerFile:
441 if not( self.__setNextFileOffline() ):
441 if not( self.__setNextFileOffline() ):
442 self.dataOut.flagNoData = True
442 self.dataOut.flagNoData = True
443 return 0
443 return 0
444
444
445 self.__setDataOut()
445 self.__setDataOut()
446 self.dataOut.flagNoData = False
446 self.dataOut.flagNoData = False
447
447
448 self.blockIndex += 1
448 self.blockIndex += 1
449
449
450 return
450 return
451
451
452 def run(self, **kwargs):
452 def run(self, **kwargs):
453
453
454 if not(self.isConfig):
454 if not(self.isConfig):
455 self.setup(**kwargs)
455 self.setup(**kwargs)
456 self.isConfig = True
456 self.isConfig = True
457
457
458 self.getData()
458 self.getData()
459
459
460 return
460 return
461
461
462 @MPDecorator
462 @MPDecorator
463 class ParamWriter(Operation):
463 class ParamWriter(Operation):
464 '''
464 '''
465 HDF5 Writer, stores parameters data in HDF5 format files
465 HDF5 Writer, stores parameters data in HDF5 format files
466
466
467 path: path where the files will be stored
467 path: path where the files will be stored
468 blocksPerFile: number of blocks that will be saved in per HDF5 format file
468 blocksPerFile: number of blocks that will be saved in per HDF5 format file
469 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
469 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
470 metadataList: list of attributes that will be stored as metadata
470 metadataList: list of attributes that will be stored as metadata
471 dataList: list of attributes that will be stores as data
471 dataList: list of attributes that will be stores as data
472 '''
472 '''
473
473
474 ext = ".hdf5"
474 ext = ".hdf5"
475 optchar = "D"
475 optchar = "D"
476 metaoptchar = "M"
476 metaoptchar = "M"
477 metaFile = None
477 metaFile = None
478 filename = None
478 filename = None
479 path = None
479 path = None
480 setFile = None
480 setFile = None
481 fp = None
481 fp = None
482 grp = None
482 grp = None
483 ds = None
483 ds = None
484 firsttime = True
484 firsttime = True
485 #Configurations
485 #Configurations
486 blocksPerFile = None
486 blocksPerFile = None
487 blockIndex = None
487 blockIndex = None
488 dataOut = None
488 dataOut = None
489 #Data Arrays
489 #Data Arrays
490 dataList = None
490 dataList = None
491 metadataList = None
491 metadataList = None
492 dsList = None #List of dictionaries with dataset properties
492 dsList = None #List of dictionaries with dataset properties
493 tableDim = None
493 tableDim = None
494 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
494 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
495 currentDay = None
495 currentDay = None
496 lastTime = None
496 lastTime = None
497 setType = None
497 setType = None
498
498
499 def __init__(self):
499 def __init__(self):
500
500
501 Operation.__init__(self)
501 Operation.__init__(self)
502 return
502 return
503
503
504 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
504 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
505 self.path = path
505 self.path = path
506 self.blocksPerFile = blocksPerFile
506 self.blocksPerFile = blocksPerFile
507 self.metadataList = metadataList
507 self.metadataList = metadataList
508 self.dataList = dataList
508 self.dataList = dataList
509 self.dataOut = dataOut
509 self.dataOut = dataOut
510 self.mode = mode
510 self.mode = mode
511 if self.mode is not None:
511 if self.mode is not None:
512 self.mode = numpy.zeros(len(self.dataList)) + mode
512 self.mode = numpy.zeros(len(self.dataList)) + mode
513 else:
513 else:
514 self.mode = numpy.ones(len(self.dataList))
514 self.mode = numpy.ones(len(self.dataList))
515
515
516 self.setType = setType
516 self.setType = setType
517
517
518 arrayDim = numpy.zeros((len(self.dataList),5))
518 arrayDim = numpy.zeros((len(self.dataList),5))
519
519
520 #Table dimensions
520 #Table dimensions
521 dtype0 = self.dtype
521 dtype0 = self.dtype
522 tableList = []
522 tableList = []
523
523
524 #Dictionary and list of tables
524 #Dictionary and list of tables
525 dsList = []
525 dsList = []
526
526
527 for i in range(len(self.dataList)):
527 for i in range(len(self.dataList)):
528 dsDict = {}
528 dsDict = {}
529 dataAux = getattr(self.dataOut, self.dataList[i])
529 dataAux = getattr(self.dataOut, self.dataList[i])
530 dsDict['variable'] = self.dataList[i]
530 dsDict['variable'] = self.dataList[i]
531 #--------------------- Conditionals ------------------------
531 #--------------------- Conditionals ------------------------
532 #There is no data
532 #There is no data
533
533
534 if dataAux is None:
534 if dataAux is None:
535
535
536 return 0
536 return 0
537
537
538 if isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
538 if isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
539 dsDict['mode'] = 0
539 dsDict['mode'] = 0
540 dsDict['nDim'] = 0
540 dsDict['nDim'] = 0
541 arrayDim[i,0] = 0
541 arrayDim[i,0] = 0
542 dsList.append(dsDict)
542 dsList.append(dsDict)
543
543
544 #Mode 2: meteors
544 #Mode 2: meteors
545 elif self.mode[i] == 2:
545 elif self.mode[i] == 2:
546 dsDict['dsName'] = 'table0'
546 dsDict['dsName'] = 'table0'
547 dsDict['mode'] = 2 # Mode meteors
547 dsDict['mode'] = 2 # Mode meteors
548 dsDict['shape'] = dataAux.shape[-1]
548 dsDict['shape'] = dataAux.shape[-1]
549 dsDict['nDim'] = 0
549 dsDict['nDim'] = 0
550 dsDict['dsNumber'] = 1
550 dsDict['dsNumber'] = 1
551 arrayDim[i,3] = dataAux.shape[-1]
551 arrayDim[i,3] = dataAux.shape[-1]
552 arrayDim[i,4] = self.mode[i] #Mode the data was stored
552 arrayDim[i,4] = self.mode[i] #Mode the data was stored
553 dsList.append(dsDict)
553 dsList.append(dsDict)
554
554
555 #Mode 1
555 #Mode 1
556 else:
556 else:
557 arrayDim0 = dataAux.shape #Data dimensions
557 arrayDim0 = dataAux.shape #Data dimensions
558 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
558 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
559 arrayDim[i,4] = self.mode[i] #Mode the data was stored
559 arrayDim[i,4] = self.mode[i] #Mode the data was stored
560 strtable = 'table'
560 strtable = 'table'
561 dsDict['mode'] = 1 # Mode parameters
561 dsDict['mode'] = 1 # Mode parameters
562
562
563 # Three-dimension arrays
563 # Three-dimension arrays
564 if len(arrayDim0) == 3:
564 if len(arrayDim0) == 3:
565 arrayDim[i,1:-1] = numpy.array(arrayDim0)
565 arrayDim[i,1:-1] = numpy.array(arrayDim0)
566 nTables = int(arrayDim[i,2])
566 nTables = int(arrayDim[i,2])
567 dsDict['dsNumber'] = nTables
567 dsDict['dsNumber'] = nTables
568 dsDict['shape'] = arrayDim[i,2:4]
568 dsDict['shape'] = arrayDim[i,2:4]
569 dsDict['nDim'] = 3
569 dsDict['nDim'] = 3
570
570
571 for j in range(nTables):
571 for j in range(nTables):
572 dsDict = dsDict.copy()
572 dsDict = dsDict.copy()
573 dsDict['dsName'] = strtable + str(j)
573 dsDict['dsName'] = strtable + str(j)
574 dsList.append(dsDict)
574 dsList.append(dsDict)
575
575
576 # Two-dimension arrays
576 # Two-dimension arrays
577 elif len(arrayDim0) == 2:
577 elif len(arrayDim0) == 2:
578 arrayDim[i,2:-1] = numpy.array(arrayDim0)
578 arrayDim[i,2:-1] = numpy.array(arrayDim0)
579 nTables = int(arrayDim[i,2])
579 nTables = int(arrayDim[i,2])
580 dsDict['dsNumber'] = nTables
580 dsDict['dsNumber'] = nTables
581 dsDict['shape'] = arrayDim[i,3]
581 dsDict['shape'] = arrayDim[i,3]
582 dsDict['nDim'] = 2
582 dsDict['nDim'] = 2
583
583
584 for j in range(nTables):
584 for j in range(nTables):
585 dsDict = dsDict.copy()
585 dsDict = dsDict.copy()
586 dsDict['dsName'] = strtable + str(j)
586 dsDict['dsName'] = strtable + str(j)
587 dsList.append(dsDict)
587 dsList.append(dsDict)
588
588
589 # One-dimension arrays
589 # One-dimension arrays
590 elif len(arrayDim0) == 1:
590 elif len(arrayDim0) == 1:
591 arrayDim[i,3] = arrayDim0[0]
591 arrayDim[i,3] = arrayDim0[0]
592 dsDict['shape'] = arrayDim0[0]
592 dsDict['shape'] = arrayDim0[0]
593 dsDict['dsNumber'] = 1
593 dsDict['dsNumber'] = 1
594 dsDict['dsName'] = strtable + str(0)
594 dsDict['dsName'] = strtable + str(0)
595 dsDict['nDim'] = 1
595 dsDict['nDim'] = 1
596 dsList.append(dsDict)
596 dsList.append(dsDict)
597
597
598 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
598 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
599 tableList.append(table)
599 tableList.append(table)
600
600
601 self.dsList = dsList
601 self.dsList = dsList
602 self.tableDim = numpy.array(tableList, dtype = dtype0)
602 self.tableDim = numpy.array(tableList, dtype = dtype0)
603 self.blockIndex = 0
603 self.blockIndex = 0
604 timeTuple = time.localtime(dataOut.utctime)
604 timeTuple = time.localtime(dataOut.utctime)
605 self.currentDay = timeTuple.tm_yday
605 self.currentDay = timeTuple.tm_yday
606
606
607 def putMetadata(self):
607 def putMetadata(self):
608
608
609 fp = self.createMetadataFile()
609 fp = self.createMetadataFile()
610 self.writeMetadata(fp)
610 self.writeMetadata(fp)
611 fp.close()
611 fp.close()
612 return
612 return
613
613
614 def createMetadataFile(self):
614 def createMetadataFile(self):
615 ext = self.ext
615 ext = self.ext
616 path = self.path
616 path = self.path
617 setFile = self.setFile
617 setFile = self.setFile
618
618
619 timeTuple = time.localtime(self.dataOut.utctime)
619 timeTuple = time.localtime(self.dataOut.utctime)
620
620
621 subfolder = ''
621 subfolder = ''
622 fullpath = os.path.join( path, subfolder )
622 fullpath = os.path.join( path, subfolder )
623
623
624 if not( os.path.exists(fullpath) ):
624 if not( os.path.exists(fullpath) ):
625 os.mkdir(fullpath)
625 os.mkdir(fullpath)
626 setFile = -1 #inicializo mi contador de seteo
626 setFile = -1 #inicializo mi contador de seteo
627
627
628 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
628 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
629 fullpath = os.path.join( path, subfolder )
629 fullpath = os.path.join( path, subfolder )
630
630
631 if not( os.path.exists(fullpath) ):
631 if not( os.path.exists(fullpath) ):
632 os.mkdir(fullpath)
632 os.mkdir(fullpath)
633 setFile = -1 #inicializo mi contador de seteo
633 setFile = -1 #inicializo mi contador de seteo
634
634
635 else:
635 else:
636 filesList = os.listdir( fullpath )
636 filesList = os.listdir( fullpath )
637 filesList = sorted( filesList, key=str.lower )
637 filesList = sorted( filesList, key=str.lower )
638 if len( filesList ) > 0:
638 if len( filesList ) > 0:
639 filesList = [k for k in filesList if k.startswith(self.metaoptchar)]
639 filesList = [k for k in filesList if k.startswith(self.metaoptchar)]
640 filen = filesList[-1]
640 filen = filesList[-1]
641 # el filename debera tener el siguiente formato
641 # el filename debera tener el siguiente formato
642 # 0 1234 567 89A BCDE (hex)
642 # 0 1234 567 89A BCDE (hex)
643 # x YYYY DDD SSS .ext
643 # x YYYY DDD SSS .ext
644 if isNumber( filen[8:11] ):
644 if isNumber( filen[8:11] ):
645 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
645 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
646 else:
646 else:
647 setFile = -1
647 setFile = -1
648 else:
648 else:
649 setFile = -1 #inicializo mi contador de seteo
649 setFile = -1 #inicializo mi contador de seteo
650
650
651 if self.setType is None:
651 if self.setType is None:
652 setFile += 1
652 setFile += 1
653 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
653 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
654 timeTuple.tm_year,
654 timeTuple.tm_year,
655 timeTuple.tm_yday,
655 timeTuple.tm_yday,
656 setFile,
656 setFile,
657 ext )
657 ext )
658 else:
658 else:
659 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
659 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
660 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
660 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
661 timeTuple.tm_year,
661 timeTuple.tm_year,
662 timeTuple.tm_yday,
662 timeTuple.tm_yday,
663 setFile,
663 setFile,
664 ext )
664 ext )
665
665
666 filename = os.path.join( path, subfolder, file )
666 filename = os.path.join( path, subfolder, file )
667 self.metaFile = file
667 self.metaFile = file
668 #Setting HDF5 File
668 #Setting HDF5 File
669 fp = h5py.File(filename,'w')
669 fp = h5py.File(filename,'w')
670
670
671 return fp
671 return fp
672
672
673 def writeMetadata(self, fp):
673 def writeMetadata(self, fp):
674
674
675 grp = fp.create_group("Metadata")
675 grp = fp.create_group("Metadata")
676 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
676 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
677
677
678 for i in range(len(self.metadataList)):
678 for i in range(len(self.metadataList)):
679 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
679 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
680 return
680 return
681
681
682 def timeFlag(self):
682 def timeFlag(self):
683 currentTime = self.dataOut.utctime
683 currentTime = self.dataOut.utctime
684
684
685 if self.lastTime is None:
685 if self.lastTime is None:
686 self.lastTime = currentTime
686 self.lastTime = currentTime
687
687
688 #Day
688 #Day
689 timeTuple = time.localtime(currentTime)
689 timeTuple = time.localtime(currentTime)
690 dataDay = timeTuple.tm_yday
690 dataDay = timeTuple.tm_yday
691
691
692 #Time
692 #Time
693 timeDiff = currentTime - self.lastTime
693 timeDiff = currentTime - self.lastTime
694
694
695 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
695 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
696 if dataDay != self.currentDay:
696 if dataDay != self.currentDay:
697 self.currentDay = dataDay
697 self.currentDay = dataDay
698 return True
698 return True
699 elif timeDiff > 3*60*60:
699 elif timeDiff > 3*60*60:
700 self.lastTime = currentTime
700 self.lastTime = currentTime
701 return True
701 return True
702 else:
702 else:
703 self.lastTime = currentTime
703 self.lastTime = currentTime
704 return False
704 return False
705
705
706 def setNextFile(self):
706 def setNextFile(self):
707
707
708 ext = self.ext
708 ext = self.ext
709 path = self.path
709 path = self.path
710 setFile = self.setFile
710 setFile = self.setFile
711 mode = self.mode
711 mode = self.mode
712
712
713 timeTuple = time.localtime(self.dataOut.utctime)
713 timeTuple = time.localtime(self.dataOut.utctime)
714 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
714 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
715
715
716 fullpath = os.path.join( path, subfolder )
716 fullpath = os.path.join( path, subfolder )
717
717
718 if os.path.exists(fullpath):
718 if os.path.exists(fullpath):
719 filesList = os.listdir( fullpath )
719 filesList = os.listdir( fullpath )
720 filesList = [k for k in filesList if 'M' in k]
720 filesList = [k for k in filesList if 'M' in k]
721 if len( filesList ) > 0:
721 if len( filesList ) > 0:
722 filesList = sorted( filesList, key=str.lower )
722 filesList = sorted( filesList, key=str.lower )
723 filen = filesList[-1]
723 filen = filesList[-1]
724 # el filename debera tener el siguiente formato
724 # el filename debera tener el siguiente formato
725 # 0 1234 567 89A BCDE (hex)
725 # 0 1234 567 89A BCDE (hex)
726 # x YYYY DDD SSS .ext
726 # x YYYY DDD SSS .ext
727 if isNumber( filen[8:11] ):
727 if isNumber( filen[8:11] ):
728 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
728 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
729 else:
729 else:
730 setFile = -1
730 setFile = -1
731 else:
731 else:
732 setFile = -1 #inicializo mi contador de seteo
732 setFile = -1 #inicializo mi contador de seteo
733 else:
733 else:
734 os.makedirs(fullpath)
734 os.makedirs(fullpath)
735 setFile = -1 #inicializo mi contador de seteo
735 setFile = -1 #inicializo mi contador de seteo
736
736
737 if self.setType is None:
737 if self.setType is None:
738 setFile += 1
738 setFile += 1
739 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
739 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
740 timeTuple.tm_year,
740 timeTuple.tm_year,
741 timeTuple.tm_yday,
741 timeTuple.tm_yday,
742 setFile,
742 setFile,
743 ext )
743 ext )
744 else:
744 else:
745 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
745 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
746 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
746 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
747 timeTuple.tm_year,
747 timeTuple.tm_year,
748 timeTuple.tm_yday,
748 timeTuple.tm_yday,
749 setFile,
749 setFile,
750 ext )
750 ext )
751
751
752 filename = os.path.join( path, subfolder, file )
752 filename = os.path.join( path, subfolder, file )
753
753
754 #Setting HDF5 File
754 #Setting HDF5 File
755 fp = h5py.File(filename,'w')
755 fp = h5py.File(filename,'w')
756 #write metadata
756 #write metadata
757 self.writeMetadata(fp)
757 self.writeMetadata(fp)
758 #Write data
758 #Write data
759 grp = fp.create_group("Data")
759 grp = fp.create_group("Data")
760 ds = []
760 ds = []
761 data = []
761 data = []
762 dsList = self.dsList
762 dsList = self.dsList
763 i = 0
763 i = 0
764 while i < len(dsList):
764 while i < len(dsList):
765 dsInfo = dsList[i]
765 dsInfo = dsList[i]
766 #One-dimension data
766 #One-dimension data
767 if dsInfo['mode'] == 0:
767 if dsInfo['mode'] == 0:
768 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
768 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
769 ds.append(ds0)
769 ds.append(ds0)
770 data.append([])
770 data.append([])
771 i += 1
771 i += 1
772 continue
772 continue
773
773
774 elif dsInfo['mode'] == 2:
774 elif dsInfo['mode'] == 2:
775 grp0 = grp.create_group(dsInfo['variable'])
775 grp0 = grp.create_group(dsInfo['variable'])
776 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
776 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
777 ds.append(ds0)
777 ds.append(ds0)
778 data.append([])
778 data.append([])
779 i += 1
779 i += 1
780 continue
780 continue
781
781
782 elif dsInfo['mode'] == 1:
782 elif dsInfo['mode'] == 1:
783 grp0 = grp.create_group(dsInfo['variable'])
783 grp0 = grp.create_group(dsInfo['variable'])
784
784
785 for j in range(dsInfo['dsNumber']):
785 for j in range(dsInfo['dsNumber']):
786 dsInfo = dsList[i]
786 dsInfo = dsList[i]
787 tableName = dsInfo['dsName']
787 tableName = dsInfo['dsName']
788
788
789
789
790 if dsInfo['nDim'] == 3:
790 if dsInfo['nDim'] == 3:
791 shape = dsInfo['shape'].astype(int)
791 shape = dsInfo['shape'].astype(int)
792 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
792 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
793 else:
793 else:
794 shape = int(dsInfo['shape'])
794 shape = int(dsInfo['shape'])
795 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
795 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
796
796
797 ds.append(ds0)
797 ds.append(ds0)
798 data.append([])
798 data.append([])
799 i += 1
799 i += 1
800
800
801 fp.flush()
801 fp.flush()
802 fp.close()
802 fp.close()
803
803
804 log.log('creating file: {}'.format(filename), 'Writing')
804 log.log('creating file: {}'.format(filename), 'Writing')
805 self.filename = filename
805 self.filename = filename
806 self.ds = ds
806 self.ds = ds
807 self.data = data
807 self.data = data
808 self.firsttime = True
808 self.firsttime = True
809 self.blockIndex = 0
809 self.blockIndex = 0
810 return
810 return
811
811
812 def putData(self):
812 def putData(self):
813
813
814 if self.blockIndex == self.blocksPerFile or self.timeFlag():
814 if self.blockIndex == self.blocksPerFile or self.timeFlag():
815 self.setNextFile()
815 self.setNextFile()
816
816
817 self.readBlock()
817 self.readBlock()
818 self.setBlock() #Prepare data to be written
818 self.setBlock() #Prepare data to be written
819 self.writeBlock() #Write data
819 self.writeBlock() #Write data
820
820
821 return
821 return
822
822
823 def readBlock(self):
823 def readBlock(self):
824
824
825 '''
825 '''
826 data Array configured
826 data Array configured
827
827
828
828
829 self.data
829 self.data
830 '''
830 '''
831 dsList = self.dsList
831 dsList = self.dsList
832 ds = self.ds
832 ds = self.ds
833 #Setting HDF5 File
833 #Setting HDF5 File
834 fp = h5py.File(self.filename,'r+')
834 fp = h5py.File(self.filename,'r+')
835 grp = fp["Data"]
835 grp = fp["Data"]
836 ind = 0
836 ind = 0
837
837
838 while ind < len(dsList):
838 while ind < len(dsList):
839 dsInfo = dsList[ind]
839 dsInfo = dsList[ind]
840
840
841 if dsInfo['mode'] == 0:
841 if dsInfo['mode'] == 0:
842 ds0 = grp[dsInfo['variable']]
842 ds0 = grp[dsInfo['variable']]
843 ds[ind] = ds0
843 ds[ind] = ds0
844 ind += 1
844 ind += 1
845 else:
845 else:
846
846
847 grp0 = grp[dsInfo['variable']]
847 grp0 = grp[dsInfo['variable']]
848
848
849 for j in range(dsInfo['dsNumber']):
849 for j in range(dsInfo['dsNumber']):
850 dsInfo = dsList[ind]
850 dsInfo = dsList[ind]
851 ds0 = grp0[dsInfo['dsName']]
851 ds0 = grp0[dsInfo['dsName']]
852 ds[ind] = ds0
852 ds[ind] = ds0
853 ind += 1
853 ind += 1
854
854
855 self.fp = fp
855 self.fp = fp
856 self.grp = grp
856 self.grp = grp
857 self.ds = ds
857 self.ds = ds
858
858
859 return
859 return
860
860
861 def setBlock(self):
861 def setBlock(self):
862 '''
862 '''
863 data Array configured
863 data Array configured
864
864
865
865
866 self.data
866 self.data
867 '''
867 '''
868 #Creating Arrays
868 #Creating Arrays
869 dsList = self.dsList
869 dsList = self.dsList
870 data = self.data
870 data = self.data
871 ind = 0
871 ind = 0
872
872 #print("dsList ",dsList)
873 #print("len ",len(dsList))
873 while ind < len(dsList):
874 while ind < len(dsList):
874 dsInfo = dsList[ind]
875 dsInfo = dsList[ind]
875 dataAux = getattr(self.dataOut, dsInfo['variable'])
876 dataAux = getattr(self.dataOut, dsInfo['variable'])
876
877
877 mode = dsInfo['mode']
878 mode = dsInfo['mode']
878 nDim = dsInfo['nDim']
879 nDim = dsInfo['nDim']
879
880
880 if mode == 0 or mode == 2 or nDim == 1:
881 if mode == 0 or mode == 2 or nDim == 1:
881 data[ind] = dataAux
882 data[ind] = dataAux
882 ind += 1
883 ind += 1
883 # elif nDim == 1:
884 # elif nDim == 1:
884 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
885 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
885 # ind += 1
886 # ind += 1
886 elif nDim == 2:
887 elif nDim == 2:
887 for j in range(dsInfo['dsNumber']):
888 for j in range(dsInfo['dsNumber']):
888 data[ind] = dataAux[j,:]
889 data[ind] = dataAux[j,:]
889 ind += 1
890 ind += 1
890 elif nDim == 3:
891 elif nDim == 3:
891 for j in range(dsInfo['dsNumber']):
892 for j in range(dsInfo['dsNumber']):
892 data[ind] = dataAux[:,j,:]
893 data[ind] = dataAux[:,j,:]
893 ind += 1
894 ind += 1
894
895
895 self.data = data
896 self.data = data
896 return
897 return
897
898
898 def writeBlock(self):
899 def writeBlock(self):
899 '''
900 '''
900 Saves the block in the HDF5 file
901 Saves the block in the HDF5 file
901 '''
902 '''
902 dsList = self.dsList
903 dsList = self.dsList
903
904
904 for i in range(len(self.ds)):
905 for i in range(len(self.ds)):
906 print("#############", i , "#######################")
905 dsInfo = dsList[i]
907 dsInfo = dsList[i]
906 nDim = dsInfo['nDim']
908 nDim = dsInfo['nDim']
907 mode = dsInfo['mode']
909 mode = dsInfo['mode']
908
910 print("dsInfo",dsInfo)
911 print("nDim",nDim)
912 print("mode",mode)
909 # First time
913 # First time
910 if self.firsttime:
914 if self.firsttime:
915 print("ENTRE FIRSTIME")
911 if type(self.data[i]) == numpy.ndarray:
916 if type(self.data[i]) == numpy.ndarray:
912
917
913 if nDim == 3:
918 if nDim == 3:
919 print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
920 print("ndim","dentro del primer if 3")
914 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
921 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
922 print(self.data[i].shape)
923 print(type(self.data[i]))
915 self.ds[i].resize(self.data[i].shape)
924 self.ds[i].resize(self.data[i].shape)
925 print(self.ds[i].shape)
926 print(type(self.ds[i]))
916 if mode == 2:
927 if mode == 2:
917 self.ds[i].resize(self.data[i].shape)
928 self.ds[i].resize(self.data[i].shape)
918 self.ds[i][:] = self.data[i]
929 try:
919 else:
930 print("PTM ODIO ESTO")
931 print(self.ds[i][:].shape)
932 self.ds[i][:] = self.data[i]
933 print("*****___________********______******")
920
934
935 except:
936 print("q habra pasaado")
937 return
938 print("LLEGUE Y CUMPLI EL IF")
939 else:
940 print("ELSE -----------------------")
921 # From second time
941 # From second time
922 # Meteors!
942 # Meteors!
923 if mode == 2:
943 if mode == 2:
924 dataShape = self.data[i].shape
944 dataShape = self.data[i].shape
925 dsShape = self.ds[i].shape
945 dsShape = self.ds[i].shape
926 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
946 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
927 self.ds[i][dsShape[0]:,:] = self.data[i]
947 self.ds[i][dsShape[0]:,:] = self.data[i]
928 # No dimension
948 # No dimension
929 elif mode == 0:
949 elif mode == 0:
930 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
950 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
931 self.ds[i][0,-1] = self.data[i]
951 self.ds[i][0,-1] = self.data[i]
932 # One dimension
952 # One dimension
933 elif nDim == 1:
953 elif nDim == 1:
934 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
954 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
935 self.ds[i][-1,:] = self.data[i]
955 self.ds[i][-1,:] = self.data[i]
936 # Two dimension
956 # Two dimension
937 elif nDim == 2:
957 elif nDim == 2:
938 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
958 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
939 self.ds[i][self.blockIndex,:] = self.data[i]
959 self.ds[i][self.blockIndex,:] = self.data[i]
940 # Three dimensions
960 # Three dimensions
941 elif nDim == 3:
961 elif nDim == 3:
942 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
962 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
943 self.ds[i][:,:,-1] = self.data[i]
963 self.ds[i][:,:,-1] = self.data[i]
944
964
945 self.firsttime = False
965 self.firsttime = False
946 self.blockIndex += 1
966 self.blockIndex += 1
947
967 print("HOLA AMIGOS COMO ESTAN LLEGUE")
968 print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
948 #Close to save changes
969 #Close to save changes
949 self.fp.flush()
970 self.fp.flush()
950 self.fp.close()
971 self.fp.close()
951 return
972 return
952
973
953 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
974 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
954
975
955 self.dataOut = dataOut
976 self.dataOut = dataOut
956 if not(self.isConfig):
977 if not(self.isConfig):
957 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
978 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
958 metadataList=metadataList, dataList=dataList, mode=mode,
979 metadataList=metadataList, dataList=dataList, mode=mode,
959 setType=setType)
980 setType=setType)
960
981
961 self.isConfig = True
982 self.isConfig = True
962 self.setNextFile()
983 self.setNextFile()
963
984
964 self.putData()
985 self.putData()
965 return
986 return
966
987
967
988
968 @MPDecorator
989 @MPDecorator
969 class ParameterReader(Reader, ProcessingUnit):
990 class ParameterReader(Reader, ProcessingUnit):
970 '''
991 '''
971 Reads HDF5 format files
992 Reads HDF5 format files
972 '''
993 '''
973
994
974 def __init__(self):
995 def __init__(self):
975 ProcessingUnit.__init__(self)
996 ProcessingUnit.__init__(self)
976 self.dataOut = Parameters()
997 self.dataOut = Parameters()
977 self.ext = ".hdf5"
998 self.ext = ".hdf5"
978 self.optchar = "D"
999 self.optchar = "D"
979 self.timezone = "lt"
1000 self.timezone = "lt"
980 self.listMetaname = []
1001 self.listMetaname = []
981 self.listMeta = []
1002 self.listMeta = []
982 self.listDataname = []
1003 self.listDataname = []
983 self.listData = []
1004 self.listData = []
984 self.listShapes = []
1005 self.listShapes = []
985 self.open_file = h5py.File
1006 self.open_file = h5py.File
986 self.open_mode = 'r'
1007 self.open_mode = 'r'
987 self.metadata = False
1008 self.metadata = False
988 self.filefmt = "*%Y%j***"
1009 self.filefmt = "*%Y%j***"
989 self.folderfmt = "*%Y%j"
1010 self.folderfmt = "*%Y%j"
990
1011
991 def setup(self, **kwargs):
1012 def setup(self, **kwargs):
992
1013
993 self.set_kwargs(**kwargs)
1014 self.set_kwargs(**kwargs)
994 if not self.ext.startswith('.'):
1015 if not self.ext.startswith('.'):
995 self.ext = '.{}'.format(self.ext)
1016 self.ext = '.{}'.format(self.ext)
996
1017
997 if self.online:
1018 if self.online:
998 log.log("Searching files in online mode...", self.name)
1019 log.log("Searching files in online mode...", self.name)
999
1020
1000 for nTries in range(self.nTries):
1021 for nTries in range(self.nTries):
1001 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1022 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1002 self.endDate, self.expLabel, self.ext, self.walk,
1023 self.endDate, self.expLabel, self.ext, self.walk,
1003 self.filefmt, self.folderfmt)
1024 self.filefmt, self.folderfmt)
1004
1025
1005 try:
1026 try:
1006 fullpath = next(fullpath)
1027 fullpath = next(fullpath)
1007 except:
1028 except:
1008 fullpath = None
1029 fullpath = None
1009
1030
1010 if fullpath:
1031 if fullpath:
1011 break
1032 break
1012
1033
1013 log.warning(
1034 log.warning(
1014 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1035 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1015 self.delay, self.path, nTries + 1),
1036 self.delay, self.path, nTries + 1),
1016 self.name)
1037 self.name)
1017 time.sleep(self.delay)
1038 time.sleep(self.delay)
1018
1039
1019 if not(fullpath):
1040 if not(fullpath):
1020 raise schainpy.admin.SchainError(
1041 raise schainpy.admin.SchainError(
1021 'There isn\'t any valid file in {}'.format(self.path))
1042 'There isn\'t any valid file in {}'.format(self.path))
1022
1043
1023 pathname, filename = os.path.split(fullpath)
1044 pathname, filename = os.path.split(fullpath)
1024 self.year = int(filename[1:5])
1045 self.year = int(filename[1:5])
1025 self.doy = int(filename[5:8])
1046 self.doy = int(filename[5:8])
1026 self.set = int(filename[8:11]) - 1
1047 self.set = int(filename[8:11]) - 1
1027 else:
1048 else:
1028 log.log("Searching files in {}".format(self.path), self.name)
1049 log.log("Searching files in {}".format(self.path), self.name)
1029 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1050 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1030 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1051 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1031
1052
1032 self.setNextFile()
1053 self.setNextFile()
1033
1054
1034 return
1055 return
1035
1056
1036 def readFirstHeader(self):
1057 def readFirstHeader(self):
1037 '''Read metadata and data'''
1058 '''Read metadata and data'''
1038
1059
1039 self.__readMetadata()
1060 self.__readMetadata()
1040 self.__readData()
1061 self.__readData()
1041 self.__setBlockList()
1062 self.__setBlockList()
1042 self.blockIndex = 0
1063 self.blockIndex = 0
1043
1064
1044 return
1065 return
1045
1066
1046 def __setBlockList(self):
1067 def __setBlockList(self):
1047 '''
1068 '''
1048 Selects the data within the times defined
1069 Selects the data within the times defined
1049
1070
1050 self.fp
1071 self.fp
1051 self.startTime
1072 self.startTime
1052 self.endTime
1073 self.endTime
1053 self.blockList
1074 self.blockList
1054 self.blocksPerFile
1075 self.blocksPerFile
1055
1076
1056 '''
1077 '''
1057
1078
1058 startTime = self.startTime
1079 startTime = self.startTime
1059 endTime = self.endTime
1080 endTime = self.endTime
1060
1081
1061 index = self.listDataname.index('utctime')
1082 index = self.listDataname.index('utctime')
1062 thisUtcTime = self.listData[index]
1083 thisUtcTime = self.listData[index]
1063 self.interval = numpy.min(thisUtcTime[1:] - thisUtcTime[:-1])
1084 self.interval = numpy.min(thisUtcTime[1:] - thisUtcTime[:-1])
1064
1085
1065 if self.timezone == 'lt':
1086 if self.timezone == 'lt':
1066 thisUtcTime -= 5*3600
1087 thisUtcTime -= 5*3600
1067
1088
1068 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
1089 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
1069
1090
1070 thisDate = thisDatetime.date()
1091 thisDate = thisDatetime.date()
1071 thisTime = thisDatetime.time()
1092 thisTime = thisDatetime.time()
1072
1093
1073 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1094 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1074 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1095 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1075
1096
1076 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
1097 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
1077
1098
1078 self.blockList = ind
1099 self.blockList = ind
1079 self.blocksPerFile = len(ind)
1100 self.blocksPerFile = len(ind)
1080 return
1101 return
1081
1102
1082 def __readMetadata(self):
1103 def __readMetadata(self):
1083 '''
1104 '''
1084 Reads Metadata
1105 Reads Metadata
1085 '''
1106 '''
1086
1107
1087 listMetaname = []
1108 listMetaname = []
1088 listMetadata = []
1109 listMetadata = []
1089 if 'Metadata' in self.fp:
1110 if 'Metadata' in self.fp:
1090 gp = self.fp['Metadata']
1111 gp = self.fp['Metadata']
1091 for item in list(gp.items()):
1112 for item in list(gp.items()):
1092 name = item[0]
1113 name = item[0]
1093
1114
1094 if name=='variables':
1115 if name=='variables':
1095 table = gp[name][:]
1116 table = gp[name][:]
1096 listShapes = {}
1117 listShapes = {}
1097 for shapes in table:
1118 for shapes in table:
1098 listShapes[shapes[0].decode()] = numpy.array([shapes[1]])
1119 listShapes[shapes[0].decode()] = numpy.array([shapes[1]])
1099 else:
1120 else:
1100 data = gp[name].value
1121 data = gp[name].value
1101 listMetaname.append(name)
1122 listMetaname.append(name)
1102 listMetadata.append(data)
1123 listMetadata.append(data)
1103 elif self.metadata:
1124 elif self.metadata:
1104 metadata = json.loads(self.metadata)
1125 metadata = json.loads(self.metadata)
1105 listShapes = {}
1126 listShapes = {}
1106 for tup in metadata:
1127 for tup in metadata:
1107 name, values, dim = tup
1128 name, values, dim = tup
1108 if dim == -1:
1129 if dim == -1:
1109 listMetaname.append(name)
1130 listMetaname.append(name)
1110 listMetadata.append(self.fp[values].value)
1131 listMetadata.append(self.fp[values].value)
1111 else:
1132 else:
1112 listShapes[name] = numpy.array([dim])
1133 listShapes[name] = numpy.array([dim])
1113 else:
1134 else:
1114 raise IOError('Missing Metadata group in file or metadata info')
1135 raise IOError('Missing Metadata group in file or metadata info')
1115
1136
1116 self.listShapes = listShapes
1137 self.listShapes = listShapes
1117 self.listMetaname = listMetaname
1138 self.listMetaname = listMetaname
1118 self.listMeta = listMetadata
1139 self.listMeta = listMetadata
1119
1140
1120 return
1141 return
1121
1142
1122 def __readData(self):
1143 def __readData(self):
1123
1144
1124 listdataname = []
1145 listdataname = []
1125 listdata = []
1146 listdata = []
1126
1147
1127 if 'Data' in self.fp:
1148 if 'Data' in self.fp:
1128 grp = self.fp['Data']
1149 grp = self.fp['Data']
1129 for item in list(grp.items()):
1150 for item in list(grp.items()):
1130 name = item[0]
1151 name = item[0]
1131 listdataname.append(name)
1152 listdataname.append(name)
1132 dim = self.listShapes[name][0]
1153 dim = self.listShapes[name][0]
1133 if dim == 0:
1154 if dim == 0:
1134 array = grp[name].value
1155 array = grp[name].value
1135 else:
1156 else:
1136 array = []
1157 array = []
1137 for i in range(dim):
1158 for i in range(dim):
1138 array.append(grp[name]['table{:02d}'.format(i)].value)
1159 array.append(grp[name]['table{:02d}'.format(i)].value)
1139 array = numpy.array(array)
1160 array = numpy.array(array)
1140
1161
1141 listdata.append(array)
1162 listdata.append(array)
1142 elif self.metadata:
1163 elif self.metadata:
1143 metadata = json.loads(self.metadata)
1164 metadata = json.loads(self.metadata)
1144 for tup in metadata:
1165 for tup in metadata:
1145 name, values, dim = tup
1166 name, values, dim = tup
1146 listdataname.append(name)
1167 listdataname.append(name)
1147 if dim == -1:
1168 if dim == -1:
1148 continue
1169 continue
1149 elif dim == 0:
1170 elif dim == 0:
1150 array = self.fp[values].value
1171 array = self.fp[values].value
1151 else:
1172 else:
1152 array = []
1173 array = []
1153 for var in values:
1174 for var in values:
1154 array.append(self.fp[var].value)
1175 array.append(self.fp[var].value)
1155 array = numpy.array(array)
1176 array = numpy.array(array)
1156 listdata.append(array)
1177 listdata.append(array)
1157 else:
1178 else:
1158 raise IOError('Missing Data group in file or metadata info')
1179 raise IOError('Missing Data group in file or metadata info')
1159
1180
1160 self.listDataname = listdataname
1181 self.listDataname = listdataname
1161 self.listData = listdata
1182 self.listData = listdata
1162 return
1183 return
1163
1184
1164 def getData(self):
1185 def getData(self):
1165
1186
1166 for i in range(len(self.listMeta)):
1187 for i in range(len(self.listMeta)):
1167 setattr(self.dataOut, self.listMetaname[i], self.listMeta[i])
1188 setattr(self.dataOut, self.listMetaname[i], self.listMeta[i])
1168
1189
1169 for j in range(len(self.listData)):
1190 for j in range(len(self.listData)):
1170 dim = self.listShapes[self.listDataname[j]][0]
1191 dim = self.listShapes[self.listDataname[j]][0]
1171 if dim == 0:
1192 if dim == 0:
1172 setattr(self.dataOut, self.listDataname[j], self.listData[j][self.blockIndex])
1193 setattr(self.dataOut, self.listDataname[j], self.listData[j][self.blockIndex])
1173 else:
1194 else:
1174 setattr(self.dataOut, self.listDataname[j], self.listData[j][:,self.blockIndex])
1195 setattr(self.dataOut, self.listDataname[j], self.listData[j][:,self.blockIndex])
1175
1196
1176 self.dataOut.paramInterval = self.interval
1197 self.dataOut.paramInterval = self.interval
1177 self.dataOut.flagNoData = False
1198 self.dataOut.flagNoData = False
1178 self.blockIndex += 1
1199 self.blockIndex += 1
1179
1200
1180 return
1201 return
1181
1202
1182 def run(self, **kwargs):
1203 def run(self, **kwargs):
1183
1204
1184 if not(self.isConfig):
1205 if not(self.isConfig):
1185 self.setup(**kwargs)
1206 self.setup(**kwargs)
1186 self.isConfig = True
1207 self.isConfig = True
1187
1208
1188 if self.blockIndex == self.blocksPerFile:
1209 if self.blockIndex == self.blocksPerFile:
1189 self.setNextFile()
1210 self.setNextFile()
1190
1211
1191 self.getData()
1212 self.getData()
1192
1213
1193 return
1214 return
1194
1215
1195 @MPDecorator
1216 @MPDecorator
1196 class ParameterWriter(Operation):
1217 class ParameterWriter(Operation):
1197 '''
1218 '''
1198 HDF5 Writer, stores parameters data in HDF5 format files
1219 HDF5 Writer, stores parameters data in HDF5 format files
1199
1220
1200 path: path where the files will be stored
1221 path: path where the files will be stored
1201 blocksPerFile: number of blocks that will be saved in per HDF5 format file
1222 blocksPerFile: number of blocks that will be saved in per HDF5 format file
1202 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
1223 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
1203 metadataList: list of attributes that will be stored as metadata
1224 metadataList: list of attributes that will be stored as metadata
1204 dataList: list of attributes that will be stores as data
1225 dataList: list of attributes that will be stores as data
1205 '''
1226 '''
1206
1227
1207
1228
1208 ext = ".hdf5"
1229 ext = ".hdf5"
1209 optchar = "D"
1230 optchar = "D"
1210 metaoptchar = "M"
1231 metaoptchar = "M"
1211 metaFile = None
1232 metaFile = None
1212 filename = None
1233 filename = None
1213 path = None
1234 path = None
1214 setFile = None
1235 setFile = None
1215 fp = None
1236 fp = None
1216 grp = None
1237 grp = None
1217 ds = None
1238 ds = None
1218 firsttime = True
1239 firsttime = True
1219 #Configurations
1240 #Configurations
1220 blocksPerFile = None
1241 blocksPerFile = None
1221 blockIndex = None
1242 blockIndex = None
1222 dataOut = None
1243 dataOut = None
1223 #Data Arrays
1244 #Data Arrays
1224 dataList = None
1245 dataList = None
1225 metadataList = None
1246 metadataList = None
1226 dsList = None #List of dictionaries with dataset properties
1247 dsList = None #List of dictionaries with dataset properties
1227 tableDim = None
1248 tableDim = None
1228 dtype = [('name', 'S20'),('nDim', 'i')]
1249 dtype = [('name', 'S20'),('nDim', 'i')]
1229 currentDay = None
1250 currentDay = None
1230 lastTime = None
1251 lastTime = None
1231
1252
1232 def __init__(self):
1253 def __init__(self):
1233
1254
1234 Operation.__init__(self)
1255 Operation.__init__(self)
1235 return
1256 return
1236
1257
1237 def setup(self, path=None, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1258 def setup(self, path=None, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1238 self.path = path
1259 self.path = path
1239 self.blocksPerFile = blocksPerFile
1260 self.blocksPerFile = blocksPerFile
1240 self.metadataList = metadataList
1261 self.metadataList = metadataList
1241 self.dataList = dataList
1262 self.dataList = dataList
1242 self.setType = setType
1263 self.setType = setType
1243
1264
1244 tableList = []
1265 tableList = []
1245 dsList = []
1266 dsList = []
1246
1267
1247 for i in range(len(self.dataList)):
1268 for i in range(len(self.dataList)):
1248 dsDict = {}
1269 dsDict = {}
1249 dataAux = getattr(self.dataOut, self.dataList[i])
1270 dataAux = getattr(self.dataOut, self.dataList[i])
1250 dsDict['variable'] = self.dataList[i]
1271 dsDict['variable'] = self.dataList[i]
1251
1272
1252 if dataAux is None:
1273 if dataAux is None:
1253 continue
1274 continue
1254 elif isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
1275 elif isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
1255 dsDict['nDim'] = 0
1276 dsDict['nDim'] = 0
1256 else:
1277 else:
1257 dsDict['nDim'] = len(dataAux.shape)
1278 dsDict['nDim'] = len(dataAux.shape)
1258 dsDict['shape'] = dataAux.shape
1279 dsDict['shape'] = dataAux.shape
1259 dsDict['dsNumber'] = dataAux.shape[0]
1280 dsDict['dsNumber'] = dataAux.shape[0]
1260
1281
1261 dsList.append(dsDict)
1282 dsList.append(dsDict)
1262 tableList.append((self.dataList[i], dsDict['nDim']))
1283 tableList.append((self.dataList[i], dsDict['nDim']))
1263
1284
1264 self.dsList = dsList
1285 self.dsList = dsList
1265 self.tableDim = numpy.array(tableList, dtype=self.dtype)
1286 self.tableDim = numpy.array(tableList, dtype=self.dtype)
1266 self.currentDay = self.dataOut.datatime.date()
1287 self.currentDay = self.dataOut.datatime.date()
1267
1288
1268 def timeFlag(self):
1289 def timeFlag(self):
1269 currentTime = self.dataOut.utctime
1290 currentTime = self.dataOut.utctime
1270 timeTuple = time.localtime(currentTime)
1291 timeTuple = time.localtime(currentTime)
1271 dataDay = timeTuple.tm_yday
1292 dataDay = timeTuple.tm_yday
1272
1293
1273 if self.lastTime is None:
1294 if self.lastTime is None:
1274 self.lastTime = currentTime
1295 self.lastTime = currentTime
1275 self.currentDay = dataDay
1296 self.currentDay = dataDay
1276 return False
1297 return False
1277
1298
1278 timeDiff = currentTime - self.lastTime
1299 timeDiff = currentTime - self.lastTime
1279
1300
1280 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
1301 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
1281 if dataDay != self.currentDay:
1302 if dataDay != self.currentDay:
1282 self.currentDay = dataDay
1303 self.currentDay = dataDay
1283 return True
1304 return True
1284 elif timeDiff > 3*60*60:
1305 elif timeDiff > 3*60*60:
1285 self.lastTime = currentTime
1306 self.lastTime = currentTime
1286 return True
1307 return True
1287 else:
1308 else:
1288 self.lastTime = currentTime
1309 self.lastTime = currentTime
1289 return False
1310 return False
1290
1311
1291 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1312 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1292
1313
1293 self.dataOut = dataOut
1314 self.dataOut = dataOut
1294 if not(self.isConfig):
1315 if not(self.isConfig):
1295 self.setup(path=path, blocksPerFile=blocksPerFile,
1316 self.setup(path=path, blocksPerFile=blocksPerFile,
1296 metadataList=metadataList, dataList=dataList,
1317 metadataList=metadataList, dataList=dataList,
1297 setType=setType)
1318 setType=setType)
1298
1319
1299 self.isConfig = True
1320 self.isConfig = True
1300 self.setNextFile()
1321 self.setNextFile()
1301
1322
1302 self.putData()
1323 self.putData()
1303 return
1324 return
1304
1325
1305 def setNextFile(self):
1326 def setNextFile(self):
1306
1327
1307 ext = self.ext
1328 ext = self.ext
1308 path = self.path
1329 path = self.path
1309 setFile = self.setFile
1330 setFile = self.setFile
1310
1331
1311 timeTuple = time.localtime(self.dataOut.utctime)
1332 timeTuple = time.localtime(self.dataOut.utctime)
1312 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1333 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1313 fullpath = os.path.join(path, subfolder)
1334 fullpath = os.path.join(path, subfolder)
1314
1335
1315 if os.path.exists(fullpath):
1336 if os.path.exists(fullpath):
1316 filesList = os.listdir(fullpath)
1337 filesList = os.listdir(fullpath)
1317 filesList = [k for k in filesList if k.startswith(self.optchar)]
1338 filesList = [k for k in filesList if k.startswith(self.optchar)]
1318 if len( filesList ) > 0:
1339 if len( filesList ) > 0:
1319 filesList = sorted(filesList, key=str.lower)
1340 filesList = sorted(filesList, key=str.lower)
1320 filen = filesList[-1]
1341 filen = filesList[-1]
1321 # el filename debera tener el siguiente formato
1342 # el filename debera tener el siguiente formato
1322 # 0 1234 567 89A BCDE (hex)
1343 # 0 1234 567 89A BCDE (hex)
1323 # x YYYY DDD SSS .ext
1344 # x YYYY DDD SSS .ext
1324 if isNumber(filen[8:11]):
1345 if isNumber(filen[8:11]):
1325 setFile = int(filen[8:11]) #inicializo mi contador de seteo al seteo del ultimo file
1346 setFile = int(filen[8:11]) #inicializo mi contador de seteo al seteo del ultimo file
1326 else:
1347 else:
1327 setFile = -1
1348 setFile = -1
1328 else:
1349 else:
1329 setFile = -1 #inicializo mi contador de seteo
1350 setFile = -1 #inicializo mi contador de seteo
1330 else:
1351 else:
1331 os.makedirs(fullpath)
1352 os.makedirs(fullpath)
1332 setFile = -1 #inicializo mi contador de seteo
1353 setFile = -1 #inicializo mi contador de seteo
1333
1354
1334 if self.setType is None:
1355 if self.setType is None:
1335 setFile += 1
1356 setFile += 1
1336 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
1357 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
1337 timeTuple.tm_year,
1358 timeTuple.tm_year,
1338 timeTuple.tm_yday,
1359 timeTuple.tm_yday,
1339 setFile,
1360 setFile,
1340 ext )
1361 ext )
1341 else:
1362 else:
1342 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
1363 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
1343 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
1364 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
1344 timeTuple.tm_year,
1365 timeTuple.tm_year,
1345 timeTuple.tm_yday,
1366 timeTuple.tm_yday,
1346 setFile,
1367 setFile,
1347 ext )
1368 ext )
1348
1369
1349 self.filename = os.path.join( path, subfolder, file )
1370 self.filename = os.path.join( path, subfolder, file )
1350
1371
1351 #Setting HDF5 File
1372 #Setting HDF5 File
1352 self.fp = h5py.File(self.filename, 'w')
1373 self.fp = h5py.File(self.filename, 'w')
1353 #write metadata
1374 #write metadata
1354 self.writeMetadata(self.fp)
1375 self.writeMetadata(self.fp)
1355 #Write data
1376 #Write data
1356 self.writeData(self.fp)
1377 self.writeData(self.fp)
1357
1378
1358 def writeMetadata(self, fp):
1379 def writeMetadata(self, fp):
1359
1380
1360 grp = fp.create_group("Metadata")
1381 grp = fp.create_group("Metadata")
1361 grp.create_dataset('variables', data=self.tableDim, dtype=self.dtype)
1382 grp.create_dataset('variables', data=self.tableDim, dtype=self.dtype)
1362
1383
1363 for i in range(len(self.metadataList)):
1384 for i in range(len(self.metadataList)):
1364 if not hasattr(self.dataOut, self.metadataList[i]):
1385 if not hasattr(self.dataOut, self.metadataList[i]):
1365 log.warning('Metadata: `{}` not found'.format(self.metadataList[i]), self.name)
1386 log.warning('Metadata: `{}` not found'.format(self.metadataList[i]), self.name)
1366 continue
1387 continue
1367 value = getattr(self.dataOut, self.metadataList[i])
1388 value = getattr(self.dataOut, self.metadataList[i])
1368 grp.create_dataset(self.metadataList[i], data=value)
1389 grp.create_dataset(self.metadataList[i], data=value)
1369 return
1390 return
1370
1391
1371 def writeData(self, fp):
1392 def writeData(self, fp):
1372
1393
1373 grp = fp.create_group("Data")
1394 grp = fp.create_group("Data")
1374 dtsets = []
1395 dtsets = []
1375 data = []
1396 data = []
1376
1397
1377 for dsInfo in self.dsList:
1398 for dsInfo in self.dsList:
1378 if dsInfo['nDim'] == 0:
1399 if dsInfo['nDim'] == 0:
1379 ds = grp.create_dataset(
1400 ds = grp.create_dataset(
1380 dsInfo['variable'],
1401 dsInfo['variable'],
1381 (self.blocksPerFile, ),
1402 (self.blocksPerFile, ),
1382 chunks=True,
1403 chunks=True,
1383 dtype=numpy.float64)
1404 dtype=numpy.float64)
1384 dtsets.append(ds)
1405 dtsets.append(ds)
1385 data.append((dsInfo['variable'], -1))
1406 data.append((dsInfo['variable'], -1))
1386 else:
1407 else:
1387 sgrp = grp.create_group(dsInfo['variable'])
1408 sgrp = grp.create_group(dsInfo['variable'])
1388 for i in range(dsInfo['dsNumber']):
1409 for i in range(dsInfo['dsNumber']):
1389 ds = sgrp.create_dataset(
1410 ds = sgrp.create_dataset(
1390 'table{:02d}'.format(i),
1411 'table{:02d}'.format(i),
1391 (self.blocksPerFile, ) + dsInfo['shape'][1:],
1412 (self.blocksPerFile, ) + dsInfo['shape'][1:],
1392 chunks=True)
1413 chunks=True)
1393 dtsets.append(ds)
1414 dtsets.append(ds)
1394 data.append((dsInfo['variable'], i))
1415 data.append((dsInfo['variable'], i))
1395 fp.flush()
1416 fp.flush()
1396
1417
1397 log.log('Creating file: {}'.format(fp.filename), self.name)
1418 log.log('Creating file: {}'.format(fp.filename), self.name)
1398
1419
1399 self.ds = dtsets
1420 self.ds = dtsets
1400 self.data = data
1421 self.data = data
1401 self.firsttime = True
1422 self.firsttime = True
1402 self.blockIndex = 0
1423 self.blockIndex = 0
1403 return
1424 return
1404
1425
1405 def putData(self):
1426 def putData(self):
1406
1427
1407 if (self.blockIndex == self.blocksPerFile) or self.timeFlag():
1428 if (self.blockIndex == self.blocksPerFile) or self.timeFlag():
1408 self.closeFile()
1429 self.closeFile()
1409 self.setNextFile()
1430 self.setNextFile()
1410
1431
1411 for i, ds in enumerate(self.ds):
1432 for i, ds in enumerate(self.ds):
1433 print(i,ds)
1412 attr, ch = self.data[i]
1434 attr, ch = self.data[i]
1413 if ch == -1:
1435 if ch == -1:
1414 ds[self.blockIndex] = getattr(self.dataOut, attr)
1436 ds[self.blockIndex] = getattr(self.dataOut, attr)
1415 else:
1437 else:
1438 print(ch, getattr(self.dataOut, attr).shape)
1416 ds[self.blockIndex] = getattr(self.dataOut, attr)[ch]
1439 ds[self.blockIndex] = getattr(self.dataOut, attr)[ch]
1417
1440
1418 self.fp.flush()
1441 self.fp.flush()
1419 self.blockIndex += 1
1442 self.blockIndex += 1
1420 log.log('Block No. {}/{}'.format(self.blockIndex, self.blocksPerFile), self.name)
1443 log.log('Block No. {}/{}'.format(self.blockIndex, self.blocksPerFile), self.name)
1421
1444
1422 return
1445 return
1423
1446
1424 def closeFile(self):
1447 def closeFile(self):
1425
1448
1426 if self.blockIndex != self.blocksPerFile:
1449 if self.blockIndex != self.blocksPerFile:
1427 for ds in self.ds:
1450 for ds in self.ds:
1428 ds.resize(self.blockIndex, axis=0)
1451 ds.resize(self.blockIndex, axis=0)
1429
1452
1430 self.fp.flush()
1453 self.fp.flush()
1431 self.fp.close()
1454 self.fp.close()
1432
1455
1433 def close(self):
1456 def close(self):
1434
1457
1435 self.closeFile()
1458 self.closeFile()
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,1056 +1,1260
1 import itertools
1 import itertools
2
2
3 import numpy
3 import numpy
4
4
5 from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation
5 from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation
6 from schainpy.model.data.jrodata import Spectra
6 from schainpy.model.data.jrodata import Spectra
7 from schainpy.model.data.jrodata import hildebrand_sekhon
7 from schainpy.model.data.jrodata import hildebrand_sekhon
8 from schainpy.utils import log
8 from schainpy.utils import log
9
9
10 @MPDecorator
10 @MPDecorator
11 class SpectraProc(ProcessingUnit):
11 class SpectraProc(ProcessingUnit):
12
12
13
13
14 def __init__(self):
14 def __init__(self):
15
15
16 ProcessingUnit.__init__(self)
16 ProcessingUnit.__init__(self)
17
17
18 self.buffer = None
18 self.buffer = None
19 self.firstdatatime = None
19 self.firstdatatime = None
20 self.profIndex = 0
20 self.profIndex = 0
21 self.dataOut = Spectra()
21 self.dataOut = Spectra()
22 self.id_min = None
22 self.id_min = None
23 self.id_max = None
23 self.id_max = None
24 self.setupReq = False #Agregar a todas las unidades de proc
24 self.setupReq = False #Agregar a todas las unidades de proc
25
25
26 def __updateSpecFromVoltage(self):
26 def __updateSpecFromVoltage(self):
27
27
28 self.dataOut.timeZone = self.dataIn.timeZone
28 self.dataOut.timeZone = self.dataIn.timeZone
29 self.dataOut.dstFlag = self.dataIn.dstFlag
29 self.dataOut.dstFlag = self.dataIn.dstFlag
30 self.dataOut.errorCount = self.dataIn.errorCount
30 self.dataOut.errorCount = self.dataIn.errorCount
31 self.dataOut.useLocalTime = self.dataIn.useLocalTime
31 self.dataOut.useLocalTime = self.dataIn.useLocalTime
32 try:
32 try:
33 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
33 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
34 except:
34 except:
35 pass
35 pass
36 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
36 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
37 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
37 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
38 self.dataOut.channelList = self.dataIn.channelList
38 self.dataOut.channelList = self.dataIn.channelList
39 self.dataOut.heightList = self.dataIn.heightList
39 self.dataOut.heightList = self.dataIn.heightList
40 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
40 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
41
41
42 self.dataOut.nBaud = self.dataIn.nBaud
42 self.dataOut.nBaud = self.dataIn.nBaud
43 self.dataOut.nCode = self.dataIn.nCode
43 self.dataOut.nCode = self.dataIn.nCode
44 self.dataOut.code = self.dataIn.code
44 self.dataOut.code = self.dataIn.code
45 self.dataOut.nProfiles = self.dataOut.nFFTPoints
45 self.dataOut.nProfiles = self.dataOut.nFFTPoints
46
46
47 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
47 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
48 self.dataOut.utctime = self.firstdatatime
48 self.dataOut.utctime = self.firstdatatime
49 # asumo q la data esta decodificada
49 # asumo q la data esta decodificada
50 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
50 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
51 # asumo q la data esta sin flip
51 # asumo q la data esta sin flip
52 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
52 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
53 self.dataOut.flagShiftFFT = False
53 self.dataOut.flagShiftFFT = False
54
54
55 self.dataOut.nCohInt = self.dataIn.nCohInt
55 self.dataOut.nCohInt = self.dataIn.nCohInt
56 self.dataOut.nIncohInt = 1
56 self.dataOut.nIncohInt = 1
57
57
58 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
58 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
59
59
60 self.dataOut.frequency = self.dataIn.frequency
60 self.dataOut.frequency = self.dataIn.frequency
61 self.dataOut.realtime = self.dataIn.realtime
61 self.dataOut.realtime = self.dataIn.realtime
62
62
63 self.dataOut.azimuth = self.dataIn.azimuth
63 self.dataOut.azimuth = self.dataIn.azimuth
64 self.dataOut.zenith = self.dataIn.zenith
64 self.dataOut.zenith = self.dataIn.zenith
65
65
66 self.dataOut.beam.codeList = self.dataIn.beam.codeList
66 self.dataOut.beam.codeList = self.dataIn.beam.codeList
67 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
67 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
68 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
68 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
69
69
70 def __getFft(self):
70 def __getFft(self):
71 """
71 """
72 Convierte valores de Voltaje a Spectra
72 Convierte valores de Voltaje a Spectra
73
73
74 Affected:
74 Affected:
75 self.dataOut.data_spc
75 self.dataOut.data_spc
76 self.dataOut.data_cspc
76 self.dataOut.data_cspc
77 self.dataOut.data_dc
77 self.dataOut.data_dc
78 self.dataOut.heightList
78 self.dataOut.heightList
79 self.profIndex
79 self.profIndex
80 self.buffer
80 self.buffer
81 self.dataOut.flagNoData
81 self.dataOut.flagNoData
82 """
82 """
83 fft_volt = numpy.fft.fft(
83 fft_volt = numpy.fft.fft(
84 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
84 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
85 fft_volt = fft_volt.astype(numpy.dtype('complex'))
85 fft_volt = fft_volt.astype(numpy.dtype('complex'))
86 dc = fft_volt[:, 0, :]
86 dc = fft_volt[:, 0, :]
87
87
88 # calculo de self-spectra
88 # calculo de self-spectra
89 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
89 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
90 spc = fft_volt * numpy.conjugate(fft_volt)
90 spc = fft_volt * numpy.conjugate(fft_volt)
91 spc = spc.real
91 spc = spc.real
92
92
93 blocksize = 0
93 blocksize = 0
94 blocksize += dc.size
94 blocksize += dc.size
95 blocksize += spc.size
95 blocksize += spc.size
96
96
97 #print("spc :",spc.shape)
98 data_wr = None
99 if self.dataOut.flagWR:
100 data_wr = fft_volt
101 blocksize = fft_volt.size
102
97 cspc = None
103 cspc = None
98 pairIndex = 0
104 pairIndex = 0
99 if self.dataOut.pairsList != None:
105 if self.dataOut.pairsList != None:
100 # calculo de cross-spectra
106 # calculo de cross-spectra
101 cspc = numpy.zeros(
107 cspc = numpy.zeros(
102 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
108 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
103 for pair in self.dataOut.pairsList:
109 for pair in self.dataOut.pairsList:
104 if pair[0] not in self.dataOut.channelList:
110 if pair[0] not in self.dataOut.channelList:
105 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
111 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
106 str(pair), str(self.dataOut.channelList)))
112 str(pair), str(self.dataOut.channelList)))
107 if pair[1] not in self.dataOut.channelList:
113 if pair[1] not in self.dataOut.channelList:
108 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
114 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
109 str(pair), str(self.dataOut.channelList)))
115 str(pair), str(self.dataOut.channelList)))
110
116
111 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
117 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
112 numpy.conjugate(fft_volt[pair[1], :, :])
118 numpy.conjugate(fft_volt[pair[1], :, :])
113 pairIndex += 1
119 pairIndex += 1
114 blocksize += cspc.size
120 blocksize += cspc.size
115
121
116 self.dataOut.data_spc = spc
122 self.dataOut.data_spc = spc
117 self.dataOut.data_cspc = cspc
123 self.dataOut.data_cspc = cspc
118 self.dataOut.data_dc = dc
124 self.dataOut.data_wr = data_wr
119 self.dataOut.blockSize = blocksize
125 self.dataOut.data_dc = dc
126 self.dataOut.blockSize = blocksize
120 self.dataOut.flagShiftFFT = False
127 self.dataOut.flagShiftFFT = False
121
128
122 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None, shift_fft=False):
129 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None, shift_fft=False,flagWR= 0):
130
131 self.dataOut.flagWR = flagWR
123
132
124 if self.dataIn.type == "Spectra":
133 if self.dataIn.type == "Spectra":
125 self.dataOut.copy(self.dataIn)
134 self.dataOut.copy(self.dataIn)
135
126 if shift_fft:
136 if shift_fft:
127 #desplaza a la derecha en el eje 2 determinadas posiciones
137 #desplaza a la derecha en el eje 2 determinadas posiciones
128 shift = int(self.dataOut.nFFTPoints/2)
138 shift = int(self.dataOut.nFFTPoints/2)
129 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
139 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
130
140
131 if self.dataOut.data_cspc is not None:
141 if self.dataOut.data_cspc is not None:
132 #desplaza a la derecha en el eje 2 determinadas posiciones
142 #desplaza a la derecha en el eje 2 determinadas posiciones
133 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
143 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
134
144
135 return True
145 return True
136
146
137 if self.dataIn.type == "Voltage":
147 if self.dataIn.type == "Voltage":
138
148 #print("VOLTAGE INPUT SPECTRA")
139 self.dataOut.flagNoData = True
149 self.dataOut.flagNoData = True
140
150
141 if nFFTPoints == None:
151 if nFFTPoints == None:
142 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
152 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
143
153
144 if nProfiles == None:
154 if nProfiles == None:
145 nProfiles = nFFTPoints
155 nProfiles = nFFTPoints
146
156
147 if ippFactor == None:
157 if ippFactor == None:
148 ippFactor = 1
158 ippFactor = 1
149
159
150 self.dataOut.ippFactor = ippFactor
160 self.dataOut.ippFactor = ippFactor
151
161
152 self.dataOut.nFFTPoints = nFFTPoints
162 self.dataOut.nFFTPoints = nFFTPoints
153 self.dataOut.pairsList = pairsList
163 self.dataOut.pairsList = pairsList
154
164
155 if self.buffer is None:
165 if self.buffer is None:
156 self.buffer = numpy.zeros((self.dataIn.nChannels,
166 self.buffer = numpy.zeros((self.dataIn.nChannels,
157 nProfiles,
167 nProfiles,
158 self.dataIn.nHeights),
168 self.dataIn.nHeights),
159 dtype='complex')
169 dtype='complex')
170 #print("buffer :",self.buffer.shape)
160
171
161 if self.dataIn.flagDataAsBlock:
172 if self.dataIn.flagDataAsBlock:
162 nVoltProfiles = self.dataIn.data.shape[1]
173 nVoltProfiles = self.dataIn.data.shape[1]
163
174
164 if nVoltProfiles == nProfiles:
175 if nVoltProfiles == nProfiles:
165 self.buffer = self.dataIn.data.copy()
176 self.buffer = self.dataIn.data.copy()
166 self.profIndex = nVoltProfiles
177 self.profIndex = nVoltProfiles
167
178
168 elif nVoltProfiles < nProfiles:
179 elif nVoltProfiles < nProfiles:
169
180
170 if self.profIndex == 0:
181 if self.profIndex == 0:
171 self.id_min = 0
182 self.id_min = 0
172 self.id_max = nVoltProfiles
183 self.id_max = nVoltProfiles
173
184
174 self.buffer[:, self.id_min:self.id_max,
185 self.buffer[:, self.id_min:self.id_max,
175 :] = self.dataIn.data
186 :] = self.dataIn.data
176 self.profIndex += nVoltProfiles
187 self.profIndex += nVoltProfiles
177 self.id_min += nVoltProfiles
188 self.id_min += nVoltProfiles
178 self.id_max += nVoltProfiles
189 self.id_max += nVoltProfiles
179 else:
190 else:
180 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
191 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
181 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
192 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
182 self.dataOut.flagNoData = True
193 self.dataOut.flagNoData = True
183 return 0
194 return 0
184 else:
195 else:
196 #print("Spectra ",self.profIndex)
185 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
197 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
186 self.profIndex += 1
198 self.profIndex += 1
187
199
188 if self.firstdatatime == None:
200 if self.firstdatatime == None:
189 self.firstdatatime = self.dataIn.utctime
201 self.firstdatatime = self.dataIn.utctime
190
202
191 if self.profIndex == nProfiles:
203 if self.profIndex == nProfiles:
192 self.__updateSpecFromVoltage()
204 self.__updateSpecFromVoltage()
193 self.__getFft()
205 self.__getFft()
206 #print(" DATAOUT SHAPE SPEC",self.dataOut.data_spc.shape)
194
207
195 self.dataOut.flagNoData = False
208 self.dataOut.flagNoData = False
196 self.firstdatatime = None
209 self.firstdatatime = None
197 self.profIndex = 0
210 self.profIndex = 0
198
211
199 return True
212 return True
200
213
201 raise ValueError("The type of input object '%s' is not valid" % (
214 raise ValueError("The type of input object '%s' is not valid" % (
202 self.dataIn.type))
215 self.dataIn.type))
203
216
204 def __selectPairs(self, pairsList):
217 def __selectPairs(self, pairsList):
205
218
206 if not pairsList:
219 if not pairsList:
207 return
220 return
208
221
209 pairs = []
222 pairs = []
210 pairsIndex = []
223 pairsIndex = []
211
224
212 for pair in pairsList:
225 for pair in pairsList:
213 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
226 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
214 continue
227 continue
215 pairs.append(pair)
228 pairs.append(pair)
216 pairsIndex.append(pairs.index(pair))
229 pairsIndex.append(pairs.index(pair))
217
230
218 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
231 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
219 self.dataOut.pairsList = pairs
232 self.dataOut.pairsList = pairs
220
233
221 return
234 return
222
235
223 def __selectPairsByChannel(self, channelList=None):
236 def __selectPairsByChannel(self, channelList=None):
224
237
225 if channelList == None:
238 if channelList == None:
226 return
239 return
227
240
228 pairsIndexListSelected = []
241 pairsIndexListSelected = []
229 for pairIndex in self.dataOut.pairsIndexList:
242 for pairIndex in self.dataOut.pairsIndexList:
230 # First pair
243 # First pair
231 if self.dataOut.pairsList[pairIndex][0] not in channelList:
244 if self.dataOut.pairsList[pairIndex][0] not in channelList:
232 continue
245 continue
233 # Second pair
246 # Second pair
234 if self.dataOut.pairsList[pairIndex][1] not in channelList:
247 if self.dataOut.pairsList[pairIndex][1] not in channelList:
235 continue
248 continue
236
249
237 pairsIndexListSelected.append(pairIndex)
250 pairsIndexListSelected.append(pairIndex)
238
251
239 if not pairsIndexListSelected:
252 if not pairsIndexListSelected:
240 self.dataOut.data_cspc = None
253 self.dataOut.data_cspc = None
241 self.dataOut.pairsList = []
254 self.dataOut.pairsList = []
242 return
255 return
243
256
244 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
257 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
245 self.dataOut.pairsList = [self.dataOut.pairsList[i]
258 self.dataOut.pairsList = [self.dataOut.pairsList[i]
246 for i in pairsIndexListSelected]
259 for i in pairsIndexListSelected]
247
260
248 return
261 return
249
262
250 def selectChannels(self, channelList):
263 def selectChannels(self, channelList):
251
264
252 channelIndexList = []
265 channelIndexList = []
253
266
254 for channel in channelList:
267 for channel in channelList:
255 if channel not in self.dataOut.channelList:
268 if channel not in self.dataOut.channelList:
256 raise ValueError("Error selecting channels, Channel %d is not valid.\nAvailable channels = %s" % (
269 raise ValueError("Error selecting channels, Channel %d is not valid.\nAvailable channels = %s" % (
257 channel, str(self.dataOut.channelList)))
270 channel, str(self.dataOut.channelList)))
258
271
259 index = self.dataOut.channelList.index(channel)
272 index = self.dataOut.channelList.index(channel)
260 channelIndexList.append(index)
273 channelIndexList.append(index)
261
274
262 self.selectChannelsByIndex(channelIndexList)
275 self.selectChannelsByIndex(channelIndexList)
263
276
264 def selectChannelsByIndex(self, channelIndexList):
277 def selectChannelsByIndex(self, channelIndexList):
265 """
278 """
266 Selecciona un bloque de datos en base a canales segun el channelIndexList
279 Selecciona un bloque de datos en base a canales segun el channelIndexList
267
280
268 Input:
281 Input:
269 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
282 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
270
283
271 Affected:
284 Affected:
272 self.dataOut.data_spc
285 self.dataOut.data_spc
273 self.dataOut.channelIndexList
286 self.dataOut.channelIndexList
274 self.dataOut.nChannels
287 self.dataOut.nChannels
275
288
276 Return:
289 Return:
277 None
290 None
278 """
291 """
279
292
280 for channelIndex in channelIndexList:
293 for channelIndex in channelIndexList:
281 if channelIndex not in self.dataOut.channelIndexList:
294 if channelIndex not in self.dataOut.channelIndexList:
282 raise ValueError("Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " % (
295 raise ValueError("Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " % (
283 channelIndex, self.dataOut.channelIndexList))
296 channelIndex, self.dataOut.channelIndexList))
284
297
285 data_spc = self.dataOut.data_spc[channelIndexList, :]
298 data_spc = self.dataOut.data_spc[channelIndexList, :]
286 data_dc = self.dataOut.data_dc[channelIndexList, :]
299 data_dc = self.dataOut.data_dc[channelIndexList, :]
287
300
288 self.dataOut.data_spc = data_spc
301 self.dataOut.data_spc = data_spc
289 self.dataOut.data_dc = data_dc
302 self.dataOut.data_dc = data_dc
290
303
291 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
304 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
292 self.dataOut.channelList = range(len(channelIndexList))
305 self.dataOut.channelList = range(len(channelIndexList))
293 self.__selectPairsByChannel(channelIndexList)
306 self.__selectPairsByChannel(channelIndexList)
294
307
295 return 1
308 return 1
296
309
297
310
298 def selectFFTs(self, minFFT, maxFFT ):
311 def selectFFTs(self, minFFT, maxFFT ):
299 """
312 """
300 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
313 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
301 minFFT<= FFT <= maxFFT
314 minFFT<= FFT <= maxFFT
302 """
315 """
303
316
304 if (minFFT > maxFFT):
317 if (minFFT > maxFFT):
305 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
318 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
306
319
307 if (minFFT < self.dataOut.getFreqRange()[0]):
320 if (minFFT < self.dataOut.getFreqRange()[0]):
308 minFFT = self.dataOut.getFreqRange()[0]
321 minFFT = self.dataOut.getFreqRange()[0]
309
322
310 if (maxFFT > self.dataOut.getFreqRange()[-1]):
323 if (maxFFT > self.dataOut.getFreqRange()[-1]):
311 maxFFT = self.dataOut.getFreqRange()[-1]
324 maxFFT = self.dataOut.getFreqRange()[-1]
312
325
313 minIndex = 0
326 minIndex = 0
314 maxIndex = 0
327 maxIndex = 0
315 FFTs = self.dataOut.getFreqRange()
328 FFTs = self.dataOut.getFreqRange()
316
329
317 inda = numpy.where(FFTs >= minFFT)
330 inda = numpy.where(FFTs >= minFFT)
318 indb = numpy.where(FFTs <= maxFFT)
331 indb = numpy.where(FFTs <= maxFFT)
319
332
320 try:
333 try:
321 minIndex = inda[0][0]
334 minIndex = inda[0][0]
322 except:
335 except:
323 minIndex = 0
336 minIndex = 0
324
337
325 try:
338 try:
326 maxIndex = indb[0][-1]
339 maxIndex = indb[0][-1]
327 except:
340 except:
328 maxIndex = len(FFTs)
341 maxIndex = len(FFTs)
329
342
330 self.selectFFTsByIndex(minIndex, maxIndex)
343 self.selectFFTsByIndex(minIndex, maxIndex)
331
344
332 return 1
345 return 1
333
346
334
347
335 def setH0(self, h0, deltaHeight = None):
348 def setH0(self, h0, deltaHeight = None):
336
349
337 if not deltaHeight:
350 if not deltaHeight:
338 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
351 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
339
352
340 nHeights = self.dataOut.nHeights
353 nHeights = self.dataOut.nHeights
341
354
342 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
355 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
343
356
344 self.dataOut.heightList = newHeiRange
357 self.dataOut.heightList = newHeiRange
345
358
346
359
347 def selectHeights(self, minHei, maxHei):
360 def selectHeights(self, minHei, maxHei):
348 """
361 """
349 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
362 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
350 minHei <= height <= maxHei
363 minHei <= height <= maxHei
351
364
352 Input:
365 Input:
353 minHei : valor minimo de altura a considerar
366 minHei : valor minimo de altura a considerar
354 maxHei : valor maximo de altura a considerar
367 maxHei : valor maximo de altura a considerar
355
368
356 Affected:
369 Affected:
357 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
370 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
358
371
359 Return:
372 Return:
360 1 si el metodo se ejecuto con exito caso contrario devuelve 0
373 1 si el metodo se ejecuto con exito caso contrario devuelve 0
361 """
374 """
362
375
363
376
364 if (minHei > maxHei):
377 if (minHei > maxHei):
365 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei))
378 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei))
366
379
367 if (minHei < self.dataOut.heightList[0]):
380 if (minHei < self.dataOut.heightList[0]):
368 minHei = self.dataOut.heightList[0]
381 minHei = self.dataOut.heightList[0]
369
382
370 if (maxHei > self.dataOut.heightList[-1]):
383 if (maxHei > self.dataOut.heightList[-1]):
371 maxHei = self.dataOut.heightList[-1]
384 maxHei = self.dataOut.heightList[-1]
372
385
373 minIndex = 0
386 minIndex = 0
374 maxIndex = 0
387 maxIndex = 0
375 heights = self.dataOut.heightList
388 heights = self.dataOut.heightList
376
389
377 inda = numpy.where(heights >= minHei)
390 inda = numpy.where(heights >= minHei)
378 indb = numpy.where(heights <= maxHei)
391 indb = numpy.where(heights <= maxHei)
379
392
380 try:
393 try:
381 minIndex = inda[0][0]
394 minIndex = inda[0][0]
382 except:
395 except:
383 minIndex = 0
396 minIndex = 0
384
397
385 try:
398 try:
386 maxIndex = indb[0][-1]
399 maxIndex = indb[0][-1]
387 except:
400 except:
388 maxIndex = len(heights)
401 maxIndex = len(heights)
389
402
390 self.selectHeightsByIndex(minIndex, maxIndex)
403 self.selectHeightsByIndex(minIndex, maxIndex)
391
404
392
405
393 return 1
406 return 1
394
407
395 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
408 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
396 newheis = numpy.where(
409 newheis = numpy.where(
397 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
410 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
398
411
399 if hei_ref != None:
412 if hei_ref != None:
400 newheis = numpy.where(self.dataOut.heightList > hei_ref)
413 newheis = numpy.where(self.dataOut.heightList > hei_ref)
401
414
402 minIndex = min(newheis[0])
415 minIndex = min(newheis[0])
403 maxIndex = max(newheis[0])
416 maxIndex = max(newheis[0])
404 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
417 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
405 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
418 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
406
419
407 # determina indices
420 # determina indices
408 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
421 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
409 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
422 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
410 avg_dB = 10 * \
423 avg_dB = 10 * \
411 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
424 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
412 beacon_dB = numpy.sort(avg_dB)[-nheis:]
425 beacon_dB = numpy.sort(avg_dB)[-nheis:]
413 beacon_heiIndexList = []
426 beacon_heiIndexList = []
414 for val in avg_dB.tolist():
427 for val in avg_dB.tolist():
415 if val >= beacon_dB[0]:
428 if val >= beacon_dB[0]:
416 beacon_heiIndexList.append(avg_dB.tolist().index(val))
429 beacon_heiIndexList.append(avg_dB.tolist().index(val))
417
430
418 #data_spc = data_spc[:,:,beacon_heiIndexList]
431 #data_spc = data_spc[:,:,beacon_heiIndexList]
419 data_cspc = None
432 data_cspc = None
420 if self.dataOut.data_cspc is not None:
433 if self.dataOut.data_cspc is not None:
421 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
434 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
422 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
435 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
423
436
424 data_dc = None
437 data_dc = None
425 if self.dataOut.data_dc is not None:
438 if self.dataOut.data_dc is not None:
426 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
439 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
427 #data_dc = data_dc[:,beacon_heiIndexList]
440 #data_dc = data_dc[:,beacon_heiIndexList]
428
441
429 self.dataOut.data_spc = data_spc
442 self.dataOut.data_spc = data_spc
430 self.dataOut.data_cspc = data_cspc
443 self.dataOut.data_cspc = data_cspc
431 self.dataOut.data_dc = data_dc
444 self.dataOut.data_dc = data_dc
432 self.dataOut.heightList = heightList
445 self.dataOut.heightList = heightList
433 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
446 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
434
447
435 return 1
448 return 1
436
449
437 def selectFFTsByIndex(self, minIndex, maxIndex):
450 def selectFFTsByIndex(self, minIndex, maxIndex):
438 """
451 """
439
452
440 """
453 """
441
454
442 if (minIndex < 0) or (minIndex > maxIndex):
455 if (minIndex < 0) or (minIndex > maxIndex):
443 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
456 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
444
457
445 if (maxIndex >= self.dataOut.nProfiles):
458 if (maxIndex >= self.dataOut.nProfiles):
446 maxIndex = self.dataOut.nProfiles-1
459 maxIndex = self.dataOut.nProfiles-1
447
460
448 #Spectra
461 #Spectra
449 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
462 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
450
463
451 data_cspc = None
464 data_cspc = None
452 if self.dataOut.data_cspc is not None:
465 if self.dataOut.data_cspc is not None:
453 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
466 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
454
467
455 data_dc = None
468 data_dc = None
456 if self.dataOut.data_dc is not None:
469 if self.dataOut.data_dc is not None:
457 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
470 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
458
471
459 self.dataOut.data_spc = data_spc
472 self.dataOut.data_spc = data_spc
460 self.dataOut.data_cspc = data_cspc
473 self.dataOut.data_cspc = data_cspc
461 self.dataOut.data_dc = data_dc
474 self.dataOut.data_dc = data_dc
462
475
463 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
476 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
464 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
477 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
465 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
478 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
466
479
467 return 1
480 return 1
468
481
469
482
470
483
471 def selectHeightsByIndex(self, minIndex, maxIndex):
484 def selectHeightsByIndex(self, minIndex, maxIndex):
472 """
485 """
473 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
486 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
474 minIndex <= index <= maxIndex
487 minIndex <= index <= maxIndex
475
488
476 Input:
489 Input:
477 minIndex : valor de indice minimo de altura a considerar
490 minIndex : valor de indice minimo de altura a considerar
478 maxIndex : valor de indice maximo de altura a considerar
491 maxIndex : valor de indice maximo de altura a considerar
479
492
480 Affected:
493 Affected:
481 self.dataOut.data_spc
494 self.dataOut.data_spc
482 self.dataOut.data_cspc
495 self.dataOut.data_cspc
483 self.dataOut.data_dc
496 self.dataOut.data_dc
484 self.dataOut.heightList
497 self.dataOut.heightList
485
498
486 Return:
499 Return:
487 1 si el metodo se ejecuto con exito caso contrario devuelve 0
500 1 si el metodo se ejecuto con exito caso contrario devuelve 0
488 """
501 """
489
502
490 if (minIndex < 0) or (minIndex > maxIndex):
503 if (minIndex < 0) or (minIndex > maxIndex):
491 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
504 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
492 minIndex, maxIndex))
505 minIndex, maxIndex))
493
506
494 if (maxIndex >= self.dataOut.nHeights):
507 if (maxIndex >= self.dataOut.nHeights):
495 maxIndex = self.dataOut.nHeights - 1
508 maxIndex = self.dataOut.nHeights - 1
496
509
497 # Spectra
510 # Spectra
498 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
511 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
499
512
500 data_cspc = None
513 data_cspc = None
501 if self.dataOut.data_cspc is not None:
514 if self.dataOut.data_cspc is not None:
502 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
515 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
503
516
504 data_dc = None
517 data_dc = None
505 if self.dataOut.data_dc is not None:
518 if self.dataOut.data_dc is not None:
506 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
519 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
507
520
508 self.dataOut.data_spc = data_spc
521 self.dataOut.data_spc = data_spc
509 self.dataOut.data_cspc = data_cspc
522 self.dataOut.data_cspc = data_cspc
510 self.dataOut.data_dc = data_dc
523 self.dataOut.data_dc = data_dc
511
524
512 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
525 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
513
526
514 return 1
527 return 1
515
528
516 def removeDC(self, mode=2):
529 def removeDC(self, mode=2):
517 jspectra = self.dataOut.data_spc
530 jspectra = self.dataOut.data_spc
518 jcspectra = self.dataOut.data_cspc
531 jcspectra = self.dataOut.data_cspc
519
532
520 num_chan = jspectra.shape[0]
533 num_chan = jspectra.shape[0]
521 num_hei = jspectra.shape[2]
534 num_hei = jspectra.shape[2]
522
535
523 if jcspectra is not None:
536 if jcspectra is not None:
524 jcspectraExist = True
537 jcspectraExist = True
525 num_pairs = jcspectra.shape[0]
538 num_pairs = jcspectra.shape[0]
526 else:
539 else:
527 jcspectraExist = False
540 jcspectraExist = False
528
541
529 freq_dc = int(jspectra.shape[1] / 2)
542 freq_dc = int(jspectra.shape[1] / 2)
530 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
543 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
531 ind_vel = ind_vel.astype(int)
544 ind_vel = ind_vel.astype(int)
532
545
533 if ind_vel[0] < 0:
546 if ind_vel[0] < 0:
534 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
547 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
535
548
536 if mode == 1:
549 if mode == 1:
537 jspectra[:, freq_dc, :] = (
550 jspectra[:, freq_dc, :] = (
538 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
551 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
539
552
540 if jcspectraExist:
553 if jcspectraExist:
541 jcspectra[:, freq_dc, :] = (
554 jcspectra[:, freq_dc, :] = (
542 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
555 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
543
556
544 if mode == 2:
557 if mode == 2:
545
558
546 vel = numpy.array([-2, -1, 1, 2])
559 vel = numpy.array([-2, -1, 1, 2])
547 xx = numpy.zeros([4, 4])
560 xx = numpy.zeros([4, 4])
548
561
549 for fil in range(4):
562 for fil in range(4):
550 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
563 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
551
564
552 xx_inv = numpy.linalg.inv(xx)
565 xx_inv = numpy.linalg.inv(xx)
553 xx_aux = xx_inv[0, :]
566 xx_aux = xx_inv[0, :]
554
567
555 for ich in range(num_chan):
568 for ich in range(num_chan):
556 yy = jspectra[ich, ind_vel, :]
569 yy = jspectra[ich, ind_vel, :]
557 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
570 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
558
571
559 junkid = jspectra[ich, freq_dc, :] <= 0
572 junkid = jspectra[ich, freq_dc, :] <= 0
560 cjunkid = sum(junkid)
573 cjunkid = sum(junkid)
561
574
562 if cjunkid.any():
575 if cjunkid.any():
563 jspectra[ich, freq_dc, junkid.nonzero()] = (
576 jspectra[ich, freq_dc, junkid.nonzero()] = (
564 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
577 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
565
578
566 if jcspectraExist:
579 if jcspectraExist:
567 for ip in range(num_pairs):
580 for ip in range(num_pairs):
568 yy = jcspectra[ip, ind_vel, :]
581 yy = jcspectra[ip, ind_vel, :]
569 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
582 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
570
583
571 self.dataOut.data_spc = jspectra
584 self.dataOut.data_spc = jspectra
572 self.dataOut.data_cspc = jcspectra
585 self.dataOut.data_cspc = jcspectra
573
586
574 return 1
587 return 1
575
588
576 def removeInterference2(self):
589 def removeInterference2(self):
577
590
578 cspc = self.dataOut.data_cspc
591 cspc = self.dataOut.data_cspc
579 spc = self.dataOut.data_spc
592 spc = self.dataOut.data_spc
580 Heights = numpy.arange(cspc.shape[2])
593 Heights = numpy.arange(cspc.shape[2])
581 realCspc = numpy.abs(cspc)
594 realCspc = numpy.abs(cspc)
582
595
583 for i in range(cspc.shape[0]):
596 for i in range(cspc.shape[0]):
584 LinePower= numpy.sum(realCspc[i], axis=0)
597 LinePower= numpy.sum(realCspc[i], axis=0)
585 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
598 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
586 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
599 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
587 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
600 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
588 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
601 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
589 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
602 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
590
603
591
604
592 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
605 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
593 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
606 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
594 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
607 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
595 cspc[i,InterferenceRange,:] = numpy.NaN
608 cspc[i,InterferenceRange,:] = numpy.NaN
596
609
597
610
598
611
599 self.dataOut.data_cspc = cspc
612 self.dataOut.data_cspc = cspc
600
613
601 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
614 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
602
615
603 jspectra = self.dataOut.data_spc
616 jspectra = self.dataOut.data_spc
604 jcspectra = self.dataOut.data_cspc
617 jcspectra = self.dataOut.data_cspc
605 jnoise = self.dataOut.getNoise()
618 jnoise = self.dataOut.getNoise()
606 num_incoh = self.dataOut.nIncohInt
619 num_incoh = self.dataOut.nIncohInt
607
620
608 num_channel = jspectra.shape[0]
621 num_channel = jspectra.shape[0]
609 num_prof = jspectra.shape[1]
622 num_prof = jspectra.shape[1]
610 num_hei = jspectra.shape[2]
623 num_hei = jspectra.shape[2]
611
624
612 # hei_interf
625 # hei_interf
613 if hei_interf is None:
626 if hei_interf is None:
614 count_hei = int(num_hei / 2)
627 count_hei = int(num_hei / 2)
615 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
628 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
616 hei_interf = numpy.asarray(hei_interf)[0]
629 hei_interf = numpy.asarray(hei_interf)[0]
617 # nhei_interf
630 # nhei_interf
618 if (nhei_interf == None):
631 if (nhei_interf == None):
619 nhei_interf = 5
632 nhei_interf = 5
620 if (nhei_interf < 1):
633 if (nhei_interf < 1):
621 nhei_interf = 1
634 nhei_interf = 1
622 if (nhei_interf > count_hei):
635 if (nhei_interf > count_hei):
623 nhei_interf = count_hei
636 nhei_interf = count_hei
624 if (offhei_interf == None):
637 if (offhei_interf == None):
625 offhei_interf = 0
638 offhei_interf = 0
626
639
627 ind_hei = list(range(num_hei))
640 ind_hei = list(range(num_hei))
628 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
641 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
629 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
642 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
630 mask_prof = numpy.asarray(list(range(num_prof)))
643 mask_prof = numpy.asarray(list(range(num_prof)))
631 num_mask_prof = mask_prof.size
644 num_mask_prof = mask_prof.size
632 comp_mask_prof = [0, num_prof / 2]
645 comp_mask_prof = [0, num_prof / 2]
633
646
634 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
647 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
635 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
648 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
636 jnoise = numpy.nan
649 jnoise = numpy.nan
637 noise_exist = jnoise[0] < numpy.Inf
650 noise_exist = jnoise[0] < numpy.Inf
638
651
639 # Subrutina de Remocion de la Interferencia
652 # Subrutina de Remocion de la Interferencia
640 for ich in range(num_channel):
653 for ich in range(num_channel):
641 # Se ordena los espectros segun su potencia (menor a mayor)
654 # Se ordena los espectros segun su potencia (menor a mayor)
642 power = jspectra[ich, mask_prof, :]
655 power = jspectra[ich, mask_prof, :]
643 power = power[:, hei_interf]
656 power = power[:, hei_interf]
644 power = power.sum(axis=0)
657 power = power.sum(axis=0)
645 psort = power.ravel().argsort()
658 psort = power.ravel().argsort()
646
659
647 # Se estima la interferencia promedio en los Espectros de Potencia empleando
660 # Se estima la interferencia promedio en los Espectros de Potencia empleando
648 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
661 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
649 offhei_interf, nhei_interf + offhei_interf))]]]
662 offhei_interf, nhei_interf + offhei_interf))]]]
650
663
651 if noise_exist:
664 if noise_exist:
652 # tmp_noise = jnoise[ich] / num_prof
665 # tmp_noise = jnoise[ich] / num_prof
653 tmp_noise = jnoise[ich]
666 tmp_noise = jnoise[ich]
654 junkspc_interf = junkspc_interf - tmp_noise
667 junkspc_interf = junkspc_interf - tmp_noise
655 #junkspc_interf[:,comp_mask_prof] = 0
668 #junkspc_interf[:,comp_mask_prof] = 0
656
669
657 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
670 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
658 jspc_interf = jspc_interf.transpose()
671 jspc_interf = jspc_interf.transpose()
659 # Calculando el espectro de interferencia promedio
672 # Calculando el espectro de interferencia promedio
660 noiseid = numpy.where(
673 noiseid = numpy.where(
661 jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
674 jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
662 noiseid = noiseid[0]
675 noiseid = noiseid[0]
663 cnoiseid = noiseid.size
676 cnoiseid = noiseid.size
664 interfid = numpy.where(
677 interfid = numpy.where(
665 jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
678 jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
666 interfid = interfid[0]
679 interfid = interfid[0]
667 cinterfid = interfid.size
680 cinterfid = interfid.size
668
681
669 if (cnoiseid > 0):
682 if (cnoiseid > 0):
670 jspc_interf[noiseid] = 0
683 jspc_interf[noiseid] = 0
671
684
672 # Expandiendo los perfiles a limpiar
685 # Expandiendo los perfiles a limpiar
673 if (cinterfid > 0):
686 if (cinterfid > 0):
674 new_interfid = (
687 new_interfid = (
675 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
688 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
676 new_interfid = numpy.asarray(new_interfid)
689 new_interfid = numpy.asarray(new_interfid)
677 new_interfid = {x for x in new_interfid}
690 new_interfid = {x for x in new_interfid}
678 new_interfid = numpy.array(list(new_interfid))
691 new_interfid = numpy.array(list(new_interfid))
679 new_cinterfid = new_interfid.size
692 new_cinterfid = new_interfid.size
680 else:
693 else:
681 new_cinterfid = 0
694 new_cinterfid = 0
682
695
683 for ip in range(new_cinterfid):
696 for ip in range(new_cinterfid):
684 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
697 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
685 jspc_interf[new_interfid[ip]
698 jspc_interf[new_interfid[ip]
686 ] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
699 ] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
687
700
688 jspectra[ich, :, ind_hei] = jspectra[ich, :,
701 jspectra[ich, :, ind_hei] = jspectra[ich, :,
689 ind_hei] - jspc_interf # Corregir indices
702 ind_hei] - jspc_interf # Corregir indices
690
703
691 # Removiendo la interferencia del punto de mayor interferencia
704 # Removiendo la interferencia del punto de mayor interferencia
692 ListAux = jspc_interf[mask_prof].tolist()
705 ListAux = jspc_interf[mask_prof].tolist()
693 maxid = ListAux.index(max(ListAux))
706 maxid = ListAux.index(max(ListAux))
694
707
695 if cinterfid > 0:
708 if cinterfid > 0:
696 for ip in range(cinterfid * (interf == 2) - 1):
709 for ip in range(cinterfid * (interf == 2) - 1):
697 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
710 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
698 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
711 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
699 cind = len(ind)
712 cind = len(ind)
700
713
701 if (cind > 0):
714 if (cind > 0):
702 jspectra[ich, interfid[ip], ind] = tmp_noise * \
715 jspectra[ich, interfid[ip], ind] = tmp_noise * \
703 (1 + (numpy.random.uniform(cind) - 0.5) /
716 (1 + (numpy.random.uniform(cind) - 0.5) /
704 numpy.sqrt(num_incoh))
717 numpy.sqrt(num_incoh))
705
718
706 ind = numpy.array([-2, -1, 1, 2])
719 ind = numpy.array([-2, -1, 1, 2])
707 xx = numpy.zeros([4, 4])
720 xx = numpy.zeros([4, 4])
708
721
709 for id1 in range(4):
722 for id1 in range(4):
710 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
723 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
711
724
712 xx_inv = numpy.linalg.inv(xx)
725 xx_inv = numpy.linalg.inv(xx)
713 xx = xx_inv[:, 0]
726 xx = xx_inv[:, 0]
714 ind = (ind + maxid + num_mask_prof) % num_mask_prof
727 ind = (ind + maxid + num_mask_prof) % num_mask_prof
715 yy = jspectra[ich, mask_prof[ind], :]
728 yy = jspectra[ich, mask_prof[ind], :]
716 jspectra[ich, mask_prof[maxid], :] = numpy.dot(
729 jspectra[ich, mask_prof[maxid], :] = numpy.dot(
717 yy.transpose(), xx)
730 yy.transpose(), xx)
718
731
719 indAux = (jspectra[ich, :, :] < tmp_noise *
732 indAux = (jspectra[ich, :, :] < tmp_noise *
720 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
733 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
721 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
734 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
722 (1 - 1 / numpy.sqrt(num_incoh))
735 (1 - 1 / numpy.sqrt(num_incoh))
723
736
724 # Remocion de Interferencia en el Cross Spectra
737 # Remocion de Interferencia en el Cross Spectra
725 if jcspectra is None:
738 if jcspectra is None:
726 return jspectra, jcspectra
739 return jspectra, jcspectra
727 num_pairs = int(jcspectra.size / (num_prof * num_hei))
740 num_pairs = int(jcspectra.size / (num_prof * num_hei))
728 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
741 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
729
742
730 for ip in range(num_pairs):
743 for ip in range(num_pairs):
731
744
732 #-------------------------------------------
745 #-------------------------------------------
733
746
734 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
747 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
735 cspower = cspower[:, hei_interf]
748 cspower = cspower[:, hei_interf]
736 cspower = cspower.sum(axis=0)
749 cspower = cspower.sum(axis=0)
737
750
738 cspsort = cspower.ravel().argsort()
751 cspsort = cspower.ravel().argsort()
739 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
752 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
740 offhei_interf, nhei_interf + offhei_interf))]]]
753 offhei_interf, nhei_interf + offhei_interf))]]]
741 junkcspc_interf = junkcspc_interf.transpose()
754 junkcspc_interf = junkcspc_interf.transpose()
742 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
755 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
743
756
744 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
757 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
745
758
746 median_real = int(numpy.median(numpy.real(
759 median_real = int(numpy.median(numpy.real(
747 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
760 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
748 median_imag = int(numpy.median(numpy.imag(
761 median_imag = int(numpy.median(numpy.imag(
749 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
762 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
750 comp_mask_prof = [int(e) for e in comp_mask_prof]
763 comp_mask_prof = [int(e) for e in comp_mask_prof]
751 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
764 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
752 median_real, median_imag)
765 median_real, median_imag)
753
766
754 for iprof in range(num_prof):
767 for iprof in range(num_prof):
755 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
768 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
756 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
769 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
757
770
758 # Removiendo la Interferencia
771 # Removiendo la Interferencia
759 jcspectra[ip, :, ind_hei] = jcspectra[ip,
772 jcspectra[ip, :, ind_hei] = jcspectra[ip,
760 :, ind_hei] - jcspc_interf
773 :, ind_hei] - jcspc_interf
761
774
762 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
775 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
763 maxid = ListAux.index(max(ListAux))
776 maxid = ListAux.index(max(ListAux))
764
777
765 ind = numpy.array([-2, -1, 1, 2])
778 ind = numpy.array([-2, -1, 1, 2])
766 xx = numpy.zeros([4, 4])
779 xx = numpy.zeros([4, 4])
767
780
768 for id1 in range(4):
781 for id1 in range(4):
769 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
782 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
770
783
771 xx_inv = numpy.linalg.inv(xx)
784 xx_inv = numpy.linalg.inv(xx)
772 xx = xx_inv[:, 0]
785 xx = xx_inv[:, 0]
773
786
774 ind = (ind + maxid + num_mask_prof) % num_mask_prof
787 ind = (ind + maxid + num_mask_prof) % num_mask_prof
775 yy = jcspectra[ip, mask_prof[ind], :]
788 yy = jcspectra[ip, mask_prof[ind], :]
776 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
789 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
777
790
778 # Guardar Resultados
791 # Guardar Resultados
779 self.dataOut.data_spc = jspectra
792 self.dataOut.data_spc = jspectra
780 self.dataOut.data_cspc = jcspectra
793 self.dataOut.data_cspc = jcspectra
781
794
782 return 1
795 return 1
783
796
784 def setRadarFrequency(self, frequency=None):
797 def setRadarFrequency(self, frequency=None):
785
798
786 if frequency != None:
799 if frequency != None:
787 self.dataOut.frequency = frequency
800 self.dataOut.frequency = frequency
788
801
789 return 1
802 return 1
790
803
791 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
804 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
792 # validacion de rango
805 # validacion de rango
793 if minHei == None:
806 if minHei == None:
794 minHei = self.dataOut.heightList[0]
807 minHei = self.dataOut.heightList[0]
795
808
796 if maxHei == None:
809 if maxHei == None:
797 maxHei = self.dataOut.heightList[-1]
810 maxHei = self.dataOut.heightList[-1]
798
811
799 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
812 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
800 print('minHei: %.2f is out of the heights range' % (minHei))
813 print('minHei: %.2f is out of the heights range' % (minHei))
801 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
814 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
802 minHei = self.dataOut.heightList[0]
815 minHei = self.dataOut.heightList[0]
803
816
804 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
817 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
805 print('maxHei: %.2f is out of the heights range' % (maxHei))
818 print('maxHei: %.2f is out of the heights range' % (maxHei))
806 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
819 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
807 maxHei = self.dataOut.heightList[-1]
820 maxHei = self.dataOut.heightList[-1]
808
821
809 # validacion de velocidades
822 # validacion de velocidades
810 velrange = self.dataOut.getVelRange(1)
823 velrange = self.dataOut.getVelRange(1)
811
824
812 if minVel == None:
825 if minVel == None:
813 minVel = velrange[0]
826 minVel = velrange[0]
814
827
815 if maxVel == None:
828 if maxVel == None:
816 maxVel = velrange[-1]
829 maxVel = velrange[-1]
817
830
818 if (minVel < velrange[0]) or (minVel > maxVel):
831 if (minVel < velrange[0]) or (minVel > maxVel):
819 print('minVel: %.2f is out of the velocity range' % (minVel))
832 print('minVel: %.2f is out of the velocity range' % (minVel))
820 print('minVel is setting to %.2f' % (velrange[0]))
833 print('minVel is setting to %.2f' % (velrange[0]))
821 minVel = velrange[0]
834 minVel = velrange[0]
822
835
823 if (maxVel > velrange[-1]) or (maxVel < minVel):
836 if (maxVel > velrange[-1]) or (maxVel < minVel):
824 print('maxVel: %.2f is out of the velocity range' % (maxVel))
837 print('maxVel: %.2f is out of the velocity range' % (maxVel))
825 print('maxVel is setting to %.2f' % (velrange[-1]))
838 print('maxVel is setting to %.2f' % (velrange[-1]))
826 maxVel = velrange[-1]
839 maxVel = velrange[-1]
827
840
828 # seleccion de indices para rango
841 # seleccion de indices para rango
829 minIndex = 0
842 minIndex = 0
830 maxIndex = 0
843 maxIndex = 0
831 heights = self.dataOut.heightList
844 heights = self.dataOut.heightList
832
845
833 inda = numpy.where(heights >= minHei)
846 inda = numpy.where(heights >= minHei)
834 indb = numpy.where(heights <= maxHei)
847 indb = numpy.where(heights <= maxHei)
835
848
836 try:
849 try:
837 minIndex = inda[0][0]
850 minIndex = inda[0][0]
838 except:
851 except:
839 minIndex = 0
852 minIndex = 0
840
853
841 try:
854 try:
842 maxIndex = indb[0][-1]
855 maxIndex = indb[0][-1]
843 except:
856 except:
844 maxIndex = len(heights)
857 maxIndex = len(heights)
845
858
846 if (minIndex < 0) or (minIndex > maxIndex):
859 if (minIndex < 0) or (minIndex > maxIndex):
847 raise ValueError("some value in (%d,%d) is not valid" % (
860 raise ValueError("some value in (%d,%d) is not valid" % (
848 minIndex, maxIndex))
861 minIndex, maxIndex))
849
862
850 if (maxIndex >= self.dataOut.nHeights):
863 if (maxIndex >= self.dataOut.nHeights):
851 maxIndex = self.dataOut.nHeights - 1
864 maxIndex = self.dataOut.nHeights - 1
852
865
853 # seleccion de indices para velocidades
866 # seleccion de indices para velocidades
854 indminvel = numpy.where(velrange >= minVel)
867 indminvel = numpy.where(velrange >= minVel)
855 indmaxvel = numpy.where(velrange <= maxVel)
868 indmaxvel = numpy.where(velrange <= maxVel)
856 try:
869 try:
857 minIndexVel = indminvel[0][0]
870 minIndexVel = indminvel[0][0]
858 except:
871 except:
859 minIndexVel = 0
872 minIndexVel = 0
860
873
861 try:
874 try:
862 maxIndexVel = indmaxvel[0][-1]
875 maxIndexVel = indmaxvel[0][-1]
863 except:
876 except:
864 maxIndexVel = len(velrange)
877 maxIndexVel = len(velrange)
865
878
866 # seleccion del espectro
879 # seleccion del espectro
867 data_spc = self.dataOut.data_spc[:,
880 data_spc = self.dataOut.data_spc[:,
868 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
881 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
869 # estimacion de ruido
882 # estimacion de ruido
870 noise = numpy.zeros(self.dataOut.nChannels)
883 noise = numpy.zeros(self.dataOut.nChannels)
871
884
872 for channel in range(self.dataOut.nChannels):
885 for channel in range(self.dataOut.nChannels):
873 daux = data_spc[channel, :, :]
886 daux = data_spc[channel, :, :]
874 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
887 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
875
888
876 self.dataOut.noise_estimation = noise.copy()
889 self.dataOut.noise_estimation = noise.copy()
877
890
878 return 1
891 return 1
879
892
880
893
881 class IncohInt(Operation):
894 class IncohInt(Operation):
882
895
883 __profIndex = 0
896 __profIndex = 0
884 __withOverapping = False
897 __withOverapping = False
885
898
886 __byTime = False
899 __byTime = False
887 __initime = None
900 __initime = None
888 __lastdatatime = None
901 __lastdatatime = None
889 __integrationtime = None
902 __integrationtime = None
890
903
891 __buffer_spc = None
904 __buffer_spc = None
892 __buffer_cspc = None
905 __buffer_cspc = None
893 __buffer_dc = None
906 __buffer_dc = None
894
907
895 __dataReady = False
908 __dataReady = False
896
909
897 __timeInterval = None
910 __timeInterval = None
898
911
899 n = None
912 n = None
900
913
901 def __init__(self):
914 def __init__(self):
902
915
903 Operation.__init__(self)
916 Operation.__init__(self)
904
917
905 def setup(self, n=None, timeInterval=None, overlapping=False):
918 def setup(self, n=None, timeInterval=None, overlapping=False):
906 """
919 """
907 Set the parameters of the integration class.
920 Set the parameters of the integration class.
908
921
909 Inputs:
922 Inputs:
910
923
911 n : Number of coherent integrations
924 n : Number of coherent integrations
912 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
925 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
913 overlapping :
926 overlapping :
914
927
915 """
928 """
916
929
917 self.__initime = None
930 self.__initime = None
918 self.__lastdatatime = 0
931 self.__lastdatatime = 0
919
932
920 self.__buffer_spc = 0
933 self.__buffer_spc = 0
921 self.__buffer_cspc = 0
934 self.__buffer_cspc = 0
922 self.__buffer_dc = 0
935 self.__buffer_dc = 0
923
936
924 self.__profIndex = 0
937 self.__profIndex = 0
925 self.__dataReady = False
938 self.__dataReady = False
926 self.__byTime = False
939 self.__byTime = False
927
940
928 if n is None and timeInterval is None:
941 if n is None and timeInterval is None:
929 raise ValueError("n or timeInterval should be specified ...")
942 raise ValueError("n or timeInterval should be specified ...")
930
943
931 if n is not None:
944 if n is not None:
932 self.n = int(n)
945 self.n = int(n)
933 else:
946 else:
934
947
935 self.__integrationtime = int(timeInterval)
948 self.__integrationtime = int(timeInterval)
936 self.n = None
949 self.n = None
937 self.__byTime = True
950 self.__byTime = True
938
951
939 def putData(self, data_spc, data_cspc, data_dc):
952 def putData(self, data_spc, data_cspc, data_dc):
940 """
953 """
941 Add a profile to the __buffer_spc and increase in one the __profileIndex
954 Add a profile to the __buffer_spc and increase in one the __profileIndex
942
955
943 """
956 """
957 print("profIndex: ",self.__profIndex)
958 print("data_spc.shape: ",data_spc.shape)
959 print("data_spc.shape: ",data_spc[0,0,:])
944
960
945 self.__buffer_spc += data_spc
961 self.__buffer_spc += data_spc
946
962
947 if data_cspc is None:
963 if data_cspc is None:
948 self.__buffer_cspc = None
964 self.__buffer_cspc = None
949 else:
965 else:
950 self.__buffer_cspc += data_cspc
966 self.__buffer_cspc += data_cspc
951
967
952 if data_dc is None:
968 if data_dc is None:
953 self.__buffer_dc = None
969 self.__buffer_dc = None
954 else:
970 else:
955 self.__buffer_dc += data_dc
971 self.__buffer_dc += data_dc
956
972
957 self.__profIndex += 1
973 self.__profIndex += 1
958
974
959 return
975 return
960
976
961 def pushData(self):
977 def pushData(self):
962 """
978 """
963 Return the sum of the last profiles and the profiles used in the sum.
979 Return the sum of the last profiles and the profiles used in the sum.
964
980
965 Affected:
981 Affected:
966
982
967 self.__profileIndex
983 self.__profileIndex
968
984
969 """
985 """
970
986
971 data_spc = self.__buffer_spc
987 data_spc = self.__buffer_spc
972 data_cspc = self.__buffer_cspc
988 data_cspc = self.__buffer_cspc
973 data_dc = self.__buffer_dc
989 data_dc = self.__buffer_dc
974 n = self.__profIndex
990 n = self.__profIndex
975
991
976 self.__buffer_spc = 0
992 self.__buffer_spc = 0
977 self.__buffer_cspc = 0
993 self.__buffer_cspc = 0
978 self.__buffer_dc = 0
994 self.__buffer_dc = 0
979 self.__profIndex = 0
995 self.__profIndex = 0
980
996
981 return data_spc, data_cspc, data_dc, n
997 return data_spc, data_cspc, data_dc, n
982
998
983 def byProfiles(self, *args):
999 def byProfiles(self, *args):
984
1000
985 self.__dataReady = False
1001 self.__dataReady = False
986 avgdata_spc = None
1002 avgdata_spc = None
987 avgdata_cspc = None
1003 avgdata_cspc = None
988 avgdata_dc = None
1004 avgdata_dc = None
989
1005
990 self.putData(*args)
1006 self.putData(*args)
991
1007
992 if self.__profIndex == self.n:
1008 if self.__profIndex == self.n:
993
1009
994 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1010 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
995 self.n = n
1011 self.n = n
996 self.__dataReady = True
1012 self.__dataReady = True
997
1013
998 return avgdata_spc, avgdata_cspc, avgdata_dc
1014 return avgdata_spc, avgdata_cspc, avgdata_dc
999
1015
1000 def byTime(self, datatime, *args):
1016 def byTime(self, datatime, *args):
1001
1017
1002 self.__dataReady = False
1018 self.__dataReady = False
1003 avgdata_spc = None
1019 avgdata_spc = None
1004 avgdata_cspc = None
1020 avgdata_cspc = None
1005 avgdata_dc = None
1021 avgdata_dc = None
1006
1022
1007 self.putData(*args)
1023 self.putData(*args)
1008
1024
1009 if (datatime - self.__initime) >= self.__integrationtime:
1025 if (datatime - self.__initime) >= self.__integrationtime:
1010 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1026 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1011 self.n = n
1027 self.n = n
1012 self.__dataReady = True
1028 self.__dataReady = True
1013
1029
1014 return avgdata_spc, avgdata_cspc, avgdata_dc
1030 return avgdata_spc, avgdata_cspc, avgdata_dc
1015
1031
1016 def integrate(self, datatime, *args):
1032 def integrate(self, datatime, *args):
1017
1033
1018 if self.__profIndex == 0:
1034 if self.__profIndex == 0:
1019 self.__initime = datatime
1035 self.__initime = datatime
1020
1036
1021 if self.__byTime:
1037 if self.__byTime:
1022 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1038 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1023 datatime, *args)
1039 datatime, *args)
1024 else:
1040 else:
1025 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1041 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1026
1042
1027 if not self.__dataReady:
1043 if not self.__dataReady:
1028 return None, None, None, None
1044 return None, None, None, None
1029
1045
1030 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1046 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1031
1047
1032 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1048 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1033 if n == 1:
1049 if n == 1:
1034 return
1050 return
1035
1051
1036 dataOut.flagNoData = True
1052 dataOut.flagNoData = True
1037
1053
1038 if not self.isConfig:
1054 if not self.isConfig:
1039 self.setup(n, timeInterval, overlapping)
1055 self.setup(n, timeInterval, overlapping)
1040 self.isConfig = True
1056 self.isConfig = True
1041
1057
1042 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1058 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1043 dataOut.data_spc,
1059 dataOut.data_spc,
1044 dataOut.data_cspc,
1060 dataOut.data_cspc,
1045 dataOut.data_dc)
1061 dataOut.data_dc)
1046
1062
1047 if self.__dataReady:
1063 if self.__dataReady:
1048
1064
1049 dataOut.data_spc = avgdata_spc
1065 dataOut.data_spc = avgdata_spc
1050 dataOut.data_cspc = avgdata_cspc
1066 dataOut.data_cspc = avgdata_cspc
1051 dataOut.data_dc = avgdata_dc
1067 dataOut.data_dc = avgdata_dc
1052 dataOut.nIncohInt *= self.n
1068 dataOut.nIncohInt *= self.n
1053 dataOut.utctime = avgdatatime
1069 dataOut.utctime = avgdatatime
1054 dataOut.flagNoData = False
1070 dataOut.flagNoData = False
1055
1071
1056 return dataOut No newline at end of file
1072 return dataOut
1073
1074
1075 class PulsePair(Operation):
1076 isConfig = False
1077 __profIndex = 0
1078 __profIndex2 = 0
1079 __initime = None
1080 __lastdatatime = None
1081 __buffer = None
1082 __buffer2 = []
1083 __buffer3 = None
1084 __dataReady = False
1085 n = None
1086
1087 __nch =0
1088 __nProf =0
1089 __nHeis =0
1090
1091 def __init__(self,**kwargs):
1092 Operation.__init__(self,**kwargs)
1093
1094 def setup(self,dataOut,n =None, m = None):
1095
1096 self.__initime = None
1097 self.__lastdatatime = 0
1098 self.__buffer = 0
1099 self.__bufferV = 0
1100 #self.__buffer2 = []
1101 self.__buffer3 = 0
1102 self.__dataReady = False
1103 self.__profIndex = 0
1104 self.__profIndex2 = 0
1105 self.count = 0
1106
1107
1108 self.__nch = dataOut.nChannels
1109 self.__nHeis = dataOut.nHeights
1110 self.__nProf = dataOut.nProfiles
1111 self.__nFFT = dataOut.nFFTPoints
1112 #print("Valores de Ch,Samples,Perfiles,nFFT",self.__nch,self.__nHeis,self.__nProf, self.__nFFT)
1113 #print("EL VALOR DE n es:",n)
1114 if n == None:
1115 raise ValueError("n Should be specified.")
1116
1117 if n != None:
1118 if n<2:
1119 raise ValueError("n Should be greather than 2 ")
1120 self.n = n
1121 if m == None:
1122 m = n
1123 if m != None:
1124 if m<2:
1125 raise ValueError("n Should be greather than 2 ")
1126
1127 self.m = m
1128 self.__buffer2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1129 self.__bufferV2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1130
1131
1132
1133 def putData(self,data):
1134 #print("###################################################")
1135 '''
1136 data_tmp = numpy.zeros(self.__nch,self.n,self.__nHeis, dtype= complex)
1137 if self.count < self.__nProf:
1138
1139 for i in range(self.n):
1140 data_tmp[:,i,:] = data[:,i+self.count,:]
1141
1142 self.__buffer = data_tmp*numpy.conjugate(data_tmp)
1143
1144
1145 #####self.__buffer = data*numpy.conjugate(data)
1146 #####self.__bufferV = data[:,(self.__nProf-1):,:]*numpy.conjugate(data[:,1:,:])
1147
1148 #self.__buffer2.append(numpy.conjugate(data))
1149
1150 #####self.__profIndex = data.shape[1]
1151 self.count = self.count + self.n -1
1152 self.__profIndex = self.n
1153 '''
1154 self.__buffer = data*numpy.conjugate(data)
1155 self.__bufferV = data[:,(self.__nProf-1):,:]*numpy.conjugate(data[:,1:,:])
1156 self.__profIndex = self.n
1157 return
1158
1159 def pushData(self):
1160
1161 data_I = numpy.zeros((self.__nch,self.__nHeis))
1162 data_IV = numpy.zeros((self.__nch,self.__nHeis))
1163
1164 for i in range(self.__nch):
1165 data_I[i,:] = numpy.sum(numpy.sum(self.__buffer[i],axis=0),axis=0)/self.n
1166 data_IV[i,:] = numpy.sum(numpy.sum(self.__bufferV[i],axis=0),axis=0)/(self.n-1)
1167
1168 n = self.__profIndex
1169 ####data_intensity = numpy.sum(numpy.sum(self.__buffer,axis=0),axis=0)/self.n
1170 #print("data_intensity push data",data_intensity.shape)
1171 #data_velocity = self.__buffer3/(self.n-1)
1172 ####n = self.__profIndex
1173
1174 self.__buffer = 0
1175 self.__buffer3 = 0
1176 self.__profIndex = 0
1177
1178 #return data_intensity,data_velocity,n
1179 return data_I,data_IV,n
1180
1181 def pulsePairbyProfiles(self,data):
1182 self.__dataReady = False
1183 data_intensity = None
1184 data_velocity = None
1185
1186 self.putData(data)
1187
1188 if self.__profIndex == self.n:
1189 #data_intensity,data_velocity,n = self.pushData()
1190 data_intensity,data_velocity,n = self.pushData()
1191 #print(data_intensity.shape)
1192 #print("self.__profIndex2", self.__profIndex2)
1193 if self.__profIndex2 == 0:
1194 #print("PRIMERA VEZ")
1195 #print("self.__buffer2",self.__buffer2)
1196 for i in range(self.__nch):
1197 self.__buffer2[i][self.__profIndex2] = data_intensity[i]
1198 self.__bufferV2[i][self.__profIndex2] = data_velocity[i]
1199 self.__profIndex2 += 1
1200 return None,None
1201
1202 if self.__profIndex2 > 0:
1203 for i in range(self.__nch):
1204 self.__buffer2[i][self.__profIndex2] = data_intensity[i]
1205 self.__bufferV2[i][self.__profIndex2] = data_velocity[i]
1206 #print("Dentro del bucle",self.__buffer2)
1207 self.__profIndex2 += 1
1208 if self.__profIndex2 == self.m :
1209 data_i = self.__buffer2
1210 data_v = self.__bufferV2
1211 #print(data_i.shape)
1212 self.__dataReady = True
1213 self.__profIndex2 = 0
1214 self.__buffer2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1215 self.__bufferV2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1216 return data_i,data_v
1217 return None,None
1218
1219 def pulsePairOp(self,data,datatime=None):
1220 if self.__initime == None:
1221 self.__initime = datatime
1222
1223 data_intensity,data_velocity = self.pulsePairbyProfiles(data)
1224 self.__lastdatatime = datatime
1225
1226 if data_intensity is None:
1227 return None,None,None
1228
1229 avgdatatime = self.__initime
1230 self.__initime = datatime
1231
1232 return data_intensity,data_velocity,avgdatatime
1233
1234 def run(self,dataOut,n =None,m=None):
1235
1236 if not self.isConfig:
1237 self.setup(dataOut = dataOut, n = n, m = m)
1238 self.isConfig = True
1239
1240 data_intensity,data_velocity,avgdatatime = self.pulsePairOp(dataOut.data_wr,dataOut.utctime)
1241 dataOut.flagNoData = True
1242
1243 if self.__dataReady:
1244 #print(" DATA " , data_intensity.shape)
1245 #dataOut.data = numpy.array([data_intensity])#aqui amigo revisa
1246 #tmp = numpy.zeros([1,data_intensity.shape[0],data_intensity.shape[1]])
1247 #tmp[0] = data_intensity
1248 dataOut.data = data_intensity
1249 dataOut.data_velocity = data_velocity
1250 #dataOut.data = tmp
1251 #print(" DATA " , dataOut.data.shape)
1252 dataOut.nIncohInt *= self.n
1253 dataOut.nProfiles = self.m
1254 dataOut.nFFTPoints = self.m
1255 #dataOut.data_intensity = data_intensity
1256 dataOut.PRFbyAngle = self.n
1257 dataOut.utctime = avgdatatime
1258 dataOut.flagNoData = False
1259 #####print("TIEMPO: ",dataOut.utctime)
1260 return dataOut
@@ -1,1328 +1,1623
1 import sys
1 import sys
2 import numpy
2 import numpy
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 @MPDecorator
10 @MPDecorator
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 # self.dataOut.copy(self.dataIn)
29 # self.dataOut.copy(self.dataIn)
30
30
31 def __updateObjFromAmisrInput(self):
31 def __updateObjFromAmisrInput(self):
32
32
33 self.dataOut.timeZone = self.dataIn.timeZone
33 self.dataOut.timeZone = self.dataIn.timeZone
34 self.dataOut.dstFlag = self.dataIn.dstFlag
34 self.dataOut.dstFlag = self.dataIn.dstFlag
35 self.dataOut.errorCount = self.dataIn.errorCount
35 self.dataOut.errorCount = self.dataIn.errorCount
36 self.dataOut.useLocalTime = self.dataIn.useLocalTime
36 self.dataOut.useLocalTime = self.dataIn.useLocalTime
37
37
38 self.dataOut.flagNoData = self.dataIn.flagNoData
38 self.dataOut.flagNoData = self.dataIn.flagNoData
39 self.dataOut.data = self.dataIn.data
39 self.dataOut.data = self.dataIn.data
40 self.dataOut.utctime = self.dataIn.utctime
40 self.dataOut.utctime = self.dataIn.utctime
41 self.dataOut.channelList = self.dataIn.channelList
41 self.dataOut.channelList = self.dataIn.channelList
42 #self.dataOut.timeInterval = self.dataIn.timeInterval
42 #self.dataOut.timeInterval = self.dataIn.timeInterval
43 self.dataOut.heightList = self.dataIn.heightList
43 self.dataOut.heightList = self.dataIn.heightList
44 self.dataOut.nProfiles = self.dataIn.nProfiles
44 self.dataOut.nProfiles = self.dataIn.nProfiles
45
45
46 self.dataOut.nCohInt = self.dataIn.nCohInt
46 self.dataOut.nCohInt = self.dataIn.nCohInt
47 self.dataOut.ippSeconds = self.dataIn.ippSeconds
47 self.dataOut.ippSeconds = self.dataIn.ippSeconds
48 self.dataOut.frequency = self.dataIn.frequency
48 self.dataOut.frequency = self.dataIn.frequency
49
49
50 self.dataOut.azimuth = self.dataIn.azimuth
50 self.dataOut.azimuth = self.dataIn.azimuth
51 self.dataOut.zenith = self.dataIn.zenith
51 self.dataOut.zenith = self.dataIn.zenith
52
52
53 self.dataOut.beam.codeList = self.dataIn.beam.codeList
53 self.dataOut.beam.codeList = self.dataIn.beam.codeList
54 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
54 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
55 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
55 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
56 #
56 #
57 # pass#
57 # pass#
58 #
58 #
59 # def init(self):
59 # def init(self):
60 #
60 #
61 #
61 #
62 # if self.dataIn.type == 'AMISR':
62 # if self.dataIn.type == 'AMISR':
63 # self.__updateObjFromAmisrInput()
63 # self.__updateObjFromAmisrInput()
64 #
64 #
65 # if self.dataIn.type == 'Voltage':
65 # if self.dataIn.type == 'Voltage':
66 # self.dataOut.copy(self.dataIn)
66 # self.dataOut.copy(self.dataIn)
67 # # No necesita copiar en cada init() los atributos de dataIn
67 # # No necesita copiar en cada init() los atributos de dataIn
68 # # la copia deberia hacerse por cada nuevo bloque de datos
68 # # la copia deberia hacerse por cada nuevo bloque de datos
69
69
70 def selectChannels(self, channelList):
70 def selectChannels(self, channelList):
71
71
72 channelIndexList = []
72 channelIndexList = []
73
73
74 for channel in channelList:
74 for channel in channelList:
75 if channel not in self.dataOut.channelList:
75 if channel not in self.dataOut.channelList:
76 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
76 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
77
77
78 index = self.dataOut.channelList.index(channel)
78 index = self.dataOut.channelList.index(channel)
79 channelIndexList.append(index)
79 channelIndexList.append(index)
80
80
81 self.selectChannelsByIndex(channelIndexList)
81 self.selectChannelsByIndex(channelIndexList)
82
82
83 def selectChannelsByIndex(self, channelIndexList):
83 def selectChannelsByIndex(self, channelIndexList):
84 """
84 """
85 Selecciona un bloque de datos en base a canales segun el channelIndexList
85 Selecciona un bloque de datos en base a canales segun el channelIndexList
86
86
87 Input:
87 Input:
88 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
88 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
89
89
90 Affected:
90 Affected:
91 self.dataOut.data
91 self.dataOut.data
92 self.dataOut.channelIndexList
92 self.dataOut.channelIndexList
93 self.dataOut.nChannels
93 self.dataOut.nChannels
94 self.dataOut.m_ProcessingHeader.totalSpectra
94 self.dataOut.m_ProcessingHeader.totalSpectra
95 self.dataOut.systemHeaderObj.numChannels
95 self.dataOut.systemHeaderObj.numChannels
96 self.dataOut.m_ProcessingHeader.blockSize
96 self.dataOut.m_ProcessingHeader.blockSize
97
97
98 Return:
98 Return:
99 None
99 None
100 """
100 """
101
101
102 for channelIndex in channelIndexList:
102 for channelIndex in channelIndexList:
103 if channelIndex not in self.dataOut.channelIndexList:
103 if channelIndex not in self.dataOut.channelIndexList:
104 print(channelIndexList)
104 print(channelIndexList)
105 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
105 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
106
106
107 if self.dataOut.flagDataAsBlock:
107 if self.dataOut.flagDataAsBlock:
108 """
108 """
109 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
109 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
110 """
110 """
111 data = self.dataOut.data[channelIndexList,:,:]
111 data = self.dataOut.data[channelIndexList,:,:]
112 else:
112 else:
113 data = self.dataOut.data[channelIndexList,:]
113 data = self.dataOut.data[channelIndexList,:]
114
114
115 self.dataOut.data = data
115 self.dataOut.data = data
116 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
116 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
117 self.dataOut.channelList = range(len(channelIndexList))
117 self.dataOut.channelList = range(len(channelIndexList))
118
118
119 return 1
119 return 1
120
120
121 def selectHeights(self, minHei=None, maxHei=None):
121 def selectHeights(self, minHei=None, maxHei=None):
122 """
122 """
123 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
123 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
124 minHei <= height <= maxHei
124 minHei <= height <= maxHei
125
125
126 Input:
126 Input:
127 minHei : valor minimo de altura a considerar
127 minHei : valor minimo de altura a considerar
128 maxHei : valor maximo de altura a considerar
128 maxHei : valor maximo de altura a considerar
129
129
130 Affected:
130 Affected:
131 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
131 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
132
132
133 Return:
133 Return:
134 1 si el metodo se ejecuto con exito caso contrario devuelve 0
134 1 si el metodo se ejecuto con exito caso contrario devuelve 0
135 """
135 """
136
136
137 if minHei == None:
137 if minHei == None:
138 minHei = self.dataOut.heightList[0]
138 minHei = self.dataOut.heightList[0]
139
139
140 if maxHei == None:
140 if maxHei == None:
141 maxHei = self.dataOut.heightList[-1]
141 maxHei = self.dataOut.heightList[-1]
142
142
143 if (minHei < self.dataOut.heightList[0]):
143 if (minHei < self.dataOut.heightList[0]):
144 minHei = self.dataOut.heightList[0]
144 minHei = self.dataOut.heightList[0]
145
145
146 if (maxHei > self.dataOut.heightList[-1]):
146 if (maxHei > self.dataOut.heightList[-1]):
147 maxHei = self.dataOut.heightList[-1]
147 maxHei = self.dataOut.heightList[-1]
148
148
149 minIndex = 0
149 minIndex = 0
150 maxIndex = 0
150 maxIndex = 0
151 heights = self.dataOut.heightList
151 heights = self.dataOut.heightList
152
152
153 inda = numpy.where(heights >= minHei)
153 inda = numpy.where(heights >= minHei)
154 indb = numpy.where(heights <= maxHei)
154 indb = numpy.where(heights <= maxHei)
155
155
156 try:
156 try:
157 minIndex = inda[0][0]
157 minIndex = inda[0][0]
158 except:
158 except:
159 minIndex = 0
159 minIndex = 0
160
160
161 try:
161 try:
162 maxIndex = indb[0][-1]
162 maxIndex = indb[0][-1]
163 except:
163 except:
164 maxIndex = len(heights)
164 maxIndex = len(heights)
165
165
166 self.selectHeightsByIndex(minIndex, maxIndex)
166 self.selectHeightsByIndex(minIndex, maxIndex)
167
167
168 return 1
168 return 1
169
169
170
170
171 def selectHeightsByIndex(self, minIndex, maxIndex):
171 def selectHeightsByIndex(self, minIndex, maxIndex):
172 """
172 """
173 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
173 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
174 minIndex <= index <= maxIndex
174 minIndex <= index <= maxIndex
175
175
176 Input:
176 Input:
177 minIndex : valor de indice minimo de altura a considerar
177 minIndex : valor de indice minimo de altura a considerar
178 maxIndex : valor de indice maximo de altura a considerar
178 maxIndex : valor de indice maximo de altura a considerar
179
179
180 Affected:
180 Affected:
181 self.dataOut.data
181 self.dataOut.data
182 self.dataOut.heightList
182 self.dataOut.heightList
183
183
184 Return:
184 Return:
185 1 si el metodo se ejecuto con exito caso contrario devuelve 0
185 1 si el metodo se ejecuto con exito caso contrario devuelve 0
186 """
186 """
187
187
188 if (minIndex < 0) or (minIndex > maxIndex):
188 if (minIndex < 0) or (minIndex > maxIndex):
189 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
189 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
190
190
191 if (maxIndex >= self.dataOut.nHeights):
191 if (maxIndex >= self.dataOut.nHeights):
192 maxIndex = self.dataOut.nHeights
192 maxIndex = self.dataOut.nHeights
193
193
194 #voltage
194 #voltage
195 if self.dataOut.flagDataAsBlock:
195 if self.dataOut.flagDataAsBlock:
196 """
196 """
197 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
197 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
198 """
198 """
199 data = self.dataOut.data[:,:, minIndex:maxIndex]
199 data = self.dataOut.data[:,:, minIndex:maxIndex]
200 else:
200 else:
201 data = self.dataOut.data[:, minIndex:maxIndex]
201 data = self.dataOut.data[:, minIndex:maxIndex]
202
202
203 # firstHeight = self.dataOut.heightList[minIndex]
203 # firstHeight = self.dataOut.heightList[minIndex]
204
204
205 self.dataOut.data = data
205 self.dataOut.data = data
206 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
206 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
207
207
208 if self.dataOut.nHeights <= 1:
208 if self.dataOut.nHeights <= 1:
209 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
209 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
210
210
211 return 1
211 return 1
212
212
213
213
214 def filterByHeights(self, window):
214 def filterByHeights(self, window):
215
215
216 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
216 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
217
217
218 if window == None:
218 if window == None:
219 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
219 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
220
220
221 newdelta = deltaHeight * window
221 newdelta = deltaHeight * window
222 r = self.dataOut.nHeights % window
222 r = self.dataOut.nHeights % window
223 newheights = (self.dataOut.nHeights-r)/window
223 newheights = (self.dataOut.nHeights-r)/window
224
224
225 if newheights <= 1:
225 if newheights <= 1:
226 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window))
226 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window))
227
227
228 if self.dataOut.flagDataAsBlock:
228 if self.dataOut.flagDataAsBlock:
229 """
229 """
230 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
230 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
231 """
231 """
232 buffer = self.dataOut.data[:, :, 0:int(self.dataOut.nHeights-r)]
232 buffer = self.dataOut.data[:, :, 0:int(self.dataOut.nHeights-r)]
233 buffer = buffer.reshape(self.dataOut.nChannels, self.dataOut.nProfiles, int(self.dataOut.nHeights/window), window)
233 buffer = buffer.reshape(self.dataOut.nChannels, self.dataOut.nProfiles, int(self.dataOut.nHeights/window), window)
234 buffer = numpy.sum(buffer,3)
234 buffer = numpy.sum(buffer,3)
235
235
236 else:
236 else:
237 buffer = self.dataOut.data[:,0:int(self.dataOut.nHeights-r)]
237 buffer = self.dataOut.data[:,0:int(self.dataOut.nHeights-r)]
238 buffer = buffer.reshape(self.dataOut.nChannels,int(self.dataOut.nHeights/window),int(window))
238 buffer = buffer.reshape(self.dataOut.nChannels,int(self.dataOut.nHeights/window),int(window))
239 buffer = numpy.sum(buffer,2)
239 buffer = numpy.sum(buffer,2)
240
240
241 self.dataOut.data = buffer
241 self.dataOut.data = buffer
242 self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta
242 self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta
243 self.dataOut.windowOfFilter = window
243 self.dataOut.windowOfFilter = window
244
244
245 def setH0(self, h0, deltaHeight = None):
245 def setH0(self, h0, deltaHeight = None):
246
246
247 if not deltaHeight:
247 if not deltaHeight:
248 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
248 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
249
249
250 nHeights = self.dataOut.nHeights
250 nHeights = self.dataOut.nHeights
251
251
252 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
252 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
253
253
254 self.dataOut.heightList = newHeiRange
254 self.dataOut.heightList = newHeiRange
255
255
256 def deFlip(self, channelList = []):
256 def deFlip(self, channelList = []):
257
257
258 data = self.dataOut.data.copy()
258 data = self.dataOut.data.copy()
259
259
260 if self.dataOut.flagDataAsBlock:
260 if self.dataOut.flagDataAsBlock:
261 flip = self.flip
261 flip = self.flip
262 profileList = list(range(self.dataOut.nProfiles))
262 profileList = list(range(self.dataOut.nProfiles))
263
263
264 if not channelList:
264 if not channelList:
265 for thisProfile in profileList:
265 for thisProfile in profileList:
266 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
266 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
267 flip *= -1.0
267 flip *= -1.0
268 else:
268 else:
269 for thisChannel in channelList:
269 for thisChannel in channelList:
270 if thisChannel not in self.dataOut.channelList:
270 if thisChannel not in self.dataOut.channelList:
271 continue
271 continue
272
272
273 for thisProfile in profileList:
273 for thisProfile in profileList:
274 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
274 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
275 flip *= -1.0
275 flip *= -1.0
276
276
277 self.flip = flip
277 self.flip = flip
278
278
279 else:
279 else:
280 if not channelList:
280 if not channelList:
281 data[:,:] = data[:,:]*self.flip
281 data[:,:] = data[:,:]*self.flip
282 else:
282 else:
283 for thisChannel in channelList:
283 for thisChannel in channelList:
284 if thisChannel not in self.dataOut.channelList:
284 if thisChannel not in self.dataOut.channelList:
285 continue
285 continue
286
286
287 data[thisChannel,:] = data[thisChannel,:]*self.flip
287 data[thisChannel,:] = data[thisChannel,:]*self.flip
288
288
289 self.flip *= -1.
289 self.flip *= -1.
290
290
291 self.dataOut.data = data
291 self.dataOut.data = data
292
292
293 def setRadarFrequency(self, frequency=None):
293 def setRadarFrequency(self, frequency=None):
294
294
295 if frequency != None:
295 if frequency != None:
296 self.dataOut.frequency = frequency
296 self.dataOut.frequency = frequency
297
297
298 return 1
298 return 1
299
299
300 def interpolateHeights(self, topLim, botLim):
300 def interpolateHeights(self, topLim, botLim):
301 #69 al 72 para julia
301 #69 al 72 para julia
302 #82-84 para meteoros
302 #82-84 para meteoros
303 if len(numpy.shape(self.dataOut.data))==2:
303 if len(numpy.shape(self.dataOut.data))==2:
304 sampInterp = (self.dataOut.data[:,botLim-1] + self.dataOut.data[:,topLim+1])/2
304 sampInterp = (self.dataOut.data[:,botLim-1] + self.dataOut.data[:,topLim+1])/2
305 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
305 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
306 #self.dataOut.data[:,botLim:limSup+1] = sampInterp
306 #self.dataOut.data[:,botLim:limSup+1] = sampInterp
307 self.dataOut.data[:,botLim:topLim+1] = sampInterp
307 self.dataOut.data[:,botLim:topLim+1] = sampInterp
308 else:
308 else:
309 nHeights = self.dataOut.data.shape[2]
309 nHeights = self.dataOut.data.shape[2]
310 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
310 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
311 y = self.dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
311 y = self.dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
312 f = interpolate.interp1d(x, y, axis = 2)
312 f = interpolate.interp1d(x, y, axis = 2)
313 xnew = numpy.arange(botLim,topLim+1)
313 xnew = numpy.arange(botLim,topLim+1)
314 ynew = f(xnew)
314 ynew = f(xnew)
315
315
316 self.dataOut.data[:,:,botLim:topLim+1] = ynew
316 self.dataOut.data[:,:,botLim:topLim+1] = ynew
317
317
318 # import collections
318 # import collections
319
319
320 class CohInt(Operation):
320 class CohInt(Operation):
321
321
322 isConfig = False
322 isConfig = False
323 __profIndex = 0
323 __profIndex = 0
324 __byTime = False
324 __byTime = False
325 __initime = None
325 __initime = None
326 __lastdatatime = None
326 __lastdatatime = None
327 __integrationtime = None
327 __integrationtime = None
328 __buffer = None
328 __buffer = None
329 __bufferStride = []
329 __bufferStride = []
330 __dataReady = False
330 __dataReady = False
331 __profIndexStride = 0
331 __profIndexStride = 0
332 __dataToPutStride = False
332 __dataToPutStride = False
333 n = None
333 n = None
334
334
335 def __init__(self, **kwargs):
335 def __init__(self, **kwargs):
336
336
337 Operation.__init__(self, **kwargs)
337 Operation.__init__(self, **kwargs)
338
338
339 # self.isConfig = False
339 # self.isConfig = False
340
340
341 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
341 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
342 """
342 """
343 Set the parameters of the integration class.
343 Set the parameters of the integration class.
344
344
345 Inputs:
345 Inputs:
346
346
347 n : Number of coherent integrations
347 n : Number of coherent integrations
348 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
348 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
349 overlapping :
349 overlapping :
350 """
350 """
351
351
352 self.__initime = None
352 self.__initime = None
353 self.__lastdatatime = 0
353 self.__lastdatatime = 0
354 self.__buffer = None
354 self.__buffer = None
355 self.__dataReady = False
355 self.__dataReady = False
356 self.byblock = byblock
356 self.byblock = byblock
357 self.stride = stride
357 self.stride = stride
358
358
359 if n == None and timeInterval == None:
359 if n == None and timeInterval == None:
360 raise ValueError("n or timeInterval should be specified ...")
360 raise ValueError("n or timeInterval should be specified ...")
361
361
362 if n != None:
362 if n != None:
363 self.n = n
363 self.n = n
364 self.__byTime = False
364 self.__byTime = False
365 else:
365 else:
366 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
366 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
367 self.n = 9999
367 self.n = 9999
368 self.__byTime = True
368 self.__byTime = True
369
369
370 if overlapping:
370 if overlapping:
371 self.__withOverlapping = True
371 self.__withOverlapping = True
372 self.__buffer = None
372 self.__buffer = None
373 else:
373 else:
374 self.__withOverlapping = False
374 self.__withOverlapping = False
375 self.__buffer = 0
375 self.__buffer = 0
376
376
377 self.__profIndex = 0
377 self.__profIndex = 0
378
378
379 def putData(self, data):
379 def putData(self, data):
380
380
381 """
381 """
382 Add a profile to the __buffer and increase in one the __profileIndex
382 Add a profile to the __buffer and increase in one the __profileIndex
383
383
384 """
384 """
385
385
386 if not self.__withOverlapping:
386 if not self.__withOverlapping:
387 print("inside over")
387 self.__buffer += data.copy()
388 self.__buffer += data.copy()
388 self.__profIndex += 1
389 self.__profIndex += 1
389 return
390 return
390
391
391 #Overlapping data
392 #Overlapping data
392 nChannels, nHeis = data.shape
393 nChannels, nHeis = data.shape
394 print("show me the light",data.shape)
393 data = numpy.reshape(data, (1, nChannels, nHeis))
395 data = numpy.reshape(data, (1, nChannels, nHeis))
394
396 print(data.shape)
395 #If the buffer is empty then it takes the data value
397 #If the buffer is empty then it takes the data value
396 if self.__buffer is None:
398 if self.__buffer is None:
397 self.__buffer = data
399 self.__buffer = data
398 self.__profIndex += 1
400 self.__profIndex += 1
399 return
401 return
400
402
401 #If the buffer length is lower than n then stakcing the data value
403 #If the buffer length is lower than n then stakcing the data value
402 if self.__profIndex < self.n:
404 if self.__profIndex < self.n:
403 self.__buffer = numpy.vstack((self.__buffer, data))
405 self.__buffer = numpy.vstack((self.__buffer, data))
404 self.__profIndex += 1
406 self.__profIndex += 1
405 return
407 return
406
408
407 #If the buffer length is equal to n then replacing the last buffer value with the data value
409 #If the buffer length is equal to n then replacing the last buffer value with the data value
408 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
410 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
409 self.__buffer[self.n-1] = data
411 self.__buffer[self.n-1] = data
410 self.__profIndex = self.n
412 self.__profIndex = self.n
411 return
413 return
412
414
413
415
414 def pushData(self):
416 def pushData(self):
415 """
417 """
416 Return the sum of the last profiles and the profiles used in the sum.
418 Return the sum of the last profiles and the profiles used in the sum.
417
419
418 Affected:
420 Affected:
419
421
420 self.__profileIndex
422 self.__profileIndex
421
423
422 """
424 """
423
425
424 if not self.__withOverlapping:
426 if not self.__withOverlapping:
427 #print("ahora que fue")
425 data = self.__buffer
428 data = self.__buffer
426 n = self.__profIndex
429 n = self.__profIndex
427
430
428 self.__buffer = 0
431 self.__buffer = 0
429 self.__profIndex = 0
432 self.__profIndex = 0
430
433
431 return data, n
434 return data, n
432
435
436 #print("cual funciona")
433 #Integration with Overlapping
437 #Integration with Overlapping
434 data = numpy.sum(self.__buffer, axis=0)
438 data = numpy.sum(self.__buffer, axis=0)
435 # print data
439 # print data
436 # raise
440 # raise
437 n = self.__profIndex
441 n = self.__profIndex
438
442
439 return data, n
443 return data, n
440
444
441 def byProfiles(self, data):
445 def byProfiles(self, data):
442
446
443 self.__dataReady = False
447 self.__dataReady = False
444 avgdata = None
448 avgdata = None
445 # n = None
449 # n = None
446 # print data
450 # print data
447 # raise
451 # raise
452 #print("beforeputdata")
448 self.putData(data)
453 self.putData(data)
449
454
450 if self.__profIndex == self.n:
455 if self.__profIndex == self.n:
451 avgdata, n = self.pushData()
456 avgdata, n = self.pushData()
452 self.__dataReady = True
457 self.__dataReady = True
453
458
454 return avgdata
459 return avgdata
455
460
456 def byTime(self, data, datatime):
461 def byTime(self, data, datatime):
457
462
458 self.__dataReady = False
463 self.__dataReady = False
459 avgdata = None
464 avgdata = None
460 n = None
465 n = None
461
466
462 self.putData(data)
467 self.putData(data)
463
468
464 if (datatime - self.__initime) >= self.__integrationtime:
469 if (datatime - self.__initime) >= self.__integrationtime:
465 avgdata, n = self.pushData()
470 avgdata, n = self.pushData()
466 self.n = n
471 self.n = n
467 self.__dataReady = True
472 self.__dataReady = True
468
473
469 return avgdata
474 return avgdata
470
475
471 def integrateByStride(self, data, datatime):
476 def integrateByStride(self, data, datatime):
472 # print data
477 # print data
473 if self.__profIndex == 0:
478 if self.__profIndex == 0:
474 self.__buffer = [[data.copy(), datatime]]
479 self.__buffer = [[data.copy(), datatime]]
475 else:
480 else:
476 self.__buffer.append([data.copy(),datatime])
481 self.__buffer.append([data.copy(),datatime])
477 self.__profIndex += 1
482 self.__profIndex += 1
478 self.__dataReady = False
483 self.__dataReady = False
479
484
480 if self.__profIndex == self.n * self.stride :
485 if self.__profIndex == self.n * self.stride :
481 self.__dataToPutStride = True
486 self.__dataToPutStride = True
482 self.__profIndexStride = 0
487 self.__profIndexStride = 0
483 self.__profIndex = 0
488 self.__profIndex = 0
484 self.__bufferStride = []
489 self.__bufferStride = []
485 for i in range(self.stride):
490 for i in range(self.stride):
486 current = self.__buffer[i::self.stride]
491 current = self.__buffer[i::self.stride]
487 data = numpy.sum([t[0] for t in current], axis=0)
492 data = numpy.sum([t[0] for t in current], axis=0)
488 avgdatatime = numpy.average([t[1] for t in current])
493 avgdatatime = numpy.average([t[1] for t in current])
489 # print data
494 # print data
490 self.__bufferStride.append((data, avgdatatime))
495 self.__bufferStride.append((data, avgdatatime))
491
496
492 if self.__dataToPutStride:
497 if self.__dataToPutStride:
493 self.__dataReady = True
498 self.__dataReady = True
494 self.__profIndexStride += 1
499 self.__profIndexStride += 1
495 if self.__profIndexStride == self.stride:
500 if self.__profIndexStride == self.stride:
496 self.__dataToPutStride = False
501 self.__dataToPutStride = False
497 # print self.__bufferStride[self.__profIndexStride - 1]
502 # print self.__bufferStride[self.__profIndexStride - 1]
498 # raise
503 # raise
499 return self.__bufferStride[self.__profIndexStride - 1]
504 return self.__bufferStride[self.__profIndexStride - 1]
500
505
501
506
502 return None, None
507 return None, None
503
508
504 def integrate(self, data, datatime=None):
509 def integrate(self, data, datatime=None):
505
510
506 if self.__initime == None:
511 if self.__initime == None:
507 self.__initime = datatime
512 self.__initime = datatime
508
513
509 if self.__byTime:
514 if self.__byTime:
510 avgdata = self.byTime(data, datatime)
515 avgdata = self.byTime(data, datatime)
511 else:
516 else:
512 avgdata = self.byProfiles(data)
517 avgdata = self.byProfiles(data)
513
518
514
519
515 self.__lastdatatime = datatime
520 self.__lastdatatime = datatime
516
521
517 if avgdata is None:
522 if avgdata is None:
518 return None, None
523 return None, None
519
524
520 avgdatatime = self.__initime
525 avgdatatime = self.__initime
521
526
522 deltatime = datatime - self.__lastdatatime
527 deltatime = datatime - self.__lastdatatime
523
528
524 if not self.__withOverlapping:
529 if not self.__withOverlapping:
525 self.__initime = datatime
530 self.__initime = datatime
526 else:
531 else:
527 self.__initime += deltatime
532 self.__initime += deltatime
528
533
529 return avgdata, avgdatatime
534 return avgdata, avgdatatime
530
535
531 def integrateByBlock(self, dataOut):
536 def integrateByBlock(self, dataOut):
532
537
533 times = int(dataOut.data.shape[1]/self.n)
538 times = int(dataOut.data.shape[1]/self.n)
534 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
539 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
535
540
536 id_min = 0
541 id_min = 0
537 id_max = self.n
542 id_max = self.n
538
543
539 for i in range(times):
544 for i in range(times):
540 junk = dataOut.data[:,id_min:id_max,:]
545 junk = dataOut.data[:,id_min:id_max,:]
541 avgdata[:,i,:] = junk.sum(axis=1)
546 avgdata[:,i,:] = junk.sum(axis=1)
542 id_min += self.n
547 id_min += self.n
543 id_max += self.n
548 id_max += self.n
544
549
545 timeInterval = dataOut.ippSeconds*self.n
550 timeInterval = dataOut.ippSeconds*self.n
546 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
551 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
547 self.__dataReady = True
552 self.__dataReady = True
548 return avgdata, avgdatatime
553 return avgdata, avgdatatime
549
554
550 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
555 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
551
556
552 if not self.isConfig:
557 if not self.isConfig:
553 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
558 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
554 self.isConfig = True
559 self.isConfig = True
555
560
556 if dataOut.flagDataAsBlock:
561 if dataOut.flagDataAsBlock:
557 """
562 """
558 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
563 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
559 """
564 """
560 avgdata, avgdatatime = self.integrateByBlock(dataOut)
565 avgdata, avgdatatime = self.integrateByBlock(dataOut)
561 dataOut.nProfiles /= self.n
566 dataOut.nProfiles /= self.n
562 else:
567 else:
563 if stride is None:
568 if stride is None:
564 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
569 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
565 else:
570 else:
566 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
571 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
567
572
568
573
569 # dataOut.timeInterval *= n
574 # dataOut.timeInterval *= n
570 dataOut.flagNoData = True
575 dataOut.flagNoData = True
571
576
572 if self.__dataReady:
577 if self.__dataReady:
573 dataOut.data = avgdata
578 dataOut.data = avgdata
574 dataOut.nCohInt *= self.n
579 dataOut.nCohInt *= self.n
575 dataOut.utctime = avgdatatime
580 dataOut.utctime = avgdatatime
576 # print avgdata, avgdatatime
581 # print avgdata, avgdatatime
577 # raise
582 # raise
578 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
583 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
579 dataOut.flagNoData = False
584 dataOut.flagNoData = False
580 return dataOut
585 return dataOut
581
586
582 class Decoder(Operation):
587 class Decoder(Operation):
583
588
584 isConfig = False
589 isConfig = False
585 __profIndex = 0
590 __profIndex = 0
586
591
587 code = None
592 code = None
588
593
589 nCode = None
594 nCode = None
590 nBaud = None
595 nBaud = None
591
596
592 def __init__(self, **kwargs):
597 def __init__(self, **kwargs):
593
598
594 Operation.__init__(self, **kwargs)
599 Operation.__init__(self, **kwargs)
595
600
596 self.times = None
601 self.times = None
597 self.osamp = None
602 self.osamp = None
598 # self.__setValues = False
603 # self.__setValues = False
599 self.isConfig = False
604 self.isConfig = False
600 self.setupReq = False
605 self.setupReq = False
601 def setup(self, code, osamp, dataOut):
606 def setup(self, code, osamp, dataOut):
602
607
603 self.__profIndex = 0
608 self.__profIndex = 0
604
609
605 self.code = code
610 self.code = code
606
611
607 self.nCode = len(code)
612 self.nCode = len(code)
608 self.nBaud = len(code[0])
613 self.nBaud = len(code[0])
609
614
610 if (osamp != None) and (osamp >1):
615 if (osamp != None) and (osamp >1):
611 self.osamp = osamp
616 self.osamp = osamp
612 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
617 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
613 self.nBaud = self.nBaud*self.osamp
618 self.nBaud = self.nBaud*self.osamp
614
619
615 self.__nChannels = dataOut.nChannels
620 self.__nChannels = dataOut.nChannels
616 self.__nProfiles = dataOut.nProfiles
621 self.__nProfiles = dataOut.nProfiles
617 self.__nHeis = dataOut.nHeights
622 self.__nHeis = dataOut.nHeights
618
623
619 if self.__nHeis < self.nBaud:
624 if self.__nHeis < self.nBaud:
620 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
625 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
621
626
622 #Frequency
627 #Frequency
623 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
628 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
624
629
625 __codeBuffer[:,0:self.nBaud] = self.code
630 __codeBuffer[:,0:self.nBaud] = self.code
626
631
627 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
632 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
628
633
629 if dataOut.flagDataAsBlock:
634 if dataOut.flagDataAsBlock:
630
635
631 self.ndatadec = self.__nHeis #- self.nBaud + 1
636 self.ndatadec = self.__nHeis #- self.nBaud + 1
632
637
633 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
638 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
634
639
635 else:
640 else:
636
641
637 #Time
642 #Time
638 self.ndatadec = self.__nHeis #- self.nBaud + 1
643 self.ndatadec = self.__nHeis #- self.nBaud + 1
639
644
640 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
645 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
641
646
642 def __convolutionInFreq(self, data):
647 def __convolutionInFreq(self, data):
643
648
644 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
649 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
645
650
646 fft_data = numpy.fft.fft(data, axis=1)
651 fft_data = numpy.fft.fft(data, axis=1)
647
652
648 conv = fft_data*fft_code
653 conv = fft_data*fft_code
649
654
650 data = numpy.fft.ifft(conv,axis=1)
655 data = numpy.fft.ifft(conv,axis=1)
651
656
652 return data
657 return data
653
658
654 def __convolutionInFreqOpt(self, data):
659 def __convolutionInFreqOpt(self, data):
655
660
656 raise NotImplementedError
661 raise NotImplementedError
657
662
658 def __convolutionInTime(self, data):
663 def __convolutionInTime(self, data):
659
664
660 code = self.code[self.__profIndex]
665 code = self.code[self.__profIndex]
661 for i in range(self.__nChannels):
666 for i in range(self.__nChannels):
662 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
667 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
663
668
664 return self.datadecTime
669 return self.datadecTime
665
670
666 def __convolutionByBlockInTime(self, data):
671 def __convolutionByBlockInTime(self, data):
667
672
668 repetitions = int(self.__nProfiles / self.nCode)
673 repetitions = int(self.__nProfiles / self.nCode)
669 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
674 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
670 junk = junk.flatten()
675 junk = junk.flatten()
671 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
676 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
672 profilesList = range(self.__nProfiles)
677 profilesList = range(self.__nProfiles)
673
678
674 for i in range(self.__nChannels):
679 for i in range(self.__nChannels):
675 for j in profilesList:
680 for j in profilesList:
676 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
681 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
677 return self.datadecTime
682 return self.datadecTime
678
683
679 def __convolutionByBlockInFreq(self, data):
684 def __convolutionByBlockInFreq(self, data):
680
685
681 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
686 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
682
687
683
688
684 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
689 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
685
690
686 fft_data = numpy.fft.fft(data, axis=2)
691 fft_data = numpy.fft.fft(data, axis=2)
687
692
688 conv = fft_data*fft_code
693 conv = fft_data*fft_code
689
694
690 data = numpy.fft.ifft(conv,axis=2)
695 data = numpy.fft.ifft(conv,axis=2)
691
696
692 return data
697 return data
693
698
694
699
695 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
700 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
696
701
697 if dataOut.flagDecodeData:
702 if dataOut.flagDecodeData:
698 print("This data is already decoded, recoding again ...")
703 print("This data is already decoded, recoding again ...")
699
704
700 if not self.isConfig:
705 if not self.isConfig:
701
706
702 if code is None:
707 if code is None:
703 if dataOut.code is None:
708 if dataOut.code is None:
704 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
709 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
705
710
706 code = dataOut.code
711 code = dataOut.code
707 else:
712 else:
708 code = numpy.array(code).reshape(nCode,nBaud)
713 code = numpy.array(code).reshape(nCode,nBaud)
709 self.setup(code, osamp, dataOut)
714 self.setup(code, osamp, dataOut)
710
715
711 self.isConfig = True
716 self.isConfig = True
712
717
713 if mode == 3:
718 if mode == 3:
714 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
719 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
715
720
716 if times != None:
721 if times != None:
717 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
722 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
718
723
719 if self.code is None:
724 if self.code is None:
720 print("Fail decoding: Code is not defined.")
725 print("Fail decoding: Code is not defined.")
721 return
726 return
722
727
723 self.__nProfiles = dataOut.nProfiles
728 self.__nProfiles = dataOut.nProfiles
724 datadec = None
729 datadec = None
725
730
726 if mode == 3:
731 if mode == 3:
727 mode = 0
732 mode = 0
728
733
729 if dataOut.flagDataAsBlock:
734 if dataOut.flagDataAsBlock:
730 """
735 """
731 Decoding when data have been read as block,
736 Decoding when data have been read as block,
732 """
737 """
733
738
734 if mode == 0:
739 if mode == 0:
735 datadec = self.__convolutionByBlockInTime(dataOut.data)
740 datadec = self.__convolutionByBlockInTime(dataOut.data)
736 if mode == 1:
741 if mode == 1:
737 datadec = self.__convolutionByBlockInFreq(dataOut.data)
742 datadec = self.__convolutionByBlockInFreq(dataOut.data)
738 else:
743 else:
739 """
744 """
740 Decoding when data have been read profile by profile
745 Decoding when data have been read profile by profile
741 """
746 """
742 if mode == 0:
747 if mode == 0:
743 datadec = self.__convolutionInTime(dataOut.data)
748 datadec = self.__convolutionInTime(dataOut.data)
744
749
745 if mode == 1:
750 if mode == 1:
746 datadec = self.__convolutionInFreq(dataOut.data)
751 datadec = self.__convolutionInFreq(dataOut.data)
747
752
748 if mode == 2:
753 if mode == 2:
749 datadec = self.__convolutionInFreqOpt(dataOut.data)
754 datadec = self.__convolutionInFreqOpt(dataOut.data)
750
755
751 if datadec is None:
756 if datadec is None:
752 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
757 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
753
758
754 dataOut.code = self.code
759 dataOut.code = self.code
755 dataOut.nCode = self.nCode
760 dataOut.nCode = self.nCode
756 dataOut.nBaud = self.nBaud
761 dataOut.nBaud = self.nBaud
757
762
758 dataOut.data = datadec
763 dataOut.data = datadec
759
764
760 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
765 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
761
766
762 dataOut.flagDecodeData = True #asumo q la data esta decodificada
767 dataOut.flagDecodeData = True #asumo q la data esta decodificada
763
768
764 if self.__profIndex == self.nCode-1:
769 if self.__profIndex == self.nCode-1:
765 self.__profIndex = 0
770 self.__profIndex = 0
766 return dataOut
771 return dataOut
767
772
768 self.__profIndex += 1
773 self.__profIndex += 1
769
774
770 return dataOut
775 return dataOut
771 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
776 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
772
777
773
778
774 class ProfileConcat(Operation):
779 class ProfileConcat(Operation):
775
780
776 isConfig = False
781 isConfig = False
777 buffer = None
782 buffer = None
778
783
779 def __init__(self, **kwargs):
784 def __init__(self, **kwargs):
780
785
781 Operation.__init__(self, **kwargs)
786 Operation.__init__(self, **kwargs)
782 self.profileIndex = 0
787 self.profileIndex = 0
783
788
784 def reset(self):
789 def reset(self):
785 self.buffer = numpy.zeros_like(self.buffer)
790 self.buffer = numpy.zeros_like(self.buffer)
786 self.start_index = 0
791 self.start_index = 0
787 self.times = 1
792 self.times = 1
788
793
789 def setup(self, data, m, n=1):
794 def setup(self, data, m, n=1):
790 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
795 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
791 self.nHeights = data.shape[1]#.nHeights
796 self.nHeights = data.shape[1]#.nHeights
792 self.start_index = 0
797 self.start_index = 0
793 self.times = 1
798 self.times = 1
794
799
795 def concat(self, data):
800 def concat(self, data):
796
801
797 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
802 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
798 self.start_index = self.start_index + self.nHeights
803 self.start_index = self.start_index + self.nHeights
799
804
800 def run(self, dataOut, m):
805 def run(self, dataOut, m):
801 dataOut.flagNoData = True
806 dataOut.flagNoData = True
802
807
803 if not self.isConfig:
808 if not self.isConfig:
804 self.setup(dataOut.data, m, 1)
809 self.setup(dataOut.data, m, 1)
805 self.isConfig = True
810 self.isConfig = True
806
811
807 if dataOut.flagDataAsBlock:
812 if dataOut.flagDataAsBlock:
808 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
813 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
809
814
810 else:
815 else:
811 self.concat(dataOut.data)
816 self.concat(dataOut.data)
812 self.times += 1
817 self.times += 1
813 if self.times > m:
818 if self.times > m:
814 dataOut.data = self.buffer
819 dataOut.data = self.buffer
815 self.reset()
820 self.reset()
816 dataOut.flagNoData = False
821 dataOut.flagNoData = False
817 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
822 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
818 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
823 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
819 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
824 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
820 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
825 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
821 dataOut.ippSeconds *= m
826 dataOut.ippSeconds *= m
822 return dataOut
827 return dataOut
823
828
824 class ProfileSelector(Operation):
829 class ProfileSelector(Operation):
825
830
826 profileIndex = None
831 profileIndex = None
827 # Tamanho total de los perfiles
832 # Tamanho total de los perfiles
828 nProfiles = None
833 nProfiles = None
829
834
830 def __init__(self, **kwargs):
835 def __init__(self, **kwargs):
831
836
832 Operation.__init__(self, **kwargs)
837 Operation.__init__(self, **kwargs)
833 self.profileIndex = 0
838 self.profileIndex = 0
834
839
835 def incProfileIndex(self):
840 def incProfileIndex(self):
836
841
837 self.profileIndex += 1
842 self.profileIndex += 1
838
843
839 if self.profileIndex >= self.nProfiles:
844 if self.profileIndex >= self.nProfiles:
840 self.profileIndex = 0
845 self.profileIndex = 0
841
846
842 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
847 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
843
848
844 if profileIndex < minIndex:
849 if profileIndex < minIndex:
845 return False
850 return False
846
851
847 if profileIndex > maxIndex:
852 if profileIndex > maxIndex:
848 return False
853 return False
849
854
850 return True
855 return True
851
856
852 def isThisProfileInList(self, profileIndex, profileList):
857 def isThisProfileInList(self, profileIndex, profileList):
853
858
854 if profileIndex not in profileList:
859 if profileIndex not in profileList:
855 return False
860 return False
856
861
857 return True
862 return True
858
863
859 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
864 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
860
865
861 """
866 """
862 ProfileSelector:
867 ProfileSelector:
863
868
864 Inputs:
869 Inputs:
865 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
870 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
866
871
867 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
872 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
868
873
869 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
874 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
870
875
871 """
876 """
872
877
873 if rangeList is not None:
878 if rangeList is not None:
874 if type(rangeList[0]) not in (tuple, list):
879 if type(rangeList[0]) not in (tuple, list):
875 rangeList = [rangeList]
880 rangeList = [rangeList]
876
881
877 dataOut.flagNoData = True
882 dataOut.flagNoData = True
878
883
879 if dataOut.flagDataAsBlock:
884 if dataOut.flagDataAsBlock:
880 """
885 """
881 data dimension = [nChannels, nProfiles, nHeis]
886 data dimension = [nChannels, nProfiles, nHeis]
882 """
887 """
883 if profileList != None:
888 if profileList != None:
884 dataOut.data = dataOut.data[:,profileList,:]
889 dataOut.data = dataOut.data[:,profileList,:]
885
890
886 if profileRangeList != None:
891 if profileRangeList != None:
887 minIndex = profileRangeList[0]
892 minIndex = profileRangeList[0]
888 maxIndex = profileRangeList[1]
893 maxIndex = profileRangeList[1]
889 profileList = list(range(minIndex, maxIndex+1))
894 profileList = list(range(minIndex, maxIndex+1))
890
895
891 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
896 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
892
897
893 if rangeList != None:
898 if rangeList != None:
894
899
895 profileList = []
900 profileList = []
896
901
897 for thisRange in rangeList:
902 for thisRange in rangeList:
898 minIndex = thisRange[0]
903 minIndex = thisRange[0]
899 maxIndex = thisRange[1]
904 maxIndex = thisRange[1]
900
905
901 profileList.extend(list(range(minIndex, maxIndex+1)))
906 profileList.extend(list(range(minIndex, maxIndex+1)))
902
907
903 dataOut.data = dataOut.data[:,profileList,:]
908 dataOut.data = dataOut.data[:,profileList,:]
904
909
905 dataOut.nProfiles = len(profileList)
910 dataOut.nProfiles = len(profileList)
906 dataOut.profileIndex = dataOut.nProfiles - 1
911 dataOut.profileIndex = dataOut.nProfiles - 1
907 dataOut.flagNoData = False
912 dataOut.flagNoData = False
908
913
909 return dataOut
914 return dataOut
910
915
911 """
916 """
912 data dimension = [nChannels, nHeis]
917 data dimension = [nChannels, nHeis]
913 """
918 """
914
919
915 if profileList != None:
920 if profileList != None:
916
921
917 if self.isThisProfileInList(dataOut.profileIndex, profileList):
922 if self.isThisProfileInList(dataOut.profileIndex, profileList):
918
923
919 self.nProfiles = len(profileList)
924 self.nProfiles = len(profileList)
920 dataOut.nProfiles = self.nProfiles
925 dataOut.nProfiles = self.nProfiles
921 dataOut.profileIndex = self.profileIndex
926 dataOut.profileIndex = self.profileIndex
922 dataOut.flagNoData = False
927 dataOut.flagNoData = False
923
928
924 self.incProfileIndex()
929 self.incProfileIndex()
925 return dataOut
930 return dataOut
926
931
927 if profileRangeList != None:
932 if profileRangeList != None:
928
933
929 minIndex = profileRangeList[0]
934 minIndex = profileRangeList[0]
930 maxIndex = profileRangeList[1]
935 maxIndex = profileRangeList[1]
931
936
932 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
937 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
933
938
934 self.nProfiles = maxIndex - minIndex + 1
939 self.nProfiles = maxIndex - minIndex + 1
935 dataOut.nProfiles = self.nProfiles
940 dataOut.nProfiles = self.nProfiles
936 dataOut.profileIndex = self.profileIndex
941 dataOut.profileIndex = self.profileIndex
937 dataOut.flagNoData = False
942 dataOut.flagNoData = False
938
943
939 self.incProfileIndex()
944 self.incProfileIndex()
940 return dataOut
945 return dataOut
941
946
942 if rangeList != None:
947 if rangeList != None:
943
948
944 nProfiles = 0
949 nProfiles = 0
945
950
946 for thisRange in rangeList:
951 for thisRange in rangeList:
947 minIndex = thisRange[0]
952 minIndex = thisRange[0]
948 maxIndex = thisRange[1]
953 maxIndex = thisRange[1]
949
954
950 nProfiles += maxIndex - minIndex + 1
955 nProfiles += maxIndex - minIndex + 1
951
956
952 for thisRange in rangeList:
957 for thisRange in rangeList:
953
958
954 minIndex = thisRange[0]
959 minIndex = thisRange[0]
955 maxIndex = thisRange[1]
960 maxIndex = thisRange[1]
956
961
957 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
962 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
958
963
959 self.nProfiles = nProfiles
964 self.nProfiles = nProfiles
960 dataOut.nProfiles = self.nProfiles
965 dataOut.nProfiles = self.nProfiles
961 dataOut.profileIndex = self.profileIndex
966 dataOut.profileIndex = self.profileIndex
962 dataOut.flagNoData = False
967 dataOut.flagNoData = False
963
968
964 self.incProfileIndex()
969 self.incProfileIndex()
965
970
966 break
971 break
967
972
968 return dataOut
973 return dataOut
969
974
970
975
971 if beam != None: #beam is only for AMISR data
976 if beam != None: #beam is only for AMISR data
972 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
977 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
973 dataOut.flagNoData = False
978 dataOut.flagNoData = False
974 dataOut.profileIndex = self.profileIndex
979 dataOut.profileIndex = self.profileIndex
975
980
976 self.incProfileIndex()
981 self.incProfileIndex()
977
982
978 return dataOut
983 return dataOut
979
984
980 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
985 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
981
986
982 #return False
987 #return False
983 return dataOut
988 return dataOut
984
989
985 class Reshaper(Operation):
990 class Reshaper(Operation):
986
991
987 def __init__(self, **kwargs):
992 def __init__(self, **kwargs):
988
993
989 Operation.__init__(self, **kwargs)
994 Operation.__init__(self, **kwargs)
990
995
991 self.__buffer = None
996 self.__buffer = None
992 self.__nitems = 0
997 self.__nitems = 0
993
998
994 def __appendProfile(self, dataOut, nTxs):
999 def __appendProfile(self, dataOut, nTxs):
995
1000
996 if self.__buffer is None:
1001 if self.__buffer is None:
997 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
1002 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
998 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
1003 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
999
1004
1000 ini = dataOut.nHeights * self.__nitems
1005 ini = dataOut.nHeights * self.__nitems
1001 end = ini + dataOut.nHeights
1006 end = ini + dataOut.nHeights
1002
1007
1003 self.__buffer[:, ini:end] = dataOut.data
1008 self.__buffer[:, ini:end] = dataOut.data
1004
1009
1005 self.__nitems += 1
1010 self.__nitems += 1
1006
1011
1007 return int(self.__nitems*nTxs)
1012 return int(self.__nitems*nTxs)
1008
1013
1009 def __getBuffer(self):
1014 def __getBuffer(self):
1010
1015
1011 if self.__nitems == int(1./self.__nTxs):
1016 if self.__nitems == int(1./self.__nTxs):
1012
1017
1013 self.__nitems = 0
1018 self.__nitems = 0
1014
1019
1015 return self.__buffer.copy()
1020 return self.__buffer.copy()
1016
1021
1017 return None
1022 return None
1018
1023
1019 def __checkInputs(self, dataOut, shape, nTxs):
1024 def __checkInputs(self, dataOut, shape, nTxs):
1020
1025
1021 if shape is None and nTxs is None:
1026 if shape is None and nTxs is None:
1022 raise ValueError("Reshaper: shape of factor should be defined")
1027 raise ValueError("Reshaper: shape of factor should be defined")
1023
1028
1024 if nTxs:
1029 if nTxs:
1025 if nTxs < 0:
1030 if nTxs < 0:
1026 raise ValueError("nTxs should be greater than 0")
1031 raise ValueError("nTxs should be greater than 0")
1027
1032
1028 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1033 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1029 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1034 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1030
1035
1031 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1036 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1032
1037
1033 return shape, nTxs
1038 return shape, nTxs
1034
1039
1035 if len(shape) != 2 and len(shape) != 3:
1040 if len(shape) != 2 and len(shape) != 3:
1036 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))
1041 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))
1037
1042
1038 if len(shape) == 2:
1043 if len(shape) == 2:
1039 shape_tuple = [dataOut.nChannels]
1044 shape_tuple = [dataOut.nChannels]
1040 shape_tuple.extend(shape)
1045 shape_tuple.extend(shape)
1041 else:
1046 else:
1042 shape_tuple = list(shape)
1047 shape_tuple = list(shape)
1043
1048
1044 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1049 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1045
1050
1046 return shape_tuple, nTxs
1051 return shape_tuple, nTxs
1047
1052
1048 def run(self, dataOut, shape=None, nTxs=None):
1053 def run(self, dataOut, shape=None, nTxs=None):
1049
1054
1050 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1055 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1051
1056
1052 dataOut.flagNoData = True
1057 dataOut.flagNoData = True
1053 profileIndex = None
1058 profileIndex = None
1054
1059
1055 if dataOut.flagDataAsBlock:
1060 if dataOut.flagDataAsBlock:
1056
1061
1057 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1062 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1058 dataOut.flagNoData = False
1063 dataOut.flagNoData = False
1059
1064
1060 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1065 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1061
1066
1062 else:
1067 else:
1063
1068
1064 if self.__nTxs < 1:
1069 if self.__nTxs < 1:
1065
1070
1066 self.__appendProfile(dataOut, self.__nTxs)
1071 self.__appendProfile(dataOut, self.__nTxs)
1067 new_data = self.__getBuffer()
1072 new_data = self.__getBuffer()
1068
1073
1069 if new_data is not None:
1074 if new_data is not None:
1070 dataOut.data = new_data
1075 dataOut.data = new_data
1071 dataOut.flagNoData = False
1076 dataOut.flagNoData = False
1072
1077
1073 profileIndex = dataOut.profileIndex*nTxs
1078 profileIndex = dataOut.profileIndex*nTxs
1074
1079
1075 else:
1080 else:
1076 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1081 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1077
1082
1078 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1083 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1079
1084
1080 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1085 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1081
1086
1082 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1087 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1083
1088
1084 dataOut.profileIndex = profileIndex
1089 dataOut.profileIndex = profileIndex
1085
1090
1086 dataOut.ippSeconds /= self.__nTxs
1091 dataOut.ippSeconds /= self.__nTxs
1087
1092
1088 return dataOut
1093 return dataOut
1089
1094
1090 class SplitProfiles(Operation):
1095 class SplitProfiles(Operation):
1091
1096
1092 def __init__(self, **kwargs):
1097 def __init__(self, **kwargs):
1093
1098
1094 Operation.__init__(self, **kwargs)
1099 Operation.__init__(self, **kwargs)
1095
1100
1096 def run(self, dataOut, n):
1101 def run(self, dataOut, n):
1097
1102
1098 dataOut.flagNoData = True
1103 dataOut.flagNoData = True
1099 profileIndex = None
1104 profileIndex = None
1100
1105
1101 if dataOut.flagDataAsBlock:
1106 if dataOut.flagDataAsBlock:
1102
1107
1103 #nchannels, nprofiles, nsamples
1108 #nchannels, nprofiles, nsamples
1104 shape = dataOut.data.shape
1109 shape = dataOut.data.shape
1105
1110
1106 if shape[2] % n != 0:
1111 if shape[2] % n != 0:
1107 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1112 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1108
1113
1109 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1114 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1110
1115
1111 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1116 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1112 dataOut.flagNoData = False
1117 dataOut.flagNoData = False
1113
1118
1114 profileIndex = int(dataOut.nProfiles/n) - 1
1119 profileIndex = int(dataOut.nProfiles/n) - 1
1115
1120
1116 else:
1121 else:
1117
1122
1118 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1123 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1119
1124
1120 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1125 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1121
1126
1122 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1127 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1123
1128
1124 dataOut.nProfiles = int(dataOut.nProfiles*n)
1129 dataOut.nProfiles = int(dataOut.nProfiles*n)
1125
1130
1126 dataOut.profileIndex = profileIndex
1131 dataOut.profileIndex = profileIndex
1127
1132
1128 dataOut.ippSeconds /= n
1133 dataOut.ippSeconds /= n
1129
1134
1130 return dataOut
1135 return dataOut
1131
1136
1132 class CombineProfiles(Operation):
1137 class CombineProfiles(Operation):
1133 def __init__(self, **kwargs):
1138 def __init__(self, **kwargs):
1134
1139
1135 Operation.__init__(self, **kwargs)
1140 Operation.__init__(self, **kwargs)
1136
1141
1137 self.__remData = None
1142 self.__remData = None
1138 self.__profileIndex = 0
1143 self.__profileIndex = 0
1139
1144
1140 def run(self, dataOut, n):
1145 def run(self, dataOut, n):
1141
1146
1142 dataOut.flagNoData = True
1147 dataOut.flagNoData = True
1143 profileIndex = None
1148 profileIndex = None
1144
1149
1145 if dataOut.flagDataAsBlock:
1150 if dataOut.flagDataAsBlock:
1146
1151
1147 #nchannels, nprofiles, nsamples
1152 #nchannels, nprofiles, nsamples
1148 shape = dataOut.data.shape
1153 shape = dataOut.data.shape
1149 new_shape = shape[0], shape[1]/n, shape[2]*n
1154 new_shape = shape[0], shape[1]/n, shape[2]*n
1150
1155
1151 if shape[1] % n != 0:
1156 if shape[1] % n != 0:
1152 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1157 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1153
1158
1154 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1159 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1155 dataOut.flagNoData = False
1160 dataOut.flagNoData = False
1156
1161
1157 profileIndex = int(dataOut.nProfiles*n) - 1
1162 profileIndex = int(dataOut.nProfiles*n) - 1
1158
1163
1159 else:
1164 else:
1160
1165
1161 #nchannels, nsamples
1166 #nchannels, nsamples
1162 if self.__remData is None:
1167 if self.__remData is None:
1163 newData = dataOut.data
1168 newData = dataOut.data
1164 else:
1169 else:
1165 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1170 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1166
1171
1167 self.__profileIndex += 1
1172 self.__profileIndex += 1
1168
1173
1169 if self.__profileIndex < n:
1174 if self.__profileIndex < n:
1170 self.__remData = newData
1175 self.__remData = newData
1171 #continue
1176 #continue
1172 return
1177 return
1173
1178
1174 self.__profileIndex = 0
1179 self.__profileIndex = 0
1175 self.__remData = None
1180 self.__remData = None
1176
1181
1177 dataOut.data = newData
1182 dataOut.data = newData
1178 dataOut.flagNoData = False
1183 dataOut.flagNoData = False
1179
1184
1180 profileIndex = dataOut.profileIndex/n
1185 profileIndex = dataOut.profileIndex/n
1181
1186
1182
1187
1183 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1188 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1184
1189
1185 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1190 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1186
1191
1187 dataOut.nProfiles = int(dataOut.nProfiles/n)
1192 dataOut.nProfiles = int(dataOut.nProfiles/n)
1188
1193
1189 dataOut.profileIndex = profileIndex
1194 dataOut.profileIndex = profileIndex
1190
1195
1191 dataOut.ippSeconds *= n
1196 dataOut.ippSeconds *= n
1192
1197
1193 return dataOut
1198 return dataOut
1199
1200
1201
1202 class CreateBlockVoltage(Operation):
1203
1204 isConfig = False
1205 __Index = 0
1206 bufferShape = None
1207 buffer = None
1208 firstdatatime = None
1209
1210 def __init__(self,**kwargs):
1211 Operation.__init__(self,**kwargs)
1212 self.isConfig = False
1213 self.__Index = 0
1214 self.firstdatatime = None
1215
1216 def setup(self,dataOut, m = None ):
1217 '''
1218 m= Numero perfiles
1219 '''
1220 #print("CONFIGURANDO CBV")
1221 self.__nChannels = dataOut.nChannels
1222 self.__nHeis = dataOut.nHeights
1223 shape = dataOut.data.shape #nchannels, nprofiles, nsamples
1224 #print("input nChannels",self.__nChannels)
1225 #print("input nHeis",self.__nHeis)
1226 #print("SETUP CREATE BLOCK VOLTAGE")
1227 #print("input Shape",shape)
1228 #print("dataOut.nProfiles",dataOut.nProfiles)
1229 numberSamples = self.__nHeis
1230 numberProfile = int(m)
1231 dataOut.nProfiles = numberProfile
1232 #print("new numberProfile",numberProfile)
1233 #print("new numberSamples",numberSamples)
1234
1235 self.bufferShape = shape[0], numberProfile, numberSamples # nchannels,nprofiles,nsamples
1236 self.buffer = numpy.zeros((self.bufferShape))
1237 self.bufferVel = numpy.zeros((self.bufferShape))
1238
1239 def run(self, dataOut, m=None):
1240 #print("RUN")
1241 dataOut.flagNoData = True
1242 dataOut.flagDataAsBlock = False
1243 #print("BLOCK INDEX ",self.__Index)
1244
1245 if not self.isConfig:
1246 self.setup(dataOut, m= m)
1247 self.isConfig = True
1248 if self.__Index < m:
1249 #print("PROFINDEX BLOCK CBV",self.__Index)
1250 self.buffer[:,self.__Index,:] = dataOut.data
1251 self.bufferVel[:,self.__Index,:] = dataOut.data_velocity
1252 self.__Index += 1
1253 dataOut.flagNoData = True
1254
1255 if self.firstdatatime == None:
1256 self.firstdatatime = dataOut.utctime
1257
1258 if self.__Index == m:
1259 #print("**********************************************")
1260 #print("self.buffer.shape ",self.buffer.shape)
1261 #print("##############",self.firstdatatime)
1262 ##print("*********************************************")
1263 ##print("*********************************************")
1264 ##print("******* nProfiles *******", dataOut.nProfiles)
1265 ##print("*********************************************")
1266 ##print("*********************************************")
1267 dataOut.data = self.buffer
1268 dataOut.data_velocity = self.bufferVel
1269 dataOut.utctime = self.firstdatatime
1270 dataOut.nProfiles = m
1271 self.firstdatatime = None
1272 dataOut.flagNoData = False
1273 dataOut.flagDataAsBlock = True
1274 self.__Index = 0
1275 dataOut.identifierWR = True
1276 return dataOut
1277
1278 class PulsePairVoltage(Operation):
1279 '''
1280 Function PulsePair(Signal Power, Velocity)
1281 The real component of Lag[0] provides Intensity Information
1282 The imag component of Lag[1] Phase provides Velocity Information
1283
1284 Configuration Parameters:
1285 nPRF = Number of Several PRF
1286 theta = Degree Azimuth angel Boundaries
1287
1288 Input:
1289 self.dataOut
1290 lag[N]
1291 Affected:
1292 self.dataOut.spc
1293 '''
1294 isConfig = False
1295 __profIndex = 0
1296 __initime = None
1297 __lastdatatime = None
1298 __buffer = None
1299 __buffer2 = []
1300 __buffer3 = None
1301 __dataReady = False
1302 n = None
1303 __nch = 0
1304 __nHeis = 0
1305
1306 def __init__(self,**kwargs):
1307 Operation.__init__(self,**kwargs)
1308
1309 def setup(self, dataOut, n = None ):
1310 '''
1311 n= Numero de PRF's de entrada
1312 '''
1313 self.__initime = None
1314 self.__lastdatatime = 0
1315 self.__dataReady = False
1316 self.__buffer = 0
1317 self.__buffer2 = []
1318 self.__buffer3 = 0
1319 self.__profIndex = 0
1320
1321 self.__nch = dataOut.nChannels
1322 self.__nHeis = dataOut.nHeights
1323
1324 print("ELVALOR DE n es:", n)
1325 if n == None:
1326 raise ValueError("n should be specified.")
1327
1328 if n != None:
1329 if n<2:
1330 raise ValueError("n should be greater than 2")
1331
1332 self.n = n
1333 self.__nProf = n
1334 '''
1335 if overlapping:
1336 self.__withOverlapping = True
1337 self.__buffer = None
1338
1339 else:
1340 #print ("estoy sin __withO")
1341 self.__withOverlapping = False
1342 self.__buffer = 0
1343 self.__buffer2 = []
1344 self.__buffer3 = 0
1345 '''
1346
1347 def putData(self,data):
1348 '''
1349 Add a profile to he __buffer and increase in one the __profiel Index
1350 '''
1351 #print("self.__profIndex :",self.__profIndex)
1352 self.__buffer += data*numpy.conjugate(data)
1353 self.__buffer2.append(numpy.conjugate(data))
1354 if self.__profIndex > 0:
1355 self.__buffer3 += self.__buffer2[self.__profIndex-1]*data
1356 self.__profIndex += 1
1357 return
1358 '''
1359 if not self.__withOverlapping:
1360 #print("Putdata inside over")
1361 self.__buffer += data* numpy.conjugate(data)
1362 self.__buffer2.append(numpy.conjugate(data))
1363
1364 if self.__profIndex >0:
1365 self.__buffer3 += self.__buffer2[self.__profIndex-1]*data
1366 self.__profIndex += 1
1367 return
1368
1369 if self.__buffer is None:
1370 #print("aqui bro")
1371 self.__buffer = data* numpy.conjugate(data)
1372 self.__buffer2.append(numpy.conjugate(data))
1373 self.__profIndex += 1
1374
1375 return
1376
1377 if self.__profIndex < self.n:
1378 self.__buffer = numpy.vstack(self.__buffer,data* numpy.conjugate(data))
1379 self.__buffer2.append(numpy.conjugate(data))
1380
1381 if self.__profIndex == 1:
1382 self.__buffer3 = self.__buffer2[self.__profIndex -1] * data
1383 else:
1384 self.__buffer3 = numpy.vstack(self.__buffer3, self.__buffer2[self.profIndex-1]*data)
1385
1386 self.__profIndex += 1
1387 return
1388 '''
1389
1390 def pushData(self):
1391 '''
1392 Return the PULSEPAIR and the profiles used in the operation
1393 Affected : self.__profileIndex
1394 '''
1395 #print("************************************************")
1396 #print("push data int vel n")
1397 data_intensity = self.__buffer/self.n
1398 data_velocity = self.__buffer3/(self.n-1)
1399 n = self.__profIndex
1400
1401 self.__buffer = 0
1402 self.__buffer2 = []
1403 self.__buffer3 = 0
1404 self.__profIndex = 0
1405
1406 return data_intensity, data_velocity,n
1407 '''
1408 if not self.__withOverlapping:
1409 #print("ahora que fue")
1410 data_intensity = self.__buffer/self.n
1411 data_velocity = self.__buffer3/(self.n-1)
1412 n = self.__profIndex
1413
1414 self.__buffer = 0
1415 self.__buffer2 = []
1416 self.__buffer3 = 0
1417 self.__profIndex = 0
1418 return data_intensity, data_velocity,n
1419
1420 data_intensity = numpy.sum(self.__buffer,axis = 0)
1421 data_velocity = numpy.sum(self.__buffer3,axis = 0)
1422 n = self.__profIndex
1423 #self.__buffer = 0
1424 #self.__buffer2 = []
1425 #self.__buffer3 = 0
1426 #self.__profIndex = 0
1427 return data_intensity, data_velocity,n
1428 '''
1429
1430 def pulsePairbyProfiles(self,data):
1431
1432 self.__dataReady = False
1433 data_intensity = None
1434 data_velocity = None
1435 #print("beforeputada")
1436 self.putData(data)
1437 #print("ProfileIndex:",self.__profIndex)
1438 if self.__profIndex == self.n:
1439 data_intensity, data_velocity, n = self.pushData()
1440 self.__dataReady = True
1441 #print("-----------------------------------------------")
1442 #print("data_intensity",data_intensity.shape,"data_velocity",data_velocity.shape)
1443 return data_intensity, data_velocity
1444
1445 def pulsePairOp(self, data, datatime= None):
1446
1447 if self.__initime == None:
1448 self.__initime = datatime
1449
1450 data_intensity, data_velocity = self.pulsePairbyProfiles(data)
1451 self.__lastdatatime = datatime
1452
1453 if data_intensity is None:
1454 return None, None, None
1455
1456 avgdatatime = self.__initime
1457 deltatime = datatime - self.__lastdatatime
1458 self.__initime = datatime
1459 '''
1460 if not self.__withOverlapping:
1461 self.__initime = datatime
1462 else:
1463 self.__initime += deltatime
1464 '''
1465 return data_intensity, data_velocity, avgdatatime
1466
1467 def run(self, dataOut,n = None, overlapping= False,**kwargs):
1468
1469 if not self.isConfig:
1470 self.setup(dataOut = dataOut, n = n , **kwargs)
1471 self.isConfig = True
1472 #print("*******************")
1473 #print("print Shape input data:",dataOut.data.shape)
1474 data_intensity, data_velocity, avgdatatime = self.pulsePairOp(dataOut.data, dataOut.utctime)
1475 dataOut.flagNoData = True
1476
1477 if self.__dataReady:
1478 #print("#------------------------------------------------------")
1479 #print("data_ready",data_intensity.shape)
1480 dataOut.data = data_intensity #valor para plotear RTI
1481 dataOut.nCohInt *= self.n
1482 dataOut.data_intensity = data_intensity #valor para intensidad
1483 dataOut.data_velocity = data_velocity #valor para velocidad
1484 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1485 dataOut.utctime = avgdatatime
1486 dataOut.flagNoData = False
1487 return dataOut
1488
1194 # import collections
1489 # import collections
1195 # from scipy.stats import mode
1490 # from scipy.stats import mode
1196 #
1491 #
1197 # class Synchronize(Operation):
1492 # class Synchronize(Operation):
1198 #
1493 #
1199 # isConfig = False
1494 # isConfig = False
1200 # __profIndex = 0
1495 # __profIndex = 0
1201 #
1496 #
1202 # def __init__(self, **kwargs):
1497 # def __init__(self, **kwargs):
1203 #
1498 #
1204 # Operation.__init__(self, **kwargs)
1499 # Operation.__init__(self, **kwargs)
1205 # # self.isConfig = False
1500 # # self.isConfig = False
1206 # self.__powBuffer = None
1501 # self.__powBuffer = None
1207 # self.__startIndex = 0
1502 # self.__startIndex = 0
1208 # self.__pulseFound = False
1503 # self.__pulseFound = False
1209 #
1504 #
1210 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1505 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1211 #
1506 #
1212 # #Read data
1507 # #Read data
1213 #
1508 #
1214 # powerdB = dataOut.getPower(channel = channel)
1509 # powerdB = dataOut.getPower(channel = channel)
1215 # noisedB = dataOut.getNoise(channel = channel)[0]
1510 # noisedB = dataOut.getNoise(channel = channel)[0]
1216 #
1511 #
1217 # self.__powBuffer.extend(powerdB.flatten())
1512 # self.__powBuffer.extend(powerdB.flatten())
1218 #
1513 #
1219 # dataArray = numpy.array(self.__powBuffer)
1514 # dataArray = numpy.array(self.__powBuffer)
1220 #
1515 #
1221 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1516 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1222 #
1517 #
1223 # maxValue = numpy.nanmax(filteredPower)
1518 # maxValue = numpy.nanmax(filteredPower)
1224 #
1519 #
1225 # if maxValue < noisedB + 10:
1520 # if maxValue < noisedB + 10:
1226 # #No se encuentra ningun pulso de transmision
1521 # #No se encuentra ningun pulso de transmision
1227 # return None
1522 # return None
1228 #
1523 #
1229 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1524 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1230 #
1525 #
1231 # if len(maxValuesIndex) < 2:
1526 # if len(maxValuesIndex) < 2:
1232 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1527 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1233 # return None
1528 # return None
1234 #
1529 #
1235 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1530 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1236 #
1531 #
1237 # #Seleccionar solo valores con un espaciamiento de nSamples
1532 # #Seleccionar solo valores con un espaciamiento de nSamples
1238 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1533 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1239 #
1534 #
1240 # if len(pulseIndex) < 2:
1535 # if len(pulseIndex) < 2:
1241 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1536 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1242 # return None
1537 # return None
1243 #
1538 #
1244 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1539 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1245 #
1540 #
1246 # #remover senales que se distancien menos de 10 unidades o muestras
1541 # #remover senales que se distancien menos de 10 unidades o muestras
1247 # #(No deberian existir IPP menor a 10 unidades)
1542 # #(No deberian existir IPP menor a 10 unidades)
1248 #
1543 #
1249 # realIndex = numpy.where(spacing > 10 )[0]
1544 # realIndex = numpy.where(spacing > 10 )[0]
1250 #
1545 #
1251 # if len(realIndex) < 2:
1546 # if len(realIndex) < 2:
1252 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1547 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1253 # return None
1548 # return None
1254 #
1549 #
1255 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1550 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1256 # realPulseIndex = pulseIndex[realIndex]
1551 # realPulseIndex = pulseIndex[realIndex]
1257 #
1552 #
1258 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1553 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1259 #
1554 #
1260 # print "IPP = %d samples" %period
1555 # print "IPP = %d samples" %period
1261 #
1556 #
1262 # self.__newNSamples = dataOut.nHeights #int(period)
1557 # self.__newNSamples = dataOut.nHeights #int(period)
1263 # self.__startIndex = int(realPulseIndex[0])
1558 # self.__startIndex = int(realPulseIndex[0])
1264 #
1559 #
1265 # return 1
1560 # return 1
1266 #
1561 #
1267 #
1562 #
1268 # def setup(self, nSamples, nChannels, buffer_size = 4):
1563 # def setup(self, nSamples, nChannels, buffer_size = 4):
1269 #
1564 #
1270 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1565 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1271 # maxlen = buffer_size*nSamples)
1566 # maxlen = buffer_size*nSamples)
1272 #
1567 #
1273 # bufferList = []
1568 # bufferList = []
1274 #
1569 #
1275 # for i in range(nChannels):
1570 # for i in range(nChannels):
1276 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1571 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1277 # maxlen = buffer_size*nSamples)
1572 # maxlen = buffer_size*nSamples)
1278 #
1573 #
1279 # bufferList.append(bufferByChannel)
1574 # bufferList.append(bufferByChannel)
1280 #
1575 #
1281 # self.__nSamples = nSamples
1576 # self.__nSamples = nSamples
1282 # self.__nChannels = nChannels
1577 # self.__nChannels = nChannels
1283 # self.__bufferList = bufferList
1578 # self.__bufferList = bufferList
1284 #
1579 #
1285 # def run(self, dataOut, channel = 0):
1580 # def run(self, dataOut, channel = 0):
1286 #
1581 #
1287 # if not self.isConfig:
1582 # if not self.isConfig:
1288 # nSamples = dataOut.nHeights
1583 # nSamples = dataOut.nHeights
1289 # nChannels = dataOut.nChannels
1584 # nChannels = dataOut.nChannels
1290 # self.setup(nSamples, nChannels)
1585 # self.setup(nSamples, nChannels)
1291 # self.isConfig = True
1586 # self.isConfig = True
1292 #
1587 #
1293 # #Append new data to internal buffer
1588 # #Append new data to internal buffer
1294 # for thisChannel in range(self.__nChannels):
1589 # for thisChannel in range(self.__nChannels):
1295 # bufferByChannel = self.__bufferList[thisChannel]
1590 # bufferByChannel = self.__bufferList[thisChannel]
1296 # bufferByChannel.extend(dataOut.data[thisChannel])
1591 # bufferByChannel.extend(dataOut.data[thisChannel])
1297 #
1592 #
1298 # if self.__pulseFound:
1593 # if self.__pulseFound:
1299 # self.__startIndex -= self.__nSamples
1594 # self.__startIndex -= self.__nSamples
1300 #
1595 #
1301 # #Finding Tx Pulse
1596 # #Finding Tx Pulse
1302 # if not self.__pulseFound:
1597 # if not self.__pulseFound:
1303 # indexFound = self.__findTxPulse(dataOut, channel)
1598 # indexFound = self.__findTxPulse(dataOut, channel)
1304 #
1599 #
1305 # if indexFound == None:
1600 # if indexFound == None:
1306 # dataOut.flagNoData = True
1601 # dataOut.flagNoData = True
1307 # return
1602 # return
1308 #
1603 #
1309 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1604 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1310 # self.__pulseFound = True
1605 # self.__pulseFound = True
1311 # self.__startIndex = indexFound
1606 # self.__startIndex = indexFound
1312 #
1607 #
1313 # #If pulse was found ...
1608 # #If pulse was found ...
1314 # for thisChannel in range(self.__nChannels):
1609 # for thisChannel in range(self.__nChannels):
1315 # bufferByChannel = self.__bufferList[thisChannel]
1610 # bufferByChannel = self.__bufferList[thisChannel]
1316 # #print self.__startIndex
1611 # #print self.__startIndex
1317 # x = numpy.array(bufferByChannel)
1612 # x = numpy.array(bufferByChannel)
1318 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1613 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1319 #
1614 #
1320 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1615 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1321 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1616 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1322 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1617 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1323 #
1618 #
1324 # dataOut.data = self.__arrayBuffer
1619 # dataOut.data = self.__arrayBuffer
1325 #
1620 #
1326 # self.__startIndex += self.__newNSamples
1621 # self.__startIndex += self.__newNSamples
1327 #
1622 #
1328 # return
1623 # return
@@ -1,183 +1,203
1 #!python
1 #!python
2 '''
2 '''
3 '''
3 '''
4
4
5 import os, sys
5 import os, sys
6 import datetime
6 import datetime
7 import time
7 import time
8
8
9 #path = os.path.dirname(os.getcwd())
9 #path = os.path.dirname(os.getcwd())
10 #path = os.path.dirname(path)
10 #path = os.path.dirname(path)
11 #sys.path.insert(0, path)
11 #sys.path.insert(0, path)
12
12
13 from schainpy.controller import Project
13 from schainpy.controller import Project
14
14
15 desc = "USRP_test"
15 desc = "USRP_test"
16 filename = "USRP_processing.xml"
16 filename = "USRP_processing.xml"
17 controllerObj = Project()
17 controllerObj = Project()
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19
19
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21
21
22 #######################################################################
22 #######################################################################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 #######################################################################
24 #######################################################################
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26
26
27
27
28 path = '/home/soporte/data_hdf5' #### with clock 35.16 db noise
28 #path = '/home/soporte/data_hdf5' #### with clock 35.16 db noise
29
29 path = '/home/alex/WEATHER_DATA/DATA'
30 figpath = '/home/soporte/data_hdf5_imag'
30 figpath = '/home/alex/WEATHER_DATA/DATA/pic'
31 #figpath = '/home/soporte/data_hdf5_imag'
31 #remotefolder = "/home/wmaster/graficos"
32 #remotefolder = "/home/wmaster/graficos"
32 #######################################################################
33 #######################################################################
33 ################# RANGO DE PLOTEO######################################
34 ################# RANGO DE PLOTEO######################################
34 #######################################################################
35 #######################################################################
35 dBmin = '30'
36 dBmin = '30'
36 dBmax = '60'
37 dBmax = '60'
37 xmin = '0'
38 xmin = '0'
38 xmax ='24'
39 xmax ='24'
39 ymin = '0'
40 ymin = '0'
40 ymax = '600'
41 ymax = '600'
41 #######################################################################
42 #######################################################################
42 ########################FECHA##########################################
43 ########################FECHA##########################################
43 #######################################################################
44 #######################################################################
44 str = datetime.date.today()
45 str = datetime.date.today()
45 today = str.strftime("%Y/%m/%d")
46 today = str.strftime("%Y/%m/%d")
46 str2 = str - datetime.timedelta(days=1)
47 str2 = str - datetime.timedelta(days=1)
47 yesterday = str2.strftime("%Y/%m/%d")
48 yesterday = str2.strftime("%Y/%m/%d")
48 #######################################################################
49 #######################################################################
49 ######################## UNIDAD DE LECTURA#############################
50 ######################## UNIDAD DE LECTURA#############################
50 #######################################################################
51 #######################################################################
51 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 path=path,
53 path=path,
53 startDate="2019/01/01",#today,
54 startDate="2019/01/01",#today,
54 endDate="2109/12/30",#today,
55 endDate="2109/12/30",#today,
55 startTime='00:00:00',
56 startTime='00:00:00',
56 endTime='23:59:59',
57 endTime='23:59:59',
57 delay=0,
58 delay=0,
58 #set=0,
59 #set=0,
59 online=0,
60 online=0,
60 walk=1,
61 walk=1,
61 ippKm = 1000)
62 ippKm = 1000)
62
63
63 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 #######################################################################
66 #######################################################################
66 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 #######################################################################
68 #######################################################################
68
69
69 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70 #
71 #
71 # codigo64='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,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,'+\
72 # codigo64='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,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,'+\
72 # '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,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
73 # '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,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
73
74
74 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
75 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
75 #opObj11.addParameter(name='frequency', value='30e6', format='float')
76 #opObj11.addParameter(name='frequency', value='30e6', format='float')
76
77
77 #opObj10 = procUnitConfObjA.addOperation(name='Scope', optype='external')
78 #opObj10 = procUnitConfObjA.addOperation(name='Scope', optype='external')
78 #opObj10.addParameter(name='id', value='10', format='int')
79 #opObj10.addParameter(name='id', value='10', format='int')
79 ##opObj10.addParameter(name='xmin', value='0', format='int')
80 ##opObj10.addParameter(name='xmin', value='0', format='int')
80 ##opObj10.addParameter(name='xmax', value='50', format='int')
81 ##opObj10.addParameter(name='xmax', value='50', format='int')
81 #opObj10.addParameter(name='type', value='iq')
82 #opObj10.addParameter(name='type', value='iq')
82 #opObj10.addParameter(name='ymin', value='-5000', format='int')
83 #opObj10.addParameter(name='ymin', value='-5000', format='int')
83 ##opObj10.addParameter(name='ymax', value='8500', format='int')
84 ##opObj10.addParameter(name='ymax', value='8500', format='int')
84
85
85 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
86 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
86 #opObj10.addParameter(name='h0', value='-5000', format='float')
87 #opObj10.addParameter(name='h0', value='-5000', format='float')
87
88
88 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
89 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
89 #opObj11.addParameter(name='window', value='1', format='int')
90 #opObj11.addParameter(name='window', value='1', format='int')
90
91
91 #codigo='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'
92 #codigo='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'
92 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
93 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
93 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
94 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
94 #opObj11.addParameter(name='nCode', value='1', format='int')
95 #opObj11.addParameter(name='nCode', value='1', format='int')
95 #opObj11.addParameter(name='nBaud', value='28', format='int')
96 #opObj11.addParameter(name='nBaud', value='28', format='int')
96
97
97 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
98 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
98 #opObj11.addParameter(name='n', value='100', format='int')
99 #opObj11.addParameter(name='n', value='10', format='int')
100
101
102 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
103 opObj11.addParameter(name='n', value='10', format='int')
104
105 opObj11 = procUnitConfObjA.addOperation(name='CreateBlockVoltage', optype='other')
106 opObj11.addParameter(name='m', value='16', format='int')
107
108 procUnitConfObj2 = controllerObj.addProcUnit(datatype='ParametersProc', inputId=procUnitConfObjA.getId())
99
109
110 #Not used because the RGB data is obtained directly from the HF Reader.
111 #opObj21 = procUnitConfObj2.addOperation(name='GetRGBData')
112
113 opObj21 = procUnitConfObj2.addOperation(name='ParamWriter', optype='external')
114 opObj21.addParameter(name='path', value=figpath+'/NEWData')
115 opObj21.addParameter(name='blocksPerFile', value='1', format='int')
116 opObj21.addParameter(name='metadataList',value='heightList',format='list')
117 opObj21.addParameter(name='dataList',value='data_intensity',format='list')
118
119 '''
100 #######################################################################
120 #######################################################################
101 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
121 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
102 #######################################################################
122 #######################################################################
103 procUnitConfObjSousySpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
123 procUnitConfObjSousySpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
104 procUnitConfObjSousySpectra.addParameter(name='nFFTPoints', value='100', format='int')
124 procUnitConfObjSousySpectra.addParameter(name='nFFTPoints', value='16', format='int')
105 procUnitConfObjSousySpectra.addParameter(name='nProfiles', value='100', format='int')
125 procUnitConfObjSousySpectra.addParameter(name='nProfiles', value='16', format='int')
106 #procUnitConfObjSousySpectra.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
126 #procUnitConfObjSousySpectra.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
107
127
108 #opObj13 = procUnitConfObjSousySpectra.addOperation(name='removeDC')
128 #opObj13 = procUnitConfObjSousySpectra.addOperation(name='removeDC')
109 #opObj13.addParameter(name='mode', value='2', format='int')
129 #opObj13.addParameter(name='mode', value='2', format='int')
110
130
111 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='IncohInt', optype='other')
131 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='IncohInt', optype='other')
112 #opObj11.addParameter(name='n', value='60', format='float')
132 #opObj11.addParameter(name='n', value='60', format='float')
113 #######################################################################
133 #######################################################################
114 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
134 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
115 #######################################################################
135 #######################################################################
116 #SpectraPlot
136 #SpectraPlot
117
137
118 opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraPlot', optype='external')
138 opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraPlot', optype='external')
119 opObj11.addParameter(name='id', value='1', format='int')
139 opObj11.addParameter(name='id', value='1', format='int')
120 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
140 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
121 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
141 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
122 #opObj11.addParameter(name='xmax', value=0.01, format='float')
142 #opObj11.addParameter(name='xmax', value=0.01, format='float')
123 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
143 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
124 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
144 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
125 #opObj11.addParameter(name='ymin', value=ymin, format='int')
145 #opObj11.addParameter(name='ymin', value=ymin, format='int')
126 #opObj11.addParameter(name='ymax', value=ymax, format='int')
146 #opObj11.addParameter(name='ymax', value=ymax, format='int')
127 opObj11.addParameter(name='showprofile', value='1', format='int')
147 opObj11.addParameter(name='showprofile', value='1', format='int')
128 opObj11.addParameter(name='save', value=figpath, format='str')
148 opObj11.addParameter(name='save', value=figpath, format='str')
129 opObj11.addParameter(name='save_period', value=10, format='int')
149 opObj11.addParameter(name='save_period', value=10, format='int')
130
150
131
151
132 #RTIPLOT
152 #RTIPLOT
133
153
134 opObj11 = procUnitConfObjSousySpectra.addOperation(name='RTIPlot', optype='external')
154 opObj11 = procUnitConfObjSousySpectra.addOperation(name='RTIPlot', optype='external')
135 opObj11.addParameter(name='id', value='2', format='int')
155 opObj11.addParameter(name='id', value='2', format='int')
136 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
156 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
137 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
157 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
138 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
158 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
139 #opObj11.addParameter(name='ymin', value=ymin, format='int')
159 #opObj11.addParameter(name='ymin', value=ymin, format='int')
140 #opObj11.addParameter(name='ymax', value=ymax, format='int')
160 #opObj11.addParameter(name='ymax', value=ymax, format='int')
141 opObj11.addParameter(name='xmin', value=0, format='int')
161 opObj11.addParameter(name='xmin', value=0, format='int')
142 opObj11.addParameter(name='xmax', value=23, format='int')
162 opObj11.addParameter(name='xmax', value=23, format='int')
143
163
144 opObj11.addParameter(name='showprofile', value='1', format='int')
164 opObj11.addParameter(name='showprofile', value='1', format='int')
145 opObj11.addParameter(name='save', value=figpath, format='str')
165 opObj11.addParameter(name='save', value=figpath, format='str')
146 opObj11.addParameter(name='save_period', value=10, format='int')
166 opObj11.addParameter(name='save_period', value=10, format='int')
147
167
148
168
149 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CrossSpectraPlot', optype='other')
169 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CrossSpectraPlot', optype='other')
150 # opObj11.addParameter(name='id', value='3', format='int')
170 # opObj11.addParameter(name='id', value='3', format='int')
151 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
171 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
152 # opObj11.addParameter(name='ymin', value=ymin, format='int')
172 # opObj11.addParameter(name='ymin', value=ymin, format='int')
153 # opObj11.addParameter(name='ymax', value=ymax, format='int')
173 # opObj11.addParameter(name='ymax', value=ymax, format='int')
154 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
174 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
155 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
175 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
156 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
176 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
157 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
177 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
158 # opObj11.addParameter(name='save', value=0, format='bool')
178 # opObj11.addParameter(name='save', value=0, format='bool')
159 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
179 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
160 # #
180 # #
161 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CoherenceMap', optype='other')
181 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CoherenceMap', optype='other')
162 # opObj11.addParameter(name='id', value='4', format='int')
182 # opObj11.addParameter(name='id', value='4', format='int')
163 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
183 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
164 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
184 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
165 # opObj11.addParameter(name='xmin', value=xmin, format='float')
185 # opObj11.addParameter(name='xmin', value=xmin, format='float')
166 # opObj11.addParameter(name='xmax', value=xmax, format='float')
186 # opObj11.addParameter(name='xmax', value=xmax, format='float')
167 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
187 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
168 # opObj11.addParameter(name='save', value=0, format='bool')
188 # opObj11.addParameter(name='save', value=0, format='bool')
169 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
189 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
170 #
190 #
171 #######################################################################
191 #######################################################################
172 ############### UNIDAD DE ESCRITURA ###################################
192 ############### UNIDAD DE ESCRITURA ###################################
173 #######################################################################
193 #######################################################################
174 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraWriter', optype='other')
194 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraWriter', optype='other')
175 #opObj11.addParameter(name='path', value=wr_path)
195 #opObj11.addParameter(name='path', value=wr_path)
176 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
196 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
197 '''
177 print ("Escribiendo el archivo XML")
198 print ("Escribiendo el archivo XML")
178 print ("Leyendo el archivo XML")
199 print ("Leyendo el archivo XML")
179
200
180
201
181
202
182 controllerObj.start()
203 controllerObj.start()
183
General Comments 0
You need to be logged in to leave comments. Login now