##// END OF EJS Templates
Test codificacion
Miguel Valdez -
r309:e432e635f5a2
parent child
Show More
@@ -1,1323 +1,1320
1 1 '''
2 2
3 3 $Author: dsuarez $
4 4 $Id: Processor.py 1 2012-11-12 18:56:07Z dsuarez $
5 5 '''
6 6 import os
7 7 import numpy
8 8 import datetime
9 9 import time
10 10
11 11 from jrodata import *
12 12 from jrodataIO import *
13 13 from jroplot import *
14 14
15 15 try:
16 16 import cfunctions
17 17 except:
18 18 pass
19 19
20 20 class ProcessingUnit:
21 21
22 22 """
23 23 Esta es la clase base para el procesamiento de datos.
24 24
25 25 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
26 26 - Metodos internos (callMethod)
27 27 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
28 28 tienen que ser agreagados con el metodo "add".
29 29
30 30 """
31 31 # objeto de datos de entrada (Voltage, Spectra o Correlation)
32 32 dataIn = None
33 33
34 34 # objeto de datos de entrada (Voltage, Spectra o Correlation)
35 35 dataOut = None
36 36
37 37
38 38 objectDict = None
39 39
40 40 def __init__(self):
41 41
42 42 self.objectDict = {}
43 43
44 44 def init(self):
45 45
46 46 raise ValueError, "Not implemented"
47 47
48 48 def addOperation(self, object, objId):
49 49
50 50 """
51 51 Agrega el objeto "object" a la lista de objetos "self.objectList" y retorna el
52 52 identificador asociado a este objeto.
53 53
54 54 Input:
55 55
56 56 object : objeto de la clase "Operation"
57 57
58 58 Return:
59 59
60 60 objId : identificador del objeto, necesario para ejecutar la operacion
61 61 """
62 62
63 63 self.objectDict[objId] = object
64 64
65 65 return objId
66 66
67 67 def operation(self, **kwargs):
68 68
69 69 """
70 70 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
71 71 atributos del objeto dataOut
72 72
73 73 Input:
74 74
75 75 **kwargs : Diccionario de argumentos de la funcion a ejecutar
76 76 """
77 77
78 78 raise ValueError, "ImplementedError"
79 79
80 80 def callMethod(self, name, **kwargs):
81 81
82 82 """
83 83 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
84 84
85 85 Input:
86 86 name : nombre del metodo a ejecutar
87 87
88 88 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
89 89
90 90 """
91 91 if name != 'run':
92 92
93 93 if name == 'init' and self.dataIn.isEmpty():
94 94 self.dataOut.flagNoData = True
95 95 return False
96 96
97 97 if name != 'init' and self.dataOut.isEmpty():
98 98 return False
99 99
100 100 methodToCall = getattr(self, name)
101 101
102 102 methodToCall(**kwargs)
103 103
104 104 if name != 'run':
105 105 return True
106 106
107 107 if self.dataOut.isEmpty():
108 108 return False
109 109
110 110 return True
111 111
112 112 def callObject(self, objId, **kwargs):
113 113
114 114 """
115 115 Ejecuta la operacion asociada al identificador del objeto "objId"
116 116
117 117 Input:
118 118
119 119 objId : identificador del objeto a ejecutar
120 120
121 121 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
122 122
123 123 Return:
124 124
125 125 None
126 126 """
127 127
128 128 if self.dataOut.isEmpty():
129 129 return False
130 130
131 131 object = self.objectDict[objId]
132 132
133 133 object.run(self.dataOut, **kwargs)
134 134
135 135 return True
136 136
137 137 def call(self, operationConf, **kwargs):
138 138
139 139 """
140 140 Return True si ejecuta la operacion "operationConf.name" con los
141 141 argumentos "**kwargs". False si la operacion no se ha ejecutado.
142 142 La operacion puede ser de dos tipos:
143 143
144 144 1. Un metodo propio de esta clase:
145 145
146 146 operation.type = "self"
147 147
148 148 2. El metodo "run" de un objeto del tipo Operation o de un derivado de ella:
149 149 operation.type = "other".
150 150
151 151 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
152 152 "addOperation" e identificado con el operation.id
153 153
154 154
155 155 con el id de la operacion.
156 156
157 157 Input:
158 158
159 159 Operation : Objeto del tipo operacion con los atributos: name, type y id.
160 160
161 161 """
162 162
163 163 if operationConf.type == 'self':
164 164 sts = self.callMethod(operationConf.name, **kwargs)
165 165
166 166 if operationConf.type == 'other':
167 167 sts = self.callObject(operationConf.id, **kwargs)
168 168
169 169 return sts
170 170
171 171 def setInput(self, dataIn):
172 172
173 173 self.dataIn = dataIn
174 174
175 175 def getOutput(self):
176 176
177 177 return self.dataOut
178 178
179 179 class Operation():
180 180
181 181 """
182 182 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
183 183 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
184 184 acumulacion dentro de esta clase
185 185
186 186 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
187 187
188 188 """
189 189
190 190 __buffer = None
191 191 __isConfig = False
192 192
193 193 def __init__(self):
194 194
195 195 pass
196 196
197 197 def run(self, dataIn, **kwargs):
198 198
199 199 """
200 200 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los atributos del objeto dataIn.
201 201
202 202 Input:
203 203
204 204 dataIn : objeto del tipo JROData
205 205
206 206 Return:
207 207
208 208 None
209 209
210 210 Affected:
211 211 __buffer : buffer de recepcion de datos.
212 212
213 213 """
214 214
215 215 raise ValueError, "ImplementedError"
216 216
217 217 class VoltageProc(ProcessingUnit):
218 218
219 219
220 220 def __init__(self):
221 221
222 222 self.objectDict = {}
223 223 self.dataOut = Voltage()
224 224 self.flip = 1
225 225
226 226 def init(self):
227 227
228 228 self.dataOut.copy(self.dataIn)
229 229 # No necesita copiar en cada init() los atributos de dataIn
230 230 # la copia deberia hacerse por cada nuevo bloque de datos
231 231
232 232 def selectChannels(self, channelList):
233 233
234 234 channelIndexList = []
235 235
236 236 for channel in channelList:
237 237 index = self.dataOut.channelList.index(channel)
238 238 channelIndexList.append(index)
239 239
240 240 self.selectChannelsByIndex(channelIndexList)
241 241
242 242 def selectChannelsByIndex(self, channelIndexList):
243 243 """
244 244 Selecciona un bloque de datos en base a canales segun el channelIndexList
245 245
246 246 Input:
247 247 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
248 248
249 249 Affected:
250 250 self.dataOut.data
251 251 self.dataOut.channelIndexList
252 252 self.dataOut.nChannels
253 253 self.dataOut.m_ProcessingHeader.totalSpectra
254 254 self.dataOut.systemHeaderObj.numChannels
255 255 self.dataOut.m_ProcessingHeader.blockSize
256 256
257 257 Return:
258 258 None
259 259 """
260 260
261 261 for channelIndex in channelIndexList:
262 262 if channelIndex not in self.dataOut.channelIndexList:
263 263 print channelIndexList
264 264 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
265 265
266 266 nChannels = len(channelIndexList)
267 267
268 268 data = self.dataOut.data[channelIndexList,:]
269 269
270 270 self.dataOut.data = data
271 271 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
272 272 # self.dataOut.nChannels = nChannels
273 273
274 274 return 1
275 275
276 276 def selectHeights(self, minHei, maxHei):
277 277 """
278 278 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
279 279 minHei <= height <= maxHei
280 280
281 281 Input:
282 282 minHei : valor minimo de altura a considerar
283 283 maxHei : valor maximo de altura a considerar
284 284
285 285 Affected:
286 286 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
287 287
288 288 Return:
289 289 1 si el metodo se ejecuto con exito caso contrario devuelve 0
290 290 """
291 291 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
292 292 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
293 293
294 294 if (maxHei > self.dataOut.heightList[-1]):
295 295 maxHei = self.dataOut.heightList[-1]
296 296 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
297 297
298 298 minIndex = 0
299 299 maxIndex = 0
300 300 heights = self.dataOut.heightList
301 301
302 302 inda = numpy.where(heights >= minHei)
303 303 indb = numpy.where(heights <= maxHei)
304 304
305 305 try:
306 306 minIndex = inda[0][0]
307 307 except:
308 308 minIndex = 0
309 309
310 310 try:
311 311 maxIndex = indb[0][-1]
312 312 except:
313 313 maxIndex = len(heights)
314 314
315 315 self.selectHeightsByIndex(minIndex, maxIndex)
316 316
317 317 return 1
318 318
319 319
320 320 def selectHeightsByIndex(self, minIndex, maxIndex):
321 321 """
322 322 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
323 323 minIndex <= index <= maxIndex
324 324
325 325 Input:
326 326 minIndex : valor de indice minimo de altura a considerar
327 327 maxIndex : valor de indice maximo de altura a considerar
328 328
329 329 Affected:
330 330 self.dataOut.data
331 331 self.dataOut.heightList
332 332
333 333 Return:
334 334 1 si el metodo se ejecuto con exito caso contrario devuelve 0
335 335 """
336 336
337 337 if (minIndex < 0) or (minIndex > maxIndex):
338 338 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
339 339
340 340 if (maxIndex >= self.dataOut.nHeights):
341 341 maxIndex = self.dataOut.nHeights-1
342 342 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
343 343
344 344 nHeights = maxIndex - minIndex + 1
345 345
346 346 #voltage
347 347 data = self.dataOut.data[:,minIndex:maxIndex+1]
348 348
349 349 firstHeight = self.dataOut.heightList[minIndex]
350 350
351 351 self.dataOut.data = data
352 352 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
353 353
354 354 return 1
355 355
356 356
357 357 def filterByHeights(self, window):
358 358 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
359 359
360 360 if window == None:
361 361 window = self.dataOut.radarControllerHeaderObj.txA / deltaHeight
362 362
363 363 newdelta = deltaHeight * window
364 364 r = self.dataOut.data.shape[1] % window
365 365 buffer = self.dataOut.data[:,0:self.dataOut.data.shape[1]-r]
366 366 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[1]/window,window)
367 367 buffer = numpy.sum(buffer,2)
368 368 self.dataOut.data = buffer
369 369 self.dataOut.heightList = numpy.arange(self.dataOut.heightList[0],newdelta*self.dataOut.nHeights/window-newdelta,newdelta)
370 370 self.dataOut.windowOfFilter = window
371 371
372 372 def deFlip(self):
373 373 self.dataOut.data *= self.flip
374 374 self.flip *= -1.
375 375
376 376
377 377 class CohInt(Operation):
378 378
379 379 __isConfig = False
380 380
381 381 __profIndex = 0
382 382 __withOverapping = False
383 383
384 384 __byTime = False
385 385 __initime = None
386 386 __lastdatatime = None
387 387 __integrationtime = None
388 388
389 389 __buffer = None
390 390
391 391 __dataReady = False
392 392
393 393 n = None
394 394
395 395
396 396 def __init__(self):
397 397
398 398 self.__isConfig = False
399 399
400 400 def setup(self, n=None, timeInterval=None, overlapping=False):
401 401 """
402 402 Set the parameters of the integration class.
403 403
404 404 Inputs:
405 405
406 406 n : Number of coherent integrations
407 407 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
408 408 overlapping :
409 409
410 410 """
411 411
412 412 self.__initime = None
413 413 self.__lastdatatime = 0
414 414 self.__buffer = None
415 415 self.__dataReady = False
416 416
417 417
418 418 if n == None and timeInterval == None:
419 419 raise ValueError, "n or timeInterval should be specified ..."
420 420
421 421 if n != None:
422 422 self.n = n
423 423 self.__byTime = False
424 424 else:
425 425 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
426 426 self.n = 9999
427 427 self.__byTime = True
428 428
429 429 if overlapping:
430 430 self.__withOverapping = True
431 431 self.__buffer = None
432 432 else:
433 433 self.__withOverapping = False
434 434 self.__buffer = 0
435 435
436 436 self.__profIndex = 0
437 437
438 438 def putData(self, data):
439 439
440 440 """
441 441 Add a profile to the __buffer and increase in one the __profileIndex
442 442
443 443 """
444 444
445 445 if not self.__withOverapping:
446 446 self.__buffer += data.copy()
447 447 self.__profIndex += 1
448 448 return
449 449
450 450 #Overlapping data
451 451 nChannels, nHeis = data.shape
452 452 data = numpy.reshape(data, (1, nChannels, nHeis))
453 453
454 454 #If the buffer is empty then it takes the data value
455 455 if self.__buffer == None:
456 456 self.__buffer = data
457 457 self.__profIndex += 1
458 458 return
459 459
460 460 #If the buffer length is lower than n then stakcing the data value
461 461 if self.__profIndex < self.n:
462 462 self.__buffer = numpy.vstack((self.__buffer, data))
463 463 self.__profIndex += 1
464 464 return
465 465
466 466 #If the buffer length is equal to n then replacing the last buffer value with the data value
467 467 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
468 468 self.__buffer[self.n-1] = data
469 469 self.__profIndex = self.n
470 470 return
471 471
472 472
473 473 def pushData(self):
474 474 """
475 475 Return the sum of the last profiles and the profiles used in the sum.
476 476
477 477 Affected:
478 478
479 479 self.__profileIndex
480 480
481 481 """
482 482
483 483 if not self.__withOverapping:
484 484 data = self.__buffer
485 485 n = self.__profIndex
486 486
487 487 self.__buffer = 0
488 488 self.__profIndex = 0
489 489
490 490 return data, n
491 491
492 492 #Integration with Overlapping
493 493 data = numpy.sum(self.__buffer, axis=0)
494 494 n = self.__profIndex
495 495
496 496 return data, n
497 497
498 498 def byProfiles(self, data):
499 499
500 500 self.__dataReady = False
501 501 avgdata = None
502 502 n = None
503 503
504 504 self.putData(data)
505 505
506 506 if self.__profIndex == self.n:
507 507
508 508 avgdata, n = self.pushData()
509 509 self.__dataReady = True
510 510
511 511 return avgdata
512 512
513 513 def byTime(self, data, datatime):
514 514
515 515 self.__dataReady = False
516 516 avgdata = None
517 517 n = None
518 518
519 519 self.putData(data)
520 520
521 521 if (datatime - self.__initime) >= self.__integrationtime:
522 522 avgdata, n = self.pushData()
523 523 self.n = n
524 524 self.__dataReady = True
525 525
526 526 return avgdata
527 527
528 528 def integrate(self, data, datatime=None):
529 529
530 530 if self.__initime == None:
531 531 self.__initime = datatime
532 532
533 533 if self.__byTime:
534 534 avgdata = self.byTime(data, datatime)
535 535 else:
536 536 avgdata = self.byProfiles(data)
537 537
538 538
539 539 self.__lastdatatime = datatime
540 540
541 541 if avgdata == None:
542 542 return None, None
543 543
544 544 avgdatatime = self.__initime
545 545
546 546 deltatime = datatime -self.__lastdatatime
547 547
548 548 if not self.__withOverapping:
549 549 self.__initime = datatime
550 550 else:
551 551 self.__initime += deltatime
552 552
553 553 return avgdata, avgdatatime
554 554
555 555 def run(self, dataOut, **kwargs):
556 556
557 557 if not self.__isConfig:
558 558 self.setup(**kwargs)
559 559 self.__isConfig = True
560 560
561 561 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
562 562
563 563 # dataOut.timeInterval *= n
564 564 dataOut.flagNoData = True
565 565
566 566 if self.__dataReady:
567 567 dataOut.data = avgdata
568 568 dataOut.nCohInt *= self.n
569 569 dataOut.utctime = avgdatatime
570 570 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
571 571 dataOut.flagNoData = False
572 572
573 573
574 574 class Decoder(Operation):
575 575
576 576 __isConfig = False
577 577 __profIndex = 0
578 578
579 579 code = None
580 580
581 581 nCode = None
582 582 nBaud = None
583 583
584 584 def __init__(self):
585 585
586 586 self.__isConfig = False
587 587
588 588 def setup(self, code, shape):
589 589
590 590 self.__profIndex = 0
591 591
592 592 self.code = code
593 593
594 594 self.nCode = len(code)
595 595 self.nBaud = len(code[0])
596 596
597 597 self.__nChannels, self.__nHeis = shape
598 598
599 599 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.float32)
600 600
601 601 __codeBuffer[:,0:self.nBaud] = self.code
602 602
603 603 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
604 604
605 605 self.ndatadec = __nHeis - nBaud + 1
606 606
607 607 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
608 608
609 609 def convolutionInFreq(self, data):
610 610
611 611 ini = time.time()
612 612
613 613 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
614 614
615 615 fft_data = numpy.fft.fft(data, axis=1)
616 616
617 617 conv = fft_data*fft_code
618 618
619 619 data = numpy.fft.ifft(conv,axis=1)
620 620
621 621 datadec = data[:,:-self.nBaud+1]
622 622
623 623 print "Freq ", time.time() - ini
624 624
625 625 return datadec
626 626
627 627 def convolutionInFreqOpt(self, data):
628 628
629 629 ini = time.time()
630 630
631 631 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
632 632
633 633 data = cfunctions.decoder(fft_code, data)
634 634
635 635 datadec = data[:,:-self.nBaud+1]
636 636
637 637 print "OptFreq ", time.time() - ini
638 638
639 639 return datadec
640 640
641 641 def convolutionInTime(self, data):
642 642
643 643 ini = time.time()
644 644
645 645 code = self.code[self.__profIndex].reshape(1,-1)
646 646
647 647 for i in range(__nChannels):
648 648 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='valid')
649 649
650 650 print "Time ", time.time() - ini
651 651
652 652 return self.datadecTime
653 653
654 654 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0):
655 655 ini = time.time()
656 656 if not self.__isConfig:
657 657
658 658 if code == None:
659 659 code = dataOut.code
660 660 else:
661 661 code = numpy.array(code).reshape(nCode,nBaud)
662 662 dataOut.code = code
663 663 dataOut.nCode = nCode
664 664 dataOut.nBaud = nBaud
665 665
666 666 if code == None:
667 667 return 1
668 668
669 669 self.setup(code, dataOut.data.shape)
670 670 self.__isConfig = True
671 671
672 672 if mode == 0:
673 ndatadec, datadec = self.convolutionInFreq(dataOut.data)
673 datadec = self.convolutionInFreq(dataOut.data)
674 674
675 675 if mode == 1:
676 print "This function is not implemented"
677 # ndatadec, datadec = self.convolutionInTime(dataOut.data)
676 datadec = self.convolutionInTime(dataOut.data)
678 677
679 678 if mode == 2:
680 ndatadec, datadec = self.convolutionInFreqOpt(dataOut.data)
681
682
679 datadec = self.convolutionInFreqOpt(dataOut.data)
683 680
684 681 dataOut.data = datadec
685 682
686 dataOut.heightList = dataOut.heightList[0:ndatadec]
683 dataOut.heightList = dataOut.heightList[0:self.ndatadec]
687 684
688 685 dataOut.flagDecodeData = True #asumo q la data no esta decodificada
689 686
690 687 print time.time() - ini, "prof = %d, nCode=%d" %(self.__profIndex, self.nCode)
691 688
692 689 if self.__profIndex == self.nCode-1:
693 690 self.__profIndex = 0
694 691 return 1
695 692
696 693 self.__profIndex += 1
697 694
698 695 return 1
699 696 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
700 697
701 698
702 699
703 700 class SpectraProc(ProcessingUnit):
704 701
705 702 def __init__(self):
706 703
707 704 self.objectDict = {}
708 705 self.buffer = None
709 706 self.firstdatatime = None
710 707 self.profIndex = 0
711 708 self.dataOut = Spectra()
712 709
713 710 def __updateObjFromInput(self):
714 711
715 712 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
716 713 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
717 714 self.dataOut.channelList = self.dataIn.channelList
718 715 self.dataOut.heightList = self.dataIn.heightList
719 716 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
720 717 # self.dataOut.nHeights = self.dataIn.nHeights
721 718 # self.dataOut.nChannels = self.dataIn.nChannels
722 719 self.dataOut.nBaud = self.dataIn.nBaud
723 720 self.dataOut.nCode = self.dataIn.nCode
724 721 self.dataOut.code = self.dataIn.code
725 722 self.dataOut.nProfiles = self.dataOut.nFFTPoints
726 723 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
727 724 self.dataOut.flagTimeBlock = self.dataIn.flagTimeBlock
728 725 self.dataOut.utctime = self.firstdatatime
729 726 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
730 727 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
731 728 self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
732 729 self.dataOut.nCohInt = self.dataIn.nCohInt
733 730 self.dataOut.nIncohInt = 1
734 731 self.dataOut.ippSeconds = self.dataIn.ippSeconds
735 732 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
736 733
737 734 self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nFFTPoints*self.dataOut.nIncohInt
738 735
739 736 def __getFft(self):
740 737 """
741 738 Convierte valores de Voltaje a Spectra
742 739
743 740 Affected:
744 741 self.dataOut.data_spc
745 742 self.dataOut.data_cspc
746 743 self.dataOut.data_dc
747 744 self.dataOut.heightList
748 745 self.profIndex
749 746 self.buffer
750 747 self.dataOut.flagNoData
751 748 """
752 749 fft_volt = numpy.fft.fft(self.buffer,axis=1)
753 750 fft_volt = fft_volt.astype(numpy.dtype('complex'))
754 751 dc = fft_volt[:,0,:]
755 752
756 753 #calculo de self-spectra
757 754 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
758 755 spc = fft_volt * numpy.conjugate(fft_volt)
759 756 spc = spc.real
760 757
761 758 blocksize = 0
762 759 blocksize += dc.size
763 760 blocksize += spc.size
764 761
765 762 cspc = None
766 763 pairIndex = 0
767 764 if self.dataOut.pairsList != None:
768 765 #calculo de cross-spectra
769 766 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
770 767 for pair in self.dataOut.pairsList:
771 768 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
772 769 pairIndex += 1
773 770 blocksize += cspc.size
774 771
775 772 self.dataOut.data_spc = spc
776 773 self.dataOut.data_cspc = cspc
777 774 self.dataOut.data_dc = dc
778 775 self.dataOut.blockSize = blocksize
779 776
780 777 def init(self, nFFTPoints=None, pairsList=None):
781 778
782 779 self.dataOut.flagNoData = True
783 780
784 781 if self.dataIn.type == "Spectra":
785 782 self.dataOut.copy(self.dataIn)
786 783 return
787 784
788 785 if self.dataIn.type == "Voltage":
789 786
790 787 if nFFTPoints == None:
791 788 raise ValueError, "This SpectraProc.init() need nFFTPoints input variable"
792 789
793 790 if pairsList == None:
794 791 nPairs = 0
795 792 else:
796 793 nPairs = len(pairsList)
797 794
798 795 self.dataOut.nFFTPoints = nFFTPoints
799 796 self.dataOut.pairsList = pairsList
800 797 self.dataOut.nPairs = nPairs
801 798
802 799 if self.buffer == None:
803 800 self.buffer = numpy.zeros((self.dataIn.nChannels,
804 801 self.dataOut.nFFTPoints,
805 802 self.dataIn.nHeights),
806 803 dtype='complex')
807 804
808 805
809 806 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
810 807 self.profIndex += 1
811 808
812 809 if self.firstdatatime == None:
813 810 self.firstdatatime = self.dataIn.utctime
814 811
815 812 if self.profIndex == self.dataOut.nFFTPoints:
816 813 self.__updateObjFromInput()
817 814 self.__getFft()
818 815
819 816 self.dataOut.flagNoData = False
820 817
821 818 self.buffer = None
822 819 self.firstdatatime = None
823 820 self.profIndex = 0
824 821
825 822 return
826 823
827 824 raise ValuError, "The type object %s is not valid"%(self.dataIn.type)
828 825
829 826 def selectChannels(self, channelList):
830 827
831 828 channelIndexList = []
832 829
833 830 for channel in channelList:
834 831 index = self.dataOut.channelList.index(channel)
835 832 channelIndexList.append(index)
836 833
837 834 self.selectChannelsByIndex(channelIndexList)
838 835
839 836 def selectChannelsByIndex(self, channelIndexList):
840 837 """
841 838 Selecciona un bloque de datos en base a canales segun el channelIndexList
842 839
843 840 Input:
844 841 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
845 842
846 843 Affected:
847 844 self.dataOut.data_spc
848 845 self.dataOut.channelIndexList
849 846 self.dataOut.nChannels
850 847
851 848 Return:
852 849 None
853 850 """
854 851
855 852 for channelIndex in channelIndexList:
856 853 if channelIndex not in self.dataOut.channelIndexList:
857 854 print channelIndexList
858 855 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
859 856
860 857 nChannels = len(channelIndexList)
861 858
862 859 data_spc = self.dataOut.data_spc[channelIndexList,:]
863 860
864 861 self.dataOut.data_spc = data_spc
865 862 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
866 863 # self.dataOut.nChannels = nChannels
867 864
868 865 return 1
869 866
870 867 def selectHeights(self, minHei, maxHei):
871 868 """
872 869 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
873 870 minHei <= height <= maxHei
874 871
875 872 Input:
876 873 minHei : valor minimo de altura a considerar
877 874 maxHei : valor maximo de altura a considerar
878 875
879 876 Affected:
880 877 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
881 878
882 879 Return:
883 880 1 si el metodo se ejecuto con exito caso contrario devuelve 0
884 881 """
885 882 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
886 883 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
887 884
888 885 if (maxHei > self.dataOut.heightList[-1]):
889 886 maxHei = self.dataOut.heightList[-1]
890 887 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
891 888
892 889 minIndex = 0
893 890 maxIndex = 0
894 891 heights = self.dataOut.heightList
895 892
896 893 inda = numpy.where(heights >= minHei)
897 894 indb = numpy.where(heights <= maxHei)
898 895
899 896 try:
900 897 minIndex = inda[0][0]
901 898 except:
902 899 minIndex = 0
903 900
904 901 try:
905 902 maxIndex = indb[0][-1]
906 903 except:
907 904 maxIndex = len(heights)
908 905
909 906 self.selectHeightsByIndex(minIndex, maxIndex)
910 907
911 908 return 1
912 909
913 910
914 911 def selectHeightsByIndex(self, minIndex, maxIndex):
915 912 """
916 913 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
917 914 minIndex <= index <= maxIndex
918 915
919 916 Input:
920 917 minIndex : valor de indice minimo de altura a considerar
921 918 maxIndex : valor de indice maximo de altura a considerar
922 919
923 920 Affected:
924 921 self.dataOut.data_spc
925 922 self.dataOut.data_cspc
926 923 self.dataOut.data_dc
927 924 self.dataOut.heightList
928 925
929 926 Return:
930 927 1 si el metodo se ejecuto con exito caso contrario devuelve 0
931 928 """
932 929
933 930 if (minIndex < 0) or (minIndex > maxIndex):
934 931 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
935 932
936 933 if (maxIndex >= self.dataOut.nHeights):
937 934 maxIndex = self.dataOut.nHeights-1
938 935 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
939 936
940 937 nHeights = maxIndex - minIndex + 1
941 938
942 939 #Spectra
943 940 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
944 941
945 942 data_cspc = None
946 943 if self.dataOut.data_cspc != None:
947 944 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
948 945
949 946 data_dc = None
950 947 if self.dataOut.data_dc != None:
951 948 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
952 949
953 950 self.dataOut.data_spc = data_spc
954 951 self.dataOut.data_cspc = data_cspc
955 952 self.dataOut.data_dc = data_dc
956 953
957 954 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
958 955
959 956 return 1
960 957
961 958 def removeDC(self, mode = 1):
962 959
963 960 dc_index = 0
964 961 freq_index = numpy.array([-2,-1,1,2])
965 962 data_spc = self.dataOut.data_spc
966 963 data_cspc = self.dataOut.data_cspc
967 964 data_dc = self.dataOut.data_dc
968 965
969 966 if self.dataOut.flagShiftFFT:
970 967 dc_index += self.dataOut.nFFTPoints/2
971 968 freq_index += self.dataOut.nFFTPoints/2
972 969
973 970 if mode == 1:
974 971 data_spc[dc_index] = (data_spc[:,freq_index[1],:] + data_spc[:,freq_index[2],:])/2
975 972 if data_cspc != None:
976 973 data_cspc[dc_index] = (data_cspc[:,freq_index[1],:] + data_cspc[:,freq_index[2],:])/2
977 974 return 1
978 975
979 976 if mode == 2:
980 977 pass
981 978
982 979 if mode == 3:
983 980 pass
984 981
985 982 raise ValueError, "mode parameter has to be 1, 2 or 3"
986 983
987 984 def removeInterference(self):
988 985
989 986 pass
990 987
991 988
992 989 class IncohInt(Operation):
993 990
994 991
995 992 __profIndex = 0
996 993 __withOverapping = False
997 994
998 995 __byTime = False
999 996 __initime = None
1000 997 __lastdatatime = None
1001 998 __integrationtime = None
1002 999
1003 1000 __buffer_spc = None
1004 1001 __buffer_cspc = None
1005 1002 __buffer_dc = None
1006 1003
1007 1004 __dataReady = False
1008 1005
1009 1006 __timeInterval = None
1010 1007
1011 1008 n = None
1012 1009
1013 1010
1014 1011
1015 1012 def __init__(self):
1016 1013
1017 1014 self.__isConfig = False
1018 1015
1019 1016 def setup(self, n=None, timeInterval=None, overlapping=False):
1020 1017 """
1021 1018 Set the parameters of the integration class.
1022 1019
1023 1020 Inputs:
1024 1021
1025 1022 n : Number of coherent integrations
1026 1023 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1027 1024 overlapping :
1028 1025
1029 1026 """
1030 1027
1031 1028 self.__initime = None
1032 1029 self.__lastdatatime = 0
1033 1030 self.__buffer_spc = None
1034 1031 self.__buffer_cspc = None
1035 1032 self.__buffer_dc = None
1036 1033 self.__dataReady = False
1037 1034
1038 1035
1039 1036 if n == None and timeInterval == None:
1040 1037 raise ValueError, "n or timeInterval should be specified ..."
1041 1038
1042 1039 if n != None:
1043 1040 self.n = n
1044 1041 self.__byTime = False
1045 1042 else:
1046 1043 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
1047 1044 self.n = 9999
1048 1045 self.__byTime = True
1049 1046
1050 1047 if overlapping:
1051 1048 self.__withOverapping = True
1052 1049 else:
1053 1050 self.__withOverapping = False
1054 1051 self.__buffer_spc = 0
1055 1052 self.__buffer_cspc = 0
1056 1053 self.__buffer_dc = 0
1057 1054
1058 1055 self.__profIndex = 0
1059 1056
1060 1057 def putData(self, data_spc, data_cspc, data_dc):
1061 1058
1062 1059 """
1063 1060 Add a profile to the __buffer_spc and increase in one the __profileIndex
1064 1061
1065 1062 """
1066 1063
1067 1064 if not self.__withOverapping:
1068 1065 self.__buffer_spc += data_spc
1069 1066
1070 1067 if data_cspc == None:
1071 1068 self.__buffer_cspc = None
1072 1069 else:
1073 1070 self.__buffer_cspc += data_cspc
1074 1071
1075 1072 if data_dc == None:
1076 1073 self.__buffer_dc = None
1077 1074 else:
1078 1075 self.__buffer_dc += data_dc
1079 1076
1080 1077 self.__profIndex += 1
1081 1078 return
1082 1079
1083 1080 #Overlapping data
1084 1081 nChannels, nFFTPoints, nHeis = data_spc.shape
1085 1082 data_spc = numpy.reshape(data_spc, (1, nChannels, nFFTPoints, nHeis))
1086 1083 if data_cspc != None:
1087 1084 data_cspc = numpy.reshape(data_cspc, (1, -1, nFFTPoints, nHeis))
1088 1085 if data_dc != None:
1089 1086 data_dc = numpy.reshape(data_dc, (1, -1, nHeis))
1090 1087
1091 1088 #If the buffer is empty then it takes the data value
1092 1089 if self.__buffer_spc == None:
1093 1090 self.__buffer_spc = data_spc
1094 1091
1095 1092 if data_cspc == None:
1096 1093 self.__buffer_cspc = None
1097 1094 else:
1098 1095 self.__buffer_cspc += data_cspc
1099 1096
1100 1097 if data_dc == None:
1101 1098 self.__buffer_dc = None
1102 1099 else:
1103 1100 self.__buffer_dc += data_dc
1104 1101
1105 1102 self.__profIndex += 1
1106 1103 return
1107 1104
1108 1105 #If the buffer length is lower than n then stakcing the data value
1109 1106 if self.__profIndex < self.n:
1110 1107 self.__buffer_spc = numpy.vstack((self.__buffer_spc, data_spc))
1111 1108
1112 1109 if data_cspc != None:
1113 1110 self.__buffer_cspc = numpy.vstack((self.__buffer_cspc, data_cspc))
1114 1111
1115 1112 if data_dc != None:
1116 1113 self.__buffer_dc = numpy.vstack((self.__buffer_dc, data_dc))
1117 1114
1118 1115 self.__profIndex += 1
1119 1116 return
1120 1117
1121 1118 #If the buffer length is equal to n then replacing the last buffer value with the data value
1122 1119 self.__buffer_spc = numpy.roll(self.__buffer_spc, -1, axis=0)
1123 1120 self.__buffer_spc[self.n-1] = data_spc
1124 1121
1125 1122 if data_cspc != None:
1126 1123 self.__buffer_cspc = numpy.roll(self.__buffer_cspc, -1, axis=0)
1127 1124 self.__buffer_cspc[self.n-1] = data_cspc
1128 1125
1129 1126 if data_dc != None:
1130 1127 self.__buffer_dc = numpy.roll(self.__buffer_dc, -1, axis=0)
1131 1128 self.__buffer_dc[self.n-1] = data_dc
1132 1129
1133 1130 self.__profIndex = self.n
1134 1131 return
1135 1132
1136 1133
1137 1134 def pushData(self):
1138 1135 """
1139 1136 Return the sum of the last profiles and the profiles used in the sum.
1140 1137
1141 1138 Affected:
1142 1139
1143 1140 self.__profileIndex
1144 1141
1145 1142 """
1146 1143 data_spc = None
1147 1144 data_cspc = None
1148 1145 data_dc = None
1149 1146
1150 1147 if not self.__withOverapping:
1151 1148 data_spc = self.__buffer_spc
1152 1149 data_cspc = self.__buffer_cspc
1153 1150 data_dc = self.__buffer_dc
1154 1151
1155 1152 n = self.__profIndex
1156 1153
1157 1154 self.__buffer_spc = 0
1158 1155 self.__buffer_cspc = 0
1159 1156 self.__buffer_dc = 0
1160 1157 self.__profIndex = 0
1161 1158
1162 1159 return data_spc, data_cspc, data_dc, n
1163 1160
1164 1161 #Integration with Overlapping
1165 1162 data_spc = numpy.sum(self.__buffer_spc, axis=0)
1166 1163
1167 1164 if self.__buffer_cspc != None:
1168 1165 data_cspc = numpy.sum(self.__buffer_cspc, axis=0)
1169 1166
1170 1167 if self.__buffer_dc != None:
1171 1168 data_dc = numpy.sum(self.__buffer_dc, axis=0)
1172 1169
1173 1170 n = self.__profIndex
1174 1171
1175 1172 return data_spc, data_cspc, data_dc, n
1176 1173
1177 1174 def byProfiles(self, *args):
1178 1175
1179 1176 self.__dataReady = False
1180 1177 avgdata_spc = None
1181 1178 avgdata_cspc = None
1182 1179 avgdata_dc = None
1183 1180 n = None
1184 1181
1185 1182 self.putData(*args)
1186 1183
1187 1184 if self.__profIndex == self.n:
1188 1185
1189 1186 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1190 1187 self.__dataReady = True
1191 1188
1192 1189 return avgdata_spc, avgdata_cspc, avgdata_dc
1193 1190
1194 1191 def byTime(self, datatime, *args):
1195 1192
1196 1193 self.__dataReady = False
1197 1194 avgdata_spc = None
1198 1195 avgdata_cspc = None
1199 1196 avgdata_dc = None
1200 1197 n = None
1201 1198
1202 1199 self.putData(*args)
1203 1200
1204 1201 if (datatime - self.__initime) >= self.__integrationtime:
1205 1202 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1206 1203 self.n = n
1207 1204 self.__dataReady = True
1208 1205
1209 1206 return avgdata_spc, avgdata_cspc, avgdata_dc
1210 1207
1211 1208 def integrate(self, datatime, *args):
1212 1209
1213 1210 if self.__initime == None:
1214 1211 self.__initime = datatime
1215 1212
1216 1213 if self.__byTime:
1217 1214 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
1218 1215 else:
1219 1216 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1220 1217
1221 1218 self.__lastdatatime = datatime
1222 1219
1223 1220 if avgdata_spc == None:
1224 1221 return None, None, None, None
1225 1222
1226 1223 avgdatatime = self.__initime
1227 1224 self.__timeInterval = (self.__lastdatatime - self.__initime)/(self.n - 1)
1228 1225
1229 1226 deltatime = datatime -self.__lastdatatime
1230 1227
1231 1228 if not self.__withOverapping:
1232 1229 self.__initime = datatime
1233 1230 else:
1234 1231 self.__initime += deltatime
1235 1232
1236 1233 return avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc
1237 1234
1238 1235 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1239 1236
1240 1237 if not self.__isConfig:
1241 1238 self.setup(n, timeInterval, overlapping)
1242 1239 self.__isConfig = True
1243 1240
1244 1241 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1245 1242 dataOut.data_spc,
1246 1243 dataOut.data_cspc,
1247 1244 dataOut.data_dc)
1248 1245
1249 1246 # dataOut.timeInterval *= n
1250 1247 dataOut.flagNoData = True
1251 1248
1252 1249 if self.__dataReady:
1253 1250
1254 1251 dataOut.data_spc = avgdata_spc
1255 1252 dataOut.data_cspc = avgdata_cspc
1256 1253 dataOut.data_dc = avgdata_dc
1257 1254
1258 1255 dataOut.nIncohInt *= self.n
1259 1256 dataOut.utctime = avgdatatime
1260 1257 #dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt * dataOut.nIncohInt * dataOut.nFFTPoints
1261 1258 dataOut.timeInterval = self.__timeInterval*self.n
1262 1259 dataOut.flagNoData = False
1263 1260
1264 1261 class ProfileSelector(Operation):
1265 1262
1266 1263 profileIndex = None
1267 1264 # Tamanho total de los perfiles
1268 1265 nProfiles = None
1269 1266
1270 1267 def __init__(self):
1271 1268
1272 1269 self.profileIndex = 0
1273 1270
1274 1271 def incIndex(self):
1275 1272 self.profileIndex += 1
1276 1273
1277 1274 if self.profileIndex >= self.nProfiles:
1278 1275 self.profileIndex = 0
1279 1276
1280 1277 def isProfileInRange(self, minIndex, maxIndex):
1281 1278
1282 1279 if self.profileIndex < minIndex:
1283 1280 return False
1284 1281
1285 1282 if self.profileIndex > maxIndex:
1286 1283 return False
1287 1284
1288 1285 return True
1289 1286
1290 1287 def isProfileInList(self, profileList):
1291 1288
1292 1289 if self.profileIndex not in profileList:
1293 1290 return False
1294 1291
1295 1292 return True
1296 1293
1297 1294 def run(self, dataOut, profileList=None, profileRangeList=None):
1298 1295
1299 1296 dataOut.flagNoData = True
1300 1297 self.nProfiles = dataOut.nProfiles
1301 1298
1302 1299 if profileList != None:
1303 1300 if self.isProfileInList(profileList):
1304 1301 dataOut.flagNoData = False
1305 1302
1306 1303 self.incIndex()
1307 1304 return 1
1308 1305
1309 1306
1310 1307 elif profileRangeList != None:
1311 1308 minIndex = profileRangeList[0]
1312 1309 maxIndex = profileRangeList[1]
1313 1310 if self.isProfileInRange(minIndex, maxIndex):
1314 1311 dataOut.flagNoData = False
1315 1312
1316 1313 self.incIndex()
1317 1314 return 1
1318 1315
1319 1316 else:
1320 1317 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
1321 1318
1322 1319 return 0
1323 1320
General Comments 0
You need to be logged in to leave comments. Login now