##// END OF EJS Templates
jroproc_spectra_lags: decoding data from Tx Pulse (real data)
Miguel Valdez -
r776:12cd779dd5fc
parent child
Show More
@@ -1,910 +1,739
1 1 import numpy
2 2
3 3 from jroproc_base import ProcessingUnit, Operation
4 4 from schainpy.model.data.jrodata import Spectra
5 5 from schainpy.model.data.jrodata import hildebrand_sekhon
6 6
7 7 class SpectraLagsProc(ProcessingUnit):
8 8
9 9 def __init__(self):
10 10
11 11 ProcessingUnit.__init__(self)
12 12
13 self.buffer = None
13 self.__input_buffer = None
14 14 self.firstdatatime = None
15 15 self.profIndex = 0
16 16 self.dataOut = Spectra()
17 17 self.id_min = None
18 18 self.id_max = None
19 self.__codeIndex = 0
20
21 self.__lags_buffer = None
19 22
20 23 def __updateSpecFromVoltage(self):
21 24
25 self.dataOut.plotting = "spectra_lags"
22 26 self.dataOut.timeZone = self.dataIn.timeZone
23 27 self.dataOut.dstFlag = self.dataIn.dstFlag
24 28 self.dataOut.errorCount = self.dataIn.errorCount
25 29 self.dataOut.useLocalTime = self.dataIn.useLocalTime
26 30
27 31 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
28 32 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
29 33 self.dataOut.ippSeconds = self.dataIn.getDeltaH()*(10**-6)/0.15
30 34
31 35 self.dataOut.channelList = self.dataIn.channelList
32 36 self.dataOut.heightList = self.dataIn.heightList
33 37 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
34 38
35 39 self.dataOut.nBaud = self.dataIn.nBaud
36 40 self.dataOut.nCode = self.dataIn.nCode
37 41 self.dataOut.code = self.dataIn.code
38 42 # self.dataOut.nProfiles = self.dataOut.nFFTPoints
39 43
40 44 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
41 45 self.dataOut.utctime = self.firstdatatime
42 46 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
43 47 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
44 48 self.dataOut.flagShiftFFT = False
45 49
46 50 self.dataOut.nCohInt = self.dataIn.nCohInt
47 51 self.dataOut.nIncohInt = 1
48 52
49 53 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
50 54
51 55 self.dataOut.frequency = self.dataIn.frequency
52 56 self.dataOut.realtime = self.dataIn.realtime
53 57
54 58 self.dataOut.azimuth = self.dataIn.azimuth
55 59 self.dataOut.zenith = self.dataIn.zenith
56 60
57 61 self.dataOut.beam.codeList = self.dataIn.beam.codeList
58 62 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
59 63 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
60 64
61 def __decodeData(self, nProfiles, code):
65 def __createLagsBlock(self, voltages):
62 66
63 if code is None:
64 return
67 if self.__lags_buffer is None:
68 self.__lags_buffer = numpy.zeros((self.dataOut.nChannels, self.dataOut.nProfiles, self.dataOut.nHeights), dtype='complex')
69
70 nsegments = self.dataOut.nHeights - self.dataOut.nProfiles
71
72 # codes = numpy.conjugate(self.__input_buffer[:,9:169])/10000
73
74 for i in range(nsegments):
75 self.__lags_buffer[:,:,i] = voltages[:,i:i+self.dataOut.nProfiles]#*codes
76
77 return self.__lags_buffer
65 78
66 for i in range(nProfiles):
67 self.buffer[:,i,:] = self.buffer[:,i,:]*code[0][i]
79 def __decodeData(self, volt_buffer, pulseIndex=None):
68 80
69 def __getFft(self):
81 if pulseIndex is None:
82 return volt_buffer
83
84 codes = numpy.conjugate(self.__input_buffer[:,pulseIndex[0]:pulseIndex[1]])/10000
85
86 nsegments = self.dataOut.nHeights - self.dataOut.nProfiles
87
88 for i in range(nsegments):
89 volt_buffer[:,:,i] = volt_buffer[:,:,i]*codes
90
91 return volt_buffer
92
93 def __getFft(self, datablock):
70 94 """
71 95 Convierte valores de Voltaje a Spectra
72 96
73 97 Affected:
74 98 self.dataOut.data_spc
75 99 self.dataOut.data_cspc
76 100 self.dataOut.data_dc
77 101 self.dataOut.heightList
78 102 self.profIndex
79 self.buffer
103 self.__input_buffer
80 104 self.dataOut.flagNoData
81 105 """
82 nsegments = self.dataOut.nHeights
83
84 _fft_buffer = numpy.zeros((self.dataOut.nChannels, self.dataOut.nProfiles, nsegments), dtype='complex')
85 106
86 for i in range(nsegments):
87 try:
88 _fft_buffer[:,:,i] = self.buffer[:,i:i+self.dataOut.nProfiles]
89
90 if self.code is not None:
91 _fft_buffer[:,:,i] = _fft_buffer[:,:,i]*self.code[0]
92 except:
93 pass
107 fft_volt = numpy.fft.fft(datablock, n=self.dataOut.nFFTPoints, axis=1)
94 108
95 fft_volt = numpy.fft.fft(_fft_buffer, n=self.dataOut.nFFTPoints, axis=1)
96 fft_volt = fft_volt.astype(numpy.dtype('complex'))
97 dc = fft_volt[:,0,:]
109 # dc = fft_volt[:,0,:]
98 110
99 111 #calculo de self-spectra
100 112 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
101 113 spc = fft_volt * numpy.conjugate(fft_volt)
102 114 spc = spc.real
103 115
104 116 blocksize = 0
105 blocksize += dc.size
117 # blocksize += dc.size
106 118 blocksize += spc.size
107 119
108 120 cspc = None
109 121 pairIndex = 0
110 122
111 123 if self.dataOut.pairsList != None:
112 124 #calculo de cross-spectra
113 125 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
114 126 for pair in self.dataOut.pairsList:
115 127 if pair[0] not in self.dataOut.channelList:
116 128 raise ValueError, "Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
117 129 if pair[1] not in self.dataOut.channelList:
118 130 raise ValueError, "Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
119 131
120 132 chan_index0 = self.dataOut.channelList.index(pair[0])
121 133 chan_index1 = self.dataOut.channelList.index(pair[1])
122 134
123 135 cspc[pairIndex,:,:] = fft_volt[chan_index0,:,:] * numpy.conjugate(fft_volt[chan_index1,:,:])
124 136 pairIndex += 1
125 137 blocksize += cspc.size
126 138
127 139 self.dataOut.data_spc = spc
128 140 self.dataOut.data_cspc = cspc
129 self.dataOut.data_dc = dc
141 # self.dataOut.data_dc = dc
130 142 self.dataOut.blockSize = blocksize
131 143 self.dataOut.flagShiftFFT = True
132 144
133 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], code=None, nCode=1, nBaud=1):
145 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], code=None, nCode=None, nBaud=None, codeFromHeader=False, pulseIndex=None):
134 146
135 147 self.dataOut.flagNoData = True
136 148
149 self.code = None
150
151 if codeFromHeader:
152 if self.dataIn.code is not None:
153 self.code = self.dataIn.code
154
137 155 if code is not None:
138 156 self.code = numpy.array(code).reshape(nCode,nBaud)
139 else:
140 self.code = None
141 157
142 158 if self.dataIn.type == "Voltage":
143 159
144 160 if nFFTPoints == None:
145 161 raise ValueError, "This SpectraProc.run() need nFFTPoints input variable"
146 162
147 163 if nProfiles == None:
148 164 nProfiles = nFFTPoints
149 165
150 self.dataOut.ippFactor = 1
166 self.profIndex == nProfiles
167 self.firstdatatime = self.dataIn.utctime
151 168
169 self.dataOut.ippFactor = 1
152 170 self.dataOut.nFFTPoints = nFFTPoints
153 171 self.dataOut.nProfiles = nProfiles
154 172 self.dataOut.pairsList = pairsList
155 173
156 # if self.buffer is None:
157 # self.buffer = numpy.zeros( (self.dataIn.nChannels, nProfiles, self.dataIn.nHeights),
158 # dtype='complex')
174 self.__updateSpecFromVoltage()
159 175
160 176 if not self.dataIn.flagDataAsBlock:
161 self.buffer = self.dataIn.data.copy()
177 self.__input_buffer = self.dataIn.data.copy()
162 178
163 # for i in range(self.dataIn.nHeights):
164 # self.buffer[:, self.profIndex, self.profIndex:] = voltage_data[:,:self.dataIn.nHeights - self.profIndex]
165 #
166 # self.profIndex += 1
179 lags_block = self.__createLagsBlock(self.__input_buffer)
167 180
168 else:
169 raise ValueError, ""
170
171 self.firstdatatime = self.dataIn.utctime
181 lags_block = self.__decodeData(lags_block, pulseIndex)
172 182
173 self.profIndex == nProfiles
174
175 self.__updateSpecFromVoltage()
183 else:
184 self.__input_buffer = self.dataIn.data.copy()
176 185
177 self.__getFft()
186 self.__getFft(lags_block)
178 187
179 188 self.dataOut.flagNoData = False
180 189
181 190 return True
182 191
183 192 raise ValueError, "The type of input object '%s' is not valid"%(self.dataIn.type)
184 193
185 194 def __selectPairs(self, pairsList):
186 195
187 196 if channelList == None:
188 197 return
189 198
190 199 pairsIndexListSelected = []
191 200
192 201 for thisPair in pairsList:
193 202
194 203 if thisPair not in self.dataOut.pairsList:
195 204 continue
196 205
197 206 pairIndex = self.dataOut.pairsList.index(thisPair)
198 207
199 208 pairsIndexListSelected.append(pairIndex)
200 209
201 210 if not pairsIndexListSelected:
202 211 self.dataOut.data_cspc = None
203 212 self.dataOut.pairsList = []
204 213 return
205 214
206 215 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
207 216 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
208 217
209 218 return
210 219
211 220 def __selectPairsByChannel(self, channelList=None):
212 221
213 222 if channelList == None:
214 223 return
215 224
216 225 pairsIndexListSelected = []
217 226 for pairIndex in self.dataOut.pairsIndexList:
218 227 #First pair
219 228 if self.dataOut.pairsList[pairIndex][0] not in channelList:
220 229 continue
221 230 #Second pair
222 231 if self.dataOut.pairsList[pairIndex][1] not in channelList:
223 232 continue
224 233
225 234 pairsIndexListSelected.append(pairIndex)
226 235
227 236 if not pairsIndexListSelected:
228 237 self.dataOut.data_cspc = None
229 238 self.dataOut.pairsList = []
230 239 return
231 240
232 241 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
233 242 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
234 243
235 244 return
236 245
237 246 def selectChannels(self, channelList):
238 247
239 248 channelIndexList = []
240 249
241 250 for channel in channelList:
242 251 if channel not in self.dataOut.channelList:
243 252 raise ValueError, "Error selecting channels, Channel %d is not valid.\nAvailable channels = %s" %(channel, str(self.dataOut.channelList))
244 253
245 254 index = self.dataOut.channelList.index(channel)
246 255 channelIndexList.append(index)
247 256
248 257 self.selectChannelsByIndex(channelIndexList)
249 258
250 259 def selectChannelsByIndex(self, channelIndexList):
251 260 """
252 261 Selecciona un bloque de datos en base a canales segun el channelIndexList
253 262
254 263 Input:
255 264 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
256 265
257 266 Affected:
258 267 self.dataOut.data_spc
259 268 self.dataOut.channelIndexList
260 269 self.dataOut.nChannels
261 270
262 271 Return:
263 272 None
264 273 """
265 274
266 275 for channelIndex in channelIndexList:
267 276 if channelIndex not in self.dataOut.channelIndexList:
268 277 raise ValueError, "Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " %(channelIndex, self.dataOut.channelIndexList)
269 278
270 279 # nChannels = len(channelIndexList)
271 280
272 281 data_spc = self.dataOut.data_spc[channelIndexList,:]
273 282 data_dc = self.dataOut.data_dc[channelIndexList,:]
274 283
275 284 self.dataOut.data_spc = data_spc
276 285 self.dataOut.data_dc = data_dc
277 286
278 287 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
279 288 # self.dataOut.nChannels = nChannels
280 289
281 290 self.__selectPairsByChannel(self.dataOut.channelList)
282 291
283 292 return 1
284 293
285 294 def selectHeights(self, minHei, maxHei):
286 295 """
287 296 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
288 297 minHei <= height <= maxHei
289 298
290 299 Input:
291 300 minHei : valor minimo de altura a considerar
292 301 maxHei : valor maximo de altura a considerar
293 302
294 303 Affected:
295 304 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
296 305
297 306 Return:
298 307 1 si el metodo se ejecuto con exito caso contrario devuelve 0
299 308 """
300 309
301 310 if (minHei > maxHei):
302 311 raise ValueError, "Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei)
303 312
304 313 if (minHei < self.dataOut.heightList[0]):
305 314 minHei = self.dataOut.heightList[0]
306 315
307 316 if (maxHei > self.dataOut.heightList[-1]):
308 317 maxHei = self.dataOut.heightList[-1]
309 318
310 319 minIndex = 0
311 320 maxIndex = 0
312 321 heights = self.dataOut.heightList
313 322
314 323 inda = numpy.where(heights >= minHei)
315 324 indb = numpy.where(heights <= maxHei)
316 325
317 326 try:
318 327 minIndex = inda[0][0]
319 328 except:
320 329 minIndex = 0
321 330
322 331 try:
323 332 maxIndex = indb[0][-1]
324 333 except:
325 334 maxIndex = len(heights)
326 335
327 336 self.selectHeightsByIndex(minIndex, maxIndex)
328 337
329 338 return 1
330 339
331 340 def getBeaconSignal(self, tauindex = 0, channelindex = 0, hei_ref=None):
332 341 newheis = numpy.where(self.dataOut.heightList>self.dataOut.radarControllerHeaderObj.Taus[tauindex])
333 342
334 343 if hei_ref != None:
335 344 newheis = numpy.where(self.dataOut.heightList>hei_ref)
336 345
337 346 minIndex = min(newheis[0])
338 347 maxIndex = max(newheis[0])
339 348 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
340 349 heightList = self.dataOut.heightList[minIndex:maxIndex+1]
341 350
342 351 # determina indices
343 352 nheis = int(self.dataOut.radarControllerHeaderObj.txB/(self.dataOut.heightList[1]-self.dataOut.heightList[0]))
344 353 avg_dB = 10*numpy.log10(numpy.sum(data_spc[channelindex,:,:],axis=0))
345 354 beacon_dB = numpy.sort(avg_dB)[-nheis:]
346 355 beacon_heiIndexList = []
347 356 for val in avg_dB.tolist():
348 357 if val >= beacon_dB[0]:
349 358 beacon_heiIndexList.append(avg_dB.tolist().index(val))
350 359
351 360 #data_spc = data_spc[:,:,beacon_heiIndexList]
352 361 data_cspc = None
353 362 if self.dataOut.data_cspc is not None:
354 363 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
355 364 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
356 365
357 366 data_dc = None
358 367 if self.dataOut.data_dc is not None:
359 368 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
360 369 #data_dc = data_dc[:,beacon_heiIndexList]
361 370
362 371 self.dataOut.data_spc = data_spc
363 372 self.dataOut.data_cspc = data_cspc
364 373 self.dataOut.data_dc = data_dc
365 374 self.dataOut.heightList = heightList
366 375 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
367 376
368 377 return 1
369 378
370 379
371 380 def selectHeightsByIndex(self, minIndex, maxIndex):
372 381 """
373 382 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
374 383 minIndex <= index <= maxIndex
375 384
376 385 Input:
377 386 minIndex : valor de indice minimo de altura a considerar
378 387 maxIndex : valor de indice maximo de altura a considerar
379 388
380 389 Affected:
381 390 self.dataOut.data_spc
382 391 self.dataOut.data_cspc
383 392 self.dataOut.data_dc
384 393 self.dataOut.heightList
385 394
386 395 Return:
387 396 1 si el metodo se ejecuto con exito caso contrario devuelve 0
388 397 """
389 398
390 399 if (minIndex < 0) or (minIndex > maxIndex):
391 400 raise ValueError, "Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex)
392 401
393 402 if (maxIndex >= self.dataOut.nHeights):
394 403 maxIndex = self.dataOut.nHeights-1
395 404
396 405 #Spectra
397 406 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
398 407
399 408 data_cspc = None
400 409 if self.dataOut.data_cspc is not None:
401 410 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
402 411
403 412 data_dc = None
404 413 if self.dataOut.data_dc is not None:
405 414 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
406 415
407 416 self.dataOut.data_spc = data_spc
408 417 self.dataOut.data_cspc = data_cspc
409 418 self.dataOut.data_dc = data_dc
410 419
411 420 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
412 421
413 422 return 1
414 423
415 424 def removeDC(self, mode = 2):
416 425 jspectra = self.dataOut.data_spc
417 426 jcspectra = self.dataOut.data_cspc
418 427
419 428
420 429 num_chan = jspectra.shape[0]
421 430 num_hei = jspectra.shape[2]
422 431
423 432 if jcspectra is not None:
424 433 jcspectraExist = True
425 434 num_pairs = jcspectra.shape[0]
426 435 else: jcspectraExist = False
427 436
428 437 freq_dc = jspectra.shape[1]/2
429 438 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
430 439
431 440 if ind_vel[0]<0:
432 441 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
433 442
434 443 if mode == 1:
435 444 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
436 445
437 446 if jcspectraExist:
438 447 jcspectra[:,freq_dc,:] = (jcspectra[:,ind_vel[1],:] + jcspectra[:,ind_vel[2],:])/2
439 448
440 449 if mode == 2:
441 450
442 451 vel = numpy.array([-2,-1,1,2])
443 452 xx = numpy.zeros([4,4])
444 453
445 454 for fil in range(4):
446 455 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
447 456
448 457 xx_inv = numpy.linalg.inv(xx)
449 458 xx_aux = xx_inv[0,:]
450 459
451 460 for ich in range(num_chan):
452 461 yy = jspectra[ich,ind_vel,:]
453 462 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
454 463
455 464 junkid = jspectra[ich,freq_dc,:]<=0
456 465 cjunkid = sum(junkid)
457 466
458 467 if cjunkid.any():
459 468 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
460 469
461 470 if jcspectraExist:
462 471 for ip in range(num_pairs):
463 472 yy = jcspectra[ip,ind_vel,:]
464 473 jcspectra[ip,freq_dc,:] = numpy.dot(xx_aux,yy)
465 474
466 475
467 476 self.dataOut.data_spc = jspectra
468 477 self.dataOut.data_cspc = jcspectra
469 478
470 479 return 1
471 480
472 481 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
473 482
474 483 jspectra = self.dataOut.data_spc
475 484 jcspectra = self.dataOut.data_cspc
476 485 jnoise = self.dataOut.getNoise()
477 486 num_incoh = self.dataOut.nIncohInt
478 487
479 488 num_channel = jspectra.shape[0]
480 489 num_prof = jspectra.shape[1]
481 490 num_hei = jspectra.shape[2]
482 491
483 492 #hei_interf
484 493 if hei_interf is None:
485 494 count_hei = num_hei/2 #Como es entero no importa
486 495 hei_interf = numpy.asmatrix(range(count_hei)) + num_hei - count_hei
487 496 hei_interf = numpy.asarray(hei_interf)[0]
488 497 #nhei_interf
489 498 if (nhei_interf == None):
490 499 nhei_interf = 5
491 500 if (nhei_interf < 1):
492 501 nhei_interf = 1
493 502 if (nhei_interf > count_hei):
494 503 nhei_interf = count_hei
495 504 if (offhei_interf == None):
496 505 offhei_interf = 0
497 506
498 507 ind_hei = range(num_hei)
499 508 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
500 509 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
501 510 mask_prof = numpy.asarray(range(num_prof))
502 511 num_mask_prof = mask_prof.size
503 512 comp_mask_prof = [0, num_prof/2]
504 513
505 514
506 515 #noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
507 516 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
508 517 jnoise = numpy.nan
509 518 noise_exist = jnoise[0] < numpy.Inf
510 519
511 520 #Subrutina de Remocion de la Interferencia
512 521 for ich in range(num_channel):
513 522 #Se ordena los espectros segun su potencia (menor a mayor)
514 523 power = jspectra[ich,mask_prof,:]
515 524 power = power[:,hei_interf]
516 525 power = power.sum(axis = 0)
517 526 psort = power.ravel().argsort()
518 527
519 528 #Se estima la interferencia promedio en los Espectros de Potencia empleando
520 529 junkspc_interf = jspectra[ich,:,hei_interf[psort[range(offhei_interf, nhei_interf + offhei_interf)]]]
521 530
522 531 if noise_exist:
523 532 # tmp_noise = jnoise[ich] / num_prof
524 533 tmp_noise = jnoise[ich]
525 534 junkspc_interf = junkspc_interf - tmp_noise
526 535 #junkspc_interf[:,comp_mask_prof] = 0
527 536
528 537 jspc_interf = junkspc_interf.sum(axis = 0) / nhei_interf
529 538 jspc_interf = jspc_interf.transpose()
530 539 #Calculando el espectro de interferencia promedio
531 540 noiseid = numpy.where(jspc_interf <= tmp_noise/ numpy.sqrt(num_incoh))
532 541 noiseid = noiseid[0]
533 542 cnoiseid = noiseid.size
534 543 interfid = numpy.where(jspc_interf > tmp_noise/ numpy.sqrt(num_incoh))
535 544 interfid = interfid[0]
536 545 cinterfid = interfid.size
537 546
538 547 if (cnoiseid > 0): jspc_interf[noiseid] = 0
539 548
540 549 #Expandiendo los perfiles a limpiar
541 550 if (cinterfid > 0):
542 551 new_interfid = (numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof)%num_prof
543 552 new_interfid = numpy.asarray(new_interfid)
544 553 new_interfid = {x for x in new_interfid}
545 554 new_interfid = numpy.array(list(new_interfid))
546 555 new_cinterfid = new_interfid.size
547 556 else: new_cinterfid = 0
548 557
549 558 for ip in range(new_cinterfid):
550 559 ind = junkspc_interf[:,new_interfid[ip]].ravel().argsort()
551 560 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf/2],new_interfid[ip]]
552 561
553 562
554 563 jspectra[ich,:,ind_hei] = jspectra[ich,:,ind_hei] - jspc_interf #Corregir indices
555 564
556 565 #Removiendo la interferencia del punto de mayor interferencia
557 566 ListAux = jspc_interf[mask_prof].tolist()
558 567 maxid = ListAux.index(max(ListAux))
559 568
560 569
561 570 if cinterfid > 0:
562 571 for ip in range(cinterfid*(interf == 2) - 1):
563 572 ind = (jspectra[ich,interfid[ip],:] < tmp_noise*(1 + 1/numpy.sqrt(num_incoh))).nonzero()
564 573 cind = len(ind)
565 574
566 575 if (cind > 0):
567 576 jspectra[ich,interfid[ip],ind] = tmp_noise*(1 + (numpy.random.uniform(cind) - 0.5)/numpy.sqrt(num_incoh))
568 577
569 578 ind = numpy.array([-2,-1,1,2])
570 579 xx = numpy.zeros([4,4])
571 580
572 581 for id1 in range(4):
573 582 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
574 583
575 584 xx_inv = numpy.linalg.inv(xx)
576 585 xx = xx_inv[:,0]
577 586 ind = (ind + maxid + num_mask_prof)%num_mask_prof
578 587 yy = jspectra[ich,mask_prof[ind],:]
579 588 jspectra[ich,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
580 589
581 590
582 591 indAux = (jspectra[ich,:,:] < tmp_noise*(1-1/numpy.sqrt(num_incoh))).nonzero()
583 592 jspectra[ich,indAux[0],indAux[1]] = tmp_noise * (1 - 1/numpy.sqrt(num_incoh))
584 593
585 594 #Remocion de Interferencia en el Cross Spectra
586 595 if jcspectra is None: return jspectra, jcspectra
587 596 num_pairs = jcspectra.size/(num_prof*num_hei)
588 597 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
589 598
590 599 for ip in range(num_pairs):
591 600
592 601 #-------------------------------------------
593 602
594 603 cspower = numpy.abs(jcspectra[ip,mask_prof,:])
595 604 cspower = cspower[:,hei_interf]
596 605 cspower = cspower.sum(axis = 0)
597 606
598 607 cspsort = cspower.ravel().argsort()
599 608 junkcspc_interf = jcspectra[ip,:,hei_interf[cspsort[range(offhei_interf, nhei_interf + offhei_interf)]]]
600 609 junkcspc_interf = junkcspc_interf.transpose()
601 610 jcspc_interf = junkcspc_interf.sum(axis = 1)/nhei_interf
602 611
603 612 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
604 613
605 614 median_real = numpy.median(numpy.real(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
606 615 median_imag = numpy.median(numpy.imag(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
607 616 junkcspc_interf[comp_mask_prof,:] = numpy.complex(median_real, median_imag)
608 617
609 618 for iprof in range(num_prof):
610 619 ind = numpy.abs(junkcspc_interf[iprof,:]).ravel().argsort()
611 620 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf/2]]
612 621
613 622 #Removiendo la Interferencia
614 623 jcspectra[ip,:,ind_hei] = jcspectra[ip,:,ind_hei] - jcspc_interf
615 624
616 625 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
617 626 maxid = ListAux.index(max(ListAux))
618 627
619 628 ind = numpy.array([-2,-1,1,2])
620 629 xx = numpy.zeros([4,4])
621 630
622 631 for id1 in range(4):
623 632 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
624 633
625 634 xx_inv = numpy.linalg.inv(xx)
626 635 xx = xx_inv[:,0]
627 636
628 637 ind = (ind + maxid + num_mask_prof)%num_mask_prof
629 638 yy = jcspectra[ip,mask_prof[ind],:]
630 639 jcspectra[ip,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
631 640
632 641 #Guardar Resultados
633 642 self.dataOut.data_spc = jspectra
634 643 self.dataOut.data_cspc = jcspectra
635 644
636 645 return 1
637 646
638 647 def setRadarFrequency(self, frequency=None):
639 648
640 649 if frequency != None:
641 650 self.dataOut.frequency = frequency
642 651
643 652 return 1
644 653
645 654 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
646 655 #validacion de rango
647 656 if minHei == None:
648 657 minHei = self.dataOut.heightList[0]
649 658
650 659 if maxHei == None:
651 660 maxHei = self.dataOut.heightList[-1]
652 661
653 662 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
654 663 print 'minHei: %.2f is out of the heights range'%(minHei)
655 664 print 'minHei is setting to %.2f'%(self.dataOut.heightList[0])
656 665 minHei = self.dataOut.heightList[0]
657 666
658 667 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
659 668 print 'maxHei: %.2f is out of the heights range'%(maxHei)
660 669 print 'maxHei is setting to %.2f'%(self.dataOut.heightList[-1])
661 670 maxHei = self.dataOut.heightList[-1]
662 671
663 672 # validacion de velocidades
664 673 velrange = self.dataOut.getVelRange(1)
665 674
666 675 if minVel == None:
667 676 minVel = velrange[0]
668 677
669 678 if maxVel == None:
670 679 maxVel = velrange[-1]
671 680
672 681 if (minVel < velrange[0]) or (minVel > maxVel):
673 682 print 'minVel: %.2f is out of the velocity range'%(minVel)
674 683 print 'minVel is setting to %.2f'%(velrange[0])
675 684 minVel = velrange[0]
676 685
677 686 if (maxVel > velrange[-1]) or (maxVel < minVel):
678 687 print 'maxVel: %.2f is out of the velocity range'%(maxVel)
679 688 print 'maxVel is setting to %.2f'%(velrange[-1])
680 689 maxVel = velrange[-1]
681 690
682 691 # seleccion de indices para rango
683 692 minIndex = 0
684 693 maxIndex = 0
685 694 heights = self.dataOut.heightList
686 695
687 696 inda = numpy.where(heights >= minHei)
688 697 indb = numpy.where(heights <= maxHei)
689 698
690 699 try:
691 700 minIndex = inda[0][0]
692 701 except:
693 702 minIndex = 0
694 703
695 704 try:
696 705 maxIndex = indb[0][-1]
697 706 except:
698 707 maxIndex = len(heights)
699 708
700 709 if (minIndex < 0) or (minIndex > maxIndex):
701 710 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
702 711
703 712 if (maxIndex >= self.dataOut.nHeights):
704 713 maxIndex = self.dataOut.nHeights-1
705 714
706 715 # seleccion de indices para velocidades
707 716 indminvel = numpy.where(velrange >= minVel)
708 717 indmaxvel = numpy.where(velrange <= maxVel)
709 718 try:
710 719 minIndexVel = indminvel[0][0]
711 720 except:
712 721 minIndexVel = 0
713 722
714 723 try:
715 724 maxIndexVel = indmaxvel[0][-1]
716 725 except:
717 726 maxIndexVel = len(velrange)
718 727
719 728 #seleccion del espectro
720 729 data_spc = self.dataOut.data_spc[:,minIndexVel:maxIndexVel+1,minIndex:maxIndex+1]
721 730 #estimacion de ruido
722 731 noise = numpy.zeros(self.dataOut.nChannels)
723 732
724 733 for channel in range(self.dataOut.nChannels):
725 734 daux = data_spc[channel,:,:]
726 735 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
727 736
728 737 self.dataOut.noise_estimation = noise.copy()
729 738
730 739 return 1
No newline at end of file
731
732 class IncohIntLags(Operation):
733
734
735 __profIndex = 0
736 __withOverapping = False
737
738 __byTime = False
739 __initime = None
740 __lastdatatime = None
741 __integrationtime = None
742
743 __buffer_spc = None
744 __buffer_cspc = None
745 __buffer_dc = None
746
747 __dataReady = False
748
749 __timeInterval = None
750
751 n = None
752
753
754
755 def __init__(self):
756
757 Operation.__init__(self)
758 # self.isConfig = False
759
760 def setup(self, n=None, timeInterval=None, overlapping=False):
761 """
762 Set the parameters of the integration class.
763
764 Inputs:
765
766 n : Number of coherent integrations
767 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
768 overlapping :
769
770 """
771
772 self.__initime = None
773 self.__lastdatatime = 0
774
775 self.__buffer_spc = 0
776 self.__buffer_cspc = 0
777 self.__buffer_dc = 0
778
779 self.__profIndex = 0
780 self.__dataReady = False
781 self.__byTime = False
782
783 if n is None and timeInterval is None:
784 raise ValueError, "n or timeInterval should be specified ..."
785
786 if n is not None:
787 self.n = int(n)
788 else:
789 self.__integrationtime = int(timeInterval) #if (type(timeInterval)!=integer) -> change this line
790 self.n = None
791 self.__byTime = True
792
793 def putData(self, data_spc, data_cspc, data_dc):
794
795 """
796 Add a profile to the __buffer_spc and increase in one the __profileIndex
797
798 """
799
800 self.__buffer_spc += data_spc
801
802 if data_cspc is None:
803 self.__buffer_cspc = None
804 else:
805 self.__buffer_cspc += data_cspc
806
807 if data_dc is None:
808 self.__buffer_dc = None
809 else:
810 self.__buffer_dc += data_dc
811
812 self.__profIndex += 1
813
814 return
815
816 def pushData(self):
817 """
818 Return the sum of the last profiles and the profiles used in the sum.
819
820 Affected:
821
822 self.__profileIndex
823
824 """
825
826 data_spc = self.__buffer_spc
827 data_cspc = self.__buffer_cspc
828 data_dc = self.__buffer_dc
829 n = self.__profIndex
830
831 self.__buffer_spc = 0
832 self.__buffer_cspc = 0
833 self.__buffer_dc = 0
834 self.__profIndex = 0
835
836 return data_spc, data_cspc, data_dc, n
837
838 def byProfiles(self, *args):
839
840 self.__dataReady = False
841 avgdata_spc = None
842 avgdata_cspc = None
843 avgdata_dc = None
844
845 self.putData(*args)
846
847 if self.__profIndex == self.n:
848
849 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
850 self.n = n
851 self.__dataReady = True
852
853 return avgdata_spc, avgdata_cspc, avgdata_dc
854
855 def byTime(self, datatime, *args):
856
857 self.__dataReady = False
858 avgdata_spc = None
859 avgdata_cspc = None
860 avgdata_dc = None
861
862 self.putData(*args)
863
864 if (datatime - self.__initime) >= self.__integrationtime:
865 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
866 self.n = n
867 self.__dataReady = True
868
869 return avgdata_spc, avgdata_cspc, avgdata_dc
870
871 def integrate(self, datatime, *args):
872
873 if self.__profIndex == 0:
874 self.__initime = datatime
875
876 if self.__byTime:
877 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
878 else:
879 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
880
881 if not self.__dataReady:
882 return None, None, None, None
883
884 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
885
886 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
887
888 if n==1:
889 return
890
891 dataOut.flagNoData = True
892
893 if not self.isConfig:
894 self.setup(n, timeInterval, overlapping)
895 self.isConfig = True
896
897 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
898 dataOut.data_spc,
899 dataOut.data_cspc,
900 dataOut.data_dc)
901
902 if self.__dataReady:
903
904 dataOut.data_spc = avgdata_spc
905 dataOut.data_cspc = avgdata_cspc
906 dataOut.data_dc = avgdata_dc
907
908 dataOut.nIncohInt *= self.n
909 dataOut.utctime = avgdatatime
910 dataOut.flagNoData = False
General Comments 0
You need to be logged in to leave comments. Login now