##// END OF EJS Templates
Coherent Integration by Blocks: Bug fixed, nProfiles is divided by number of integrations
Miguel Valdez -
r720:7c23a7f6f4e8
parent child
Show More
@@ -0,0 +1,34
1 #!/usr/bin/env python
2 '''
3 Created on Jul 7, 2014
4
5 @author: roj-idl71
6 '''
7 import os, sys
8
9 schainpy_path = os.path.dirname(os.getcwd())
10 source_path = os.path.dirname(schainpy_path)
11 sys.path.insert(0, source_path)
12
13 from schainpy.controller_api import ControllerThread
14
15 def main():
16 desc = "Segundo Test"
17 filename = "/Users/miguel/Downloads/mst_blocks.xml"
18
19 controllerObj = ControllerThread()
20 controllerObj.readXml(filename)
21
22 #Configure use of external plotter before start
23 plotterObj = controllerObj.useExternalPlotter()
24 ########################################
25
26 controllerObj.start()
27 plotterObj.start()
28
29
30 if __name__ == '__main__':
31 import time
32 start_time = time.time()
33 main()
34 print("--- %s seconds ---" % (time.time() - start_time)) No newline at end of file
@@ -1,1123 +1,1123
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
10
11 from jroheaderIO import SystemHeader, RadarControllerHeader
11 from jroheaderIO import SystemHeader, RadarControllerHeader
12
12
13 def getNumpyDtype(dataTypeCode):
13 def getNumpyDtype(dataTypeCode):
14
14
15 if dataTypeCode == 0:
15 if dataTypeCode == 0:
16 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
16 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
17 elif dataTypeCode == 1:
17 elif dataTypeCode == 1:
18 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
18 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
19 elif dataTypeCode == 2:
19 elif dataTypeCode == 2:
20 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
20 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
21 elif dataTypeCode == 3:
21 elif dataTypeCode == 3:
22 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
22 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
23 elif dataTypeCode == 4:
23 elif dataTypeCode == 4:
24 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
24 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
25 elif dataTypeCode == 5:
25 elif dataTypeCode == 5:
26 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
26 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
27 else:
27 else:
28 raise ValueError, 'dataTypeCode was not defined'
28 raise ValueError, 'dataTypeCode was not defined'
29
29
30 return numpyDtype
30 return numpyDtype
31
31
32 def getDataTypeCode(numpyDtype):
32 def getDataTypeCode(numpyDtype):
33
33
34 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
34 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
35 datatype = 0
35 datatype = 0
36 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
36 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
37 datatype = 1
37 datatype = 1
38 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
38 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
39 datatype = 2
39 datatype = 2
40 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
40 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
41 datatype = 3
41 datatype = 3
42 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
42 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
43 datatype = 4
43 datatype = 4
44 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
44 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
45 datatype = 5
45 datatype = 5
46 else:
46 else:
47 datatype = None
47 datatype = None
48
48
49 return datatype
49 return datatype
50
50
51 def hildebrand_sekhon(data, navg):
51 def hildebrand_sekhon(data, navg):
52 """
52 """
53 This method is for the objective determination of the noise level in Doppler spectra. This
53 This method is for the objective determination of the noise level in Doppler spectra. This
54 implementation technique is based on the fact that the standard deviation of the spectral
54 implementation technique is based on the fact that the standard deviation of the spectral
55 densities is equal to the mean spectral density for white Gaussian noise
55 densities is equal to the mean spectral density for white Gaussian noise
56
56
57 Inputs:
57 Inputs:
58 Data : heights
58 Data : heights
59 navg : numbers of averages
59 navg : numbers of averages
60
60
61 Return:
61 Return:
62 -1 : any error
62 -1 : any error
63 anoise : noise's level
63 anoise : noise's level
64 """
64 """
65
65
66 sortdata = numpy.sort(data,axis=None)
66 sortdata = numpy.sort(data,axis=None)
67 lenOfData = len(sortdata)
67 lenOfData = len(sortdata)
68 nums_min = lenOfData*0.2
68 nums_min = lenOfData*0.2
69
69
70 if nums_min <= 5:
70 if nums_min <= 5:
71 nums_min = 5
71 nums_min = 5
72
72
73 sump = 0.
73 sump = 0.
74
74
75 sumq = 0.
75 sumq = 0.
76
76
77 j = 0
77 j = 0
78
78
79 cont = 1
79 cont = 1
80
80
81 while((cont==1)and(j<lenOfData)):
81 while((cont==1)and(j<lenOfData)):
82
82
83 sump += sortdata[j]
83 sump += sortdata[j]
84
84
85 sumq += sortdata[j]**2
85 sumq += sortdata[j]**2
86
86
87 if j > nums_min:
87 if j > nums_min:
88 rtest = float(j)/(j-1) + 1.0/navg
88 rtest = float(j)/(j-1) + 1.0/navg
89 if ((sumq*j) > (rtest*sump**2)):
89 if ((sumq*j) > (rtest*sump**2)):
90 j = j - 1
90 j = j - 1
91 sump = sump - sortdata[j]
91 sump = sump - sortdata[j]
92 sumq = sumq - sortdata[j]**2
92 sumq = sumq - sortdata[j]**2
93 cont = 0
93 cont = 0
94
94
95 j += 1
95 j += 1
96
96
97 lnoise = sump /j
97 lnoise = sump /j
98 stdv = numpy.sqrt((sumq - lnoise**2)/(j - 1))
98 stdv = numpy.sqrt((sumq - lnoise**2)/(j - 1))
99 return lnoise
99 return lnoise
100
100
101 class Beam:
101 class Beam:
102 def __init__(self):
102 def __init__(self):
103 self.codeList = []
103 self.codeList = []
104 self.azimuthList = []
104 self.azimuthList = []
105 self.zenithList = []
105 self.zenithList = []
106
106
107 class GenericData(object):
107 class GenericData(object):
108
108
109 flagNoData = True
109 flagNoData = True
110
110
111 def __init__(self):
111 def __init__(self):
112
112
113 raise NotImplementedError
113 raise NotImplementedError
114
114
115 def copy(self, inputObj=None):
115 def copy(self, inputObj=None):
116
116
117 if inputObj == None:
117 if inputObj == None:
118 return copy.deepcopy(self)
118 return copy.deepcopy(self)
119
119
120 for key in inputObj.__dict__.keys():
120 for key in inputObj.__dict__.keys():
121 self.__dict__[key] = inputObj.__dict__[key]
121 self.__dict__[key] = inputObj.__dict__[key]
122
122
123 def deepcopy(self):
123 def deepcopy(self):
124
124
125 return copy.deepcopy(self)
125 return copy.deepcopy(self)
126
126
127 def isEmpty(self):
127 def isEmpty(self):
128
128
129 return self.flagNoData
129 return self.flagNoData
130
130
131 class JROData(GenericData):
131 class JROData(GenericData):
132
132
133 # m_BasicHeader = BasicHeader()
133 # m_BasicHeader = BasicHeader()
134 # m_ProcessingHeader = ProcessingHeader()
134 # m_ProcessingHeader = ProcessingHeader()
135
135
136 systemHeaderObj = SystemHeader()
136 systemHeaderObj = SystemHeader()
137
137
138 radarControllerHeaderObj = RadarControllerHeader()
138 radarControllerHeaderObj = RadarControllerHeader()
139
139
140 # data = None
140 # data = None
141
141
142 type = None
142 type = None
143
143
144 datatype = None #dtype but in string
144 datatype = None #dtype but in string
145
145
146 # dtype = None
146 # dtype = None
147
147
148 # nChannels = None
148 # nChannels = None
149
149
150 # nHeights = None
150 # nHeights = None
151
151
152 nProfiles = None
152 nProfiles = None
153
153
154 heightList = None
154 heightList = None
155
155
156 channelList = None
156 channelList = None
157
157
158 flagDiscontinuousBlock = False
158 flagDiscontinuousBlock = False
159
159
160 useLocalTime = False
160 useLocalTime = False
161
161
162 utctime = None
162 utctime = None
163
163
164 timeZone = None
164 timeZone = None
165
165
166 dstFlag = None
166 dstFlag = None
167
167
168 errorCount = None
168 errorCount = None
169
169
170 blocksize = None
170 blocksize = None
171
171
172 # nCode = None
172 # nCode = None
173 #
173 #
174 # nBaud = None
174 # nBaud = None
175 #
175 #
176 # code = None
176 # code = None
177
177
178 flagDecodeData = False #asumo q la data no esta decodificada
178 flagDecodeData = False #asumo q la data no esta decodificada
179
179
180 flagDeflipData = False #asumo q la data no esta sin flip
180 flagDeflipData = False #asumo q la data no esta sin flip
181
181
182 flagShiftFFT = False
182 flagShiftFFT = False
183
183
184 # ippSeconds = None
184 # ippSeconds = None
185
185
186 # timeInterval = None
186 # timeInterval = None
187
187
188 nCohInt = None
188 nCohInt = None
189
189
190 # noise = None
190 # noise = None
191
191
192 windowOfFilter = 1
192 windowOfFilter = 1
193
193
194 #Speed of ligth
194 #Speed of ligth
195 C = 3e8
195 C = 3e8
196
196
197 frequency = 49.92e6
197 frequency = 49.92e6
198
198
199 realtime = False
199 realtime = False
200
200
201 beacon_heiIndexList = None
201 beacon_heiIndexList = None
202
202
203 last_block = None
203 last_block = None
204
204
205 blocknow = None
205 blocknow = None
206
206
207 azimuth = None
207 azimuth = None
208
208
209 zenith = None
209 zenith = None
210
210
211 beam = Beam()
211 beam = Beam()
212
212
213 profileIndex = None
213 profileIndex = None
214
214
215 def __init__(self):
215 def __init__(self):
216
216
217 raise NotImplementedError
217 raise NotImplementedError
218
218
219 def getNoise(self):
219 def getNoise(self):
220
220
221 raise NotImplementedError
221 raise NotImplementedError
222
222
223 def getNChannels(self):
223 def getNChannels(self):
224
224
225 return len(self.channelList)
225 return len(self.channelList)
226
226
227 def getChannelIndexList(self):
227 def getChannelIndexList(self):
228
228
229 return range(self.nChannels)
229 return range(self.nChannels)
230
230
231 def getNHeights(self):
231 def getNHeights(self):
232
232
233 return len(self.heightList)
233 return len(self.heightList)
234
234
235 def getHeiRange(self, extrapoints=0):
235 def getHeiRange(self, extrapoints=0):
236
236
237 heis = self.heightList
237 heis = self.heightList
238 # deltah = self.heightList[1] - self.heightList[0]
238 # deltah = self.heightList[1] - self.heightList[0]
239 #
239 #
240 # heis.append(self.heightList[-1])
240 # heis.append(self.heightList[-1])
241
241
242 return heis
242 return heis
243
243
244 def getltctime(self):
244 def getltctime(self):
245
245
246 if self.useLocalTime:
246 if self.useLocalTime:
247 return self.utctime - self.timeZone*60
247 return self.utctime - self.timeZone*60
248
248
249 return self.utctime
249 return self.utctime
250
250
251 def getDatatime(self):
251 def getDatatime(self):
252
252
253 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
253 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
254 return datatimeValue
254 return datatimeValue
255
255
256 def getTimeRange(self):
256 def getTimeRange(self):
257
257
258 datatime = []
258 datatime = []
259
259
260 datatime.append(self.ltctime)
260 datatime.append(self.ltctime)
261 datatime.append(self.ltctime + self.timeInterval+60)
261 datatime.append(self.ltctime + self.timeInterval+60)
262
262
263 datatime = numpy.array(datatime)
263 datatime = numpy.array(datatime)
264
264
265 return datatime
265 return datatime
266
266
267 def getFmax(self):
267 def getFmax(self):
268
268
269 PRF = 1./(self.ippSeconds * self.nCohInt)
269 PRF = 1./(self.ippSeconds * self.nCohInt)
270
270
271 fmax = PRF/2.
271 fmax = PRF/2.
272
272
273 return fmax
273 return fmax
274
274
275 def getVmax(self):
275 def getVmax(self):
276
276
277 _lambda = self.C/self.frequency
277 _lambda = self.C/self.frequency
278
278
279 vmax = self.getFmax() * _lambda
279 vmax = self.getFmax() * _lambda
280
280
281 return vmax
281 return vmax
282
282
283 def get_ippSeconds(self):
283 def get_ippSeconds(self):
284 '''
284 '''
285 '''
285 '''
286 return self.radarControllerHeaderObj.ippSeconds
286 return self.radarControllerHeaderObj.ippSeconds
287
287
288 def set_ippSeconds(self, ippSeconds):
288 def set_ippSeconds(self, ippSeconds):
289 '''
289 '''
290 '''
290 '''
291
291
292 self.radarControllerHeaderObj.ippSeconds = ippSeconds
292 self.radarControllerHeaderObj.ippSeconds = ippSeconds
293
293
294 return
294 return
295
295
296 def get_dtype(self):
296 def get_dtype(self):
297 '''
297 '''
298 '''
298 '''
299 return getNumpyDtype(self.datatype)
299 return getNumpyDtype(self.datatype)
300
300
301 def set_dtype(self, numpyDtype):
301 def set_dtype(self, numpyDtype):
302 '''
302 '''
303 '''
303 '''
304
304
305 self.datatype = getDataTypeCode(numpyDtype)
305 self.datatype = getDataTypeCode(numpyDtype)
306
306
307 def get_code(self):
307 def get_code(self):
308 '''
308 '''
309 '''
309 '''
310 return self.radarControllerHeaderObj.code
310 return self.radarControllerHeaderObj.code
311
311
312 def set_code(self, code):
312 def set_code(self, code):
313 '''
313 '''
314 '''
314 '''
315 self.radarControllerHeaderObj.code = code
315 self.radarControllerHeaderObj.code = code
316
316
317 return
317 return
318
318
319 def get_ncode(self):
319 def get_ncode(self):
320 '''
320 '''
321 '''
321 '''
322 return self.radarControllerHeaderObj.nCode
322 return self.radarControllerHeaderObj.nCode
323
323
324 def set_ncode(self, nCode):
324 def set_ncode(self, nCode):
325 '''
325 '''
326 '''
326 '''
327 self.radarControllerHeaderObj.nCode = nCode
327 self.radarControllerHeaderObj.nCode = nCode
328
328
329 return
329 return
330
330
331 def get_nbaud(self):
331 def get_nbaud(self):
332 '''
332 '''
333 '''
333 '''
334 return self.radarControllerHeaderObj.nBaud
334 return self.radarControllerHeaderObj.nBaud
335
335
336 def set_nbaud(self, nBaud):
336 def set_nbaud(self, nBaud):
337 '''
337 '''
338 '''
338 '''
339 self.radarControllerHeaderObj.nBaud = nBaud
339 self.radarControllerHeaderObj.nBaud = nBaud
340
340
341 return
341 return
342
342
343 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
343 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
344 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
344 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
345 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
345 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
346 #noise = property(getNoise, "I'm the 'nHeights' property.")
346 #noise = property(getNoise, "I'm the 'nHeights' property.")
347 datatime = property(getDatatime, "I'm the 'datatime' property")
347 datatime = property(getDatatime, "I'm the 'datatime' property")
348 ltctime = property(getltctime, "I'm the 'ltctime' property")
348 ltctime = property(getltctime, "I'm the 'ltctime' property")
349 ippSeconds = property(get_ippSeconds, set_ippSeconds)
349 ippSeconds = property(get_ippSeconds, set_ippSeconds)
350 dtype = property(get_dtype, set_dtype)
350 dtype = property(get_dtype, set_dtype)
351 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
351 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
352 code = property(get_code, set_code)
352 code = property(get_code, set_code)
353 nCode = property(get_ncode, set_ncode)
353 nCode = property(get_ncode, set_ncode)
354 nBaud = property(get_nbaud, set_nbaud)
354 nBaud = property(get_nbaud, set_nbaud)
355
355
356 class Voltage(JROData):
356 class Voltage(JROData):
357
357
358 #data es un numpy array de 2 dmensiones (canales, alturas)
358 #data es un numpy array de 2 dmensiones (canales, alturas)
359 data = None
359 data = None
360
360
361 def __init__(self):
361 def __init__(self):
362 '''
362 '''
363 Constructor
363 Constructor
364 '''
364 '''
365
365
366 self.useLocalTime = True
366 self.useLocalTime = True
367
367
368 self.radarControllerHeaderObj = RadarControllerHeader()
368 self.radarControllerHeaderObj = RadarControllerHeader()
369
369
370 self.systemHeaderObj = SystemHeader()
370 self.systemHeaderObj = SystemHeader()
371
371
372 self.type = "Voltage"
372 self.type = "Voltage"
373
373
374 self.data = None
374 self.data = None
375
375
376 # self.dtype = None
376 # self.dtype = None
377
377
378 # self.nChannels = 0
378 # self.nChannels = 0
379
379
380 # self.nHeights = 0
380 # self.nHeights = 0
381
381
382 self.nProfiles = None
382 self.nProfiles = None
383
383
384 self.heightList = None
384 self.heightList = None
385
385
386 self.channelList = None
386 self.channelList = None
387
387
388 # self.channelIndexList = None
388 # self.channelIndexList = None
389
389
390 self.flagNoData = True
390 self.flagNoData = True
391
391
392 self.flagDiscontinuousBlock = False
392 self.flagDiscontinuousBlock = False
393
393
394 self.utctime = None
394 self.utctime = None
395
395
396 self.timeZone = None
396 self.timeZone = None
397
397
398 self.dstFlag = None
398 self.dstFlag = None
399
399
400 self.errorCount = None
400 self.errorCount = None
401
401
402 self.nCohInt = None
402 self.nCohInt = None
403
403
404 self.blocksize = None
404 self.blocksize = None
405
405
406 self.flagDecodeData = False #asumo q la data no esta decodificada
406 self.flagDecodeData = False #asumo q la data no esta decodificada
407
407
408 self.flagDeflipData = False #asumo q la data no esta sin flip
408 self.flagDeflipData = False #asumo q la data no esta sin flip
409
409
410 self.flagShiftFFT = False
410 self.flagShiftFFT = False
411
411
412 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
412 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
413
413
414 self.profileIndex = 0
414 self.profileIndex = 0
415
415
416 def getNoisebyHildebrand(self, channel = None):
416 def getNoisebyHildebrand(self, channel = None):
417 """
417 """
418 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
418 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
419
419
420 Return:
420 Return:
421 noiselevel
421 noiselevel
422 """
422 """
423
423
424 if channel != None:
424 if channel != None:
425 data = self.data[channel]
425 data = self.data[channel]
426 nChannels = 1
426 nChannels = 1
427 else:
427 else:
428 data = self.data
428 data = self.data
429 nChannels = self.nChannels
429 nChannels = self.nChannels
430
430
431 noise = numpy.zeros(nChannels)
431 noise = numpy.zeros(nChannels)
432 power = data * numpy.conjugate(data)
432 power = data * numpy.conjugate(data)
433
433
434 for thisChannel in range(nChannels):
434 for thisChannel in range(nChannels):
435 if nChannels == 1:
435 if nChannels == 1:
436 daux = power[:].real
436 daux = power[:].real
437 else:
437 else:
438 daux = power[thisChannel,:].real
438 daux = power[thisChannel,:].real
439 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
439 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
440
440
441 return noise
441 return noise
442
442
443 def getNoise(self, type = 1, channel = None):
443 def getNoise(self, type = 1, channel = None):
444
444
445 if type == 1:
445 if type == 1:
446 noise = self.getNoisebyHildebrand(channel)
446 noise = self.getNoisebyHildebrand(channel)
447
447
448 return 10*numpy.log10(noise)
448 return noise
449
449
450 def getPower(self, channel = None):
450 def getPower(self, channel = None):
451
451
452 if channel != None:
452 if channel != None:
453 data = self.data[channel]
453 data = self.data[channel]
454 else:
454 else:
455 data = self.data
455 data = self.data
456
456
457 power = data * numpy.conjugate(data)
457 power = data * numpy.conjugate(data)
458
458
459 return 10*numpy.log10(power.real)
459 return 10*numpy.log10(power.real)
460
460
461 def getTimeInterval(self):
461 def getTimeInterval(self):
462
462
463 timeInterval = self.ippSeconds * self.nCohInt
463 timeInterval = self.ippSeconds * self.nCohInt
464
464
465 return timeInterval
465 return timeInterval
466
466
467 noise = property(getNoise, "I'm the 'nHeights' property.")
467 noise = property(getNoise, "I'm the 'nHeights' property.")
468 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
468 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
469
469
470 class Spectra(JROData):
470 class Spectra(JROData):
471
471
472 #data es un numpy array de 2 dmensiones (canales, perfiles, alturas)
472 #data es un numpy array de 2 dmensiones (canales, perfiles, alturas)
473 data_spc = None
473 data_spc = None
474
474
475 #data es un numpy array de 2 dmensiones (canales, pares, alturas)
475 #data es un numpy array de 2 dmensiones (canales, pares, alturas)
476 data_cspc = None
476 data_cspc = None
477
477
478 #data es un numpy array de 2 dmensiones (canales, alturas)
478 #data es un numpy array de 2 dmensiones (canales, alturas)
479 data_dc = None
479 data_dc = None
480
480
481 nFFTPoints = None
481 nFFTPoints = None
482
482
483 # nPairs = None
483 # nPairs = None
484
484
485 pairsList = None
485 pairsList = None
486
486
487 nIncohInt = None
487 nIncohInt = None
488
488
489 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
489 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
490
490
491 nCohInt = None #se requiere para determinar el valor de timeInterval
491 nCohInt = None #se requiere para determinar el valor de timeInterval
492
492
493 ippFactor = None
493 ippFactor = None
494
494
495 profileIndex = 0
495 profileIndex = 0
496
496
497 def __init__(self):
497 def __init__(self):
498 '''
498 '''
499 Constructor
499 Constructor
500 '''
500 '''
501
501
502 self.useLocalTime = True
502 self.useLocalTime = True
503
503
504 self.radarControllerHeaderObj = RadarControllerHeader()
504 self.radarControllerHeaderObj = RadarControllerHeader()
505
505
506 self.systemHeaderObj = SystemHeader()
506 self.systemHeaderObj = SystemHeader()
507
507
508 self.type = "Spectra"
508 self.type = "Spectra"
509
509
510 # self.data = None
510 # self.data = None
511
511
512 # self.dtype = None
512 # self.dtype = None
513
513
514 # self.nChannels = 0
514 # self.nChannels = 0
515
515
516 # self.nHeights = 0
516 # self.nHeights = 0
517
517
518 self.nProfiles = None
518 self.nProfiles = None
519
519
520 self.heightList = None
520 self.heightList = None
521
521
522 self.channelList = None
522 self.channelList = None
523
523
524 # self.channelIndexList = None
524 # self.channelIndexList = None
525
525
526 self.pairsList = None
526 self.pairsList = None
527
527
528 self.flagNoData = True
528 self.flagNoData = True
529
529
530 self.flagDiscontinuousBlock = False
530 self.flagDiscontinuousBlock = False
531
531
532 self.utctime = None
532 self.utctime = None
533
533
534 self.nCohInt = None
534 self.nCohInt = None
535
535
536 self.nIncohInt = None
536 self.nIncohInt = None
537
537
538 self.blocksize = None
538 self.blocksize = None
539
539
540 self.nFFTPoints = None
540 self.nFFTPoints = None
541
541
542 self.wavelength = None
542 self.wavelength = None
543
543
544 self.flagDecodeData = False #asumo q la data no esta decodificada
544 self.flagDecodeData = False #asumo q la data no esta decodificada
545
545
546 self.flagDeflipData = False #asumo q la data no esta sin flip
546 self.flagDeflipData = False #asumo q la data no esta sin flip
547
547
548 self.flagShiftFFT = False
548 self.flagShiftFFT = False
549
549
550 self.ippFactor = 1
550 self.ippFactor = 1
551
551
552 #self.noise = None
552 #self.noise = None
553
553
554 self.beacon_heiIndexList = []
554 self.beacon_heiIndexList = []
555
555
556 self.noise_estimation = None
556 self.noise_estimation = None
557
557
558
558
559 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
559 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
560 """
560 """
561 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
561 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
562
562
563 Return:
563 Return:
564 noiselevel
564 noiselevel
565 """
565 """
566
566
567 noise = numpy.zeros(self.nChannels)
567 noise = numpy.zeros(self.nChannels)
568
568
569 for channel in range(self.nChannels):
569 for channel in range(self.nChannels):
570 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
570 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
571 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
571 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
572
572
573 return noise
573 return noise
574
574
575 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
575 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
576
576
577 if self.noise_estimation != None:
577 if self.noise_estimation != None:
578 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
578 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
579 else:
579 else:
580 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
580 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
581 return noise
581 return noise
582
582
583
583
584 def getFreqRange(self, extrapoints=0):
584 def getFreqRange(self, extrapoints=0):
585
585
586 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
586 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
587 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
587 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
588
588
589 return freqrange
589 return freqrange
590
590
591 def getVelRange(self, extrapoints=0):
591 def getVelRange(self, extrapoints=0):
592
592
593 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
593 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
594 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltav/2
594 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltav/2
595
595
596 return velrange
596 return velrange
597
597
598 def getNPairs(self):
598 def getNPairs(self):
599
599
600 return len(self.pairsList)
600 return len(self.pairsList)
601
601
602 def getPairsIndexList(self):
602 def getPairsIndexList(self):
603
603
604 return range(self.nPairs)
604 return range(self.nPairs)
605
605
606 def getNormFactor(self):
606 def getNormFactor(self):
607
607
608 pwcode = 1
608 pwcode = 1
609
609
610 if self.flagDecodeData:
610 if self.flagDecodeData:
611 pwcode = numpy.sum(self.code[0]**2)
611 pwcode = numpy.sum(self.code[0]**2)
612 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
612 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
613 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
613 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
614
614
615 return normFactor
615 return normFactor
616
616
617 def getFlagCspc(self):
617 def getFlagCspc(self):
618
618
619 if self.data_cspc is None:
619 if self.data_cspc is None:
620 return True
620 return True
621
621
622 return False
622 return False
623
623
624 def getFlagDc(self):
624 def getFlagDc(self):
625
625
626 if self.data_dc is None:
626 if self.data_dc is None:
627 return True
627 return True
628
628
629 return False
629 return False
630
630
631 def getTimeInterval(self):
631 def getTimeInterval(self):
632
632
633 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
633 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
634
634
635 return timeInterval
635 return timeInterval
636
636
637 def setValue(self, value):
637 def setValue(self, value):
638
638
639 print "This property should not be initialized"
639 print "This property should not be initialized"
640
640
641 return
641 return
642
642
643 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
643 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
644 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
644 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
645 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
645 normFactor = property(getNormFactor, setValue, "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, "I'm the 'timeInterval' property")
649 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
650
650
651 class SpectraHeis(Spectra):
651 class SpectraHeis(Spectra):
652
652
653 data_spc = None
653 data_spc = None
654
654
655 data_cspc = None
655 data_cspc = None
656
656
657 data_dc = None
657 data_dc = None
658
658
659 nFFTPoints = None
659 nFFTPoints = None
660
660
661 # nPairs = None
661 # nPairs = None
662
662
663 pairsList = None
663 pairsList = None
664
664
665 nCohInt = None
665 nCohInt = None
666
666
667 nIncohInt = None
667 nIncohInt = None
668
668
669 def __init__(self):
669 def __init__(self):
670
670
671 self.radarControllerHeaderObj = RadarControllerHeader()
671 self.radarControllerHeaderObj = RadarControllerHeader()
672
672
673 self.systemHeaderObj = SystemHeader()
673 self.systemHeaderObj = SystemHeader()
674
674
675 self.type = "SpectraHeis"
675 self.type = "SpectraHeis"
676
676
677 # self.dtype = None
677 # self.dtype = None
678
678
679 # self.nChannels = 0
679 # self.nChannels = 0
680
680
681 # self.nHeights = 0
681 # self.nHeights = 0
682
682
683 self.nProfiles = None
683 self.nProfiles = None
684
684
685 self.heightList = None
685 self.heightList = None
686
686
687 self.channelList = None
687 self.channelList = None
688
688
689 # self.channelIndexList = None
689 # self.channelIndexList = None
690
690
691 self.flagNoData = True
691 self.flagNoData = True
692
692
693 self.flagDiscontinuousBlock = False
693 self.flagDiscontinuousBlock = False
694
694
695 # self.nPairs = 0
695 # self.nPairs = 0
696
696
697 self.utctime = None
697 self.utctime = None
698
698
699 self.blocksize = None
699 self.blocksize = None
700
700
701 self.profileIndex = 0
701 self.profileIndex = 0
702
702
703 self.nCohInt = 1
703 self.nCohInt = 1
704
704
705 self.nIncohInt = 1
705 self.nIncohInt = 1
706
706
707 def getNormFactor(self):
707 def getNormFactor(self):
708 pwcode = 1
708 pwcode = 1
709 if self.flagDecodeData:
709 if self.flagDecodeData:
710 pwcode = numpy.sum(self.code[0]**2)
710 pwcode = numpy.sum(self.code[0]**2)
711
711
712 normFactor = self.nIncohInt*self.nCohInt*pwcode
712 normFactor = self.nIncohInt*self.nCohInt*pwcode
713
713
714 return normFactor
714 return normFactor
715
715
716 def getTimeInterval(self):
716 def getTimeInterval(self):
717
717
718 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
718 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
719
719
720 return timeInterval
720 return timeInterval
721
721
722 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
722 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
723 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
723 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
724
724
725 class Fits(JROData):
725 class Fits(JROData):
726
726
727 heightList = None
727 heightList = None
728
728
729 channelList = None
729 channelList = None
730
730
731 flagNoData = True
731 flagNoData = True
732
732
733 flagDiscontinuousBlock = False
733 flagDiscontinuousBlock = False
734
734
735 useLocalTime = False
735 useLocalTime = False
736
736
737 utctime = None
737 utctime = None
738
738
739 timeZone = None
739 timeZone = None
740
740
741 # ippSeconds = None
741 # ippSeconds = None
742
742
743 # timeInterval = None
743 # timeInterval = None
744
744
745 nCohInt = None
745 nCohInt = None
746
746
747 nIncohInt = None
747 nIncohInt = None
748
748
749 noise = None
749 noise = None
750
750
751 windowOfFilter = 1
751 windowOfFilter = 1
752
752
753 #Speed of ligth
753 #Speed of ligth
754 C = 3e8
754 C = 3e8
755
755
756 frequency = 49.92e6
756 frequency = 49.92e6
757
757
758 realtime = False
758 realtime = False
759
759
760
760
761 def __init__(self):
761 def __init__(self):
762
762
763 self.type = "Fits"
763 self.type = "Fits"
764
764
765 self.nProfiles = None
765 self.nProfiles = None
766
766
767 self.heightList = None
767 self.heightList = None
768
768
769 self.channelList = None
769 self.channelList = None
770
770
771 # self.channelIndexList = None
771 # self.channelIndexList = None
772
772
773 self.flagNoData = True
773 self.flagNoData = True
774
774
775 self.utctime = None
775 self.utctime = None
776
776
777 self.nCohInt = 1
777 self.nCohInt = 1
778
778
779 self.nIncohInt = 1
779 self.nIncohInt = 1
780
780
781 self.useLocalTime = True
781 self.useLocalTime = True
782
782
783 self.profileIndex = 0
783 self.profileIndex = 0
784
784
785 # self.utctime = None
785 # self.utctime = None
786 # self.timeZone = None
786 # self.timeZone = None
787 # self.ltctime = None
787 # self.ltctime = None
788 # self.timeInterval = None
788 # self.timeInterval = None
789 # self.header = None
789 # self.header = None
790 # self.data_header = None
790 # self.data_header = None
791 # self.data = None
791 # self.data = None
792 # self.datatime = None
792 # self.datatime = None
793 # self.flagNoData = False
793 # self.flagNoData = False
794 # self.expName = ''
794 # self.expName = ''
795 # self.nChannels = None
795 # self.nChannels = None
796 # self.nSamples = None
796 # self.nSamples = None
797 # self.dataBlocksPerFile = None
797 # self.dataBlocksPerFile = None
798 # self.comments = ''
798 # self.comments = ''
799 #
799 #
800
800
801
801
802 def getltctime(self):
802 def getltctime(self):
803
803
804 if self.useLocalTime:
804 if self.useLocalTime:
805 return self.utctime - self.timeZone*60
805 return self.utctime - self.timeZone*60
806
806
807 return self.utctime
807 return self.utctime
808
808
809 def getDatatime(self):
809 def getDatatime(self):
810
810
811 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
811 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
812 return datatime
812 return datatime
813
813
814 def getTimeRange(self):
814 def getTimeRange(self):
815
815
816 datatime = []
816 datatime = []
817
817
818 datatime.append(self.ltctime)
818 datatime.append(self.ltctime)
819 datatime.append(self.ltctime + self.timeInterval)
819 datatime.append(self.ltctime + self.timeInterval)
820
820
821 datatime = numpy.array(datatime)
821 datatime = numpy.array(datatime)
822
822
823 return datatime
823 return datatime
824
824
825 def getHeiRange(self):
825 def getHeiRange(self):
826
826
827 heis = self.heightList
827 heis = self.heightList
828
828
829 return heis
829 return heis
830
830
831 def getNHeights(self):
831 def getNHeights(self):
832
832
833 return len(self.heightList)
833 return len(self.heightList)
834
834
835 def getNChannels(self):
835 def getNChannels(self):
836
836
837 return len(self.channelList)
837 return len(self.channelList)
838
838
839 def getChannelIndexList(self):
839 def getChannelIndexList(self):
840
840
841 return range(self.nChannels)
841 return range(self.nChannels)
842
842
843 def getNoise(self, type = 1):
843 def getNoise(self, type = 1):
844
844
845 #noise = numpy.zeros(self.nChannels)
845 #noise = numpy.zeros(self.nChannels)
846
846
847 if type == 1:
847 if type == 1:
848 noise = self.getNoisebyHildebrand()
848 noise = self.getNoisebyHildebrand()
849
849
850 if type == 2:
850 if type == 2:
851 noise = self.getNoisebySort()
851 noise = self.getNoisebySort()
852
852
853 if type == 3:
853 if type == 3:
854 noise = self.getNoisebyWindow()
854 noise = self.getNoisebyWindow()
855
855
856 return noise
856 return noise
857
857
858 def getTimeInterval(self):
858 def getTimeInterval(self):
859
859
860 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
860 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
861
861
862 return timeInterval
862 return timeInterval
863
863
864 datatime = property(getDatatime, "I'm the 'datatime' property")
864 datatime = property(getDatatime, "I'm the 'datatime' property")
865 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
865 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
866 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
866 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
867 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
867 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
868 noise = property(getNoise, "I'm the 'nHeights' property.")
868 noise = property(getNoise, "I'm the 'nHeights' property.")
869
869
870 ltctime = property(getltctime, "I'm the 'ltctime' property")
870 ltctime = property(getltctime, "I'm the 'ltctime' property")
871 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
871 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
872
872
873 class Correlation(JROData):
873 class Correlation(JROData):
874
874
875 noise = None
875 noise = None
876
876
877 SNR = None
877 SNR = None
878
878
879 pairsAutoCorr = None #Pairs of Autocorrelation
879 pairsAutoCorr = None #Pairs of Autocorrelation
880
880
881 #--------------------------------------------------
881 #--------------------------------------------------
882
882
883 data_corr = None
883 data_corr = None
884
884
885 data_volt = None
885 data_volt = None
886
886
887 lagT = None # each element value is a profileIndex
887 lagT = None # each element value is a profileIndex
888
888
889 lagR = None # each element value is in km
889 lagR = None # each element value is in km
890
890
891 pairsList = None
891 pairsList = None
892
892
893 calculateVelocity = None
893 calculateVelocity = None
894
894
895 nPoints = None
895 nPoints = None
896
896
897 nAvg = None
897 nAvg = None
898
898
899 bufferSize = None
899 bufferSize = None
900
900
901 def __init__(self):
901 def __init__(self):
902 '''
902 '''
903 Constructor
903 Constructor
904 '''
904 '''
905 self.radarControllerHeaderObj = RadarControllerHeader()
905 self.radarControllerHeaderObj = RadarControllerHeader()
906
906
907 self.systemHeaderObj = SystemHeader()
907 self.systemHeaderObj = SystemHeader()
908
908
909 self.type = "Correlation"
909 self.type = "Correlation"
910
910
911 self.data = None
911 self.data = None
912
912
913 self.dtype = None
913 self.dtype = None
914
914
915 self.nProfiles = None
915 self.nProfiles = None
916
916
917 self.heightList = None
917 self.heightList = None
918
918
919 self.channelList = None
919 self.channelList = None
920
920
921 self.flagNoData = True
921 self.flagNoData = True
922
922
923 self.flagDiscontinuousBlock = False
923 self.flagDiscontinuousBlock = False
924
924
925 self.utctime = None
925 self.utctime = None
926
926
927 self.timeZone = None
927 self.timeZone = None
928
928
929 self.dstFlag = None
929 self.dstFlag = None
930
930
931 self.errorCount = None
931 self.errorCount = None
932
932
933 self.blocksize = None
933 self.blocksize = None
934
934
935 self.flagDecodeData = False #asumo q la data no esta decodificada
935 self.flagDecodeData = False #asumo q la data no esta decodificada
936
936
937 self.flagDeflipData = False #asumo q la data no esta sin flip
937 self.flagDeflipData = False #asumo q la data no esta sin flip
938
938
939 self.pairsList = None
939 self.pairsList = None
940
940
941 self.nPoints = None
941 self.nPoints = None
942
942
943 def getLagTRange(self, extrapoints=0):
943 def getLagTRange(self, extrapoints=0):
944
944
945 lagTRange = self.lagT
945 lagTRange = self.lagT
946 diff = lagTRange[1] - lagTRange[0]
946 diff = lagTRange[1] - lagTRange[0]
947 extra = numpy.arange(1,extrapoints + 1)*diff + lagTRange[-1]
947 extra = numpy.arange(1,extrapoints + 1)*diff + lagTRange[-1]
948 lagTRange = numpy.hstack((lagTRange, extra))
948 lagTRange = numpy.hstack((lagTRange, extra))
949
949
950 return lagTRange
950 return lagTRange
951
951
952 def getLagRRange(self, extrapoints=0):
952 def getLagRRange(self, extrapoints=0):
953
953
954 return self.lagR
954 return self.lagR
955
955
956 def getPairsList(self):
956 def getPairsList(self):
957
957
958 return self.pairsList
958 return self.pairsList
959
959
960 def getCalculateVelocity(self):
960 def getCalculateVelocity(self):
961
961
962 return self.calculateVelocity
962 return self.calculateVelocity
963
963
964 def getNPoints(self):
964 def getNPoints(self):
965
965
966 return self.nPoints
966 return self.nPoints
967
967
968 def getNAvg(self):
968 def getNAvg(self):
969
969
970 return self.nAvg
970 return self.nAvg
971
971
972 def getBufferSize(self):
972 def getBufferSize(self):
973
973
974 return self.bufferSize
974 return self.bufferSize
975
975
976 def getPairsAutoCorr(self):
976 def getPairsAutoCorr(self):
977 pairsList = self.pairsList
977 pairsList = self.pairsList
978 pairsAutoCorr = numpy.zeros(self.nChannels, dtype = 'int')*numpy.nan
978 pairsAutoCorr = numpy.zeros(self.nChannels, dtype = 'int')*numpy.nan
979
979
980 for l in range(len(pairsList)):
980 for l in range(len(pairsList)):
981 firstChannel = pairsList[l][0]
981 firstChannel = pairsList[l][0]
982 secondChannel = pairsList[l][1]
982 secondChannel = pairsList[l][1]
983
983
984 #Obteniendo pares de Autocorrelacion
984 #Obteniendo pares de Autocorrelacion
985 if firstChannel == secondChannel:
985 if firstChannel == secondChannel:
986 pairsAutoCorr[firstChannel] = int(l)
986 pairsAutoCorr[firstChannel] = int(l)
987
987
988 pairsAutoCorr = pairsAutoCorr.astype(int)
988 pairsAutoCorr = pairsAutoCorr.astype(int)
989
989
990 return pairsAutoCorr
990 return pairsAutoCorr
991
991
992 def getNoise(self, mode = 2):
992 def getNoise(self, mode = 2):
993
993
994 indR = numpy.where(self.lagR == 0)[0][0]
994 indR = numpy.where(self.lagR == 0)[0][0]
995 indT = numpy.where(self.lagT == 0)[0][0]
995 indT = numpy.where(self.lagT == 0)[0][0]
996
996
997 jspectra0 = self.data_corr[:,:,indR,:]
997 jspectra0 = self.data_corr[:,:,indR,:]
998 jspectra = copy.copy(jspectra0)
998 jspectra = copy.copy(jspectra0)
999
999
1000 num_chan = jspectra.shape[0]
1000 num_chan = jspectra.shape[0]
1001 num_hei = jspectra.shape[2]
1001 num_hei = jspectra.shape[2]
1002
1002
1003 freq_dc = jspectra.shape[1]/2
1003 freq_dc = jspectra.shape[1]/2
1004 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1004 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1005
1005
1006 if ind_vel[0]<0:
1006 if ind_vel[0]<0:
1007 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1007 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1008
1008
1009 if mode == 1:
1009 if mode == 1:
1010 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1010 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1011
1011
1012 if mode == 2:
1012 if mode == 2:
1013
1013
1014 vel = numpy.array([-2,-1,1,2])
1014 vel = numpy.array([-2,-1,1,2])
1015 xx = numpy.zeros([4,4])
1015 xx = numpy.zeros([4,4])
1016
1016
1017 for fil in range(4):
1017 for fil in range(4):
1018 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1018 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1019
1019
1020 xx_inv = numpy.linalg.inv(xx)
1020 xx_inv = numpy.linalg.inv(xx)
1021 xx_aux = xx_inv[0,:]
1021 xx_aux = xx_inv[0,:]
1022
1022
1023 for ich in range(num_chan):
1023 for ich in range(num_chan):
1024 yy = jspectra[ich,ind_vel,:]
1024 yy = jspectra[ich,ind_vel,:]
1025 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1025 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1026
1026
1027 junkid = jspectra[ich,freq_dc,:]<=0
1027 junkid = jspectra[ich,freq_dc,:]<=0
1028 cjunkid = sum(junkid)
1028 cjunkid = sum(junkid)
1029
1029
1030 if cjunkid.any():
1030 if cjunkid.any():
1031 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1031 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1032
1032
1033 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1033 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1034
1034
1035 return noise
1035 return noise
1036
1036
1037 def getTimeInterval(self):
1037 def getTimeInterval(self):
1038
1038
1039 timeInterval = self.ippSeconds * self.nCohInt * self.nPoints
1039 timeInterval = self.ippSeconds * self.nCohInt * self.nPoints
1040
1040
1041 return timeInterval
1041 return timeInterval
1042
1042
1043 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1043 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1044 # pairsList = property(getPairsList, "I'm the 'pairsList' property.")
1044 # pairsList = property(getPairsList, "I'm the 'pairsList' property.")
1045 # nPoints = property(getNPoints, "I'm the 'nPoints' property.")
1045 # nPoints = property(getNPoints, "I'm the 'nPoints' property.")
1046 calculateVelocity = property(getCalculateVelocity, "I'm the 'calculateVelocity' property.")
1046 calculateVelocity = property(getCalculateVelocity, "I'm the 'calculateVelocity' property.")
1047 nAvg = property(getNAvg, "I'm the 'nAvg' property.")
1047 nAvg = property(getNAvg, "I'm the 'nAvg' property.")
1048 bufferSize = property(getBufferSize, "I'm the 'bufferSize' property.")
1048 bufferSize = property(getBufferSize, "I'm the 'bufferSize' property.")
1049
1049
1050
1050
1051 class Parameters(JROData):
1051 class Parameters(JROData):
1052
1052
1053 #Information from previous data
1053 #Information from previous data
1054
1054
1055 inputUnit = None #Type of data to be processed
1055 inputUnit = None #Type of data to be processed
1056
1056
1057 operation = None #Type of operation to parametrize
1057 operation = None #Type of operation to parametrize
1058
1058
1059 normFactor = None #Normalization Factor
1059 normFactor = None #Normalization Factor
1060
1060
1061 groupList = None #List of Pairs, Groups, etc
1061 groupList = None #List of Pairs, Groups, etc
1062
1062
1063 #Parameters
1063 #Parameters
1064
1064
1065 data_param = None #Parameters obtained
1065 data_param = None #Parameters obtained
1066
1066
1067 data_pre = None #Data Pre Parametrization
1067 data_pre = None #Data Pre Parametrization
1068
1068
1069 data_SNR = None #Signal to Noise Ratio
1069 data_SNR = None #Signal to Noise Ratio
1070
1070
1071 # heightRange = None #Heights
1071 # heightRange = None #Heights
1072
1072
1073 abscissaList = None #Abscissa, can be velocities, lags or time
1073 abscissaList = None #Abscissa, can be velocities, lags or time
1074
1074
1075 noise = None #Noise Potency
1075 noise = None #Noise Potency
1076
1076
1077 utctimeInit = None #Initial UTC time
1077 utctimeInit = None #Initial UTC time
1078
1078
1079 paramInterval = None #Time interval to calculate Parameters in seconds
1079 paramInterval = None #Time interval to calculate Parameters in seconds
1080
1080
1081 #Fitting
1081 #Fitting
1082
1082
1083 data_error = None #Error of the estimation
1083 data_error = None #Error of the estimation
1084
1084
1085 constants = None
1085 constants = None
1086
1086
1087 library = None
1087 library = None
1088
1088
1089 #Output signal
1089 #Output signal
1090
1090
1091 outputInterval = None #Time interval to calculate output signal in seconds
1091 outputInterval = None #Time interval to calculate output signal in seconds
1092
1092
1093 data_output = None #Out signal
1093 data_output = None #Out signal
1094
1094
1095
1095
1096
1096
1097 def __init__(self):
1097 def __init__(self):
1098 '''
1098 '''
1099 Constructor
1099 Constructor
1100 '''
1100 '''
1101 self.radarControllerHeaderObj = RadarControllerHeader()
1101 self.radarControllerHeaderObj = RadarControllerHeader()
1102
1102
1103 self.systemHeaderObj = SystemHeader()
1103 self.systemHeaderObj = SystemHeader()
1104
1104
1105 self.type = "Parameters"
1105 self.type = "Parameters"
1106
1106
1107 def getTimeRange1(self):
1107 def getTimeRange1(self):
1108
1108
1109 datatime = []
1109 datatime = []
1110
1110
1111 if self.useLocalTime:
1111 if self.useLocalTime:
1112 time1 = self.utctimeInit - self.timeZone*60
1112 time1 = self.utctimeInit - self.timeZone*60
1113 else:
1113 else:
1114 time1 = utctimeInit
1114 time1 = utctimeInit
1115
1115
1116 # datatime.append(self.utctimeInit)
1116 # datatime.append(self.utctimeInit)
1117 # datatime.append(self.utctimeInit + self.outputInterval)
1117 # datatime.append(self.utctimeInit + self.outputInterval)
1118 datatime.append(time1)
1118 datatime.append(time1)
1119 datatime.append(time1 + self.outputInterval)
1119 datatime.append(time1 + self.outputInterval)
1120
1120
1121 datatime = numpy.array(datatime)
1121 datatime = numpy.array(datatime)
1122
1122
1123 return datatime
1123 return datatime
@@ -1,875 +1,878
1 import numpy
1 import numpy
2 import math
2 import math
3
3
4 from jroproc_base import ProcessingUnit, Operation
4 from jroproc_base import ProcessingUnit, Operation
5 from schainpy.model.data.jrodata import Spectra
5 from schainpy.model.data.jrodata import Spectra
6 from schainpy.model.data.jrodata import hildebrand_sekhon
6 from schainpy.model.data.jrodata import hildebrand_sekhon
7
7
8 class SpectraProc(ProcessingUnit):
8 class SpectraProc(ProcessingUnit):
9
9
10 def __init__(self):
10 def __init__(self):
11
11
12 ProcessingUnit.__init__(self)
12 ProcessingUnit.__init__(self)
13
13
14 self.buffer = None
14 self.buffer = None
15 self.firstdatatime = None
15 self.firstdatatime = None
16 self.profIndex = 0
16 self.profIndex = 0
17 self.dataOut = Spectra()
17 self.dataOut = Spectra()
18 self.id_min = None
18 self.id_min = None
19 self.id_max = None
19 self.id_max = None
20
20
21 def __updateSpecFromVoltage(self):
21 def __updateSpecFromVoltage(self):
22
22
23 self.dataOut.timeZone = self.dataIn.timeZone
23 self.dataOut.timeZone = self.dataIn.timeZone
24 self.dataOut.dstFlag = self.dataIn.dstFlag
24 self.dataOut.dstFlag = self.dataIn.dstFlag
25 self.dataOut.errorCount = self.dataIn.errorCount
25 self.dataOut.errorCount = self.dataIn.errorCount
26 self.dataOut.useLocalTime = self.dataIn.useLocalTime
26 self.dataOut.useLocalTime = self.dataIn.useLocalTime
27
27
28 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
28 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
29 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
29 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
30 self.dataOut.channelList = self.dataIn.channelList
30 self.dataOut.channelList = self.dataIn.channelList
31 self.dataOut.heightList = self.dataIn.heightList
31 self.dataOut.heightList = self.dataIn.heightList
32 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
32 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
33
33
34 self.dataOut.nBaud = self.dataIn.nBaud
34 self.dataOut.nBaud = self.dataIn.nBaud
35 self.dataOut.nCode = self.dataIn.nCode
35 self.dataOut.nCode = self.dataIn.nCode
36 self.dataOut.code = self.dataIn.code
36 self.dataOut.code = self.dataIn.code
37 self.dataOut.nProfiles = self.dataOut.nFFTPoints
37 self.dataOut.nProfiles = self.dataOut.nFFTPoints
38
38
39 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
39 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
40 self.dataOut.utctime = self.firstdatatime
40 self.dataOut.utctime = self.firstdatatime
41 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
41 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
42 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
42 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
43 self.dataOut.flagShiftFFT = False
43 self.dataOut.flagShiftFFT = False
44
44
45 self.dataOut.nCohInt = self.dataIn.nCohInt
45 self.dataOut.nCohInt = self.dataIn.nCohInt
46 self.dataOut.nIncohInt = 1
46 self.dataOut.nIncohInt = 1
47
47
48 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
48 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
49
49
50 self.dataOut.frequency = self.dataIn.frequency
50 self.dataOut.frequency = self.dataIn.frequency
51 self.dataOut.realtime = self.dataIn.realtime
51 self.dataOut.realtime = self.dataIn.realtime
52
52
53 self.dataOut.azimuth = self.dataIn.azimuth
53 self.dataOut.azimuth = self.dataIn.azimuth
54 self.dataOut.zenith = self.dataIn.zenith
54 self.dataOut.zenith = self.dataIn.zenith
55
55
56 self.dataOut.beam.codeList = self.dataIn.beam.codeList
56 self.dataOut.beam.codeList = self.dataIn.beam.codeList
57 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
57 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
58 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
58 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
59
59
60 def __getFft(self):
60 def __getFft(self):
61 """
61 """
62 Convierte valores de Voltaje a Spectra
62 Convierte valores de Voltaje a Spectra
63
63
64 Affected:
64 Affected:
65 self.dataOut.data_spc
65 self.dataOut.data_spc
66 self.dataOut.data_cspc
66 self.dataOut.data_cspc
67 self.dataOut.data_dc
67 self.dataOut.data_dc
68 self.dataOut.heightList
68 self.dataOut.heightList
69 self.profIndex
69 self.profIndex
70 self.buffer
70 self.buffer
71 self.dataOut.flagNoData
71 self.dataOut.flagNoData
72 """
72 """
73 fft_volt = numpy.fft.fft(self.buffer,n=self.dataOut.nFFTPoints,axis=1)
73 fft_volt = numpy.fft.fft(self.buffer,n=self.dataOut.nFFTPoints,axis=1)
74 fft_volt = fft_volt.astype(numpy.dtype('complex'))
74 fft_volt = fft_volt.astype(numpy.dtype('complex'))
75 dc = fft_volt[:,0,:]
75 dc = fft_volt[:,0,:]
76
76
77 #calculo de self-spectra
77 #calculo de self-spectra
78 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
78 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
79 spc = fft_volt * numpy.conjugate(fft_volt)
79 spc = fft_volt * numpy.conjugate(fft_volt)
80 spc = spc.real
80 spc = spc.real
81
81
82 blocksize = 0
82 blocksize = 0
83 blocksize += dc.size
83 blocksize += dc.size
84 blocksize += spc.size
84 blocksize += spc.size
85
85
86 cspc = None
86 cspc = None
87 pairIndex = 0
87 pairIndex = 0
88 if self.dataOut.pairsList != None:
88 if self.dataOut.pairsList != None:
89 #calculo de cross-spectra
89 #calculo de cross-spectra
90 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
90 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
91 for pair in self.dataOut.pairsList:
91 for pair in self.dataOut.pairsList:
92 if pair[0] not in self.dataOut.channelList:
92 if pair[0] not in self.dataOut.channelList:
93 raise ValueError, "Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
93 raise ValueError, "Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
94 if pair[1] not in self.dataOut.channelList:
94 if pair[1] not in self.dataOut.channelList:
95 raise ValueError, "Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
95 raise ValueError, "Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
96
96
97 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
97 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
98 pairIndex += 1
98 pairIndex += 1
99 blocksize += cspc.size
99 blocksize += cspc.size
100
100
101 self.dataOut.data_spc = spc
101 self.dataOut.data_spc = spc
102 self.dataOut.data_cspc = cspc
102 self.dataOut.data_cspc = cspc
103 self.dataOut.data_dc = dc
103 self.dataOut.data_dc = dc
104 self.dataOut.blockSize = blocksize
104 self.dataOut.blockSize = blocksize
105 self.dataOut.flagShiftFFT = True
105 self.dataOut.flagShiftFFT = True
106
106
107 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None):
107 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None):
108
108
109 self.dataOut.flagNoData = True
109 self.dataOut.flagNoData = True
110
110
111 if self.dataIn.type == "Spectra":
111 if self.dataIn.type == "Spectra":
112 self.dataOut.copy(self.dataIn)
112 self.dataOut.copy(self.dataIn)
113 return True
113 return True
114
114
115 if self.dataIn.type == "Voltage":
115 if self.dataIn.type == "Voltage":
116
116
117 if nFFTPoints == None:
117 if nFFTPoints == None:
118 raise ValueError, "This SpectraProc.run() need nFFTPoints input variable"
118 raise ValueError, "This SpectraProc.run() need nFFTPoints input variable"
119
119
120 if nProfiles == None:
120 if nProfiles == None:
121 nProfiles = nFFTPoints
121 nProfiles = nFFTPoints
122
122
123 if ippFactor == None:
123 if ippFactor == None:
124 ippFactor = 1
124 ippFactor = 1
125
125
126 self.dataOut.ippFactor = ippFactor
126 self.dataOut.ippFactor = ippFactor
127
127
128 self.dataOut.nFFTPoints = nFFTPoints
128 self.dataOut.nFFTPoints = nFFTPoints
129 self.dataOut.pairsList = pairsList
129 self.dataOut.pairsList = pairsList
130
130
131 if self.buffer is None:
131 if self.buffer is None:
132 self.buffer = numpy.zeros( (self.dataIn.nChannels,
132 self.buffer = numpy.zeros( (self.dataIn.nChannels,
133 nProfiles,
133 nProfiles,
134 self.dataIn.nHeights),
134 self.dataIn.nHeights),
135 dtype='complex')
135 dtype='complex')
136
136
137 if self.dataIn.flagDataAsBlock:
137 if self.dataIn.flagDataAsBlock:
138 #data dimension: [nChannels, nProfiles, nSamples]
139 nVoltProfiles = self.dataIn.data.shape[1]
140 nVoltProfiles = self.dataIn.nProfiles
138
141
139 if self.dataIn.nProfiles == nProfiles:
142 if nVoltProfiles == nProfiles:
140 self.buffer = self.dataIn.data.copy()
143 self.buffer = self.dataIn.data.copy()
141 self.profIndex = nProfiles
144 self.profIndex = nVoltProfiles
142
145
143 elif self.dataIn.nProfiles < nProfiles:
146 elif nVoltProfiles < nProfiles:
144
147
145 if self.profIndex == 0:
148 if self.profIndex == 0:
146 self.id_min = 0
149 self.id_min = 0
147 self.id_max = self.dataIn.nProfiles
150 self.id_max = nVoltProfiles
148
151
149 self.buffer[:,self.id_min:self.id_max,:] = self.dataIn.data
152 self.buffer[:,self.id_min:self.id_max,:] = self.dataIn.data
150 self.profIndex += self.dataIn.nProfiles
153 self.profIndex += nVoltProfiles
151 self.id_min += self.dataIn.data.shape[1]
154 self.id_min += nVoltProfiles
152 self.id_max += self.dataIn.data.shape[1]
155 self.id_max += nVoltProfiles
153 else:
156 else:
154 raise ValueError, "The type object %s has %d profiles, it should be equal to %d profiles"%(self.dataIn.type,self.dataIn.data.shape[1],nProfiles)
157 raise ValueError, "The type object %s has %d profiles, it should be equal to %d profiles"%(self.dataIn.type,self.dataIn.data.shape[1],nProfiles)
155 self.dataOut.flagNoData = True
158 self.dataOut.flagNoData = True
156 return 0
159 return 0
157 else:
160 else:
158 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
161 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
159 self.profIndex += 1
162 self.profIndex += 1
160
163
161 if self.firstdatatime == None:
164 if self.firstdatatime == None:
162 self.firstdatatime = self.dataIn.utctime
165 self.firstdatatime = self.dataIn.utctime
163
166
164 if self.profIndex == nProfiles:
167 if self.profIndex == nProfiles:
165 self.__updateSpecFromVoltage()
168 self.__updateSpecFromVoltage()
166 self.__getFft()
169 self.__getFft()
167
170
168 self.dataOut.flagNoData = False
171 self.dataOut.flagNoData = False
169 self.firstdatatime = None
172 self.firstdatatime = None
170 self.profIndex = 0
173 self.profIndex = 0
171
174
172 return True
175 return True
173
176
174 raise ValueError, "The type of input object '%s' is not valid"%(self.dataIn.type)
177 raise ValueError, "The type of input object '%s' is not valid"%(self.dataIn.type)
175
178
176 def __selectPairs(self, channelList=None):
179 def __selectPairs(self, channelList=None):
177
180
178 if channelList == None:
181 if channelList == None:
179 return
182 return
180
183
181 pairsIndexListSelected = []
184 pairsIndexListSelected = []
182 for pairIndex in self.dataOut.pairsIndexList:
185 for pairIndex in self.dataOut.pairsIndexList:
183 #First pair
186 #First pair
184 if self.dataOut.pairsList[pairIndex][0] not in channelList:
187 if self.dataOut.pairsList[pairIndex][0] not in channelList:
185 continue
188 continue
186 #Second pair
189 #Second pair
187 if self.dataOut.pairsList[pairIndex][1] not in channelList:
190 if self.dataOut.pairsList[pairIndex][1] not in channelList:
188 continue
191 continue
189
192
190 pairsIndexListSelected.append(pairIndex)
193 pairsIndexListSelected.append(pairIndex)
191
194
192 if not pairsIndexListSelected:
195 if not pairsIndexListSelected:
193 self.dataOut.data_cspc = None
196 self.dataOut.data_cspc = None
194 self.dataOut.pairsList = []
197 self.dataOut.pairsList = []
195 return
198 return
196
199
197 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
200 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
198 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
201 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
199
202
200 return
203 return
201
204
202 def selectChannels(self, channelList):
205 def selectChannels(self, channelList):
203
206
204 channelIndexList = []
207 channelIndexList = []
205
208
206 for channel in channelList:
209 for channel in channelList:
207 if channel not in self.dataOut.channelList:
210 if channel not in self.dataOut.channelList:
208 raise ValueError, "Error selecting channels: The value %d in channelList is not valid.\nAvailable channels = %s" %(channel, str(self.dataOut.channelList))
211 raise ValueError, "Error selecting channels: The value %d in channelList is not valid.\nAvailable channels = %s" %(channel, str(self.dataOut.channelList))
209
212
210 index = self.dataOut.channelList.index(channel)
213 index = self.dataOut.channelList.index(channel)
211 channelIndexList.append(index)
214 channelIndexList.append(index)
212
215
213 self.selectChannelsByIndex(channelIndexList)
216 self.selectChannelsByIndex(channelIndexList)
214
217
215 def selectChannelsByIndex(self, channelIndexList):
218 def selectChannelsByIndex(self, channelIndexList):
216 """
219 """
217 Selecciona un bloque de datos en base a canales segun el channelIndexList
220 Selecciona un bloque de datos en base a canales segun el channelIndexList
218
221
219 Input:
222 Input:
220 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
223 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
221
224
222 Affected:
225 Affected:
223 self.dataOut.data_spc
226 self.dataOut.data_spc
224 self.dataOut.channelIndexList
227 self.dataOut.channelIndexList
225 self.dataOut.nChannels
228 self.dataOut.nChannels
226
229
227 Return:
230 Return:
228 None
231 None
229 """
232 """
230
233
231 for channelIndex in channelIndexList:
234 for channelIndex in channelIndexList:
232 if channelIndex not in self.dataOut.channelIndexList:
235 if channelIndex not in self.dataOut.channelIndexList:
233 raise ValueError, "Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " %(channelIndex, self.dataOut.channelIndexList)
236 raise ValueError, "Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " %(channelIndex, self.dataOut.channelIndexList)
234
237
235 # nChannels = len(channelIndexList)
238 # nChannels = len(channelIndexList)
236
239
237 data_spc = self.dataOut.data_spc[channelIndexList,:]
240 data_spc = self.dataOut.data_spc[channelIndexList,:]
238 data_dc = self.dataOut.data_dc[channelIndexList,:]
241 data_dc = self.dataOut.data_dc[channelIndexList,:]
239
242
240 self.dataOut.data_spc = data_spc
243 self.dataOut.data_spc = data_spc
241 self.dataOut.data_dc = data_dc
244 self.dataOut.data_dc = data_dc
242
245
243 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
246 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
244 # self.dataOut.nChannels = nChannels
247 # self.dataOut.nChannels = nChannels
245
248
246 self.__selectPairs(self.dataOut.channelList)
249 self.__selectPairs(self.dataOut.channelList)
247
250
248 return 1
251 return 1
249
252
250 def selectHeights(self, minHei, maxHei):
253 def selectHeights(self, minHei, maxHei):
251 """
254 """
252 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
255 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
253 minHei <= height <= maxHei
256 minHei <= height <= maxHei
254
257
255 Input:
258 Input:
256 minHei : valor minimo de altura a considerar
259 minHei : valor minimo de altura a considerar
257 maxHei : valor maximo de altura a considerar
260 maxHei : valor maximo de altura a considerar
258
261
259 Affected:
262 Affected:
260 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
263 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
261
264
262 Return:
265 Return:
263 1 si el metodo se ejecuto con exito caso contrario devuelve 0
266 1 si el metodo se ejecuto con exito caso contrario devuelve 0
264 """
267 """
265
268
266 if (minHei > maxHei):
269 if (minHei > maxHei):
267 raise ValueError, "Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei)
270 raise ValueError, "Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei)
268
271
269 if (minHei < self.dataOut.heightList[0]):
272 if (minHei < self.dataOut.heightList[0]):
270 minHei = self.dataOut.heightList[0]
273 minHei = self.dataOut.heightList[0]
271
274
272 if (maxHei > self.dataOut.heightList[-1]):
275 if (maxHei > self.dataOut.heightList[-1]):
273 maxHei = self.dataOut.heightList[-1]
276 maxHei = self.dataOut.heightList[-1]
274
277
275 minIndex = 0
278 minIndex = 0
276 maxIndex = 0
279 maxIndex = 0
277 heights = self.dataOut.heightList
280 heights = self.dataOut.heightList
278
281
279 inda = numpy.where(heights >= minHei)
282 inda = numpy.where(heights >= minHei)
280 indb = numpy.where(heights <= maxHei)
283 indb = numpy.where(heights <= maxHei)
281
284
282 try:
285 try:
283 minIndex = inda[0][0]
286 minIndex = inda[0][0]
284 except:
287 except:
285 minIndex = 0
288 minIndex = 0
286
289
287 try:
290 try:
288 maxIndex = indb[0][-1]
291 maxIndex = indb[0][-1]
289 except:
292 except:
290 maxIndex = len(heights)
293 maxIndex = len(heights)
291
294
292 self.selectHeightsByIndex(minIndex, maxIndex)
295 self.selectHeightsByIndex(minIndex, maxIndex)
293
296
294 return 1
297 return 1
295
298
296 def getBeaconSignal(self, tauindex = 0, channelindex = 0, hei_ref=None):
299 def getBeaconSignal(self, tauindex = 0, channelindex = 0, hei_ref=None):
297 newheis = numpy.where(self.dataOut.heightList>self.dataOut.radarControllerHeaderObj.Taus[tauindex])
300 newheis = numpy.where(self.dataOut.heightList>self.dataOut.radarControllerHeaderObj.Taus[tauindex])
298
301
299 if hei_ref != None:
302 if hei_ref != None:
300 newheis = numpy.where(self.dataOut.heightList>hei_ref)
303 newheis = numpy.where(self.dataOut.heightList>hei_ref)
301
304
302 minIndex = min(newheis[0])
305 minIndex = min(newheis[0])
303 maxIndex = max(newheis[0])
306 maxIndex = max(newheis[0])
304 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
307 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
305 heightList = self.dataOut.heightList[minIndex:maxIndex+1]
308 heightList = self.dataOut.heightList[minIndex:maxIndex+1]
306
309
307 # determina indices
310 # determina indices
308 nheis = int(self.dataOut.radarControllerHeaderObj.txB/(self.dataOut.heightList[1]-self.dataOut.heightList[0]))
311 nheis = int(self.dataOut.radarControllerHeaderObj.txB/(self.dataOut.heightList[1]-self.dataOut.heightList[0]))
309 avg_dB = 10*numpy.log10(numpy.sum(data_spc[channelindex,:,:],axis=0))
312 avg_dB = 10*numpy.log10(numpy.sum(data_spc[channelindex,:,:],axis=0))
310 beacon_dB = numpy.sort(avg_dB)[-nheis:]
313 beacon_dB = numpy.sort(avg_dB)[-nheis:]
311 beacon_heiIndexList = []
314 beacon_heiIndexList = []
312 for val in avg_dB.tolist():
315 for val in avg_dB.tolist():
313 if val >= beacon_dB[0]:
316 if val >= beacon_dB[0]:
314 beacon_heiIndexList.append(avg_dB.tolist().index(val))
317 beacon_heiIndexList.append(avg_dB.tolist().index(val))
315
318
316 #data_spc = data_spc[:,:,beacon_heiIndexList]
319 #data_spc = data_spc[:,:,beacon_heiIndexList]
317 data_cspc = None
320 data_cspc = None
318 if self.dataOut.data_cspc is not None:
321 if self.dataOut.data_cspc is not None:
319 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
322 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
320 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
323 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
321
324
322 data_dc = None
325 data_dc = None
323 if self.dataOut.data_dc is not None:
326 if self.dataOut.data_dc is not None:
324 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
327 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
325 #data_dc = data_dc[:,beacon_heiIndexList]
328 #data_dc = data_dc[:,beacon_heiIndexList]
326
329
327 self.dataOut.data_spc = data_spc
330 self.dataOut.data_spc = data_spc
328 self.dataOut.data_cspc = data_cspc
331 self.dataOut.data_cspc = data_cspc
329 self.dataOut.data_dc = data_dc
332 self.dataOut.data_dc = data_dc
330 self.dataOut.heightList = heightList
333 self.dataOut.heightList = heightList
331 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
334 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
332
335
333 return 1
336 return 1
334
337
335
338
336 def selectHeightsByIndex(self, minIndex, maxIndex):
339 def selectHeightsByIndex(self, minIndex, maxIndex):
337 """
340 """
338 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
341 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
339 minIndex <= index <= maxIndex
342 minIndex <= index <= maxIndex
340
343
341 Input:
344 Input:
342 minIndex : valor de indice minimo de altura a considerar
345 minIndex : valor de indice minimo de altura a considerar
343 maxIndex : valor de indice maximo de altura a considerar
346 maxIndex : valor de indice maximo de altura a considerar
344
347
345 Affected:
348 Affected:
346 self.dataOut.data_spc
349 self.dataOut.data_spc
347 self.dataOut.data_cspc
350 self.dataOut.data_cspc
348 self.dataOut.data_dc
351 self.dataOut.data_dc
349 self.dataOut.heightList
352 self.dataOut.heightList
350
353
351 Return:
354 Return:
352 1 si el metodo se ejecuto con exito caso contrario devuelve 0
355 1 si el metodo se ejecuto con exito caso contrario devuelve 0
353 """
356 """
354
357
355 if (minIndex < 0) or (minIndex > maxIndex):
358 if (minIndex < 0) or (minIndex > maxIndex):
356 raise ValueError, "Error selecting heights by index: Index range in (%d,%d) is not valid" % (minIndex, maxIndex)
359 raise ValueError, "Error selecting heights by index: Index range in (%d,%d) is not valid" % (minIndex, maxIndex)
357
360
358 if (maxIndex >= self.dataOut.nHeights):
361 if (maxIndex >= self.dataOut.nHeights):
359 maxIndex = self.dataOut.nHeights-1
362 maxIndex = self.dataOut.nHeights-1
360
363
361 #Spectra
364 #Spectra
362 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
365 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
363
366
364 data_cspc = None
367 data_cspc = None
365 if self.dataOut.data_cspc is not None:
368 if self.dataOut.data_cspc is not None:
366 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
369 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
367
370
368 data_dc = None
371 data_dc = None
369 if self.dataOut.data_dc is not None:
372 if self.dataOut.data_dc is not None:
370 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
373 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
371
374
372 self.dataOut.data_spc = data_spc
375 self.dataOut.data_spc = data_spc
373 self.dataOut.data_cspc = data_cspc
376 self.dataOut.data_cspc = data_cspc
374 self.dataOut.data_dc = data_dc
377 self.dataOut.data_dc = data_dc
375
378
376 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
379 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
377
380
378 return 1
381 return 1
379
382
380 def removeDC(self, mode = 2):
383 def removeDC(self, mode = 2):
381 jspectra = self.dataOut.data_spc
384 jspectra = self.dataOut.data_spc
382 jcspectra = self.dataOut.data_cspc
385 jcspectra = self.dataOut.data_cspc
383
386
384
387
385 num_chan = jspectra.shape[0]
388 num_chan = jspectra.shape[0]
386 num_hei = jspectra.shape[2]
389 num_hei = jspectra.shape[2]
387
390
388 if jcspectra is not None:
391 if jcspectra is not None:
389 jcspectraExist = True
392 jcspectraExist = True
390 num_pairs = jcspectra.shape[0]
393 num_pairs = jcspectra.shape[0]
391 else: jcspectraExist = False
394 else: jcspectraExist = False
392
395
393 freq_dc = jspectra.shape[1]/2
396 freq_dc = jspectra.shape[1]/2
394 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
397 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
395
398
396 if ind_vel[0]<0:
399 if ind_vel[0]<0:
397 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
400 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
398
401
399 if mode == 1:
402 if mode == 1:
400 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
403 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
401
404
402 if jcspectraExist:
405 if jcspectraExist:
403 jcspectra[:,freq_dc,:] = (jcspectra[:,ind_vel[1],:] + jcspectra[:,ind_vel[2],:])/2
406 jcspectra[:,freq_dc,:] = (jcspectra[:,ind_vel[1],:] + jcspectra[:,ind_vel[2],:])/2
404
407
405 if mode == 2:
408 if mode == 2:
406
409
407 vel = numpy.array([-2,-1,1,2])
410 vel = numpy.array([-2,-1,1,2])
408 xx = numpy.zeros([4,4])
411 xx = numpy.zeros([4,4])
409
412
410 for fil in range(4):
413 for fil in range(4):
411 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
414 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
412
415
413 xx_inv = numpy.linalg.inv(xx)
416 xx_inv = numpy.linalg.inv(xx)
414 xx_aux = xx_inv[0,:]
417 xx_aux = xx_inv[0,:]
415
418
416 for ich in range(num_chan):
419 for ich in range(num_chan):
417 yy = jspectra[ich,ind_vel,:]
420 yy = jspectra[ich,ind_vel,:]
418 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
421 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
419
422
420 junkid = jspectra[ich,freq_dc,:]<=0
423 junkid = jspectra[ich,freq_dc,:]<=0
421 cjunkid = sum(junkid)
424 cjunkid = sum(junkid)
422
425
423 if cjunkid.any():
426 if cjunkid.any():
424 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
427 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
425
428
426 if jcspectraExist:
429 if jcspectraExist:
427 for ip in range(num_pairs):
430 for ip in range(num_pairs):
428 yy = jcspectra[ip,ind_vel,:]
431 yy = jcspectra[ip,ind_vel,:]
429 jcspectra[ip,freq_dc,:] = numpy.dot(xx_aux,yy)
432 jcspectra[ip,freq_dc,:] = numpy.dot(xx_aux,yy)
430
433
431
434
432 self.dataOut.data_spc = jspectra
435 self.dataOut.data_spc = jspectra
433 self.dataOut.data_cspc = jcspectra
436 self.dataOut.data_cspc = jcspectra
434
437
435 return 1
438 return 1
436
439
437 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
440 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
438
441
439 jspectra = self.dataOut.data_spc
442 jspectra = self.dataOut.data_spc
440 jcspectra = self.dataOut.data_cspc
443 jcspectra = self.dataOut.data_cspc
441 jnoise = self.dataOut.getNoise()
444 jnoise = self.dataOut.getNoise()
442 num_incoh = self.dataOut.nIncohInt
445 num_incoh = self.dataOut.nIncohInt
443
446
444 num_channel = jspectra.shape[0]
447 num_channel = jspectra.shape[0]
445 num_prof = jspectra.shape[1]
448 num_prof = jspectra.shape[1]
446 num_hei = jspectra.shape[2]
449 num_hei = jspectra.shape[2]
447
450
448 #hei_interf
451 #hei_interf
449 if hei_interf is None:
452 if hei_interf is None:
450 count_hei = num_hei/2 #Como es entero no importa
453 count_hei = num_hei/2 #Como es entero no importa
451 hei_interf = numpy.asmatrix(range(count_hei)) + num_hei - count_hei
454 hei_interf = numpy.asmatrix(range(count_hei)) + num_hei - count_hei
452 hei_interf = numpy.asarray(hei_interf)[0]
455 hei_interf = numpy.asarray(hei_interf)[0]
453 #nhei_interf
456 #nhei_interf
454 if (nhei_interf == None):
457 if (nhei_interf == None):
455 nhei_interf = 5
458 nhei_interf = 5
456 if (nhei_interf < 1):
459 if (nhei_interf < 1):
457 nhei_interf = 1
460 nhei_interf = 1
458 if (nhei_interf > count_hei):
461 if (nhei_interf > count_hei):
459 nhei_interf = count_hei
462 nhei_interf = count_hei
460 if (offhei_interf == None):
463 if (offhei_interf == None):
461 offhei_interf = 0
464 offhei_interf = 0
462
465
463 ind_hei = range(num_hei)
466 ind_hei = range(num_hei)
464 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
467 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
465 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
468 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
466 mask_prof = numpy.asarray(range(num_prof))
469 mask_prof = numpy.asarray(range(num_prof))
467 num_mask_prof = mask_prof.size
470 num_mask_prof = mask_prof.size
468 comp_mask_prof = [0, num_prof/2]
471 comp_mask_prof = [0, num_prof/2]
469
472
470
473
471 #noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
474 #noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
472 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
475 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
473 jnoise = numpy.nan
476 jnoise = numpy.nan
474 noise_exist = jnoise[0] < numpy.Inf
477 noise_exist = jnoise[0] < numpy.Inf
475
478
476 #Subrutina de Remocion de la Interferencia
479 #Subrutina de Remocion de la Interferencia
477 for ich in range(num_channel):
480 for ich in range(num_channel):
478 #Se ordena los espectros segun su potencia (menor a mayor)
481 #Se ordena los espectros segun su potencia (menor a mayor)
479 power = jspectra[ich,mask_prof,:]
482 power = jspectra[ich,mask_prof,:]
480 power = power[:,hei_interf]
483 power = power[:,hei_interf]
481 power = power.sum(axis = 0)
484 power = power.sum(axis = 0)
482 psort = power.ravel().argsort()
485 psort = power.ravel().argsort()
483
486
484 #Se estima la interferencia promedio en los Espectros de Potencia empleando
487 #Se estima la interferencia promedio en los Espectros de Potencia empleando
485 junkspc_interf = jspectra[ich,:,hei_interf[psort[range(offhei_interf, nhei_interf + offhei_interf)]]]
488 junkspc_interf = jspectra[ich,:,hei_interf[psort[range(offhei_interf, nhei_interf + offhei_interf)]]]
486
489
487 if noise_exist:
490 if noise_exist:
488 # tmp_noise = jnoise[ich] / num_prof
491 # tmp_noise = jnoise[ich] / num_prof
489 tmp_noise = jnoise[ich]
492 tmp_noise = jnoise[ich]
490 junkspc_interf = junkspc_interf - tmp_noise
493 junkspc_interf = junkspc_interf - tmp_noise
491 #junkspc_interf[:,comp_mask_prof] = 0
494 #junkspc_interf[:,comp_mask_prof] = 0
492
495
493 jspc_interf = junkspc_interf.sum(axis = 0) / nhei_interf
496 jspc_interf = junkspc_interf.sum(axis = 0) / nhei_interf
494 jspc_interf = jspc_interf.transpose()
497 jspc_interf = jspc_interf.transpose()
495 #Calculando el espectro de interferencia promedio
498 #Calculando el espectro de interferencia promedio
496 noiseid = numpy.where(jspc_interf <= tmp_noise/ math.sqrt(num_incoh))
499 noiseid = numpy.where(jspc_interf <= tmp_noise/ math.sqrt(num_incoh))
497 noiseid = noiseid[0]
500 noiseid = noiseid[0]
498 cnoiseid = noiseid.size
501 cnoiseid = noiseid.size
499 interfid = numpy.where(jspc_interf > tmp_noise/ math.sqrt(num_incoh))
502 interfid = numpy.where(jspc_interf > tmp_noise/ math.sqrt(num_incoh))
500 interfid = interfid[0]
503 interfid = interfid[0]
501 cinterfid = interfid.size
504 cinterfid = interfid.size
502
505
503 if (cnoiseid > 0): jspc_interf[noiseid] = 0
506 if (cnoiseid > 0): jspc_interf[noiseid] = 0
504
507
505 #Expandiendo los perfiles a limpiar
508 #Expandiendo los perfiles a limpiar
506 if (cinterfid > 0):
509 if (cinterfid > 0):
507 new_interfid = (numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof)%num_prof
510 new_interfid = (numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof)%num_prof
508 new_interfid = numpy.asarray(new_interfid)
511 new_interfid = numpy.asarray(new_interfid)
509 new_interfid = {x for x in new_interfid}
512 new_interfid = {x for x in new_interfid}
510 new_interfid = numpy.array(list(new_interfid))
513 new_interfid = numpy.array(list(new_interfid))
511 new_cinterfid = new_interfid.size
514 new_cinterfid = new_interfid.size
512 else: new_cinterfid = 0
515 else: new_cinterfid = 0
513
516
514 for ip in range(new_cinterfid):
517 for ip in range(new_cinterfid):
515 ind = junkspc_interf[:,new_interfid[ip]].ravel().argsort()
518 ind = junkspc_interf[:,new_interfid[ip]].ravel().argsort()
516 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf/2],new_interfid[ip]]
519 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf/2],new_interfid[ip]]
517
520
518
521
519 jspectra[ich,:,ind_hei] = jspectra[ich,:,ind_hei] - jspc_interf #Corregir indices
522 jspectra[ich,:,ind_hei] = jspectra[ich,:,ind_hei] - jspc_interf #Corregir indices
520
523
521 #Removiendo la interferencia del punto de mayor interferencia
524 #Removiendo la interferencia del punto de mayor interferencia
522 ListAux = jspc_interf[mask_prof].tolist()
525 ListAux = jspc_interf[mask_prof].tolist()
523 maxid = ListAux.index(max(ListAux))
526 maxid = ListAux.index(max(ListAux))
524
527
525
528
526 if cinterfid > 0:
529 if cinterfid > 0:
527 for ip in range(cinterfid*(interf == 2) - 1):
530 for ip in range(cinterfid*(interf == 2) - 1):
528 ind = (jspectra[ich,interfid[ip],:] < tmp_noise*(1 + 1/math.sqrt(num_incoh))).nonzero()
531 ind = (jspectra[ich,interfid[ip],:] < tmp_noise*(1 + 1/math.sqrt(num_incoh))).nonzero()
529 cind = len(ind)
532 cind = len(ind)
530
533
531 if (cind > 0):
534 if (cind > 0):
532 jspectra[ich,interfid[ip],ind] = tmp_noise*(1 + (numpy.random.uniform(cind) - 0.5)/math.sqrt(num_incoh))
535 jspectra[ich,interfid[ip],ind] = tmp_noise*(1 + (numpy.random.uniform(cind) - 0.5)/math.sqrt(num_incoh))
533
536
534 ind = numpy.array([-2,-1,1,2])
537 ind = numpy.array([-2,-1,1,2])
535 xx = numpy.zeros([4,4])
538 xx = numpy.zeros([4,4])
536
539
537 for id1 in range(4):
540 for id1 in range(4):
538 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
541 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
539
542
540 xx_inv = numpy.linalg.inv(xx)
543 xx_inv = numpy.linalg.inv(xx)
541 xx = xx_inv[:,0]
544 xx = xx_inv[:,0]
542 ind = (ind + maxid + num_mask_prof)%num_mask_prof
545 ind = (ind + maxid + num_mask_prof)%num_mask_prof
543 yy = jspectra[ich,mask_prof[ind],:]
546 yy = jspectra[ich,mask_prof[ind],:]
544 jspectra[ich,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
547 jspectra[ich,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
545
548
546
549
547 indAux = (jspectra[ich,:,:] < tmp_noise*(1-1/math.sqrt(num_incoh))).nonzero()
550 indAux = (jspectra[ich,:,:] < tmp_noise*(1-1/math.sqrt(num_incoh))).nonzero()
548 jspectra[ich,indAux[0],indAux[1]] = tmp_noise * (1 - 1/math.sqrt(num_incoh))
551 jspectra[ich,indAux[0],indAux[1]] = tmp_noise * (1 - 1/math.sqrt(num_incoh))
549
552
550 #Remocion de Interferencia en el Cross Spectra
553 #Remocion de Interferencia en el Cross Spectra
551 if jcspectra is None: return jspectra, jcspectra
554 if jcspectra is None: return jspectra, jcspectra
552 num_pairs = jcspectra.size/(num_prof*num_hei)
555 num_pairs = jcspectra.size/(num_prof*num_hei)
553 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
556 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
554
557
555 for ip in range(num_pairs):
558 for ip in range(num_pairs):
556
559
557 #-------------------------------------------
560 #-------------------------------------------
558
561
559 cspower = numpy.abs(jcspectra[ip,mask_prof,:])
562 cspower = numpy.abs(jcspectra[ip,mask_prof,:])
560 cspower = cspower[:,hei_interf]
563 cspower = cspower[:,hei_interf]
561 cspower = cspower.sum(axis = 0)
564 cspower = cspower.sum(axis = 0)
562
565
563 cspsort = cspower.ravel().argsort()
566 cspsort = cspower.ravel().argsort()
564 junkcspc_interf = jcspectra[ip,:,hei_interf[cspsort[range(offhei_interf, nhei_interf + offhei_interf)]]]
567 junkcspc_interf = jcspectra[ip,:,hei_interf[cspsort[range(offhei_interf, nhei_interf + offhei_interf)]]]
565 junkcspc_interf = junkcspc_interf.transpose()
568 junkcspc_interf = junkcspc_interf.transpose()
566 jcspc_interf = junkcspc_interf.sum(axis = 1)/nhei_interf
569 jcspc_interf = junkcspc_interf.sum(axis = 1)/nhei_interf
567
570
568 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
571 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
569
572
570 median_real = numpy.median(numpy.real(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
573 median_real = numpy.median(numpy.real(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
571 median_imag = numpy.median(numpy.imag(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
574 median_imag = numpy.median(numpy.imag(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
572 junkcspc_interf[comp_mask_prof,:] = numpy.complex(median_real, median_imag)
575 junkcspc_interf[comp_mask_prof,:] = numpy.complex(median_real, median_imag)
573
576
574 for iprof in range(num_prof):
577 for iprof in range(num_prof):
575 ind = numpy.abs(junkcspc_interf[iprof,:]).ravel().argsort()
578 ind = numpy.abs(junkcspc_interf[iprof,:]).ravel().argsort()
576 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf/2]]
579 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf/2]]
577
580
578 #Removiendo la Interferencia
581 #Removiendo la Interferencia
579 jcspectra[ip,:,ind_hei] = jcspectra[ip,:,ind_hei] - jcspc_interf
582 jcspectra[ip,:,ind_hei] = jcspectra[ip,:,ind_hei] - jcspc_interf
580
583
581 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
584 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
582 maxid = ListAux.index(max(ListAux))
585 maxid = ListAux.index(max(ListAux))
583
586
584 ind = numpy.array([-2,-1,1,2])
587 ind = numpy.array([-2,-1,1,2])
585 xx = numpy.zeros([4,4])
588 xx = numpy.zeros([4,4])
586
589
587 for id1 in range(4):
590 for id1 in range(4):
588 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
591 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
589
592
590 xx_inv = numpy.linalg.inv(xx)
593 xx_inv = numpy.linalg.inv(xx)
591 xx = xx_inv[:,0]
594 xx = xx_inv[:,0]
592
595
593 ind = (ind + maxid + num_mask_prof)%num_mask_prof
596 ind = (ind + maxid + num_mask_prof)%num_mask_prof
594 yy = jcspectra[ip,mask_prof[ind],:]
597 yy = jcspectra[ip,mask_prof[ind],:]
595 jcspectra[ip,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
598 jcspectra[ip,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
596
599
597 #Guardar Resultados
600 #Guardar Resultados
598 self.dataOut.data_spc = jspectra
601 self.dataOut.data_spc = jspectra
599 self.dataOut.data_cspc = jcspectra
602 self.dataOut.data_cspc = jcspectra
600
603
601 return 1
604 return 1
602
605
603 def setRadarFrequency(self, frequency=None):
606 def setRadarFrequency(self, frequency=None):
604
607
605 if frequency != None:
608 if frequency != None:
606 self.dataOut.frequency = frequency
609 self.dataOut.frequency = frequency
607
610
608 return 1
611 return 1
609
612
610 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
613 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
611 #validacion de rango
614 #validacion de rango
612 if minHei == None:
615 if minHei == None:
613 minHei = self.dataOut.heightList[0]
616 minHei = self.dataOut.heightList[0]
614
617
615 if maxHei == None:
618 if maxHei == None:
616 maxHei = self.dataOut.heightList[-1]
619 maxHei = self.dataOut.heightList[-1]
617
620
618 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
621 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
619 print 'minHei: %.2f is out of the heights range'%(minHei)
622 print 'minHei: %.2f is out of the heights range'%(minHei)
620 print 'minHei is setting to %.2f'%(self.dataOut.heightList[0])
623 print 'minHei is setting to %.2f'%(self.dataOut.heightList[0])
621 minHei = self.dataOut.heightList[0]
624 minHei = self.dataOut.heightList[0]
622
625
623 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
626 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
624 print 'maxHei: %.2f is out of the heights range'%(maxHei)
627 print 'maxHei: %.2f is out of the heights range'%(maxHei)
625 print 'maxHei is setting to %.2f'%(self.dataOut.heightList[-1])
628 print 'maxHei is setting to %.2f'%(self.dataOut.heightList[-1])
626 maxHei = self.dataOut.heightList[-1]
629 maxHei = self.dataOut.heightList[-1]
627
630
628 # validacion de velocidades
631 # validacion de velocidades
629 velrange = self.dataOut.getVelRange(1)
632 velrange = self.dataOut.getVelRange(1)
630
633
631 if minVel == None:
634 if minVel == None:
632 minVel = velrange[0]
635 minVel = velrange[0]
633
636
634 if maxVel == None:
637 if maxVel == None:
635 maxVel = velrange[-1]
638 maxVel = velrange[-1]
636
639
637 if (minVel < velrange[0]) or (minVel > maxVel):
640 if (minVel < velrange[0]) or (minVel > maxVel):
638 print 'minVel: %.2f is out of the velocity range'%(minVel)
641 print 'minVel: %.2f is out of the velocity range'%(minVel)
639 print 'minVel is setting to %.2f'%(velrange[0])
642 print 'minVel is setting to %.2f'%(velrange[0])
640 minVel = velrange[0]
643 minVel = velrange[0]
641
644
642 if (maxVel > velrange[-1]) or (maxVel < minVel):
645 if (maxVel > velrange[-1]) or (maxVel < minVel):
643 print 'maxVel: %.2f is out of the velocity range'%(maxVel)
646 print 'maxVel: %.2f is out of the velocity range'%(maxVel)
644 print 'maxVel is setting to %.2f'%(velrange[-1])
647 print 'maxVel is setting to %.2f'%(velrange[-1])
645 maxVel = velrange[-1]
648 maxVel = velrange[-1]
646
649
647 # seleccion de indices para rango
650 # seleccion de indices para rango
648 minIndex = 0
651 minIndex = 0
649 maxIndex = 0
652 maxIndex = 0
650 heights = self.dataOut.heightList
653 heights = self.dataOut.heightList
651
654
652 inda = numpy.where(heights >= minHei)
655 inda = numpy.where(heights >= minHei)
653 indb = numpy.where(heights <= maxHei)
656 indb = numpy.where(heights <= maxHei)
654
657
655 try:
658 try:
656 minIndex = inda[0][0]
659 minIndex = inda[0][0]
657 except:
660 except:
658 minIndex = 0
661 minIndex = 0
659
662
660 try:
663 try:
661 maxIndex = indb[0][-1]
664 maxIndex = indb[0][-1]
662 except:
665 except:
663 maxIndex = len(heights)
666 maxIndex = len(heights)
664
667
665 if (minIndex < 0) or (minIndex > maxIndex):
668 if (minIndex < 0) or (minIndex > maxIndex):
666 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
669 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
667
670
668 if (maxIndex >= self.dataOut.nHeights):
671 if (maxIndex >= self.dataOut.nHeights):
669 maxIndex = self.dataOut.nHeights-1
672 maxIndex = self.dataOut.nHeights-1
670
673
671 # seleccion de indices para velocidades
674 # seleccion de indices para velocidades
672 indminvel = numpy.where(velrange >= minVel)
675 indminvel = numpy.where(velrange >= minVel)
673 indmaxvel = numpy.where(velrange <= maxVel)
676 indmaxvel = numpy.where(velrange <= maxVel)
674 try:
677 try:
675 minIndexVel = indminvel[0][0]
678 minIndexVel = indminvel[0][0]
676 except:
679 except:
677 minIndexVel = 0
680 minIndexVel = 0
678
681
679 try:
682 try:
680 maxIndexVel = indmaxvel[0][-1]
683 maxIndexVel = indmaxvel[0][-1]
681 except:
684 except:
682 maxIndexVel = len(velrange)
685 maxIndexVel = len(velrange)
683
686
684 #seleccion del espectro
687 #seleccion del espectro
685 data_spc = self.dataOut.data_spc[:,minIndexVel:maxIndexVel+1,minIndex:maxIndex+1]
688 data_spc = self.dataOut.data_spc[:,minIndexVel:maxIndexVel+1,minIndex:maxIndex+1]
686 #estimacion de ruido
689 #estimacion de ruido
687 noise = numpy.zeros(self.dataOut.nChannels)
690 noise = numpy.zeros(self.dataOut.nChannels)
688
691
689 for channel in range(self.dataOut.nChannels):
692 for channel in range(self.dataOut.nChannels):
690 daux = data_spc[channel,:,:]
693 daux = data_spc[channel,:,:]
691 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
694 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
692
695
693 self.dataOut.noise_estimation = noise.copy()
696 self.dataOut.noise_estimation = noise.copy()
694
697
695 return 1
698 return 1
696
699
697 class IncohInt(Operation):
700 class IncohInt(Operation):
698
701
699
702
700 __profIndex = 0
703 __profIndex = 0
701 __withOverapping = False
704 __withOverapping = False
702
705
703 __byTime = False
706 __byTime = False
704 __initime = None
707 __initime = None
705 __lastdatatime = None
708 __lastdatatime = None
706 __integrationtime = None
709 __integrationtime = None
707
710
708 __buffer_spc = None
711 __buffer_spc = None
709 __buffer_cspc = None
712 __buffer_cspc = None
710 __buffer_dc = None
713 __buffer_dc = None
711
714
712 __dataReady = False
715 __dataReady = False
713
716
714 __timeInterval = None
717 __timeInterval = None
715
718
716 n = None
719 n = None
717
720
718
721
719
722
720 def __init__(self):
723 def __init__(self):
721
724
722 Operation.__init__(self)
725 Operation.__init__(self)
723 # self.isConfig = False
726 # self.isConfig = False
724
727
725 def setup(self, n=None, timeInterval=None, overlapping=False):
728 def setup(self, n=None, timeInterval=None, overlapping=False):
726 """
729 """
727 Set the parameters of the integration class.
730 Set the parameters of the integration class.
728
731
729 Inputs:
732 Inputs:
730
733
731 n : Number of coherent integrations
734 n : Number of coherent integrations
732 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
735 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
733 overlapping :
736 overlapping :
734
737
735 """
738 """
736
739
737 self.__initime = None
740 self.__initime = None
738 self.__lastdatatime = 0
741 self.__lastdatatime = 0
739
742
740 self.__buffer_spc = 0
743 self.__buffer_spc = 0
741 self.__buffer_cspc = 0
744 self.__buffer_cspc = 0
742 self.__buffer_dc = 0
745 self.__buffer_dc = 0
743
746
744 self.__profIndex = 0
747 self.__profIndex = 0
745 self.__dataReady = False
748 self.__dataReady = False
746 self.__byTime = False
749 self.__byTime = False
747
750
748 if n is None and timeInterval is None:
751 if n is None and timeInterval is None:
749 raise ValueError, "n or timeInterval should be specified ..."
752 raise ValueError, "n or timeInterval should be specified ..."
750
753
751 if n is not None:
754 if n is not None:
752 self.n = int(n)
755 self.n = int(n)
753 else:
756 else:
754 self.__integrationtime = int(timeInterval) #if (type(timeInterval)!=integer) -> change this line
757 self.__integrationtime = int(timeInterval) #if (type(timeInterval)!=integer) -> change this line
755 self.n = None
758 self.n = None
756 self.__byTime = True
759 self.__byTime = True
757
760
758 def putData(self, data_spc, data_cspc, data_dc):
761 def putData(self, data_spc, data_cspc, data_dc):
759
762
760 """
763 """
761 Add a profile to the __buffer_spc and increase in one the __profileIndex
764 Add a profile to the __buffer_spc and increase in one the __profileIndex
762
765
763 """
766 """
764
767
765 self.__buffer_spc += data_spc
768 self.__buffer_spc += data_spc
766
769
767 if data_cspc is None:
770 if data_cspc is None:
768 self.__buffer_cspc = None
771 self.__buffer_cspc = None
769 else:
772 else:
770 self.__buffer_cspc += data_cspc
773 self.__buffer_cspc += data_cspc
771
774
772 if data_dc is None:
775 if data_dc is None:
773 self.__buffer_dc = None
776 self.__buffer_dc = None
774 else:
777 else:
775 self.__buffer_dc += data_dc
778 self.__buffer_dc += data_dc
776
779
777 self.__profIndex += 1
780 self.__profIndex += 1
778
781
779 return
782 return
780
783
781 def pushData(self):
784 def pushData(self):
782 """
785 """
783 Return the sum of the last profiles and the profiles used in the sum.
786 Return the sum of the last profiles and the profiles used in the sum.
784
787
785 Affected:
788 Affected:
786
789
787 self.__profileIndex
790 self.__profileIndex
788
791
789 """
792 """
790
793
791 data_spc = self.__buffer_spc
794 data_spc = self.__buffer_spc
792 data_cspc = self.__buffer_cspc
795 data_cspc = self.__buffer_cspc
793 data_dc = self.__buffer_dc
796 data_dc = self.__buffer_dc
794 n = self.__profIndex
797 n = self.__profIndex
795
798
796 self.__buffer_spc = 0
799 self.__buffer_spc = 0
797 self.__buffer_cspc = 0
800 self.__buffer_cspc = 0
798 self.__buffer_dc = 0
801 self.__buffer_dc = 0
799 self.__profIndex = 0
802 self.__profIndex = 0
800
803
801 return data_spc, data_cspc, data_dc, n
804 return data_spc, data_cspc, data_dc, n
802
805
803 def byProfiles(self, *args):
806 def byProfiles(self, *args):
804
807
805 self.__dataReady = False
808 self.__dataReady = False
806 avgdata_spc = None
809 avgdata_spc = None
807 avgdata_cspc = None
810 avgdata_cspc = None
808 avgdata_dc = None
811 avgdata_dc = None
809
812
810 self.putData(*args)
813 self.putData(*args)
811
814
812 if self.__profIndex == self.n:
815 if self.__profIndex == self.n:
813
816
814 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
817 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
815 self.n = n
818 self.n = n
816 self.__dataReady = True
819 self.__dataReady = True
817
820
818 return avgdata_spc, avgdata_cspc, avgdata_dc
821 return avgdata_spc, avgdata_cspc, avgdata_dc
819
822
820 def byTime(self, datatime, *args):
823 def byTime(self, datatime, *args):
821
824
822 self.__dataReady = False
825 self.__dataReady = False
823 avgdata_spc = None
826 avgdata_spc = None
824 avgdata_cspc = None
827 avgdata_cspc = None
825 avgdata_dc = None
828 avgdata_dc = None
826
829
827 self.putData(*args)
830 self.putData(*args)
828
831
829 if (datatime - self.__initime) >= self.__integrationtime:
832 if (datatime - self.__initime) >= self.__integrationtime:
830 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
833 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
831 self.n = n
834 self.n = n
832 self.__dataReady = True
835 self.__dataReady = True
833
836
834 return avgdata_spc, avgdata_cspc, avgdata_dc
837 return avgdata_spc, avgdata_cspc, avgdata_dc
835
838
836 def integrate(self, datatime, *args):
839 def integrate(self, datatime, *args):
837
840
838 if self.__profIndex == 0:
841 if self.__profIndex == 0:
839 self.__initime = datatime
842 self.__initime = datatime
840
843
841 if self.__byTime:
844 if self.__byTime:
842 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
845 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
843 else:
846 else:
844 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
847 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
845
848
846 if not self.__dataReady:
849 if not self.__dataReady:
847 return None, None, None, None
850 return None, None, None, None
848
851
849 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
852 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
850
853
851 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
854 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
852
855
853 if n==1:
856 if n==1:
854 return
857 return
855
858
856 dataOut.flagNoData = True
859 dataOut.flagNoData = True
857
860
858 if not self.isConfig:
861 if not self.isConfig:
859 self.setup(n, timeInterval, overlapping)
862 self.setup(n, timeInterval, overlapping)
860 self.isConfig = True
863 self.isConfig = True
861
864
862 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
865 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
863 dataOut.data_spc,
866 dataOut.data_spc,
864 dataOut.data_cspc,
867 dataOut.data_cspc,
865 dataOut.data_dc)
868 dataOut.data_dc)
866
869
867 if self.__dataReady:
870 if self.__dataReady:
868
871
869 dataOut.data_spc = avgdata_spc
872 dataOut.data_spc = avgdata_spc
870 dataOut.data_cspc = avgdata_cspc
873 dataOut.data_cspc = avgdata_cspc
871 dataOut.data_dc = avgdata_dc
874 dataOut.data_dc = avgdata_dc
872
875
873 dataOut.nIncohInt *= self.n
876 dataOut.nIncohInt *= self.n
874 dataOut.utctime = avgdatatime
877 dataOut.utctime = avgdatatime
875 dataOut.flagNoData = False
878 dataOut.flagNoData = False
@@ -1,1071 +1,1072
1 import numpy
1 import numpy
2
2
3 from jroproc_base import ProcessingUnit, Operation
3 from jroproc_base import ProcessingUnit, Operation
4 from schainpy.model.data.jrodata import Voltage
4 from schainpy.model.data.jrodata import Voltage
5
5
6 class VoltageProc(ProcessingUnit):
6 class VoltageProc(ProcessingUnit):
7
7
8
8
9 def __init__(self):
9 def __init__(self):
10
10
11 ProcessingUnit.__init__(self)
11 ProcessingUnit.__init__(self)
12
12
13 # self.objectDict = {}
13 # self.objectDict = {}
14 self.dataOut = Voltage()
14 self.dataOut = Voltage()
15 self.flip = 1
15 self.flip = 1
16
16
17 def run(self):
17 def run(self):
18 if self.dataIn.type == 'AMISR':
18 if self.dataIn.type == 'AMISR':
19 self.__updateObjFromAmisrInput()
19 self.__updateObjFromAmisrInput()
20
20
21 if self.dataIn.type == 'Voltage':
21 if self.dataIn.type == 'Voltage':
22 self.dataOut.copy(self.dataIn)
22 self.dataOut.copy(self.dataIn)
23
23
24 # self.dataOut.copy(self.dataIn)
24 # self.dataOut.copy(self.dataIn)
25
25
26 def __updateObjFromAmisrInput(self):
26 def __updateObjFromAmisrInput(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
32
33 self.dataOut.flagNoData = self.dataIn.flagNoData
33 self.dataOut.flagNoData = self.dataIn.flagNoData
34 self.dataOut.data = self.dataIn.data
34 self.dataOut.data = self.dataIn.data
35 self.dataOut.utctime = self.dataIn.utctime
35 self.dataOut.utctime = self.dataIn.utctime
36 self.dataOut.channelList = self.dataIn.channelList
36 self.dataOut.channelList = self.dataIn.channelList
37 # self.dataOut.timeInterval = self.dataIn.timeInterval
37 # self.dataOut.timeInterval = self.dataIn.timeInterval
38 self.dataOut.heightList = self.dataIn.heightList
38 self.dataOut.heightList = self.dataIn.heightList
39 self.dataOut.nProfiles = self.dataIn.nProfiles
39 self.dataOut.nProfiles = self.dataIn.nProfiles
40
40
41 self.dataOut.nCohInt = self.dataIn.nCohInt
41 self.dataOut.nCohInt = self.dataIn.nCohInt
42 self.dataOut.ippSeconds = self.dataIn.ippSeconds
42 self.dataOut.ippSeconds = self.dataIn.ippSeconds
43 self.dataOut.frequency = self.dataIn.frequency
43 self.dataOut.frequency = self.dataIn.frequency
44
44
45 self.dataOut.azimuth = self.dataIn.azimuth
45 self.dataOut.azimuth = self.dataIn.azimuth
46 self.dataOut.zenith = self.dataIn.zenith
46 self.dataOut.zenith = self.dataIn.zenith
47
47
48 self.dataOut.beam.codeList = self.dataIn.beam.codeList
48 self.dataOut.beam.codeList = self.dataIn.beam.codeList
49 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
49 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
50 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
50 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
51 #
51 #
52 # pass#
52 # pass#
53 #
53 #
54 # def init(self):
54 # def init(self):
55 #
55 #
56 #
56 #
57 # if self.dataIn.type == 'AMISR':
57 # if self.dataIn.type == 'AMISR':
58 # self.__updateObjFromAmisrInput()
58 # self.__updateObjFromAmisrInput()
59 #
59 #
60 # if self.dataIn.type == 'Voltage':
60 # if self.dataIn.type == 'Voltage':
61 # self.dataOut.copy(self.dataIn)
61 # self.dataOut.copy(self.dataIn)
62 # # No necesita copiar en cada init() los atributos de dataIn
62 # # No necesita copiar en cada init() los atributos de dataIn
63 # # la copia deberia hacerse por cada nuevo bloque de datos
63 # # la copia deberia hacerse por cada nuevo bloque de datos
64
64
65 def selectChannels(self, channelList):
65 def selectChannels(self, channelList):
66
66
67 channelIndexList = []
67 channelIndexList = []
68
68
69 for channel in channelList:
69 for channel in channelList:
70 if channel not in self.dataOut.channelList:
70 if channel not in self.dataOut.channelList:
71 raise ValueError, "Channel %d is not in %s" %(channel, str(self.dataOut.channelList))
71 raise ValueError, "Channel %d is not in %s" %(channel, str(self.dataOut.channelList))
72
72
73 index = self.dataOut.channelList.index(channel)
73 index = self.dataOut.channelList.index(channel)
74 channelIndexList.append(index)
74 channelIndexList.append(index)
75
75
76 self.selectChannelsByIndex(channelIndexList)
76 self.selectChannelsByIndex(channelIndexList)
77
77
78 def selectChannelsByIndex(self, channelIndexList):
78 def selectChannelsByIndex(self, channelIndexList):
79 """
79 """
80 Selecciona un bloque de datos en base a canales segun el channelIndexList
80 Selecciona un bloque de datos en base a canales segun el channelIndexList
81
81
82 Input:
82 Input:
83 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
83 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
84
84
85 Affected:
85 Affected:
86 self.dataOut.data
86 self.dataOut.data
87 self.dataOut.channelIndexList
87 self.dataOut.channelIndexList
88 self.dataOut.nChannels
88 self.dataOut.nChannels
89 self.dataOut.m_ProcessingHeader.totalSpectra
89 self.dataOut.m_ProcessingHeader.totalSpectra
90 self.dataOut.systemHeaderObj.numChannels
90 self.dataOut.systemHeaderObj.numChannels
91 self.dataOut.m_ProcessingHeader.blockSize
91 self.dataOut.m_ProcessingHeader.blockSize
92
92
93 Return:
93 Return:
94 None
94 None
95 """
95 """
96
96
97 for channelIndex in channelIndexList:
97 for channelIndex in channelIndexList:
98 if channelIndex not in self.dataOut.channelIndexList:
98 if channelIndex not in self.dataOut.channelIndexList:
99 print channelIndexList
99 print channelIndexList
100 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
100 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
101
101
102 if self.dataOut.flagDataAsBlock:
102 if self.dataOut.flagDataAsBlock:
103 """
103 """
104 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
104 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
105 """
105 """
106 data = self.dataOut.data[channelIndexList,:,:]
106 data = self.dataOut.data[channelIndexList,:,:]
107 else:
107 else:
108 data = self.dataOut.data[channelIndexList,:]
108 data = self.dataOut.data[channelIndexList,:]
109
109
110 self.dataOut.data = data
110 self.dataOut.data = data
111 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
111 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
112 # self.dataOut.nChannels = nChannels
112 # self.dataOut.nChannels = nChannels
113
113
114 return 1
114 return 1
115
115
116 def selectHeights(self, minHei=None, maxHei=None):
116 def selectHeights(self, minHei=None, maxHei=None):
117 """
117 """
118 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
118 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
119 minHei <= height <= maxHei
119 minHei <= height <= maxHei
120
120
121 Input:
121 Input:
122 minHei : valor minimo de altura a considerar
122 minHei : valor minimo de altura a considerar
123 maxHei : valor maximo de altura a considerar
123 maxHei : valor maximo de altura a considerar
124
124
125 Affected:
125 Affected:
126 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
126 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
127
127
128 Return:
128 Return:
129 1 si el metodo se ejecuto con exito caso contrario devuelve 0
129 1 si el metodo se ejecuto con exito caso contrario devuelve 0
130 """
130 """
131
131
132 if minHei == None:
132 if minHei == None:
133 minHei = self.dataOut.heightList[0]
133 minHei = self.dataOut.heightList[0]
134
134
135 if maxHei == None:
135 if maxHei == None:
136 maxHei = self.dataOut.heightList[-1]
136 maxHei = self.dataOut.heightList[-1]
137
137
138 if (minHei < self.dataOut.heightList[0]):
138 if (minHei < self.dataOut.heightList[0]):
139 minHei = self.dataOut.heightList[0]
139 minHei = self.dataOut.heightList[0]
140
140
141 if (maxHei > self.dataOut.heightList[-1]):
141 if (maxHei > self.dataOut.heightList[-1]):
142 maxHei = self.dataOut.heightList[-1]
142 maxHei = self.dataOut.heightList[-1]
143
143
144 minIndex = 0
144 minIndex = 0
145 maxIndex = 0
145 maxIndex = 0
146 heights = self.dataOut.heightList
146 heights = self.dataOut.heightList
147
147
148 inda = numpy.where(heights >= minHei)
148 inda = numpy.where(heights >= minHei)
149 indb = numpy.where(heights <= maxHei)
149 indb = numpy.where(heights <= maxHei)
150
150
151 try:
151 try:
152 minIndex = inda[0][0]
152 minIndex = inda[0][0]
153 except:
153 except:
154 minIndex = 0
154 minIndex = 0
155
155
156 try:
156 try:
157 maxIndex = indb[0][-1]
157 maxIndex = indb[0][-1]
158 except:
158 except:
159 maxIndex = len(heights)
159 maxIndex = len(heights)
160
160
161 self.selectHeightsByIndex(minIndex, maxIndex)
161 self.selectHeightsByIndex(minIndex, maxIndex)
162
162
163 return 1
163 return 1
164
164
165
165
166 def selectHeightsByIndex(self, minIndex, maxIndex):
166 def selectHeightsByIndex(self, minIndex, maxIndex):
167 """
167 """
168 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
168 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
169 minIndex <= index <= maxIndex
169 minIndex <= index <= maxIndex
170
170
171 Input:
171 Input:
172 minIndex : valor de indice minimo de altura a considerar
172 minIndex : valor de indice minimo de altura a considerar
173 maxIndex : valor de indice maximo de altura a considerar
173 maxIndex : valor de indice maximo de altura a considerar
174
174
175 Affected:
175 Affected:
176 self.dataOut.data
176 self.dataOut.data
177 self.dataOut.heightList
177 self.dataOut.heightList
178
178
179 Return:
179 Return:
180 1 si el metodo se ejecuto con exito caso contrario devuelve 0
180 1 si el metodo se ejecuto con exito caso contrario devuelve 0
181 """
181 """
182
182
183 if (minIndex < 0) or (minIndex > maxIndex):
183 if (minIndex < 0) or (minIndex > maxIndex):
184 raise ValueError, "Height index range (%d,%d) is not valid" % (minIndex, maxIndex)
184 raise ValueError, "Height index range (%d,%d) is not valid" % (minIndex, maxIndex)
185
185
186 if (maxIndex >= self.dataOut.nHeights):
186 if (maxIndex >= self.dataOut.nHeights):
187 maxIndex = self.dataOut.nHeights
187 maxIndex = self.dataOut.nHeights
188
188
189 #voltage
189 #voltage
190 if self.dataOut.flagDataAsBlock:
190 if self.dataOut.flagDataAsBlock:
191 """
191 """
192 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
192 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
193 """
193 """
194 data = self.dataOut.data[:,:, minIndex:maxIndex]
194 data = self.dataOut.data[:,:, minIndex:maxIndex]
195 else:
195 else:
196 data = self.dataOut.data[:, minIndex:maxIndex]
196 data = self.dataOut.data[:, minIndex:maxIndex]
197
197
198 # firstHeight = self.dataOut.heightList[minIndex]
198 # firstHeight = self.dataOut.heightList[minIndex]
199
199
200 self.dataOut.data = data
200 self.dataOut.data = data
201 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
201 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
202
202
203 if self.dataOut.nHeights <= 1:
203 if self.dataOut.nHeights <= 1:
204 raise ValueError, "selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights)
204 raise ValueError, "selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights)
205
205
206 return 1
206 return 1
207
207
208
208
209 def filterByHeights(self, window):
209 def filterByHeights(self, window):
210
210
211 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
211 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
212
212
213 if window == None:
213 if window == None:
214 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
214 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
215
215
216 newdelta = deltaHeight * window
216 newdelta = deltaHeight * window
217 r = self.dataOut.nHeights % window
217 r = self.dataOut.nHeights % window
218 newheights = (self.dataOut.nHeights-r)/window
218 newheights = (self.dataOut.nHeights-r)/window
219
219
220 if newheights <= 1:
220 if newheights <= 1:
221 raise ValueError, "filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window)
221 raise ValueError, "filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window)
222
222
223 if self.dataOut.flagDataAsBlock:
223 if self.dataOut.flagDataAsBlock:
224 """
224 """
225 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
225 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
226 """
226 """
227 buffer = self.dataOut.data[:, :, 0:self.dataOut.nHeights-r]
227 buffer = self.dataOut.data[:, :, 0:self.dataOut.nHeights-r]
228 buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nProfiles,self.dataOut.nHeights/window,window)
228 buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nProfiles,self.dataOut.nHeights/window,window)
229 buffer = numpy.sum(buffer,3)
229 buffer = numpy.sum(buffer,3)
230
230
231 else:
231 else:
232 buffer = self.dataOut.data[:,0:self.dataOut.nHeights-r]
232 buffer = self.dataOut.data[:,0:self.dataOut.nHeights-r]
233 buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nHeights/window,window)
233 buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nHeights/window,window)
234 buffer = numpy.sum(buffer,2)
234 buffer = numpy.sum(buffer,2)
235
235
236 self.dataOut.data = buffer
236 self.dataOut.data = buffer
237 self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta
237 self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta
238 self.dataOut.windowOfFilter = window
238 self.dataOut.windowOfFilter = window
239
239
240 def setH0(self, h0, deltaHeight = None):
240 def setH0(self, h0, deltaHeight = None):
241
241
242 if not deltaHeight:
242 if not deltaHeight:
243 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
243 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
244
244
245 nHeights = self.dataOut.nHeights
245 nHeights = self.dataOut.nHeights
246
246
247 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
247 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
248
248
249 self.dataOut.heightList = newHeiRange
249 self.dataOut.heightList = newHeiRange
250
250
251 def deFlip(self, channelList = []):
251 def deFlip(self, channelList = []):
252
252
253 data = self.dataOut.data.copy()
253 data = self.dataOut.data.copy()
254
254
255 if self.dataOut.flagDataAsBlock:
255 if self.dataOut.flagDataAsBlock:
256 flip = self.flip
256 flip = self.flip
257 profileList = range(self.dataOut.nProfiles)
257 profileList = range(self.dataOut.nProfiles)
258
258
259 if not channelList:
259 if not channelList:
260 for thisProfile in profileList:
260 for thisProfile in profileList:
261 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
261 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
262 flip *= -1.0
262 flip *= -1.0
263 else:
263 else:
264 for thisChannel in channelList:
264 for thisChannel in channelList:
265 if thisChannel not in self.dataOut.channelList:
265 if thisChannel not in self.dataOut.channelList:
266 continue
266 continue
267
267
268 for thisProfile in profileList:
268 for thisProfile in profileList:
269 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
269 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
270 flip *= -1.0
270 flip *= -1.0
271
271
272 self.flip = flip
272 self.flip = flip
273
273
274 else:
274 else:
275 if not channelList:
275 if not channelList:
276 data[:,:] = data[:,:]*self.flip
276 data[:,:] = data[:,:]*self.flip
277 else:
277 else:
278 for thisChannel in channelList:
278 for thisChannel in channelList:
279 if thisChannel not in self.dataOut.channelList:
279 if thisChannel not in self.dataOut.channelList:
280 continue
280 continue
281
281
282 data[thisChannel,:] = data[thisChannel,:]*self.flip
282 data[thisChannel,:] = data[thisChannel,:]*self.flip
283
283
284 self.flip *= -1.
284 self.flip *= -1.
285
285
286 self.dataOut.data = data
286 self.dataOut.data = data
287
287
288 def setRadarFrequency(self, frequency=None):
288 def setRadarFrequency(self, frequency=None):
289
289
290 if frequency != None:
290 if frequency != None:
291 self.dataOut.frequency = frequency
291 self.dataOut.frequency = frequency
292
292
293 return 1
293 return 1
294
294
295 class CohInt(Operation):
295 class CohInt(Operation):
296
296
297 isConfig = False
297 isConfig = False
298
298
299 __profIndex = 0
299 __profIndex = 0
300 __withOverapping = False
300 __withOverapping = False
301
301
302 __byTime = False
302 __byTime = False
303 __initime = None
303 __initime = None
304 __lastdatatime = None
304 __lastdatatime = None
305 __integrationtime = None
305 __integrationtime = None
306
306
307 __buffer = None
307 __buffer = None
308
308
309 __dataReady = False
309 __dataReady = False
310
310
311 n = None
311 n = None
312
312
313
313
314 def __init__(self):
314 def __init__(self):
315
315
316 Operation.__init__(self)
316 Operation.__init__(self)
317
317
318 # self.isConfig = False
318 # self.isConfig = False
319
319
320 def setup(self, n=None, timeInterval=None, overlapping=False, byblock=False):
320 def setup(self, n=None, timeInterval=None, overlapping=False, byblock=False):
321 """
321 """
322 Set the parameters of the integration class.
322 Set the parameters of the integration class.
323
323
324 Inputs:
324 Inputs:
325
325
326 n : Number of coherent integrations
326 n : Number of coherent integrations
327 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
327 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
328 overlapping :
328 overlapping :
329
329
330 """
330 """
331
331
332 self.__initime = None
332 self.__initime = None
333 self.__lastdatatime = 0
333 self.__lastdatatime = 0
334 self.__buffer = None
334 self.__buffer = None
335 self.__dataReady = False
335 self.__dataReady = False
336 self.byblock = byblock
336 self.byblock = byblock
337
337
338 if n == None and timeInterval == None:
338 if n == None and timeInterval == None:
339 raise ValueError, "n or timeInterval should be specified ..."
339 raise ValueError, "n or timeInterval should be specified ..."
340
340
341 if n != None:
341 if n != None:
342 self.n = n
342 self.n = n
343 self.__byTime = False
343 self.__byTime = False
344 else:
344 else:
345 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
345 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
346 self.n = 9999
346 self.n = 9999
347 self.__byTime = True
347 self.__byTime = True
348
348
349 if overlapping:
349 if overlapping:
350 self.__withOverapping = True
350 self.__withOverapping = True
351 self.__buffer = None
351 self.__buffer = None
352 else:
352 else:
353 self.__withOverapping = False
353 self.__withOverapping = False
354 self.__buffer = 0
354 self.__buffer = 0
355
355
356 self.__profIndex = 0
356 self.__profIndex = 0
357
357
358 def putData(self, data):
358 def putData(self, data):
359
359
360 """
360 """
361 Add a profile to the __buffer and increase in one the __profileIndex
361 Add a profile to the __buffer and increase in one the __profileIndex
362
362
363 """
363 """
364
364
365 if not self.__withOverapping:
365 if not self.__withOverapping:
366 self.__buffer += data.copy()
366 self.__buffer += data.copy()
367 self.__profIndex += 1
367 self.__profIndex += 1
368 return
368 return
369
369
370 #Overlapping data
370 #Overlapping data
371 nChannels, nHeis = data.shape
371 nChannels, nHeis = data.shape
372 data = numpy.reshape(data, (1, nChannels, nHeis))
372 data = numpy.reshape(data, (1, nChannels, nHeis))
373
373
374 #If the buffer is empty then it takes the data value
374 #If the buffer is empty then it takes the data value
375 if self.__buffer is None:
375 if self.__buffer is None:
376 self.__buffer = data
376 self.__buffer = data
377 self.__profIndex += 1
377 self.__profIndex += 1
378 return
378 return
379
379
380 #If the buffer length is lower than n then stakcing the data value
380 #If the buffer length is lower than n then stakcing the data value
381 if self.__profIndex < self.n:
381 if self.__profIndex < self.n:
382 self.__buffer = numpy.vstack((self.__buffer, data))
382 self.__buffer = numpy.vstack((self.__buffer, data))
383 self.__profIndex += 1
383 self.__profIndex += 1
384 return
384 return
385
385
386 #If the buffer length is equal to n then replacing the last buffer value with the data value
386 #If the buffer length is equal to n then replacing the last buffer value with the data value
387 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
387 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
388 self.__buffer[self.n-1] = data
388 self.__buffer[self.n-1] = data
389 self.__profIndex = self.n
389 self.__profIndex = self.n
390 return
390 return
391
391
392
392
393 def pushData(self):
393 def pushData(self):
394 """
394 """
395 Return the sum of the last profiles and the profiles used in the sum.
395 Return the sum of the last profiles and the profiles used in the sum.
396
396
397 Affected:
397 Affected:
398
398
399 self.__profileIndex
399 self.__profileIndex
400
400
401 """
401 """
402
402
403 if not self.__withOverapping:
403 if not self.__withOverapping:
404 data = self.__buffer
404 data = self.__buffer
405 n = self.__profIndex
405 n = self.__profIndex
406
406
407 self.__buffer = 0
407 self.__buffer = 0
408 self.__profIndex = 0
408 self.__profIndex = 0
409
409
410 return data, n
410 return data, n
411
411
412 #Integration with Overlapping
412 #Integration with Overlapping
413 data = numpy.sum(self.__buffer, axis=0)
413 data = numpy.sum(self.__buffer, axis=0)
414 n = self.__profIndex
414 n = self.__profIndex
415
415
416 return data, n
416 return data, n
417
417
418 def byProfiles(self, data):
418 def byProfiles(self, data):
419
419
420 self.__dataReady = False
420 self.__dataReady = False
421 avgdata = None
421 avgdata = None
422 # n = None
422 # n = None
423
423
424 self.putData(data)
424 self.putData(data)
425
425
426 if self.__profIndex == self.n:
426 if self.__profIndex == self.n:
427
427
428 avgdata, n = self.pushData()
428 avgdata, n = self.pushData()
429 self.__dataReady = True
429 self.__dataReady = True
430
430
431 return avgdata
431 return avgdata
432
432
433 def byTime(self, data, datatime):
433 def byTime(self, data, datatime):
434
434
435 self.__dataReady = False
435 self.__dataReady = False
436 avgdata = None
436 avgdata = None
437 n = None
437 n = None
438
438
439 self.putData(data)
439 self.putData(data)
440
440
441 if (datatime - self.__initime) >= self.__integrationtime:
441 if (datatime - self.__initime) >= self.__integrationtime:
442 avgdata, n = self.pushData()
442 avgdata, n = self.pushData()
443 self.n = n
443 self.n = n
444 self.__dataReady = True
444 self.__dataReady = True
445
445
446 return avgdata
446 return avgdata
447
447
448 def integrate(self, data, datatime=None):
448 def integrate(self, data, datatime=None):
449
449
450 if self.__initime == None:
450 if self.__initime == None:
451 self.__initime = datatime
451 self.__initime = datatime
452
452
453 if self.__byTime:
453 if self.__byTime:
454 avgdata = self.byTime(data, datatime)
454 avgdata = self.byTime(data, datatime)
455 else:
455 else:
456 avgdata = self.byProfiles(data)
456 avgdata = self.byProfiles(data)
457
457
458
458
459 self.__lastdatatime = datatime
459 self.__lastdatatime = datatime
460
460
461 if avgdata is None:
461 if avgdata is None:
462 return None, None
462 return None, None
463
463
464 avgdatatime = self.__initime
464 avgdatatime = self.__initime
465
465
466 deltatime = datatime -self.__lastdatatime
466 deltatime = datatime -self.__lastdatatime
467
467
468 if not self.__withOverapping:
468 if not self.__withOverapping:
469 self.__initime = datatime
469 self.__initime = datatime
470 else:
470 else:
471 self.__initime += deltatime
471 self.__initime += deltatime
472
472
473 return avgdata, avgdatatime
473 return avgdata, avgdatatime
474
474
475 def integrateByBlock(self, dataOut):
475 def integrateByBlock(self, dataOut):
476
476
477 times = int(dataOut.data.shape[1]/self.n)
477 times = int(dataOut.data.shape[1]/self.n)
478 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
478 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
479
479
480 id_min = 0
480 id_min = 0
481 id_max = self.n
481 id_max = self.n
482
482
483 for i in range(times):
483 for i in range(times):
484 junk = dataOut.data[:,id_min:id_max,:]
484 junk = dataOut.data[:,id_min:id_max,:]
485 avgdata[:,i,:] = junk.sum(axis=1)
485 avgdata[:,i,:] = junk.sum(axis=1)
486 id_min += self.n
486 id_min += self.n
487 id_max += self.n
487 id_max += self.n
488
488
489 timeInterval = dataOut.ippSeconds*self.n
489 timeInterval = dataOut.ippSeconds*self.n
490 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
490 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
491 self.__dataReady = True
491 self.__dataReady = True
492 return avgdata, avgdatatime
492 return avgdata, avgdatatime
493
493
494 def run(self, dataOut, **kwargs):
494 def run(self, dataOut, **kwargs):
495
495
496 if not self.isConfig:
496 if not self.isConfig:
497 self.setup(**kwargs)
497 self.setup(**kwargs)
498 self.isConfig = True
498 self.isConfig = True
499
499
500 if dataOut.flagDataAsBlock:
500 if dataOut.flagDataAsBlock:
501 """
501 """
502 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
502 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
503 """
503 """
504 avgdata, avgdatatime = self.integrateByBlock(dataOut)
504 avgdata, avgdatatime = self.integrateByBlock(dataOut)
505 dataOut.nProfiles /= self.n
505 else:
506 else:
506 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
507 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
507
508
508 # dataOut.timeInterval *= n
509 # dataOut.timeInterval *= n
509 dataOut.flagNoData = True
510 dataOut.flagNoData = True
510
511
511 if self.__dataReady:
512 if self.__dataReady:
512 dataOut.data = avgdata
513 dataOut.data = avgdata
513 dataOut.nCohInt *= self.n
514 dataOut.nCohInt *= self.n
514 dataOut.utctime = avgdatatime
515 dataOut.utctime = avgdatatime
515 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
516 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
516 dataOut.flagNoData = False
517 dataOut.flagNoData = False
517
518
518 class Decoder(Operation):
519 class Decoder(Operation):
519
520
520 isConfig = False
521 isConfig = False
521 __profIndex = 0
522 __profIndex = 0
522
523
523 code = None
524 code = None
524
525
525 nCode = None
526 nCode = None
526 nBaud = None
527 nBaud = None
527
528
528
529
529 def __init__(self):
530 def __init__(self):
530
531
531 Operation.__init__(self)
532 Operation.__init__(self)
532
533
533 self.times = None
534 self.times = None
534 self.osamp = None
535 self.osamp = None
535 # self.__setValues = False
536 # self.__setValues = False
536 self.isConfig = False
537 self.isConfig = False
537
538
538 def setup(self, code, osamp, dataOut):
539 def setup(self, code, osamp, dataOut):
539
540
540 self.__profIndex = 0
541 self.__profIndex = 0
541
542
542 self.code = code
543 self.code = code
543
544
544 self.nCode = len(code)
545 self.nCode = len(code)
545 self.nBaud = len(code[0])
546 self.nBaud = len(code[0])
546
547
547 if (osamp != None) and (osamp >1):
548 if (osamp != None) and (osamp >1):
548 self.osamp = osamp
549 self.osamp = osamp
549 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
550 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
550 self.nBaud = self.nBaud*self.osamp
551 self.nBaud = self.nBaud*self.osamp
551
552
552 self.__nChannels = dataOut.nChannels
553 self.__nChannels = dataOut.nChannels
553 self.__nProfiles = dataOut.nProfiles
554 self.__nProfiles = dataOut.nProfiles
554 self.__nHeis = dataOut.nHeights
555 self.__nHeis = dataOut.nHeights
555
556
556 if self.__nHeis < self.nBaud:
557 if self.__nHeis < self.nBaud:
557 raise ValueError, 'Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud)
558 raise ValueError, 'Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud)
558
559
559 #Frequency
560 #Frequency
560 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
561 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
561
562
562 __codeBuffer[:,0:self.nBaud] = self.code
563 __codeBuffer[:,0:self.nBaud] = self.code
563
564
564 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
565 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
565
566
566 if dataOut.flagDataAsBlock:
567 if dataOut.flagDataAsBlock:
567
568
568 self.ndatadec = self.__nHeis #- self.nBaud + 1
569 self.ndatadec = self.__nHeis #- self.nBaud + 1
569
570
570 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
571 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
571
572
572 else:
573 else:
573
574
574 #Time
575 #Time
575 self.ndatadec = self.__nHeis #- self.nBaud + 1
576 self.ndatadec = self.__nHeis #- self.nBaud + 1
576
577
577 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
578 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
578
579
579 def __convolutionInFreq(self, data):
580 def __convolutionInFreq(self, data):
580
581
581 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
582 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
582
583
583 fft_data = numpy.fft.fft(data, axis=1)
584 fft_data = numpy.fft.fft(data, axis=1)
584
585
585 conv = fft_data*fft_code
586 conv = fft_data*fft_code
586
587
587 data = numpy.fft.ifft(conv,axis=1)
588 data = numpy.fft.ifft(conv,axis=1)
588
589
589 return data
590 return data
590
591
591 def __convolutionInFreqOpt(self, data):
592 def __convolutionInFreqOpt(self, data):
592
593
593 raise NotImplementedError
594 raise NotImplementedError
594
595
595 def __convolutionInTime(self, data):
596 def __convolutionInTime(self, data):
596
597
597 code = self.code[self.__profIndex]
598 code = self.code[self.__profIndex]
598
599
599 for i in range(self.__nChannels):
600 for i in range(self.__nChannels):
600 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
601 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
601
602
602 return self.datadecTime
603 return self.datadecTime
603
604
604 def __convolutionByBlockInTime(self, data):
605 def __convolutionByBlockInTime(self, data):
605
606
606 repetitions = self.__nProfiles / self.nCode
607 repetitions = self.__nProfiles / self.nCode
607
608
608 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
609 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
609 junk = junk.flatten()
610 junk = junk.flatten()
610 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
611 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
611
612
612 for i in range(self.__nChannels):
613 for i in range(self.__nChannels):
613 for j in range(self.__nProfiles):
614 for j in range(self.__nProfiles):
614 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
615 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
615
616
616 return self.datadecTime
617 return self.datadecTime
617
618
618 def __convolutionByBlockInFreq(self, data):
619 def __convolutionByBlockInFreq(self, data):
619
620
620 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
621 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
621
622
622 fft_data = numpy.fft.fft(data, axis=2)
623 fft_data = numpy.fft.fft(data, axis=2)
623
624
624 conv = fft_data*fft_code
625 conv = fft_data*fft_code
625
626
626 data = numpy.fft.ifft(conv,axis=2)
627 data = numpy.fft.ifft(conv,axis=2)
627
628
628 return data
629 return data
629
630
630 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
631 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
631
632
632 if dataOut.flagDecodeData:
633 if dataOut.flagDecodeData:
633 print "This data is already decoded, recoding again ..."
634 print "This data is already decoded, recoding again ..."
634
635
635 if not self.isConfig:
636 if not self.isConfig:
636
637
637 if code is None:
638 if code is None:
638 if dataOut.code is None:
639 if dataOut.code is None:
639 raise ValueError, "Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type
640 raise ValueError, "Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type
640
641
641 code = dataOut.code
642 code = dataOut.code
642 else:
643 else:
643 code = numpy.array(code).reshape(nCode,nBaud)
644 code = numpy.array(code).reshape(nCode,nBaud)
644
645
645 self.setup(code, osamp, dataOut)
646 self.setup(code, osamp, dataOut)
646
647
647 self.isConfig = True
648 self.isConfig = True
648
649
649 if self.code is None:
650 if self.code is None:
650 print "Fail decoding: Code is not defined."
651 print "Fail decoding: Code is not defined."
651 return
652 return
652
653
653 datadec = None
654 datadec = None
654
655
655 if dataOut.flagDataAsBlock:
656 if dataOut.flagDataAsBlock:
656 """
657 """
657 Decoding when data have been read as block,
658 Decoding when data have been read as block,
658 """
659 """
659 if mode == 0:
660 if mode == 0:
660 datadec = self.__convolutionByBlockInTime(dataOut.data)
661 datadec = self.__convolutionByBlockInTime(dataOut.data)
661 if mode == 1:
662 if mode == 1:
662 datadec = self.__convolutionByBlockInFreq(dataOut.data)
663 datadec = self.__convolutionByBlockInFreq(dataOut.data)
663 else:
664 else:
664 """
665 """
665 Decoding when data have been read profile by profile
666 Decoding when data have been read profile by profile
666 """
667 """
667 if mode == 0:
668 if mode == 0:
668 datadec = self.__convolutionInTime(dataOut.data)
669 datadec = self.__convolutionInTime(dataOut.data)
669
670
670 if mode == 1:
671 if mode == 1:
671 datadec = self.__convolutionInFreq(dataOut.data)
672 datadec = self.__convolutionInFreq(dataOut.data)
672
673
673 if mode == 2:
674 if mode == 2:
674 datadec = self.__convolutionInFreqOpt(dataOut.data)
675 datadec = self.__convolutionInFreqOpt(dataOut.data)
675
676
676 if datadec is None:
677 if datadec is None:
677 raise ValueError, "Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode
678 raise ValueError, "Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode
678
679
679 dataOut.code = self.code
680 dataOut.code = self.code
680 dataOut.nCode = self.nCode
681 dataOut.nCode = self.nCode
681 dataOut.nBaud = self.nBaud
682 dataOut.nBaud = self.nBaud
682
683
683 dataOut.data = datadec
684 dataOut.data = datadec
684
685
685 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
686 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
686
687
687 dataOut.flagDecodeData = True #asumo q la data esta decodificada
688 dataOut.flagDecodeData = True #asumo q la data esta decodificada
688
689
689 if self.__profIndex == self.nCode-1:
690 if self.__profIndex == self.nCode-1:
690 self.__profIndex = 0
691 self.__profIndex = 0
691 return 1
692 return 1
692
693
693 self.__profIndex += 1
694 self.__profIndex += 1
694
695
695 return 1
696 return 1
696 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
697 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
697
698
698
699
699 class ProfileConcat(Operation):
700 class ProfileConcat(Operation):
700
701
701 isConfig = False
702 isConfig = False
702 buffer = None
703 buffer = None
703
704
704 def __init__(self):
705 def __init__(self):
705
706
706 Operation.__init__(self)
707 Operation.__init__(self)
707 self.profileIndex = 0
708 self.profileIndex = 0
708
709
709 def reset(self):
710 def reset(self):
710 self.buffer = numpy.zeros_like(self.buffer)
711 self.buffer = numpy.zeros_like(self.buffer)
711 self.start_index = 0
712 self.start_index = 0
712 self.times = 1
713 self.times = 1
713
714
714 def setup(self, data, m, n=1):
715 def setup(self, data, m, n=1):
715 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
716 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
716 self.nHeights = data.nHeights
717 self.nHeights = data.nHeights
717 self.start_index = 0
718 self.start_index = 0
718 self.times = 1
719 self.times = 1
719
720
720 def concat(self, data):
721 def concat(self, data):
721
722
722 self.buffer[:,self.start_index:self.profiles*self.times] = data.copy()
723 self.buffer[:,self.start_index:self.profiles*self.times] = data.copy()
723 self.start_index = self.start_index + self.nHeights
724 self.start_index = self.start_index + self.nHeights
724
725
725 def run(self, dataOut, m):
726 def run(self, dataOut, m):
726
727
727 dataOut.flagNoData = True
728 dataOut.flagNoData = True
728
729
729 if not self.isConfig:
730 if not self.isConfig:
730 self.setup(dataOut.data, m, 1)
731 self.setup(dataOut.data, m, 1)
731 self.isConfig = True
732 self.isConfig = True
732
733
733 if dataOut.flagDataAsBlock:
734 if dataOut.flagDataAsBlock:
734 raise ValueError, "ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False"
735 raise ValueError, "ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False"
735
736
736 else:
737 else:
737 self.concat(dataOut.data)
738 self.concat(dataOut.data)
738 self.times += 1
739 self.times += 1
739 if self.times > m:
740 if self.times > m:
740 dataOut.data = self.buffer
741 dataOut.data = self.buffer
741 self.reset()
742 self.reset()
742 dataOut.flagNoData = False
743 dataOut.flagNoData = False
743 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
744 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
744 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
745 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
745 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
746 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
746 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
747 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
747 dataOut.ippSeconds *= m
748 dataOut.ippSeconds *= m
748
749
749 class ProfileSelector(Operation):
750 class ProfileSelector(Operation):
750
751
751 profileIndex = None
752 profileIndex = None
752 # Tamanho total de los perfiles
753 # Tamanho total de los perfiles
753 nProfiles = None
754 nProfiles = None
754
755
755 def __init__(self):
756 def __init__(self):
756
757
757 Operation.__init__(self)
758 Operation.__init__(self)
758 self.profileIndex = 0
759 self.profileIndex = 0
759
760
760 def incIndex(self):
761 def incIndex(self):
761
762
762 self.profileIndex += 1
763 self.profileIndex += 1
763
764
764 if self.profileIndex >= self.nProfiles:
765 if self.profileIndex >= self.nProfiles:
765 self.profileIndex = 0
766 self.profileIndex = 0
766
767
767 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
768 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
768
769
769 if profileIndex < minIndex:
770 if profileIndex < minIndex:
770 return False
771 return False
771
772
772 if profileIndex > maxIndex:
773 if profileIndex > maxIndex:
773 return False
774 return False
774
775
775 return True
776 return True
776
777
777 def isThisProfileInList(self, profileIndex, profileList):
778 def isThisProfileInList(self, profileIndex, profileList):
778
779
779 if profileIndex not in profileList:
780 if profileIndex not in profileList:
780 return False
781 return False
781
782
782 return True
783 return True
783
784
784 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
785 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
785
786
786 """
787 """
787 ProfileSelector:
788 ProfileSelector:
788
789
789 Inputs:
790 Inputs:
790 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
791 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
791
792
792 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
793 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
793
794
794 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
795 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
795
796
796 """
797 """
797
798
798 dataOut.flagNoData = True
799 dataOut.flagNoData = True
799
800
800 if dataOut.flagDataAsBlock:
801 if dataOut.flagDataAsBlock:
801 """
802 """
802 data dimension = [nChannels, nProfiles, nHeis]
803 data dimension = [nChannels, nProfiles, nHeis]
803 """
804 """
804 if profileList != None:
805 if profileList != None:
805 dataOut.data = dataOut.data[:,profileList,:]
806 dataOut.data = dataOut.data[:,profileList,:]
806 dataOut.nProfiles = len(profileList)
807 dataOut.nProfiles = len(profileList)
807 dataOut.profileIndex = dataOut.nProfiles - 1
808 dataOut.profileIndex = dataOut.nProfiles - 1
808
809
809 if profileRangeList != None:
810 if profileRangeList != None:
810 minIndex = profileRangeList[0]
811 minIndex = profileRangeList[0]
811 maxIndex = profileRangeList[1]
812 maxIndex = profileRangeList[1]
812
813
813 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
814 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
814 dataOut.nProfiles = maxIndex - minIndex + 1
815 dataOut.nProfiles = maxIndex - minIndex + 1
815 dataOut.profileIndex = dataOut.nProfiles - 1
816 dataOut.profileIndex = dataOut.nProfiles - 1
816
817
817 if rangeList != None:
818 if rangeList != None:
818 raise ValueError, "Profile Selector: Invalid argument rangeList. Not implemented for getByBlock yet"
819 raise ValueError, "Profile Selector: Invalid argument rangeList. Not implemented for getByBlock yet"
819
820
820 dataOut.flagNoData = False
821 dataOut.flagNoData = False
821
822
822 return True
823 return True
823
824
824 """
825 """
825 data dimension = [nChannels, nHeis]
826 data dimension = [nChannels, nHeis]
826 """
827 """
827
828
828 if nProfiles:
829 if nProfiles:
829 self.nProfiles = nProfiles
830 self.nProfiles = nProfiles
830 else:
831 else:
831 self.nProfiles = dataOut.nProfiles
832 self.nProfiles = dataOut.nProfiles
832
833
833 if profileList != None:
834 if profileList != None:
834
835
835 dataOut.nProfiles = len(profileList)
836 dataOut.nProfiles = len(profileList)
836
837
837 if self.isThisProfileInList(dataOut.profileIndex, profileList):
838 if self.isThisProfileInList(dataOut.profileIndex, profileList):
838 dataOut.flagNoData = False
839 dataOut.flagNoData = False
839 dataOut.profileIndex = self.profileIndex
840 dataOut.profileIndex = self.profileIndex
840
841
841 self.incIndex()
842 self.incIndex()
842 return True
843 return True
843
844
844 if profileRangeList != None:
845 if profileRangeList != None:
845
846
846 minIndex = profileRangeList[0]
847 minIndex = profileRangeList[0]
847 maxIndex = profileRangeList[1]
848 maxIndex = profileRangeList[1]
848
849
849 dataOut.nProfiles = maxIndex - minIndex + 1
850 dataOut.nProfiles = maxIndex - minIndex + 1
850
851
851 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
852 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
852 dataOut.flagNoData = False
853 dataOut.flagNoData = False
853 dataOut.profileIndex = self.profileIndex
854 dataOut.profileIndex = self.profileIndex
854
855
855 self.incIndex()
856 self.incIndex()
856 return True
857 return True
857
858
858 if rangeList != None:
859 if rangeList != None:
859
860
860 nProfiles = 0
861 nProfiles = 0
861
862
862 for thisRange in rangeList:
863 for thisRange in rangeList:
863 minIndex = thisRange[0]
864 minIndex = thisRange[0]
864 maxIndex = thisRange[1]
865 maxIndex = thisRange[1]
865
866
866 nProfiles += maxIndex - minIndex + 1
867 nProfiles += maxIndex - minIndex + 1
867
868
868 dataOut.nProfiles = nProfiles
869 dataOut.nProfiles = nProfiles
869
870
870 for thisRange in rangeList:
871 for thisRange in rangeList:
871
872
872 minIndex = thisRange[0]
873 minIndex = thisRange[0]
873 maxIndex = thisRange[1]
874 maxIndex = thisRange[1]
874
875
875 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
876 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
876
877
877 # print "profileIndex = ", dataOut.profileIndex
878 # print "profileIndex = ", dataOut.profileIndex
878
879
879 dataOut.flagNoData = False
880 dataOut.flagNoData = False
880 dataOut.profileIndex = self.profileIndex
881 dataOut.profileIndex = self.profileIndex
881
882
882 self.incIndex()
883 self.incIndex()
883 break
884 break
884 return True
885 return True
885
886
886
887
887 if beam != None: #beam is only for AMISR data
888 if beam != None: #beam is only for AMISR data
888 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
889 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
889 dataOut.flagNoData = False
890 dataOut.flagNoData = False
890 dataOut.profileIndex = self.profileIndex
891 dataOut.profileIndex = self.profileIndex
891
892
892 self.incIndex()
893 self.incIndex()
893
894
894 return True
895 return True
895
896
896 raise ValueError, "ProfileSelector needs profileList, profileRangeList or rangeList parameter"
897 raise ValueError, "ProfileSelector needs profileList, profileRangeList or rangeList parameter"
897
898
898 return False
899 return False
899
900
900
901
901
902
902 class Reshaper(Operation):
903 class Reshaper(Operation):
903
904
904 def __init__(self):
905 def __init__(self):
905
906
906 Operation.__init__(self)
907 Operation.__init__(self)
907 self.updateNewHeights = True
908 self.updateNewHeights = True
908
909
909 def run(self, dataOut, shape):
910 def run(self, dataOut, shape):
910
911
911 if not dataOut.flagDataAsBlock:
912 if not dataOut.flagDataAsBlock:
912 raise ValueError, "Reshaper can only be used when voltage have been read as Block, getBlock = True"
913 raise ValueError, "Reshaper can only be used when voltage have been read as Block, getBlock = True"
913
914
914 if len(shape) != 3:
915 if len(shape) != 3:
915 raise ValueError, "shape len should be equal to 3, (nChannels, nProfiles, nHeis)"
916 raise ValueError, "shape len should be equal to 3, (nChannels, nProfiles, nHeis)"
916
917
917 shape_tuple = tuple(shape)
918 shape_tuple = tuple(shape)
918 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
919 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
919 dataOut.flagNoData = False
920 dataOut.flagNoData = False
920
921
921 if self.updateNewHeights:
922 if self.updateNewHeights:
922
923
923 old_nheights = dataOut.nHeights
924 old_nheights = dataOut.nHeights
924 new_nheights = dataOut.data.shape[2]
925 new_nheights = dataOut.data.shape[2]
925 factor = 1.0*new_nheights / old_nheights
926 factor = 1.0*new_nheights / old_nheights
926
927
927 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
928 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
928
929
929 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * factor
930 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * factor
930
931
931 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
932 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
932
933
933 dataOut.nProfiles = dataOut.data.shape[1]
934 dataOut.nProfiles = dataOut.data.shape[1]
934
935
935 dataOut.ippSeconds *= factor
936 dataOut.ippSeconds *= factor
936 #
937 #
937 # import collections
938 # import collections
938 # from scipy.stats import mode
939 # from scipy.stats import mode
939 #
940 #
940 # class Synchronize(Operation):
941 # class Synchronize(Operation):
941 #
942 #
942 # isConfig = False
943 # isConfig = False
943 # __profIndex = 0
944 # __profIndex = 0
944 #
945 #
945 # def __init__(self):
946 # def __init__(self):
946 #
947 #
947 # Operation.__init__(self)
948 # Operation.__init__(self)
948 # # self.isConfig = False
949 # # self.isConfig = False
949 # self.__powBuffer = None
950 # self.__powBuffer = None
950 # self.__startIndex = 0
951 # self.__startIndex = 0
951 # self.__pulseFound = False
952 # self.__pulseFound = False
952 #
953 #
953 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
954 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
954 #
955 #
955 # #Read data
956 # #Read data
956 #
957 #
957 # powerdB = dataOut.getPower(channel = channel)
958 # powerdB = dataOut.getPower(channel = channel)
958 # noisedB = dataOut.getNoise(channel = channel)[0]
959 # noisedB = dataOut.getNoise(channel = channel)[0]
959 #
960 #
960 # self.__powBuffer.extend(powerdB.flatten())
961 # self.__powBuffer.extend(powerdB.flatten())
961 #
962 #
962 # dataArray = numpy.array(self.__powBuffer)
963 # dataArray = numpy.array(self.__powBuffer)
963 #
964 #
964 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
965 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
965 #
966 #
966 # maxValue = numpy.nanmax(filteredPower)
967 # maxValue = numpy.nanmax(filteredPower)
967 #
968 #
968 # if maxValue < noisedB + 10:
969 # if maxValue < noisedB + 10:
969 # #No se encuentra ningun pulso de transmision
970 # #No se encuentra ningun pulso de transmision
970 # return None
971 # return None
971 #
972 #
972 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
973 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
973 #
974 #
974 # if len(maxValuesIndex) < 2:
975 # if len(maxValuesIndex) < 2:
975 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
976 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
976 # return None
977 # return None
977 #
978 #
978 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
979 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
979 #
980 #
980 # #Seleccionar solo valores con un espaciamiento de nSamples
981 # #Seleccionar solo valores con un espaciamiento de nSamples
981 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
982 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
982 #
983 #
983 # if len(pulseIndex) < 2:
984 # if len(pulseIndex) < 2:
984 # #Solo se encontro un pulso de transmision con ancho mayor a 1
985 # #Solo se encontro un pulso de transmision con ancho mayor a 1
985 # return None
986 # return None
986 #
987 #
987 # spacing = pulseIndex[1:] - pulseIndex[:-1]
988 # spacing = pulseIndex[1:] - pulseIndex[:-1]
988 #
989 #
989 # #remover senales que se distancien menos de 10 unidades o muestras
990 # #remover senales que se distancien menos de 10 unidades o muestras
990 # #(No deberian existir IPP menor a 10 unidades)
991 # #(No deberian existir IPP menor a 10 unidades)
991 #
992 #
992 # realIndex = numpy.where(spacing > 10 )[0]
993 # realIndex = numpy.where(spacing > 10 )[0]
993 #
994 #
994 # if len(realIndex) < 2:
995 # if len(realIndex) < 2:
995 # #Solo se encontro un pulso de transmision con ancho mayor a 1
996 # #Solo se encontro un pulso de transmision con ancho mayor a 1
996 # return None
997 # return None
997 #
998 #
998 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
999 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
999 # realPulseIndex = pulseIndex[realIndex]
1000 # realPulseIndex = pulseIndex[realIndex]
1000 #
1001 #
1001 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1002 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1002 #
1003 #
1003 # print "IPP = %d samples" %period
1004 # print "IPP = %d samples" %period
1004 #
1005 #
1005 # self.__newNSamples = dataOut.nHeights #int(period)
1006 # self.__newNSamples = dataOut.nHeights #int(period)
1006 # self.__startIndex = int(realPulseIndex[0])
1007 # self.__startIndex = int(realPulseIndex[0])
1007 #
1008 #
1008 # return 1
1009 # return 1
1009 #
1010 #
1010 #
1011 #
1011 # def setup(self, nSamples, nChannels, buffer_size = 4):
1012 # def setup(self, nSamples, nChannels, buffer_size = 4):
1012 #
1013 #
1013 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1014 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1014 # maxlen = buffer_size*nSamples)
1015 # maxlen = buffer_size*nSamples)
1015 #
1016 #
1016 # bufferList = []
1017 # bufferList = []
1017 #
1018 #
1018 # for i in range(nChannels):
1019 # for i in range(nChannels):
1019 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1020 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1020 # maxlen = buffer_size*nSamples)
1021 # maxlen = buffer_size*nSamples)
1021 #
1022 #
1022 # bufferList.append(bufferByChannel)
1023 # bufferList.append(bufferByChannel)
1023 #
1024 #
1024 # self.__nSamples = nSamples
1025 # self.__nSamples = nSamples
1025 # self.__nChannels = nChannels
1026 # self.__nChannels = nChannels
1026 # self.__bufferList = bufferList
1027 # self.__bufferList = bufferList
1027 #
1028 #
1028 # def run(self, dataOut, channel = 0):
1029 # def run(self, dataOut, channel = 0):
1029 #
1030 #
1030 # if not self.isConfig:
1031 # if not self.isConfig:
1031 # nSamples = dataOut.nHeights
1032 # nSamples = dataOut.nHeights
1032 # nChannels = dataOut.nChannels
1033 # nChannels = dataOut.nChannels
1033 # self.setup(nSamples, nChannels)
1034 # self.setup(nSamples, nChannels)
1034 # self.isConfig = True
1035 # self.isConfig = True
1035 #
1036 #
1036 # #Append new data to internal buffer
1037 # #Append new data to internal buffer
1037 # for thisChannel in range(self.__nChannels):
1038 # for thisChannel in range(self.__nChannels):
1038 # bufferByChannel = self.__bufferList[thisChannel]
1039 # bufferByChannel = self.__bufferList[thisChannel]
1039 # bufferByChannel.extend(dataOut.data[thisChannel])
1040 # bufferByChannel.extend(dataOut.data[thisChannel])
1040 #
1041 #
1041 # if self.__pulseFound:
1042 # if self.__pulseFound:
1042 # self.__startIndex -= self.__nSamples
1043 # self.__startIndex -= self.__nSamples
1043 #
1044 #
1044 # #Finding Tx Pulse
1045 # #Finding Tx Pulse
1045 # if not self.__pulseFound:
1046 # if not self.__pulseFound:
1046 # indexFound = self.__findTxPulse(dataOut, channel)
1047 # indexFound = self.__findTxPulse(dataOut, channel)
1047 #
1048 #
1048 # if indexFound == None:
1049 # if indexFound == None:
1049 # dataOut.flagNoData = True
1050 # dataOut.flagNoData = True
1050 # return
1051 # return
1051 #
1052 #
1052 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1053 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1053 # self.__pulseFound = True
1054 # self.__pulseFound = True
1054 # self.__startIndex = indexFound
1055 # self.__startIndex = indexFound
1055 #
1056 #
1056 # #If pulse was found ...
1057 # #If pulse was found ...
1057 # for thisChannel in range(self.__nChannels):
1058 # for thisChannel in range(self.__nChannels):
1058 # bufferByChannel = self.__bufferList[thisChannel]
1059 # bufferByChannel = self.__bufferList[thisChannel]
1059 # #print self.__startIndex
1060 # #print self.__startIndex
1060 # x = numpy.array(bufferByChannel)
1061 # x = numpy.array(bufferByChannel)
1061 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1062 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1062 #
1063 #
1063 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1064 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1064 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1065 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1065 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1066 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1066 #
1067 #
1067 # dataOut.data = self.__arrayBuffer
1068 # dataOut.data = self.__arrayBuffer
1068 #
1069 #
1069 # self.__startIndex += self.__newNSamples
1070 # self.__startIndex += self.__newNSamples
1070 #
1071 #
1071 # return No newline at end of file
1072 # return
General Comments 0
You need to be logged in to leave comments. Login now