##// END OF EJS Templates
Test codificacion
Miguel Valdez -
r313:289c81e447b8
parent child
Show More
@@ -1,1328 +1,1331
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 = self.__nHeis - self.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 print "Freq0 ", time.time() - ini
616 616
617 617 fft_data = numpy.fft.fft(data, axis=1)
618 618
619 619 print "Freq1 ", time.time() - ini
620 620
621 621 conv = fft_data*fft_code
622 622
623 623 print "Freq2 ", time.time() - ini
624 624
625 625 data = numpy.fft.ifft(conv,axis=1)
626 626
627 627 print "Freq3 ", time.time() - ini
628 628
629 629 datadec = data[:,:-self.nBaud+1]
630 630
631 631 print "Freq4 ", time.time() - ini
632 632
633 633 return datadec
634 634
635 635 def convolutionInFreqOpt(self, data):
636 636
637 637 ini = time.time()
638 638
639 639 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
640 640
641 641 data = cfunctions.decoder(fft_code, data)
642 642
643 643 datadec = data[:,:-self.nBaud+1]
644 644
645 645 print "OptFreq ", time.time() - ini
646 646
647 647 return datadec
648 648
649 649 def convolutionInTime(self, data):
650 650
651 651 ini = time.time()
652 print self.datadecTime.shape, data.shape, code.shape
652 653
653 654 code = self.code[self.__profIndex].reshape(1,-1)
654 655
655 656 for i in range(self.__nChannels):
656 657 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='valid')
657 658
658 659 print "Time ", time.time() - ini
659 660
660 661 return self.datadecTime
661 662
662 663 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0):
663 664 ini = time.time()
664 665 if not self.__isConfig:
665 666
666 667 if code == None:
667 668 code = dataOut.code
668 669 else:
669 670 code = numpy.array(code).reshape(nCode,nBaud)
670 671 dataOut.code = code
671 672 dataOut.nCode = nCode
672 673 dataOut.nBaud = nBaud
673 674
674 675 if code == None:
675 676 return 1
676 677
677 678 self.setup(code, dataOut.data.shape)
678 679 self.__isConfig = True
679 680
681 print "DAta shape ", dataOut.data.shape
682
680 683 if mode == 0:
681 684 datadec = self.convolutionInFreq(dataOut.data)
682 685
683 686 if mode == 1:
684 687 datadec = self.convolutionInTime(dataOut.data)
685 688
686 689 if mode == 2:
687 690 datadec = self.convolutionInFreqOpt(dataOut.data)
688 691
689 692 dataOut.data = datadec
690 693
691 694 dataOut.heightList = dataOut.heightList[0:self.ndatadec]
692 695
693 696 dataOut.flagDecodeData = True #asumo q la data no esta decodificada
694 697
695 698 print time.time() - ini, "prof = %d, nCode=%d" %(self.__profIndex, self.nCode)
696 699
697 700 if self.__profIndex == self.nCode-1:
698 701 self.__profIndex = 0
699 702 return 1
700 703
701 704 self.__profIndex += 1
702 705
703 706 return 1
704 707 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
705 708
706 709
707 710
708 711 class SpectraProc(ProcessingUnit):
709 712
710 713 def __init__(self):
711 714
712 715 self.objectDict = {}
713 716 self.buffer = None
714 717 self.firstdatatime = None
715 718 self.profIndex = 0
716 719 self.dataOut = Spectra()
717 720
718 721 def __updateObjFromInput(self):
719 722
720 723 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
721 724 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
722 725 self.dataOut.channelList = self.dataIn.channelList
723 726 self.dataOut.heightList = self.dataIn.heightList
724 727 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
725 728 # self.dataOut.nHeights = self.dataIn.nHeights
726 729 # self.dataOut.nChannels = self.dataIn.nChannels
727 730 self.dataOut.nBaud = self.dataIn.nBaud
728 731 self.dataOut.nCode = self.dataIn.nCode
729 732 self.dataOut.code = self.dataIn.code
730 733 self.dataOut.nProfiles = self.dataOut.nFFTPoints
731 734 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
732 735 self.dataOut.flagTimeBlock = self.dataIn.flagTimeBlock
733 736 self.dataOut.utctime = self.firstdatatime
734 737 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
735 738 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
736 739 self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
737 740 self.dataOut.nCohInt = self.dataIn.nCohInt
738 741 self.dataOut.nIncohInt = 1
739 742 self.dataOut.ippSeconds = self.dataIn.ippSeconds
740 743 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
741 744
742 745 self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nFFTPoints*self.dataOut.nIncohInt
743 746
744 747 def __getFft(self):
745 748 """
746 749 Convierte valores de Voltaje a Spectra
747 750
748 751 Affected:
749 752 self.dataOut.data_spc
750 753 self.dataOut.data_cspc
751 754 self.dataOut.data_dc
752 755 self.dataOut.heightList
753 756 self.profIndex
754 757 self.buffer
755 758 self.dataOut.flagNoData
756 759 """
757 760 fft_volt = numpy.fft.fft(self.buffer,axis=1)
758 761 fft_volt = fft_volt.astype(numpy.dtype('complex'))
759 762 dc = fft_volt[:,0,:]
760 763
761 764 #calculo de self-spectra
762 765 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
763 766 spc = fft_volt * numpy.conjugate(fft_volt)
764 767 spc = spc.real
765 768
766 769 blocksize = 0
767 770 blocksize += dc.size
768 771 blocksize += spc.size
769 772
770 773 cspc = None
771 774 pairIndex = 0
772 775 if self.dataOut.pairsList != None:
773 776 #calculo de cross-spectra
774 777 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
775 778 for pair in self.dataOut.pairsList:
776 779 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
777 780 pairIndex += 1
778 781 blocksize += cspc.size
779 782
780 783 self.dataOut.data_spc = spc
781 784 self.dataOut.data_cspc = cspc
782 785 self.dataOut.data_dc = dc
783 786 self.dataOut.blockSize = blocksize
784 787
785 788 def init(self, nFFTPoints=None, pairsList=None):
786 789
787 790 self.dataOut.flagNoData = True
788 791
789 792 if self.dataIn.type == "Spectra":
790 793 self.dataOut.copy(self.dataIn)
791 794 return
792 795
793 796 if self.dataIn.type == "Voltage":
794 797
795 798 if nFFTPoints == None:
796 799 raise ValueError, "This SpectraProc.init() need nFFTPoints input variable"
797 800
798 801 if pairsList == None:
799 802 nPairs = 0
800 803 else:
801 804 nPairs = len(pairsList)
802 805
803 806 self.dataOut.nFFTPoints = nFFTPoints
804 807 self.dataOut.pairsList = pairsList
805 808 self.dataOut.nPairs = nPairs
806 809
807 810 if self.buffer == None:
808 811 self.buffer = numpy.zeros((self.dataIn.nChannels,
809 812 self.dataOut.nFFTPoints,
810 813 self.dataIn.nHeights),
811 814 dtype='complex')
812 815
813 816
814 817 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
815 818 self.profIndex += 1
816 819
817 820 if self.firstdatatime == None:
818 821 self.firstdatatime = self.dataIn.utctime
819 822
820 823 if self.profIndex == self.dataOut.nFFTPoints:
821 824 self.__updateObjFromInput()
822 825 self.__getFft()
823 826
824 827 self.dataOut.flagNoData = False
825 828
826 829 self.buffer = None
827 830 self.firstdatatime = None
828 831 self.profIndex = 0
829 832
830 833 return
831 834
832 835 raise ValuError, "The type object %s is not valid"%(self.dataIn.type)
833 836
834 837 def selectChannels(self, channelList):
835 838
836 839 channelIndexList = []
837 840
838 841 for channel in channelList:
839 842 index = self.dataOut.channelList.index(channel)
840 843 channelIndexList.append(index)
841 844
842 845 self.selectChannelsByIndex(channelIndexList)
843 846
844 847 def selectChannelsByIndex(self, channelIndexList):
845 848 """
846 849 Selecciona un bloque de datos en base a canales segun el channelIndexList
847 850
848 851 Input:
849 852 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
850 853
851 854 Affected:
852 855 self.dataOut.data_spc
853 856 self.dataOut.channelIndexList
854 857 self.dataOut.nChannels
855 858
856 859 Return:
857 860 None
858 861 """
859 862
860 863 for channelIndex in channelIndexList:
861 864 if channelIndex not in self.dataOut.channelIndexList:
862 865 print channelIndexList
863 866 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
864 867
865 868 nChannels = len(channelIndexList)
866 869
867 870 data_spc = self.dataOut.data_spc[channelIndexList,:]
868 871
869 872 self.dataOut.data_spc = data_spc
870 873 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
871 874 # self.dataOut.nChannels = nChannels
872 875
873 876 return 1
874 877
875 878 def selectHeights(self, minHei, maxHei):
876 879 """
877 880 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
878 881 minHei <= height <= maxHei
879 882
880 883 Input:
881 884 minHei : valor minimo de altura a considerar
882 885 maxHei : valor maximo de altura a considerar
883 886
884 887 Affected:
885 888 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
886 889
887 890 Return:
888 891 1 si el metodo se ejecuto con exito caso contrario devuelve 0
889 892 """
890 893 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
891 894 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
892 895
893 896 if (maxHei > self.dataOut.heightList[-1]):
894 897 maxHei = self.dataOut.heightList[-1]
895 898 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
896 899
897 900 minIndex = 0
898 901 maxIndex = 0
899 902 heights = self.dataOut.heightList
900 903
901 904 inda = numpy.where(heights >= minHei)
902 905 indb = numpy.where(heights <= maxHei)
903 906
904 907 try:
905 908 minIndex = inda[0][0]
906 909 except:
907 910 minIndex = 0
908 911
909 912 try:
910 913 maxIndex = indb[0][-1]
911 914 except:
912 915 maxIndex = len(heights)
913 916
914 917 self.selectHeightsByIndex(minIndex, maxIndex)
915 918
916 919 return 1
917 920
918 921
919 922 def selectHeightsByIndex(self, minIndex, maxIndex):
920 923 """
921 924 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
922 925 minIndex <= index <= maxIndex
923 926
924 927 Input:
925 928 minIndex : valor de indice minimo de altura a considerar
926 929 maxIndex : valor de indice maximo de altura a considerar
927 930
928 931 Affected:
929 932 self.dataOut.data_spc
930 933 self.dataOut.data_cspc
931 934 self.dataOut.data_dc
932 935 self.dataOut.heightList
933 936
934 937 Return:
935 938 1 si el metodo se ejecuto con exito caso contrario devuelve 0
936 939 """
937 940
938 941 if (minIndex < 0) or (minIndex > maxIndex):
939 942 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
940 943
941 944 if (maxIndex >= self.dataOut.nHeights):
942 945 maxIndex = self.dataOut.nHeights-1
943 946 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
944 947
945 948 nHeights = maxIndex - minIndex + 1
946 949
947 950 #Spectra
948 951 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
949 952
950 953 data_cspc = None
951 954 if self.dataOut.data_cspc != None:
952 955 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
953 956
954 957 data_dc = None
955 958 if self.dataOut.data_dc != None:
956 959 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
957 960
958 961 self.dataOut.data_spc = data_spc
959 962 self.dataOut.data_cspc = data_cspc
960 963 self.dataOut.data_dc = data_dc
961 964
962 965 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
963 966
964 967 return 1
965 968
966 969 def removeDC(self, mode = 1):
967 970
968 971 dc_index = 0
969 972 freq_index = numpy.array([-2,-1,1,2])
970 973 data_spc = self.dataOut.data_spc
971 974 data_cspc = self.dataOut.data_cspc
972 975 data_dc = self.dataOut.data_dc
973 976
974 977 if self.dataOut.flagShiftFFT:
975 978 dc_index += self.dataOut.nFFTPoints/2
976 979 freq_index += self.dataOut.nFFTPoints/2
977 980
978 981 if mode == 1:
979 982 data_spc[dc_index] = (data_spc[:,freq_index[1],:] + data_spc[:,freq_index[2],:])/2
980 983 if data_cspc != None:
981 984 data_cspc[dc_index] = (data_cspc[:,freq_index[1],:] + data_cspc[:,freq_index[2],:])/2
982 985 return 1
983 986
984 987 if mode == 2:
985 988 pass
986 989
987 990 if mode == 3:
988 991 pass
989 992
990 993 raise ValueError, "mode parameter has to be 1, 2 or 3"
991 994
992 995 def removeInterference(self):
993 996
994 997 pass
995 998
996 999
997 1000 class IncohInt(Operation):
998 1001
999 1002
1000 1003 __profIndex = 0
1001 1004 __withOverapping = False
1002 1005
1003 1006 __byTime = False
1004 1007 __initime = None
1005 1008 __lastdatatime = None
1006 1009 __integrationtime = None
1007 1010
1008 1011 __buffer_spc = None
1009 1012 __buffer_cspc = None
1010 1013 __buffer_dc = None
1011 1014
1012 1015 __dataReady = False
1013 1016
1014 1017 __timeInterval = None
1015 1018
1016 1019 n = None
1017 1020
1018 1021
1019 1022
1020 1023 def __init__(self):
1021 1024
1022 1025 self.__isConfig = False
1023 1026
1024 1027 def setup(self, n=None, timeInterval=None, overlapping=False):
1025 1028 """
1026 1029 Set the parameters of the integration class.
1027 1030
1028 1031 Inputs:
1029 1032
1030 1033 n : Number of coherent integrations
1031 1034 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
1032 1035 overlapping :
1033 1036
1034 1037 """
1035 1038
1036 1039 self.__initime = None
1037 1040 self.__lastdatatime = 0
1038 1041 self.__buffer_spc = None
1039 1042 self.__buffer_cspc = None
1040 1043 self.__buffer_dc = None
1041 1044 self.__dataReady = False
1042 1045
1043 1046
1044 1047 if n == None and timeInterval == None:
1045 1048 raise ValueError, "n or timeInterval should be specified ..."
1046 1049
1047 1050 if n != None:
1048 1051 self.n = n
1049 1052 self.__byTime = False
1050 1053 else:
1051 1054 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
1052 1055 self.n = 9999
1053 1056 self.__byTime = True
1054 1057
1055 1058 if overlapping:
1056 1059 self.__withOverapping = True
1057 1060 else:
1058 1061 self.__withOverapping = False
1059 1062 self.__buffer_spc = 0
1060 1063 self.__buffer_cspc = 0
1061 1064 self.__buffer_dc = 0
1062 1065
1063 1066 self.__profIndex = 0
1064 1067
1065 1068 def putData(self, data_spc, data_cspc, data_dc):
1066 1069
1067 1070 """
1068 1071 Add a profile to the __buffer_spc and increase in one the __profileIndex
1069 1072
1070 1073 """
1071 1074
1072 1075 if not self.__withOverapping:
1073 1076 self.__buffer_spc += data_spc
1074 1077
1075 1078 if data_cspc == None:
1076 1079 self.__buffer_cspc = None
1077 1080 else:
1078 1081 self.__buffer_cspc += data_cspc
1079 1082
1080 1083 if data_dc == None:
1081 1084 self.__buffer_dc = None
1082 1085 else:
1083 1086 self.__buffer_dc += data_dc
1084 1087
1085 1088 self.__profIndex += 1
1086 1089 return
1087 1090
1088 1091 #Overlapping data
1089 1092 nChannels, nFFTPoints, nHeis = data_spc.shape
1090 1093 data_spc = numpy.reshape(data_spc, (1, nChannels, nFFTPoints, nHeis))
1091 1094 if data_cspc != None:
1092 1095 data_cspc = numpy.reshape(data_cspc, (1, -1, nFFTPoints, nHeis))
1093 1096 if data_dc != None:
1094 1097 data_dc = numpy.reshape(data_dc, (1, -1, nHeis))
1095 1098
1096 1099 #If the buffer is empty then it takes the data value
1097 1100 if self.__buffer_spc == None:
1098 1101 self.__buffer_spc = data_spc
1099 1102
1100 1103 if data_cspc == None:
1101 1104 self.__buffer_cspc = None
1102 1105 else:
1103 1106 self.__buffer_cspc += data_cspc
1104 1107
1105 1108 if data_dc == None:
1106 1109 self.__buffer_dc = None
1107 1110 else:
1108 1111 self.__buffer_dc += data_dc
1109 1112
1110 1113 self.__profIndex += 1
1111 1114 return
1112 1115
1113 1116 #If the buffer length is lower than n then stakcing the data value
1114 1117 if self.__profIndex < self.n:
1115 1118 self.__buffer_spc = numpy.vstack((self.__buffer_spc, data_spc))
1116 1119
1117 1120 if data_cspc != None:
1118 1121 self.__buffer_cspc = numpy.vstack((self.__buffer_cspc, data_cspc))
1119 1122
1120 1123 if data_dc != None:
1121 1124 self.__buffer_dc = numpy.vstack((self.__buffer_dc, data_dc))
1122 1125
1123 1126 self.__profIndex += 1
1124 1127 return
1125 1128
1126 1129 #If the buffer length is equal to n then replacing the last buffer value with the data value
1127 1130 self.__buffer_spc = numpy.roll(self.__buffer_spc, -1, axis=0)
1128 1131 self.__buffer_spc[self.n-1] = data_spc
1129 1132
1130 1133 if data_cspc != None:
1131 1134 self.__buffer_cspc = numpy.roll(self.__buffer_cspc, -1, axis=0)
1132 1135 self.__buffer_cspc[self.n-1] = data_cspc
1133 1136
1134 1137 if data_dc != None:
1135 1138 self.__buffer_dc = numpy.roll(self.__buffer_dc, -1, axis=0)
1136 1139 self.__buffer_dc[self.n-1] = data_dc
1137 1140
1138 1141 self.__profIndex = self.n
1139 1142 return
1140 1143
1141 1144
1142 1145 def pushData(self):
1143 1146 """
1144 1147 Return the sum of the last profiles and the profiles used in the sum.
1145 1148
1146 1149 Affected:
1147 1150
1148 1151 self.__profileIndex
1149 1152
1150 1153 """
1151 1154 data_spc = None
1152 1155 data_cspc = None
1153 1156 data_dc = None
1154 1157
1155 1158 if not self.__withOverapping:
1156 1159 data_spc = self.__buffer_spc
1157 1160 data_cspc = self.__buffer_cspc
1158 1161 data_dc = self.__buffer_dc
1159 1162
1160 1163 n = self.__profIndex
1161 1164
1162 1165 self.__buffer_spc = 0
1163 1166 self.__buffer_cspc = 0
1164 1167 self.__buffer_dc = 0
1165 1168 self.__profIndex = 0
1166 1169
1167 1170 return data_spc, data_cspc, data_dc, n
1168 1171
1169 1172 #Integration with Overlapping
1170 1173 data_spc = numpy.sum(self.__buffer_spc, axis=0)
1171 1174
1172 1175 if self.__buffer_cspc != None:
1173 1176 data_cspc = numpy.sum(self.__buffer_cspc, axis=0)
1174 1177
1175 1178 if self.__buffer_dc != None:
1176 1179 data_dc = numpy.sum(self.__buffer_dc, axis=0)
1177 1180
1178 1181 n = self.__profIndex
1179 1182
1180 1183 return data_spc, data_cspc, data_dc, n
1181 1184
1182 1185 def byProfiles(self, *args):
1183 1186
1184 1187 self.__dataReady = False
1185 1188 avgdata_spc = None
1186 1189 avgdata_cspc = None
1187 1190 avgdata_dc = None
1188 1191 n = None
1189 1192
1190 1193 self.putData(*args)
1191 1194
1192 1195 if self.__profIndex == self.n:
1193 1196
1194 1197 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1195 1198 self.__dataReady = True
1196 1199
1197 1200 return avgdata_spc, avgdata_cspc, avgdata_dc
1198 1201
1199 1202 def byTime(self, datatime, *args):
1200 1203
1201 1204 self.__dataReady = False
1202 1205 avgdata_spc = None
1203 1206 avgdata_cspc = None
1204 1207 avgdata_dc = None
1205 1208 n = None
1206 1209
1207 1210 self.putData(*args)
1208 1211
1209 1212 if (datatime - self.__initime) >= self.__integrationtime:
1210 1213 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1211 1214 self.n = n
1212 1215 self.__dataReady = True
1213 1216
1214 1217 return avgdata_spc, avgdata_cspc, avgdata_dc
1215 1218
1216 1219 def integrate(self, datatime, *args):
1217 1220
1218 1221 if self.__initime == None:
1219 1222 self.__initime = datatime
1220 1223
1221 1224 if self.__byTime:
1222 1225 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
1223 1226 else:
1224 1227 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1225 1228
1226 1229 self.__lastdatatime = datatime
1227 1230
1228 1231 if avgdata_spc == None:
1229 1232 return None, None, None, None
1230 1233
1231 1234 avgdatatime = self.__initime
1232 1235 self.__timeInterval = (self.__lastdatatime - self.__initime)/(self.n - 1)
1233 1236
1234 1237 deltatime = datatime -self.__lastdatatime
1235 1238
1236 1239 if not self.__withOverapping:
1237 1240 self.__initime = datatime
1238 1241 else:
1239 1242 self.__initime += deltatime
1240 1243
1241 1244 return avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc
1242 1245
1243 1246 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1244 1247
1245 1248 if not self.__isConfig:
1246 1249 self.setup(n, timeInterval, overlapping)
1247 1250 self.__isConfig = True
1248 1251
1249 1252 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1250 1253 dataOut.data_spc,
1251 1254 dataOut.data_cspc,
1252 1255 dataOut.data_dc)
1253 1256
1254 1257 # dataOut.timeInterval *= n
1255 1258 dataOut.flagNoData = True
1256 1259
1257 1260 if self.__dataReady:
1258 1261
1259 1262 dataOut.data_spc = avgdata_spc
1260 1263 dataOut.data_cspc = avgdata_cspc
1261 1264 dataOut.data_dc = avgdata_dc
1262 1265
1263 1266 dataOut.nIncohInt *= self.n
1264 1267 dataOut.utctime = avgdatatime
1265 1268 #dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt * dataOut.nIncohInt * dataOut.nFFTPoints
1266 1269 dataOut.timeInterval = self.__timeInterval*self.n
1267 1270 dataOut.flagNoData = False
1268 1271
1269 1272 class ProfileSelector(Operation):
1270 1273
1271 1274 profileIndex = None
1272 1275 # Tamanho total de los perfiles
1273 1276 nProfiles = None
1274 1277
1275 1278 def __init__(self):
1276 1279
1277 1280 self.profileIndex = 0
1278 1281
1279 1282 def incIndex(self):
1280 1283 self.profileIndex += 1
1281 1284
1282 1285 if self.profileIndex >= self.nProfiles:
1283 1286 self.profileIndex = 0
1284 1287
1285 1288 def isProfileInRange(self, minIndex, maxIndex):
1286 1289
1287 1290 if self.profileIndex < minIndex:
1288 1291 return False
1289 1292
1290 1293 if self.profileIndex > maxIndex:
1291 1294 return False
1292 1295
1293 1296 return True
1294 1297
1295 1298 def isProfileInList(self, profileList):
1296 1299
1297 1300 if self.profileIndex not in profileList:
1298 1301 return False
1299 1302
1300 1303 return True
1301 1304
1302 1305 def run(self, dataOut, profileList=None, profileRangeList=None):
1303 1306
1304 1307 dataOut.flagNoData = True
1305 1308 self.nProfiles = dataOut.nProfiles
1306 1309
1307 1310 if profileList != None:
1308 1311 if self.isProfileInList(profileList):
1309 1312 dataOut.flagNoData = False
1310 1313
1311 1314 self.incIndex()
1312 1315 return 1
1313 1316
1314 1317
1315 1318 elif profileRangeList != None:
1316 1319 minIndex = profileRangeList[0]
1317 1320 maxIndex = profileRangeList[1]
1318 1321 if self.isProfileInRange(minIndex, maxIndex):
1319 1322 dataOut.flagNoData = False
1320 1323
1321 1324 self.incIndex()
1322 1325 return 1
1323 1326
1324 1327 else:
1325 1328 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
1326 1329
1327 1330 return 0
1328 1331
General Comments 0
You need to be logged in to leave comments. Login now