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

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

@@ -1,1372 +1,1372
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 5 '''
6 6
7 7 import copy
8 8 import numpy
9 9 import datetime
10 10 import json
11 11
12 12 from schainpy.utils import log
13 13 from .jroheaderIO import SystemHeader, RadarControllerHeader
14 14
15 15
16 16 def getNumpyDtype(dataTypeCode):
17 17
18 18 if dataTypeCode == 0:
19 19 numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
20 20 elif dataTypeCode == 1:
21 21 numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
22 22 elif dataTypeCode == 2:
23 23 numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
24 24 elif dataTypeCode == 3:
25 25 numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
26 26 elif dataTypeCode == 4:
27 27 numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
28 28 elif dataTypeCode == 5:
29 29 numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
30 30 else:
31 31 raise ValueError('dataTypeCode was not defined')
32 32
33 33 return numpyDtype
34 34
35 35
36 36 def getDataTypeCode(numpyDtype):
37 37
38 38 if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
39 39 datatype = 0
40 40 elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
41 41 datatype = 1
42 42 elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
43 43 datatype = 2
44 44 elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
45 45 datatype = 3
46 46 elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
47 47 datatype = 4
48 48 elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
49 49 datatype = 5
50 50 else:
51 51 datatype = None
52 52
53 53 return datatype
54 54
55 55
56 56 def hildebrand_sekhon(data, navg):
57 57 """
58 58 This method is for the objective determination of the noise level in Doppler spectra. This
59 59 implementation technique is based on the fact that the standard deviation of the spectral
60 60 densities is equal to the mean spectral density for white Gaussian noise
61 61
62 62 Inputs:
63 63 Data : heights
64 64 navg : numbers of averages
65 65
66 66 Return:
67 67 mean : noise's level
68 68 """
69 69
70 70 sortdata = numpy.sort(data, axis=None)
71 71 lenOfData = len(sortdata)
72 72 nums_min = lenOfData*0.2
73 73
74 74 if nums_min <= 5:
75 75
76 76 nums_min = 5
77 77
78 78 sump = 0.
79 79 sumq = 0.
80 80
81 81 j = 0
82 82 cont = 1
83 83
84 84 while((cont == 1)and(j < lenOfData)):
85 85
86 86 sump += sortdata[j]
87 87 sumq += sortdata[j]**2
88 88
89 89 if j > nums_min:
90 90 rtest = float(j)/(j-1) + 1.0/navg
91 91 if ((sumq*j) > (rtest*sump**2)):
92 92 j = j - 1
93 93 sump = sump - sortdata[j]
94 94 sumq = sumq - sortdata[j]**2
95 95 cont = 0
96 96
97 97 j += 1
98 98
99 99 lnoise = sump / j
100 100
101 101 return lnoise
102 102
103 103
104 104 class Beam:
105 105
106 106 def __init__(self):
107 107 self.codeList = []
108 108 self.azimuthList = []
109 109 self.zenithList = []
110 110
111 111
112 112 class GenericData(object):
113 113
114 114 flagNoData = True
115 115
116 116 def copy(self, inputObj=None):
117 117
118 118 if inputObj == None:
119 119 return copy.deepcopy(self)
120 120
121 121 for key in list(inputObj.__dict__.keys()):
122 122
123 123 attribute = inputObj.__dict__[key]
124 124
125 125 # If this attribute is a tuple or list
126 126 if type(inputObj.__dict__[key]) in (tuple, list):
127 127 self.__dict__[key] = attribute[:]
128 128 continue
129 129
130 130 # If this attribute is another object or instance
131 131 if hasattr(attribute, '__dict__'):
132 132 self.__dict__[key] = attribute.copy()
133 133 continue
134 134
135 135 self.__dict__[key] = inputObj.__dict__[key]
136 136
137 137 def deepcopy(self):
138 138
139 139 return copy.deepcopy(self)
140 140
141 141 def isEmpty(self):
142 142
143 143 return self.flagNoData
144 144
145 145
146 146 class JROData(GenericData):
147 147
148 148 # m_BasicHeader = BasicHeader()
149 149 # m_ProcessingHeader = ProcessingHeader()
150 150
151 151 systemHeaderObj = SystemHeader()
152 152 radarControllerHeaderObj = RadarControllerHeader()
153 153 # data = None
154 154 type = None
155 155 datatype = None # dtype but in string
156 156 # dtype = None
157 157 # nChannels = None
158 158 # nHeights = None
159 159 nProfiles = None
160 160 heightList = None
161 161 channelList = None
162 162 flagDiscontinuousBlock = False
163 163 useLocalTime = False
164 164 utctime = None
165 165 timeZone = None
166 166 dstFlag = None
167 167 errorCount = None
168 168 blocksize = None
169 169 # nCode = None
170 170 # nBaud = None
171 171 # code = None
172 172 flagDecodeData = False # asumo q la data no esta decodificada
173 173 flagDeflipData = False # asumo q la data no esta sin flip
174 174 flagShiftFFT = False
175 175 # ippSeconds = None
176 176 # timeInterval = None
177 177 nCohInt = None
178 178 # noise = None
179 179 windowOfFilter = 1
180 180 # Speed of ligth
181 181 C = 3e8
182 182 frequency = 49.92e6
183 183 realtime = False
184 184 beacon_heiIndexList = None
185 185 last_block = None
186 186 blocknow = None
187 187 azimuth = None
188 188 zenith = None
189 189 beam = Beam()
190 190 profileIndex = None
191 191 error = None
192 192 data = None
193 193 nmodes = None
194 194
195 195 def __str__(self):
196 196
197 197 return '{} - {}'.format(self.type, self.getDatatime())
198 198
199 199 def getNoise(self):
200 200
201 201 raise NotImplementedError
202 202
203 203 def getNChannels(self):
204 204
205 205 return len(self.channelList)
206 206
207 207 def getChannelIndexList(self):
208 208
209 209 return list(range(self.nChannels))
210 210
211 211 def getNHeights(self):
212 212
213 213 return len(self.heightList)
214 214
215 215 def getHeiRange(self, extrapoints=0):
216 216
217 217 heis = self.heightList
218 218 # deltah = self.heightList[1] - self.heightList[0]
219 219 #
220 220 # heis.append(self.heightList[-1])
221 221
222 222 return heis
223 223
224 224 def getDeltaH(self):
225 225
226 226 delta = self.heightList[1] - self.heightList[0]
227 227
228 228 return delta
229 229
230 230 def getltctime(self):
231 231
232 232 if self.useLocalTime:
233 233 return self.utctime - self.timeZone * 60
234 234
235 235 return self.utctime
236 236
237 237 def getDatatime(self):
238 238
239 239 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
240 240 return datatimeValue
241 241
242 242 def getTimeRange(self):
243 243
244 244 datatime = []
245 245
246 246 datatime.append(self.ltctime)
247 247 datatime.append(self.ltctime + self.timeInterval + 1)
248 248
249 249 datatime = numpy.array(datatime)
250 250
251 251 return datatime
252 252
253 253 def getFmaxTimeResponse(self):
254 254
255 255 period = (10**-6) * self.getDeltaH() / (0.15)
256 256
257 257 PRF = 1. / (period * self.nCohInt)
258 258
259 259 fmax = PRF
260 260
261 261 return fmax
262 262
263 263 def getFmax(self):
264 264 PRF = 1. / (self.ippSeconds * self.nCohInt)
265 265
266 266 fmax = PRF
267 267 return fmax
268 268
269 269 def getVmax(self):
270 270
271 271 _lambda = self.C / self.frequency
272 272
273 273 vmax = self.getFmax() * _lambda / 2
274 274
275 275 return vmax
276 276
277 277 def get_ippSeconds(self):
278 278 '''
279 279 '''
280 280 return self.radarControllerHeaderObj.ippSeconds
281 281
282 282 def set_ippSeconds(self, ippSeconds):
283 283 '''
284 284 '''
285 285
286 286 self.radarControllerHeaderObj.ippSeconds = ippSeconds
287 287
288 288 return
289 289
290 290 def get_dtype(self):
291 291 '''
292 292 '''
293 293 return getNumpyDtype(self.datatype)
294 294
295 295 def set_dtype(self, numpyDtype):
296 296 '''
297 297 '''
298 298
299 299 self.datatype = getDataTypeCode(numpyDtype)
300 300
301 301 def get_code(self):
302 302 '''
303 303 '''
304 304 return self.radarControllerHeaderObj.code
305 305
306 306 def set_code(self, code):
307 307 '''
308 308 '''
309 309 self.radarControllerHeaderObj.code = code
310 310
311 311 return
312 312
313 313 def get_ncode(self):
314 314 '''
315 315 '''
316 316 return self.radarControllerHeaderObj.nCode
317 317
318 318 def set_ncode(self, nCode):
319 319 '''
320 320 '''
321 321 self.radarControllerHeaderObj.nCode = nCode
322 322
323 323 return
324 324
325 325 def get_nbaud(self):
326 326 '''
327 327 '''
328 328 return self.radarControllerHeaderObj.nBaud
329 329
330 330 def set_nbaud(self, nBaud):
331 331 '''
332 332 '''
333 333 self.radarControllerHeaderObj.nBaud = nBaud
334 334
335 335 return
336 336
337 337 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
338 338 channelIndexList = property(
339 339 getChannelIndexList, "I'm the 'channelIndexList' property.")
340 340 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
341 341 #noise = property(getNoise, "I'm the 'nHeights' property.")
342 342 datatime = property(getDatatime, "I'm the 'datatime' property")
343 343 ltctime = property(getltctime, "I'm the 'ltctime' property")
344 344 ippSeconds = property(get_ippSeconds, set_ippSeconds)
345 345 dtype = property(get_dtype, set_dtype)
346 346 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
347 347 code = property(get_code, set_code)
348 348 nCode = property(get_ncode, set_ncode)
349 349 nBaud = property(get_nbaud, set_nbaud)
350 350
351 351
352 352 class Voltage(JROData):
353 353
354 354 # data es un numpy array de 2 dmensiones (canales, alturas)
355 355 data = None
356 356
357 357 def __init__(self):
358 358 '''
359 359 Constructor
360 360 '''
361 361
362 362 self.useLocalTime = True
363 363 self.radarControllerHeaderObj = RadarControllerHeader()
364 364 self.systemHeaderObj = SystemHeader()
365 365 self.type = "Voltage"
366 366 self.data = None
367 367 # self.dtype = None
368 368 # self.nChannels = 0
369 369 # self.nHeights = 0
370 370 self.nProfiles = None
371 371 self.heightList = None
372 372 self.channelList = None
373 373 # self.channelIndexList = None
374 374 self.flagNoData = True
375 375 self.flagDiscontinuousBlock = False
376 376 self.utctime = None
377 377 self.timeZone = None
378 378 self.dstFlag = None
379 379 self.errorCount = None
380 380 self.nCohInt = None
381 381 self.blocksize = None
382 382 self.flagDecodeData = False # asumo q la data no esta decodificada
383 383 self.flagDeflipData = False # asumo q la data no esta sin flip
384 384 self.flagShiftFFT = False
385 385 self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
386 386 self.profileIndex = 0
387 387
388 388 def getNoisebyHildebrand(self, channel=None):
389 389 """
390 390 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
391 391
392 392 Return:
393 393 noiselevel
394 394 """
395 395
396 396 if channel != None:
397 397 data = self.data[channel]
398 398 nChannels = 1
399 399 else:
400 400 data = self.data
401 401 nChannels = self.nChannels
402 402
403 403 noise = numpy.zeros(nChannels)
404 404 power = data * numpy.conjugate(data)
405 405
406 406 for thisChannel in range(nChannels):
407 407 if nChannels == 1:
408 408 daux = power[:].real
409 409 else:
410 410 daux = power[thisChannel, :].real
411 411 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
412 412
413 413 return noise
414 414
415 415 def getNoise(self, type=1, channel=None):
416 416
417 417 if type == 1:
418 418 noise = self.getNoisebyHildebrand(channel)
419 419
420 420 return noise
421 421
422 422 def getPower(self, channel=None):
423 423
424 424 if channel != None:
425 425 data = self.data[channel]
426 426 else:
427 427 data = self.data
428 428
429 429 power = data * numpy.conjugate(data)
430 430 powerdB = 10 * numpy.log10(power.real)
431 431 powerdB = numpy.squeeze(powerdB)
432 432
433 433 return powerdB
434 434
435 435 def getTimeInterval(self):
436 436
437 437 timeInterval = self.ippSeconds * self.nCohInt
438 438
439 439 return timeInterval
440 440
441 441 noise = property(getNoise, "I'm the 'nHeights' property.")
442 442 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
443 443
444 444
445 445 class Spectra(JROData):
446 446
447 447 # data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
448 448 data_spc = None
449 449 # data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
450 450 data_cspc = None
451 451 # data dc es un numpy array de 2 dmensiones (canales, alturas)
452 452 data_dc = None
453 453 # data power
454 454 data_pwr = None
455 455 nFFTPoints = None
456 456 # nPairs = None
457 457 pairsList = None
458 458 nIncohInt = None
459 459 wavelength = None # Necesario para cacular el rango de velocidad desde la frecuencia
460 460 nCohInt = None # se requiere para determinar el valor de timeInterval
461 461 ippFactor = None
462 462 profileIndex = 0
463 463 plotting = "spectra"
464 464
465 465 def __init__(self):
466 466 '''
467 467 Constructor
468 468 '''
469 469
470 470 self.useLocalTime = True
471 471 self.radarControllerHeaderObj = RadarControllerHeader()
472 472 self.systemHeaderObj = SystemHeader()
473 473 self.type = "Spectra"
474 474 # self.data = None
475 475 # self.dtype = None
476 476 # self.nChannels = 0
477 477 # self.nHeights = 0
478 478 self.nProfiles = None
479 479 self.heightList = None
480 480 self.channelList = None
481 481 # self.channelIndexList = None
482 482 self.pairsList = None
483 483 self.flagNoData = True
484 484 self.flagDiscontinuousBlock = False
485 485 self.utctime = None
486 486 self.nCohInt = None
487 487 self.nIncohInt = None
488 488 self.blocksize = None
489 489 self.nFFTPoints = None
490 490 self.wavelength = None
491 491 self.flagDecodeData = False # asumo q la data no esta decodificada
492 492 self.flagDeflipData = False # asumo q la data no esta sin flip
493 493 self.flagShiftFFT = False
494 494 self.ippFactor = 1
495 495 #self.noise = None
496 496 self.beacon_heiIndexList = []
497 497 self.noise_estimation = None
498 498
499 499 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
500 500 """
501 501 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
502 502
503 503 Return:
504 504 noiselevel
505 505 """
506 506
507 507 noise = numpy.zeros(self.nChannels)
508 508
509 509 for channel in range(self.nChannels):
510 510 daux = self.data_spc[channel,
511 511 xmin_index:xmax_index, ymin_index:ymax_index]
512 512 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
513 513
514 514 return noise
515 515
516 516 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
517 517
518 518 if self.noise_estimation is not None:
519 519 # this was estimated by getNoise Operation defined in jroproc_spectra.py
520 520 return self.noise_estimation
521 521 else:
522 522 noise = self.getNoisebyHildebrand(
523 523 xmin_index, xmax_index, ymin_index, ymax_index)
524 524 return noise
525 525
526 526 def getFreqRangeTimeResponse(self, extrapoints=0):
527 527
528 528 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
529 529 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
530 530
531 531 return freqrange
532 532
533 533 def getAcfRange(self, extrapoints=0):
534 534
535 535 deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
536 536 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
537 537
538 538 return freqrange
539 539
540 540 def getFreqRange(self, extrapoints=0):
541 541
542 542 deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
543 543 freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
544 544
545 545 return freqrange
546 546
547 547 def getVelRange(self, extrapoints=0):
548 548
549 549 deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
550 550 velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
551
551
552 552 if self.nmodes:
553 553 return velrange/self.nmodes
554 554 else:
555 555 return velrange
556 556
557 557 def getNPairs(self):
558 558
559 559 return len(self.pairsList)
560 560
561 561 def getPairsIndexList(self):
562 562
563 563 return list(range(self.nPairs))
564 564
565 565 def getNormFactor(self):
566 566
567 567 pwcode = 1
568 568
569 569 if self.flagDecodeData:
570 570 pwcode = numpy.sum(self.code[0]**2)
571 571 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
572 572 normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
573 573
574 574 return normFactor
575 575
576 576 def getFlagCspc(self):
577 577
578 578 if self.data_cspc is None:
579 579 return True
580 580
581 581 return False
582 582
583 583 def getFlagDc(self):
584 584
585 585 if self.data_dc is None:
586 586 return True
587 587
588 588 return False
589 589
590 590 def getTimeInterval(self):
591 591
592 592 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
593 593 if self.nmodes:
594 594 return self.nmodes*timeInterval
595 595 else:
596 596 return timeInterval
597 597
598 598 def getPower(self):
599 599
600 600 factor = self.normFactor
601 601 z = self.data_spc / factor
602 602 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
603 603 avg = numpy.average(z, axis=1)
604 604
605 605 return 10 * numpy.log10(avg)
606 606
607 607 def getCoherence(self, pairsList=None, phase=False):
608 608
609 609 z = []
610 610 if pairsList is None:
611 611 pairsIndexList = self.pairsIndexList
612 612 else:
613 613 pairsIndexList = []
614 614 for pair in pairsList:
615 615 if pair not in self.pairsList:
616 616 raise ValueError("Pair %s is not in dataOut.pairsList" % (
617 617 pair))
618 618 pairsIndexList.append(self.pairsList.index(pair))
619 619 for i in range(len(pairsIndexList)):
620 620 pair = self.pairsList[pairsIndexList[i]]
621 621 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
622 622 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
623 623 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
624 624 avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
625 625 if phase:
626 626 data = numpy.arctan2(avgcoherenceComplex.imag,
627 627 avgcoherenceComplex.real) * 180 / numpy.pi
628 628 else:
629 629 data = numpy.abs(avgcoherenceComplex)
630 630
631 631 z.append(data)
632 632
633 633 return numpy.array(z)
634 634
635 635 def setValue(self, value):
636 636
637 637 print("This property should not be initialized")
638 638
639 639 return
640 640
641 641 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
642 642 pairsIndexList = property(
643 643 getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
644 644 normFactor = property(getNormFactor, setValue,
645 645 "I'm the 'getNormFactor' property.")
646 646 flag_cspc = property(getFlagCspc, setValue)
647 647 flag_dc = property(getFlagDc, setValue)
648 648 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
649 649 timeInterval = property(getTimeInterval, setValue,
650 650 "I'm the 'timeInterval' property")
651 651
652 652
653 653 class SpectraHeis(Spectra):
654 654
655 655 data_spc = None
656 656 data_cspc = None
657 657 data_dc = None
658 658 nFFTPoints = None
659 659 # nPairs = None
660 660 pairsList = None
661 661 nCohInt = None
662 662 nIncohInt = None
663 663
664 664 def __init__(self):
665 665
666 666 self.radarControllerHeaderObj = RadarControllerHeader()
667 667
668 668 self.systemHeaderObj = SystemHeader()
669 669
670 670 self.type = "SpectraHeis"
671 671
672 672 # self.dtype = None
673 673
674 674 # self.nChannels = 0
675 675
676 676 # self.nHeights = 0
677 677
678 678 self.nProfiles = None
679 679
680 680 self.heightList = None
681 681
682 682 self.channelList = None
683 683
684 684 # self.channelIndexList = None
685 685
686 686 self.flagNoData = True
687 687
688 688 self.flagDiscontinuousBlock = False
689 689
690 690 # self.nPairs = 0
691 691
692 692 self.utctime = None
693 693
694 694 self.blocksize = None
695 695
696 696 self.profileIndex = 0
697 697
698 698 self.nCohInt = 1
699 699
700 700 self.nIncohInt = 1
701 701
702 702 def getNormFactor(self):
703 703 pwcode = 1
704 704 if self.flagDecodeData:
705 705 pwcode = numpy.sum(self.code[0]**2)
706 706
707 707 normFactor = self.nIncohInt * self.nCohInt * pwcode
708 708
709 709 return normFactor
710 710
711 711 def getTimeInterval(self):
712 712
713 713 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
714 714
715 715 return timeInterval
716 716
717 717 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
718 718 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
719 719
720 720
721 721 class Fits(JROData):
722 722
723 723 heightList = None
724 724 channelList = None
725 725 flagNoData = True
726 726 flagDiscontinuousBlock = False
727 727 useLocalTime = False
728 728 utctime = None
729 729 timeZone = None
730 730 # ippSeconds = None
731 731 # timeInterval = None
732 732 nCohInt = None
733 733 nIncohInt = None
734 734 noise = None
735 735 windowOfFilter = 1
736 736 # Speed of ligth
737 737 C = 3e8
738 738 frequency = 49.92e6
739 739 realtime = False
740 740
741 741 def __init__(self):
742 742
743 743 self.type = "Fits"
744 744
745 745 self.nProfiles = None
746 746
747 747 self.heightList = None
748 748
749 749 self.channelList = None
750 750
751 751 # self.channelIndexList = None
752 752
753 753 self.flagNoData = True
754 754
755 755 self.utctime = None
756 756
757 757 self.nCohInt = 1
758 758
759 759 self.nIncohInt = 1
760 760
761 761 self.useLocalTime = True
762 762
763 763 self.profileIndex = 0
764 764
765 765 # self.utctime = None
766 766 # self.timeZone = None
767 767 # self.ltctime = None
768 768 # self.timeInterval = None
769 769 # self.header = None
770 770 # self.data_header = None
771 771 # self.data = None
772 772 # self.datatime = None
773 773 # self.flagNoData = False
774 774 # self.expName = ''
775 775 # self.nChannels = None
776 776 # self.nSamples = None
777 777 # self.dataBlocksPerFile = None
778 778 # self.comments = ''
779 779 #
780 780
781 781 def getltctime(self):
782 782
783 783 if self.useLocalTime:
784 784 return self.utctime - self.timeZone * 60
785 785
786 786 return self.utctime
787 787
788 788 def getDatatime(self):
789 789
790 790 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
791 791 return datatime
792 792
793 793 def getTimeRange(self):
794 794
795 795 datatime = []
796 796
797 797 datatime.append(self.ltctime)
798 798 datatime.append(self.ltctime + self.timeInterval)
799 799
800 800 datatime = numpy.array(datatime)
801 801
802 802 return datatime
803 803
804 804 def getHeiRange(self):
805 805
806 806 heis = self.heightList
807 807
808 808 return heis
809 809
810 810 def getNHeights(self):
811 811
812 812 return len(self.heightList)
813 813
814 814 def getNChannels(self):
815 815
816 816 return len(self.channelList)
817 817
818 818 def getChannelIndexList(self):
819 819
820 820 return list(range(self.nChannels))
821 821
822 822 def getNoise(self, type=1):
823 823
824 824 #noise = numpy.zeros(self.nChannels)
825 825
826 826 if type == 1:
827 827 noise = self.getNoisebyHildebrand()
828 828
829 829 if type == 2:
830 830 noise = self.getNoisebySort()
831 831
832 832 if type == 3:
833 833 noise = self.getNoisebyWindow()
834 834
835 835 return noise
836 836
837 837 def getTimeInterval(self):
838 838
839 839 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
840 840
841 841 return timeInterval
842 842
843 843 def get_ippSeconds(self):
844 844 '''
845 845 '''
846 846 return self.ipp_sec
847 847
848 848
849 849 datatime = property(getDatatime, "I'm the 'datatime' property")
850 850 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
851 851 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
852 852 channelIndexList = property(
853 853 getChannelIndexList, "I'm the 'channelIndexList' property.")
854 854 noise = property(getNoise, "I'm the 'nHeights' property.")
855 855
856 856 ltctime = property(getltctime, "I'm the 'ltctime' property")
857 857 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
858 858 ippSeconds = property(get_ippSeconds, '')
859 859
860 860 class Correlation(JROData):
861 861
862 862 noise = None
863 863 SNR = None
864 864 #--------------------------------------------------
865 865 mode = None
866 866 split = False
867 867 data_cf = None
868 868 lags = None
869 869 lagRange = None
870 870 pairsList = None
871 871 normFactor = None
872 872 #--------------------------------------------------
873 873 # calculateVelocity = None
874 874 nLags = None
875 875 nPairs = None
876 876 nAvg = None
877 877
878 878 def __init__(self):
879 879 '''
880 880 Constructor
881 881 '''
882 882 self.radarControllerHeaderObj = RadarControllerHeader()
883 883
884 884 self.systemHeaderObj = SystemHeader()
885 885
886 886 self.type = "Correlation"
887 887
888 888 self.data = None
889 889
890 890 self.dtype = None
891 891
892 892 self.nProfiles = None
893 893
894 894 self.heightList = None
895 895
896 896 self.channelList = None
897 897
898 898 self.flagNoData = True
899 899
900 900 self.flagDiscontinuousBlock = False
901 901
902 902 self.utctime = None
903 903
904 904 self.timeZone = None
905 905
906 906 self.dstFlag = None
907 907
908 908 self.errorCount = None
909 909
910 910 self.blocksize = None
911 911
912 912 self.flagDecodeData = False # asumo q la data no esta decodificada
913 913
914 914 self.flagDeflipData = False # asumo q la data no esta sin flip
915 915
916 916 self.pairsList = None
917 917
918 918 self.nPoints = None
919 919
920 920 def getPairsList(self):
921 921
922 922 return self.pairsList
923 923
924 924 def getNoise(self, mode=2):
925 925
926 926 indR = numpy.where(self.lagR == 0)[0][0]
927 927 indT = numpy.where(self.lagT == 0)[0][0]
928 928
929 929 jspectra0 = self.data_corr[:, :, indR, :]
930 930 jspectra = copy.copy(jspectra0)
931 931
932 932 num_chan = jspectra.shape[0]
933 933 num_hei = jspectra.shape[2]
934 934
935 935 freq_dc = jspectra.shape[1] / 2
936 936 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
937 937
938 938 if ind_vel[0] < 0:
939 939 ind_vel[list(range(0, 1))] = ind_vel[list(
940 940 range(0, 1))] + self.num_prof
941 941
942 942 if mode == 1:
943 943 jspectra[:, freq_dc, :] = (
944 944 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
945 945
946 946 if mode == 2:
947 947
948 948 vel = numpy.array([-2, -1, 1, 2])
949 949 xx = numpy.zeros([4, 4])
950 950
951 951 for fil in range(4):
952 952 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
953 953
954 954 xx_inv = numpy.linalg.inv(xx)
955 955 xx_aux = xx_inv[0, :]
956 956
957 957 for ich in range(num_chan):
958 958 yy = jspectra[ich, ind_vel, :]
959 959 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
960 960
961 961 junkid = jspectra[ich, freq_dc, :] <= 0
962 962 cjunkid = sum(junkid)
963 963
964 964 if cjunkid.any():
965 965 jspectra[ich, freq_dc, junkid.nonzero()] = (
966 966 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
967 967
968 968 noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
969 969
970 970 return noise
971 971
972 972 def getTimeInterval(self):
973 973
974 974 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
975 975
976 976 return timeInterval
977 977
978 978 def splitFunctions(self):
979 979
980 980 pairsList = self.pairsList
981 981 ccf_pairs = []
982 982 acf_pairs = []
983 983 ccf_ind = []
984 984 acf_ind = []
985 985 for l in range(len(pairsList)):
986 986 chan0 = pairsList[l][0]
987 987 chan1 = pairsList[l][1]
988 988
989 989 # Obteniendo pares de Autocorrelacion
990 990 if chan0 == chan1:
991 991 acf_pairs.append(chan0)
992 992 acf_ind.append(l)
993 993 else:
994 994 ccf_pairs.append(pairsList[l])
995 995 ccf_ind.append(l)
996 996
997 997 data_acf = self.data_cf[acf_ind]
998 998 data_ccf = self.data_cf[ccf_ind]
999 999
1000 1000 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1001 1001
1002 1002 def getNormFactor(self):
1003 1003 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1004 1004 acf_pairs = numpy.array(acf_pairs)
1005 1005 normFactor = numpy.zeros((self.nPairs, self.nHeights))
1006 1006
1007 1007 for p in range(self.nPairs):
1008 1008 pair = self.pairsList[p]
1009 1009
1010 1010 ch0 = pair[0]
1011 1011 ch1 = pair[1]
1012 1012
1013 1013 ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
1014 1014 ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
1015 1015 normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
1016 1016
1017 1017 return normFactor
1018 1018
1019 1019 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1020 1020 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1021 1021
1022 1022
1023 1023 class Parameters(Spectra):
1024 1024
1025 1025 experimentInfo = None # Information about the experiment
1026 1026 # Information from previous data
1027 1027 inputUnit = None # Type of data to be processed
1028 1028 operation = None # Type of operation to parametrize
1029 1029 # normFactor = None #Normalization Factor
1030 1030 groupList = None # List of Pairs, Groups, etc
1031 1031 # Parameters
1032 1032 data_param = None # Parameters obtained
1033 1033 data_pre = None # Data Pre Parametrization
1034 1034 data_SNR = None # Signal to Noise Ratio
1035 1035 # heightRange = None #Heights
1036 1036 abscissaList = None # Abscissa, can be velocities, lags or time
1037 1037 # noise = None #Noise Potency
1038 1038 utctimeInit = None # Initial UTC time
1039 1039 paramInterval = None # Time interval to calculate Parameters in seconds
1040 1040 useLocalTime = True
1041 1041 # Fitting
1042 1042 data_error = None # Error of the estimation
1043 1043 constants = None
1044 1044 library = None
1045 1045 # Output signal
1046 1046 outputInterval = None # Time interval to calculate output signal in seconds
1047 1047 data_output = None # Out signal
1048 1048 nAvg = None
1049 1049 noise_estimation = None
1050 1050 GauSPC = None # Fit gaussian SPC
1051 1051
1052 1052 def __init__(self):
1053 1053 '''
1054 1054 Constructor
1055 1055 '''
1056 1056 self.radarControllerHeaderObj = RadarControllerHeader()
1057 1057
1058 1058 self.systemHeaderObj = SystemHeader()
1059 1059
1060 1060 self.type = "Parameters"
1061 1061
1062 1062 def getTimeRange1(self, interval):
1063 1063
1064 1064 datatime = []
1065 1065
1066 1066 if self.useLocalTime:
1067 1067 time1 = self.utctimeInit - self.timeZone * 60
1068 1068 else:
1069 1069 time1 = self.utctimeInit
1070 1070
1071 1071 datatime.append(time1)
1072 1072 datatime.append(time1 + interval)
1073 1073 datatime = numpy.array(datatime)
1074 1074
1075 1075 return datatime
1076 1076
1077 1077 def getTimeInterval(self):
1078 1078
1079 1079 if hasattr(self, 'timeInterval1'):
1080 1080 return self.timeInterval1
1081 1081 else:
1082 1082 return self.paramInterval
1083 1083
1084 1084 def setValue(self, value):
1085 1085
1086 1086 print("This property should not be initialized")
1087 1087
1088 1088 return
1089 1089
1090 1090 def getNoise(self):
1091 1091
1092 1092 return self.spc_noise
1093 1093
1094 1094 timeInterval = property(getTimeInterval)
1095 1095 noise = property(getNoise, setValue, "I'm the 'Noise' property.")
1096 1096
1097 1097
1098 1098 class PlotterData(object):
1099 1099 '''
1100 1100 Object to hold data to be plotted
1101 1101 '''
1102 1102
1103 1103 MAXNUMX = 100
1104 1104 MAXNUMY = 100
1105 1105
1106 1106 def __init__(self, code, throttle_value, exp_code, buffering=True, snr=False):
1107
1107
1108 1108 self.key = code
1109 1109 self.throttle = throttle_value
1110 1110 self.exp_code = exp_code
1111 1111 self.buffering = buffering
1112 1112 self.ready = False
1113 1113 self.localtime = False
1114 1114 self.data = {}
1115 1115 self.meta = {}
1116 1116 self.__times = []
1117 1117 self.__heights = []
1118 1118
1119 1119 if 'snr' in code:
1120 1120 self.plottypes = ['snr']
1121 1121 elif code == 'spc':
1122 1122 self.plottypes = ['spc', 'noise', 'rti']
1123 1123 elif code == 'rti':
1124 1124 self.plottypes = ['noise', 'rti']
1125 1125 else:
1126 1126 self.plottypes = [code]
1127 1127
1128 1128 if 'snr' not in self.plottypes and snr:
1129 1129 self.plottypes.append('snr')
1130 1130
1131 1131 for plot in self.plottypes:
1132 1132 self.data[plot] = {}
1133 1133
1134 1134 def __str__(self):
1135 1135 dum = ['{}{}'.format(key, self.shape(key)) for key in self.data]
1136 1136 return 'Data[{}][{}]'.format(';'.join(dum), len(self.__times))
1137 1137
1138 1138 def __len__(self):
1139 1139 return len(self.__times)
1140 1140
1141 1141 def __getitem__(self, key):
1142
1142
1143 1143 if key not in self.data:
1144 1144 raise KeyError(log.error('Missing key: {}'.format(key)))
1145 1145 if 'spc' in key or not self.buffering:
1146 1146 ret = self.data[key]
1147 1147 elif 'scope' in key:
1148 1148 ret = numpy.array(self.data[key][float(self.tm)])
1149 1149 else:
1150 1150 ret = numpy.array([self.data[key][x] for x in self.times])
1151 1151 if ret.ndim > 1:
1152 1152 ret = numpy.swapaxes(ret, 0, 1)
1153 1153 return ret
1154 1154
1155 1155 def __contains__(self, key):
1156 1156 return key in self.data
1157 1157
1158 1158 def setup(self):
1159 1159 '''
1160 1160 Configure object
1161 1161 '''
1162 1162
1163 1163 self.type = ''
1164 1164 self.ready = False
1165 1165 self.data = {}
1166 1166 self.__times = []
1167 1167 self.__heights = []
1168 1168 self.__all_heights = set()
1169 1169 for plot in self.plottypes:
1170 1170 if 'snr' in plot:
1171 1171 plot = 'snr'
1172 1172 elif 'spc_moments' == plot:
1173 1173 plot = 'moments'
1174 1174 self.data[plot] = {}
1175
1175
1176 1176 if 'spc' in self.data or 'rti' in self.data or 'cspc' in self.data or 'moments' in self.data:
1177 1177 self.data['noise'] = {}
1178 1178 self.data['rti'] = {}
1179 1179 if 'noise' not in self.plottypes:
1180 1180 self.plottypes.append('noise')
1181 1181 if 'rti' not in self.plottypes:
1182 1182 self.plottypes.append('rti')
1183
1183
1184 1184 def shape(self, key):
1185 1185 '''
1186 1186 Get the shape of the one-element data for the given key
1187 1187 '''
1188 1188
1189 1189 if len(self.data[key]):
1190 1190 if 'spc' in key or not self.buffering:
1191 1191 return self.data[key].shape
1192 1192 return self.data[key][self.__times[0]].shape
1193 1193 return (0,)
1194 1194
1195 1195 def update(self, dataOut, tm):
1196 1196 '''
1197 1197 Update data object with new dataOut
1198 1198 '''
1199
1199
1200 1200 if tm in self.__times:
1201 1201 return
1202 1202 self.profileIndex = dataOut.profileIndex
1203 1203 self.tm = tm
1204 1204 self.type = dataOut.type
1205 1205 self.parameters = getattr(dataOut, 'parameters', [])
1206
1206
1207 1207 if hasattr(dataOut, 'meta'):
1208 1208 self.meta.update(dataOut.meta)
1209
1209
1210 1210 self.pairs = dataOut.pairsList
1211 1211 self.interval = dataOut.getTimeInterval()
1212 1212 self.localtime = dataOut.useLocalTime
1213 1213 if 'spc' in self.plottypes or 'cspc' in self.plottypes or 'spc_moments' in self.plottypes:
1214 1214 self.xrange = (dataOut.getFreqRange(1)/1000.,
1215 1215 dataOut.getAcfRange(1), dataOut.getVelRange(1))
1216 1216 self.factor = dataOut.normFactor
1217 1217 self.__heights.append(dataOut.heightList)
1218 1218 self.__all_heights.update(dataOut.heightList)
1219 1219 self.__times.append(tm)
1220
1220
1221 1221 for plot in self.plottypes:
1222 1222 if plot in ('spc', 'spc_moments'):
1223 1223 z = dataOut.data_spc/dataOut.normFactor
1224 1224 buffer = 10*numpy.log10(z)
1225 1225 if plot == 'cspc':
1226 1226 z = dataOut.data_spc/dataOut.normFactor
1227 1227 buffer = (dataOut.data_spc, dataOut.data_cspc)
1228 1228 if plot == 'noise':
1229 1229 buffer = 10*numpy.log10(dataOut.getNoise()/dataOut.normFactor)
1230 1230 if plot == 'rti':
1231 1231 buffer = dataOut.getPower()
1232 1232 if plot == 'snr_db':
1233 1233 buffer = dataOut.data_SNR
1234 1234 if plot == 'snr':
1235 1235 buffer = 10*numpy.log10(dataOut.data_SNR)
1236 1236 if plot == 'dop':
1237 1237 buffer = dataOut.data_DOP
1238 1238 if plot == 'pow':
1239 1239 buffer = 10*numpy.log10(dataOut.data_POW)
1240 1240 if plot == 'width':
1241 1241 buffer = dataOut.data_WIDTH
1242 1242 if plot == 'coh':
1243 1243 buffer = dataOut.getCoherence()
1244 1244 if plot == 'phase':
1245 1245 buffer = dataOut.getCoherence(phase=True)
1246 1246 if plot == 'output':
1247 1247 buffer = dataOut.data_output
1248 1248 if plot == 'param':
1249 1249 buffer = dataOut.data_param
1250 1250 if plot == 'scope':
1251 1251 buffer = dataOut.data
1252 1252 self.flagDataAsBlock = dataOut.flagDataAsBlock
1253 self.nProfiles = dataOut.nProfiles
1254
1253 self.nProfiles = dataOut.nProfiles
1254
1255 1255 if plot == 'spc':
1256 1256 self.data['spc'] = buffer
1257 1257 elif plot == 'cspc':
1258 1258 self.data['spc'] = buffer[0]
1259 1259 self.data['cspc'] = buffer[1]
1260 1260 elif plot == 'spc_moments':
1261 1261 self.data['spc'] = buffer
1262 1262 self.data['moments'][tm] = dataOut.moments
1263 1263 else:
1264 1264 if self.buffering:
1265 1265 self.data[plot][tm] = buffer
1266 1266 else:
1267 1267 self.data[plot] = buffer
1268 1268
1269 1269 if dataOut.channelList is None:
1270 1270 self.channels = range(buffer.shape[0])
1271 1271 else:
1272 1272 self.channels = dataOut.channelList
1273 1273
1274 1274 def normalize_heights(self):
1275 1275 '''
1276 1276 Ensure same-dimension of the data for different heighList
1277 1277 '''
1278 1278
1279 1279 H = numpy.array(list(self.__all_heights))
1280 1280 H.sort()
1281 1281 for key in self.data:
1282 1282 shape = self.shape(key)[:-1] + H.shape
1283 1283 for tm, obj in list(self.data[key].items()):
1284 1284 h = self.__heights[self.__times.index(tm)]
1285 1285 if H.size == h.size:
1286 1286 continue
1287 1287 index = numpy.where(numpy.in1d(H, h))[0]
1288 1288 dummy = numpy.zeros(shape) + numpy.nan
1289 1289 if len(shape) == 2:
1290 1290 dummy[:, index] = obj
1291 1291 else:
1292 1292 dummy[index] = obj
1293 1293 self.data[key][tm] = dummy
1294 1294
1295 1295 self.__heights = [H for tm in self.__times]
1296 1296
1297 1297 def jsonify(self, plot_name, plot_type, decimate=False):
1298 1298 '''
1299 1299 Convert data to json
1300 1300 '''
1301 1301
1302 1302 tm = self.times[-1]
1303 1303 dy = int(self.heights.size/self.MAXNUMY) + 1
1304 1304 if self.key in ('spc', 'cspc') or not self.buffering:
1305 1305 dx = int(self.data[self.key].shape[1]/self.MAXNUMX) + 1
1306 1306 data = self.roundFloats(
1307 1307 self.data[self.key][::, ::dx, ::dy].tolist())
1308 1308 else:
1309 1309 data = self.roundFloats(self.data[self.key][tm].tolist())
1310 1310 if self.key is 'noise':
1311 1311 data = [[x] for x in data]
1312 1312
1313 1313 meta = {}
1314 1314 ret = {
1315 1315 'plot': plot_name,
1316 1316 'code': self.exp_code,
1317 1317 'time': float(tm),
1318 1318 'data': data,
1319 1319 }
1320 1320 meta['type'] = plot_type
1321 1321 meta['interval'] = float(self.interval)
1322 1322 meta['localtime'] = self.localtime
1323 1323 meta['yrange'] = self.roundFloats(self.heights[::dy].tolist())
1324 1324 if 'spc' in self.data or 'cspc' in self.data:
1325 1325 meta['xrange'] = self.roundFloats(self.xrange[2][::dx].tolist())
1326 1326 else:
1327 1327 meta['xrange'] = []
1328 1328
1329 meta.update(self.meta)
1329 meta.update(self.meta)
1330 1330 ret['metadata'] = meta
1331 1331 return json.dumps(ret)
1332 1332
1333 1333 @property
1334 1334 def times(self):
1335 1335 '''
1336 1336 Return the list of times of the current data
1337 1337 '''
1338 1338
1339 1339 ret = numpy.array(self.__times)
1340 1340 ret.sort()
1341 1341 return ret
1342 1342
1343 1343 @property
1344 1344 def min_time(self):
1345 1345 '''
1346 1346 Return the minimun time value
1347 1347 '''
1348 1348
1349 1349 return self.times[0]
1350 1350
1351 1351 @property
1352 1352 def max_time(self):
1353 1353 '''
1354 1354 Return the maximun time value
1355 1355 '''
1356 1356
1357 1357 return self.times[-1]
1358 1358
1359 1359 @property
1360 1360 def heights(self):
1361 1361 '''
1362 1362 Return the list of heights of the current data
1363 1363 '''
1364 1364
1365 1365 return numpy.array(self.__heights[-1])
1366 1366
1367 1367 @staticmethod
1368 1368 def roundFloats(obj):
1369 1369 if isinstance(obj, list):
1370 1370 return list(map(PlotterData.roundFloats, obj))
1371 1371 elif isinstance(obj, float):
1372 1372 return round(obj, 2)
@@ -1,1589 +1,1809
1 1 '''
2 2 Created on Jul 9, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import datetime
8 8 import numpy
9 9
10 10 from .figure import Figure, isRealtime, isTimeInHourRange
11 11 from .plotting_codes import *
12 12 from schainpy.model.proc.jroproc_base import MPDecorator
13 13
14 14 from schainpy.utils import log
15 15
16 16 @MPDecorator
17 17 class SpectraPlot_(Figure):
18 18
19 19 isConfig = None
20 20 __nsubplots = None
21 21
22 22 WIDTHPROF = None
23 23 HEIGHTPROF = None
24 24 PREFIX = 'spc'
25 25
26 26 def __init__(self):
27 27 Figure.__init__(self)
28 28 self.isConfig = False
29 29 self.__nsubplots = 1
30 30 self.WIDTH = 250
31 31 self.HEIGHT = 250
32 32 self.WIDTHPROF = 120
33 33 self.HEIGHTPROF = 0
34 34 self.counter_imagwr = 0
35 35
36 36 self.PLOT_CODE = SPEC_CODE
37 37
38 38 self.FTP_WEI = None
39 39 self.EXP_CODE = None
40 40 self.SUB_EXP_CODE = None
41 41 self.PLOT_POS = None
42 42
43 43 self.__xfilter_ena = False
44 44 self.__yfilter_ena = False
45
45
46 46 self.indice=1
47 47
48 48 def getSubplots(self):
49 49
50 50 ncol = int(numpy.sqrt(self.nplots)+0.9)
51 51 nrow = int(self.nplots*1./ncol + 0.9)
52 52
53 53 return nrow, ncol
54 54
55 55 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
56 56
57 57 self.__showprofile = showprofile
58 58 self.nplots = nplots
59 59
60 60 ncolspan = 1
61 61 colspan = 1
62 62 if showprofile:
63 63 ncolspan = 3
64 64 colspan = 2
65 65 self.__nsubplots = 2
66 66
67 67 self.createFigure(id = id,
68 68 wintitle = wintitle,
69 69 widthplot = self.WIDTH + self.WIDTHPROF,
70 70 heightplot = self.HEIGHT + self.HEIGHTPROF,
71 71 show=show)
72 72
73 73 nrow, ncol = self.getSubplots()
74 74
75 75 counter = 0
76 76 for y in range(nrow):
77 77 for x in range(ncol):
78 78
79 79 if counter >= self.nplots:
80 80 break
81 81
82 82 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
83 83
84 84 if showprofile:
85 85 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
86 86
87 87 counter += 1
88 88
89 89 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
90 90 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
91 91 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
92 92 server=None, folder=None, username=None, password=None,
93 93 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
94 94 xaxis="frequency", colormap='jet', normFactor=None):
95 95
96 96 """
97 97
98 98 Input:
99 99 dataOut :
100 100 id :
101 101 wintitle :
102 102 channelList :
103 103 showProfile :
104 104 xmin : None,
105 105 xmax : None,
106 106 ymin : None,
107 107 ymax : None,
108 108 zmin : None,
109 109 zmax : None
110 110 """
111 111 if dataOut.flagNoData:
112 112 return dataOut
113 113
114 114 if realtime:
115 115 if not(isRealtime(utcdatatime = dataOut.utctime)):
116 116 print('Skipping this plot function')
117 117 return
118 118
119 119 if channelList == None:
120 120 channelIndexList = dataOut.channelIndexList
121 121 else:
122 122 channelIndexList = []
123 123 for channel in channelList:
124 124 if channel not in dataOut.channelList:
125 125 raise ValueError("Channel %d is not in dataOut.channelList" %channel)
126 126 channelIndexList.append(dataOut.channelList.index(channel))
127 127
128 128 if normFactor is None:
129 129 factor = dataOut.normFactor
130 130 else:
131 131 factor = normFactor
132 132 if xaxis == "frequency":
133 133 x = dataOut.getFreqRange(1)/1000.
134 134 xlabel = "Frequency (kHz)"
135 135
136 136 elif xaxis == "time":
137 137 x = dataOut.getAcfRange(1)
138 138 xlabel = "Time (ms)"
139 139
140 140 else:
141 141 x = dataOut.getVelRange(1)
142 142 xlabel = "Velocity (m/s)"
143 143
144 144 ylabel = "Range (km)"
145 145
146 146 y = dataOut.getHeiRange()
147 147 z = dataOut.data_spc/factor
148 148 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
149 149 zdB = 10*numpy.log10(z)
150 150
151 151 avg = numpy.average(z, axis=1)
152 152 avgdB = 10*numpy.log10(avg)
153 153
154 154 noise = dataOut.getNoise()/factor
155 155 noisedB = 10*numpy.log10(noise)
156 156
157 157 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
158 158 title = wintitle + " Spectra"
159 159
160 160 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
161 161 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
162 162
163 163 if not self.isConfig:
164 164
165 165 nplots = len(channelIndexList)
166 166
167 167 self.setup(id=id,
168 168 nplots=nplots,
169 169 wintitle=wintitle,
170 170 showprofile=showprofile,
171 171 show=show)
172 172
173 173 if xmin == None: xmin = numpy.nanmin(x)
174 174 if xmax == None: xmax = numpy.nanmax(x)
175 175 if ymin == None: ymin = numpy.nanmin(y)
176 176 if ymax == None: ymax = numpy.nanmax(y)
177 177 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
178 178 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
179 179
180 180 self.FTP_WEI = ftp_wei
181 181 self.EXP_CODE = exp_code
182 182 self.SUB_EXP_CODE = sub_exp_code
183 183 self.PLOT_POS = plot_pos
184 184
185 185 self.isConfig = True
186 186
187 187 self.setWinTitle(title)
188 188
189 189 for i in range(self.nplots):
190 190 index = channelIndexList[i]
191 191 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
192 192 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
193 193 if len(dataOut.beam.codeList) != 0:
194 194 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
195 195
196 196 axes = self.axesList[i*self.__nsubplots]
197 197 axes.pcolor(x, y, zdB[index,:,:],
198 198 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
199 199 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
200 200 ticksize=9, cblabel='')
201 201
202 202 if self.__showprofile:
203 203 axes = self.axesList[i*self.__nsubplots +1]
204 204 axes.pline(avgdB[index,:], y,
205 205 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
206 206 xlabel='dB', ylabel='', title='',
207 207 ytick_visible=False,
208 208 grid='x')
209 209
210 210 noiseline = numpy.repeat(noisedB[index], len(y))
211 211 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
212 212
213 213 self.draw()
214 214
215 215 if figfile == None:
216 216 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
217 217 name = str_datetime
218 218 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
219 219 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
220 220 figfile = self.getFilename(name)
221 221
222 222 self.save(figpath=figpath,
223 223 figfile=figfile,
224 224 save=save,
225 225 ftp=ftp,
226 226 wr_period=wr_period,
227 227 thisDatetime=thisDatetime)
228
228
229 229
230 230 return dataOut
231 231
232 232 @MPDecorator
233 class WpowerPlot_(Figure):
234
235 isConfig = None
236 __nsubplots = None
237
238 WIDTHPROF = None
239 HEIGHTPROF = None
240 PREFIX = 'wpo'
241
242 def __init__(self):
243 Figure.__init__(self)
244 self.isConfig = False
245 self.__nsubplots = 1
246 self.WIDTH = 250
247 self.HEIGHT = 250
248 self.WIDTHPROF = 120
249 self.HEIGHTPROF = 0
250 self.counter_imagwr = 0
251
252 self.PLOT_CODE = WPO_CODE
253
254 self.FTP_WEI = None
255 self.EXP_CODE = None
256 self.SUB_EXP_CODE = None
257 self.PLOT_POS = None
258
259 self.__xfilter_ena = False
260 self.__yfilter_ena = False
261
262 self.indice=1
263
264 def getSubplots(self):
265
266 ncol = int(numpy.sqrt(self.nplots)+0.9)
267 nrow = int(self.nplots*1./ncol + 0.9)
268
269 return nrow, ncol
270
271 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
272
273 self.__showprofile = showprofile
274 self.nplots = nplots
275
276 ncolspan = 1
277 colspan = 1
278 if showprofile:
279 ncolspan = 3
280 colspan = 2
281 self.__nsubplots = 2
282
283 self.createFigure(id = id,
284 wintitle = wintitle,
285 widthplot = self.WIDTH + self.WIDTHPROF,
286 heightplot = self.HEIGHT + self.HEIGHTPROF,
287 show=show)
288
289 nrow, ncol = self.getSubplots()
290
291 counter = 0
292 for y in range(nrow):
293 for x in range(ncol):
294
295 if counter >= self.nplots:
296 break
297
298 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
299
300 if showprofile:
301 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
302
303 counter += 1
304
305 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
306 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
307 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
308 server=None, folder=None, username=None, password=None,
309 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
310 xaxis="frequency", colormap='jet', normFactor=None):
311
312 """
313
314 Input:
315 dataOut :
316 id :
317 wintitle :
318 channelList :
319 showProfile :
320 xmin : None,
321 xmax : None,
322 ymin : None,
323 ymax : None,
324 zmin : None,
325 zmax : None
326 """
327 print("***************PLOTEO******************")
328 print("DATAOUT SHAPE : ",dataOut.data.shape)
329 if dataOut.flagNoData:
330 return dataOut
331
332 if realtime:
333 if not(isRealtime(utcdatatime = dataOut.utctime)):
334 print('Skipping this plot function')
335 return
336
337 if channelList == None:
338 channelIndexList = dataOut.channelIndexList
339 else:
340 channelIndexList = []
341 for channel in channelList:
342 if channel not in dataOut.channelList:
343 raise ValueError("Channel %d is not in dataOut.channelList" %channel)
344 channelIndexList.append(dataOut.channelList.index(channel))
345
346
347 print("channelIndexList",channelIndexList)
348 if normFactor is None:
349 factor = dataOut.normFactor
350 else:
351 factor = normFactor
352 if xaxis == "frequency":
353 x = dataOut.getFreqRange(1)/1000.
354 xlabel = "Frequency (kHz)"
355
356 elif xaxis == "time":
357 x = dataOut.getAcfRange(1)
358 xlabel = "Time (ms)"
359
360 else:
361 x = dataOut.getVelRange(1)
362 xlabel = "Velocity (m/s)"
363
364 ylabel = "Range (km)"
365
366 y = dataOut.getHeiRange()
367 print("factor",factor)
368
369 z = dataOut.data/factor # dividido /factor
370 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
371 zdB = 10*numpy.log10(z)
372
373 avg = numpy.average(z, axis=1)
374 avgdB = 10*numpy.log10(avg)
375
376 noise = dataOut.getNoise()/factor
377 noisedB = 10*numpy.log10(noise)
378
379 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
380 title = wintitle + "Weather Power"
381
382 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
383 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
384
385 if not self.isConfig:
386
387 nplots = len(channelIndexList)
388
389 self.setup(id=id,
390 nplots=nplots,
391 wintitle=wintitle,
392 showprofile=showprofile,
393 show=show)
394
395 if xmin == None: xmin = numpy.nanmin(x)
396 if xmax == None: xmax = numpy.nanmax(x)
397 if ymin == None: ymin = numpy.nanmin(y)
398 if ymax == None: ymax = numpy.nanmax(y)
399 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
400 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
401
402 self.FTP_WEI = ftp_wei
403 self.EXP_CODE = exp_code
404 self.SUB_EXP_CODE = sub_exp_code
405 self.PLOT_POS = plot_pos
406
407 self.isConfig = True
408
409 self.setWinTitle(title)
410
411 for i in range(self.nplots):
412 index = channelIndexList[i]
413 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
414 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
415 if len(dataOut.beam.codeList) != 0:
416 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[index], noisedB[index], dataOut.beam.azimuthList[index], dataOut.beam.zenithList[index], str_datetime)
417
418 axes = self.axesList[i*self.__nsubplots]
419 axes.pcolor(x, y, zdB[index,:,:],
420 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
421 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
422 ticksize=9, cblabel='')
423
424 if self.__showprofile:
425 axes = self.axesList[i*self.__nsubplots +1]
426 axes.pline(avgdB[index,:], y,
427 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
428 xlabel='dB', ylabel='', title='',
429 ytick_visible=False,
430 grid='x')
431
432 noiseline = numpy.repeat(noisedB[index], len(y))
433 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
434
435 self.draw()
436
437 if figfile == None:
438 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
439 name = str_datetime
440 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
441 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
442 figfile = self.getFilename(name)
443
444 self.save(figpath=figpath,
445 figfile=figfile,
446 save=save,
447 ftp=ftp,
448 wr_period=wr_period,
449 thisDatetime=thisDatetime)
450 return dataOut
451
452 @MPDecorator
233 453 class CrossSpectraPlot_(Figure):
234 454
235 455 isConfig = None
236 456 __nsubplots = None
237 457
238 458 WIDTH = None
239 459 HEIGHT = None
240 460 WIDTHPROF = None
241 461 HEIGHTPROF = None
242 462 PREFIX = 'cspc'
243 463
244 464 def __init__(self):
245 465 Figure.__init__(self)
246 466 self.isConfig = False
247 467 self.__nsubplots = 4
248 468 self.counter_imagwr = 0
249 469 self.WIDTH = 250
250 470 self.HEIGHT = 250
251 471 self.WIDTHPROF = 0
252 472 self.HEIGHTPROF = 0
253 473
254 474 self.PLOT_CODE = CROSS_CODE
255 475 self.FTP_WEI = None
256 476 self.EXP_CODE = None
257 477 self.SUB_EXP_CODE = None
258 478 self.PLOT_POS = None
259
479
260 480 self.indice=0
261 481
262 482 def getSubplots(self):
263 483
264 484 ncol = 4
265 485 nrow = self.nplots
266 486
267 487 return nrow, ncol
268 488
269 489 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
270 490
271 491 self.__showprofile = showprofile
272 492 self.nplots = nplots
273 493
274 494 ncolspan = 1
275 495 colspan = 1
276 496
277 497 self.createFigure(id = id,
278 498 wintitle = wintitle,
279 499 widthplot = self.WIDTH + self.WIDTHPROF,
280 500 heightplot = self.HEIGHT + self.HEIGHTPROF,
281 501 show=True)
282 502
283 503 nrow, ncol = self.getSubplots()
284 504
285 505 counter = 0
286 506 for y in range(nrow):
287 507 for x in range(ncol):
288 508 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
289 509
290 510 counter += 1
291 511
292 512 def run(self, dataOut, id, wintitle="", pairsList=None,
293 513 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
294 514 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
295 515 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
296 516 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
297 517 server=None, folder=None, username=None, password=None,
298 518 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
299 519 xaxis='frequency'):
300 520
301 521 """
302 522
303 523 Input:
304 524 dataOut :
305 525 id :
306 526 wintitle :
307 527 channelList :
308 528 showProfile :
309 529 xmin : None,
310 530 xmax : None,
311 531 ymin : None,
312 532 ymax : None,
313 533 zmin : None,
314 534 zmax : None
315 535 """
316 536
317 if dataOut.flagNoData:
537 if dataOut.flagNoData:
318 538 return dataOut
319 539
320 540 if pairsList == None:
321 541 pairsIndexList = dataOut.pairsIndexList
322 542 else:
323 543 pairsIndexList = []
324 544 for pair in pairsList:
325 545 if pair not in dataOut.pairsList:
326 546 raise ValueError("Pair %s is not in dataOut.pairsList" %str(pair))
327 547 pairsIndexList.append(dataOut.pairsList.index(pair))
328 548
329 549 if not pairsIndexList:
330 550 return
331 551
332 552 if len(pairsIndexList) > 4:
333 553 pairsIndexList = pairsIndexList[0:4]
334
554
335 555 if normFactor is None:
336 556 factor = dataOut.normFactor
337 557 else:
338 558 factor = normFactor
339 559 x = dataOut.getVelRange(1)
340 560 y = dataOut.getHeiRange()
341 561 z = dataOut.data_spc[:,:,:]/factor
342 562 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
343 563
344 564 noise = dataOut.noise/factor
345 565
346 566 zdB = 10*numpy.log10(z)
347 567 noisedB = 10*numpy.log10(noise)
348 568
349 569 if coh_min == None:
350 570 coh_min = 0.0
351 571 if coh_max == None:
352 572 coh_max = 1.0
353 573
354 574 if phase_min == None:
355 575 phase_min = -180
356 576 if phase_max == None:
357 577 phase_max = 180
358 578
359 579 #thisDatetime = dataOut.datatime
360 580 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
361 581 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
362 582 # xlabel = "Velocity (m/s)"
363 583 ylabel = "Range (Km)"
364 584
365 585 if xaxis == "frequency":
366 586 x = dataOut.getFreqRange(1)/1000.
367 587 xlabel = "Frequency (kHz)"
368 588
369 589 elif xaxis == "time":
370 590 x = dataOut.getAcfRange(1)
371 591 xlabel = "Time (ms)"
372 592
373 593 else:
374 594 x = dataOut.getVelRange(1)
375 595 xlabel = "Velocity (m/s)"
376 596
377 597 if not self.isConfig:
378 598
379 599 nplots = len(pairsIndexList)
380 600
381 601 self.setup(id=id,
382 602 nplots=nplots,
383 603 wintitle=wintitle,
384 604 showprofile=False,
385 605 show=show)
386 606
387 607 avg = numpy.abs(numpy.average(z, axis=1))
388 608 avgdB = 10*numpy.log10(avg)
389 609
390 610 if xmin == None: xmin = numpy.nanmin(x)
391 611 if xmax == None: xmax = numpy.nanmax(x)
392 612 if ymin == None: ymin = numpy.nanmin(y)
393 613 if ymax == None: ymax = numpy.nanmax(y)
394 614 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
395 615 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
396 616
397 617 self.FTP_WEI = ftp_wei
398 618 self.EXP_CODE = exp_code
399 619 self.SUB_EXP_CODE = sub_exp_code
400 620 self.PLOT_POS = plot_pos
401 621
402 622 self.isConfig = True
403 623
404 624 self.setWinTitle(title)
405
625
406 626
407 627 for i in range(self.nplots):
408 628 pair = dataOut.pairsList[pairsIndexList[i]]
409 629
410 630 chan_index0 = dataOut.channelList.index(pair[0])
411 631 chan_index1 = dataOut.channelList.index(pair[1])
412 632
413 633 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
414 634 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
415 635 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
416 636 axes0 = self.axesList[i*self.__nsubplots]
417 637 axes0.pcolor(x, y, zdB,
418 638 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
419 639 xlabel=xlabel, ylabel=ylabel, title=title,
420 640 ticksize=9, colormap=power_cmap, cblabel='')
421 641
422 642 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
423 643 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
424 644 axes0 = self.axesList[i*self.__nsubplots+1]
425 645 axes0.pcolor(x, y, zdB,
426 646 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
427 647 xlabel=xlabel, ylabel=ylabel, title=title,
428 648 ticksize=9, colormap=power_cmap, cblabel='')
429 649
430 650 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:] / numpy.sqrt( dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:] )
431 651 coherence = numpy.abs(coherenceComplex)
432 652 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
433 653 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
434 654
435 655 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
436 656 axes0 = self.axesList[i*self.__nsubplots+2]
437 657 axes0.pcolor(x, y, coherence,
438 658 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
439 659 xlabel=xlabel, ylabel=ylabel, title=title,
440 660 ticksize=9, colormap=coherence_cmap, cblabel='')
441 661
442 662 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
443 663 axes0 = self.axesList[i*self.__nsubplots+3]
444 664 axes0.pcolor(x, y, phase,
445 665 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
446 666 xlabel=xlabel, ylabel=ylabel, title=title,
447 667 ticksize=9, colormap=phase_cmap, cblabel='')
448 668
449 669 self.draw()
450 670
451 671 self.save(figpath=figpath,
452 672 figfile=figfile,
453 673 save=save,
454 674 ftp=ftp,
455 675 wr_period=wr_period,
456 676 thisDatetime=thisDatetime)
457 677
458 678 return dataOut
459 679
460 680 @MPDecorator
461 681 class RTIPlot_(Figure):
462 682
463 683 __isConfig = None
464 684 __nsubplots = None
465 685
466 686 WIDTHPROF = None
467 687 HEIGHTPROF = None
468 688 PREFIX = 'rti'
469 689
470 690 def __init__(self):
471 691
472 692 Figure.__init__(self)
473 693 self.timerange = None
474 694 self.isConfig = False
475 695 self.__nsubplots = 1
476 696
477 697 self.WIDTH = 800
478 698 self.HEIGHT = 250
479 699 self.WIDTHPROF = 120
480 700 self.HEIGHTPROF = 0
481 701 self.counter_imagwr = 0
482 702
483 703 self.PLOT_CODE = RTI_CODE
484 704
485 705 self.FTP_WEI = None
486 706 self.EXP_CODE = None
487 707 self.SUB_EXP_CODE = None
488 708 self.PLOT_POS = None
489 709 self.tmin = None
490 710 self.tmax = None
491 711
492 712 self.xmin = None
493 713 self.xmax = None
494 714
495 715 self.figfile = None
496 716
497 717 def getSubplots(self):
498 718
499 719 ncol = 1
500 720 nrow = self.nplots
501 721
502 722 return nrow, ncol
503 723
504 724 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
505 725
506 726 self.__showprofile = showprofile
507 727 self.nplots = nplots
508 728
509 729 ncolspan = 1
510 730 colspan = 1
511 731 if showprofile:
512 732 ncolspan = 7
513 733 colspan = 6
514 734 self.__nsubplots = 2
515 735
516 736 self.createFigure(id = id,
517 737 wintitle = wintitle,
518 738 widthplot = self.WIDTH + self.WIDTHPROF,
519 739 heightplot = self.HEIGHT + self.HEIGHTPROF,
520 740 show=show)
521 741
522 742 nrow, ncol = self.getSubplots()
523 743
524 744 counter = 0
525 745 for y in range(nrow):
526 746 for x in range(ncol):
527 747
528 748 if counter >= self.nplots:
529 749 break
530 750
531 751 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
532 752
533 753 if showprofile:
534 754 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
535 755
536 756 counter += 1
537 757
538 758 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
539 759 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
540 760 timerange=None, colormap='jet',
541 761 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
542 762 server=None, folder=None, username=None, password=None,
543 763 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
544 764
545 765 """
546 766
547 767 Input:
548 768 dataOut :
549 769 id :
550 770 wintitle :
551 771 channelList :
552 772 showProfile :
553 773 xmin : None,
554 774 xmax : None,
555 775 ymin : None,
556 776 ymax : None,
557 777 zmin : None,
558 778 zmax : None
559 779 """
560 780 if dataOut.flagNoData:
561 781 return dataOut
562 782
563 783 #colormap = kwargs.get('colormap', 'jet')
564 784 if HEIGHT is not None:
565 785 self.HEIGHT = HEIGHT
566
786
567 787 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
568 788 return
569 789
570 790 if channelList == None:
571 791 channelIndexList = dataOut.channelIndexList
572 792 else:
573 793 channelIndexList = []
574 794 for channel in channelList:
575 795 if channel not in dataOut.channelList:
576 796 raise ValueError("Channel %d is not in dataOut.channelList")
577 797 channelIndexList.append(dataOut.channelList.index(channel))
578 798
579 799 if normFactor is None:
580 800 factor = dataOut.normFactor
581 801 else:
582 802 factor = normFactor
583 803
584 804 #factor = dataOut.normFactor
585 805 x = dataOut.getTimeRange()
586 806 y = dataOut.getHeiRange()
587 807
588 808 z = dataOut.data_spc/factor
589 809 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
590 810 avg = numpy.average(z, axis=1)
591 811 avgdB = 10.*numpy.log10(avg)
592 812 # avgdB = dataOut.getPower()
593 813
594 814
595 815 thisDatetime = dataOut.datatime
596 816 #thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
597 817 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
598 818 xlabel = ""
599 819 ylabel = "Range (Km)"
600 820
601 821 update_figfile = False
602 822
603 823 if self.xmax is not None and dataOut.ltctime >= self.xmax: #yong
604 824 self.counter_imagwr = wr_period
605 825 self.isConfig = False
606 826 update_figfile = True
607 827
608 828 if not self.isConfig:
609 829
610 830 nplots = len(channelIndexList)
611 831
612 832 self.setup(id=id,
613 833 nplots=nplots,
614 834 wintitle=wintitle,
615 835 showprofile=showprofile,
616 836 show=show)
617 837
618 838 if timerange != None:
619 839 self.timerange = timerange
620 840
621 841 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
622 842
623 843 noise = dataOut.noise/factor
624 844 noisedB = 10*numpy.log10(noise)
625 845
626 846 if ymin == None: ymin = numpy.nanmin(y)
627 847 if ymax == None: ymax = numpy.nanmax(y)
628 848 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
629 849 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
630 850
631 851 self.FTP_WEI = ftp_wei
632 852 self.EXP_CODE = exp_code
633 853 self.SUB_EXP_CODE = sub_exp_code
634 854 self.PLOT_POS = plot_pos
635 855
636 856 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
637 857 self.isConfig = True
638 858 self.figfile = figfile
639 859 update_figfile = True
640 860
641 861 self.setWinTitle(title)
642 862
643 863 for i in range(self.nplots):
644 864 index = channelIndexList[i]
645 865 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
646 866 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
647 867 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
648 868 axes = self.axesList[i*self.__nsubplots]
649 869 zdB = avgdB[index].reshape((1,-1))
650 870 axes.pcolorbuffer(x, y, zdB,
651 871 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
652 872 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
653 873 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
654 874
655 875 if self.__showprofile:
656 876 axes = self.axesList[i*self.__nsubplots +1]
657 877 axes.pline(avgdB[index], y,
658 878 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
659 879 xlabel='dB', ylabel='', title='',
660 880 ytick_visible=False,
661 881 grid='x')
662 882
663 883 self.draw()
664 884
665 885 self.save(figpath=figpath,
666 886 figfile=figfile,
667 887 save=save,
668 888 ftp=ftp,
669 889 wr_period=wr_period,
670 890 thisDatetime=thisDatetime,
671 891 update_figfile=update_figfile)
672 892 return dataOut
673 893
674 894 @MPDecorator
675 895 class CoherenceMap_(Figure):
676 896 isConfig = None
677 897 __nsubplots = None
678 898
679 899 WIDTHPROF = None
680 900 HEIGHTPROF = None
681 901 PREFIX = 'cmap'
682 902
683 903 def __init__(self):
684 904 Figure.__init__(self)
685 905 self.timerange = 2*60*60
686 906 self.isConfig = False
687 907 self.__nsubplots = 1
688 908
689 909 self.WIDTH = 800
690 910 self.HEIGHT = 180
691 911 self.WIDTHPROF = 120
692 912 self.HEIGHTPROF = 0
693 913 self.counter_imagwr = 0
694 914
695 915 self.PLOT_CODE = COH_CODE
696 916
697 917 self.FTP_WEI = None
698 918 self.EXP_CODE = None
699 919 self.SUB_EXP_CODE = None
700 920 self.PLOT_POS = None
701 921 self.counter_imagwr = 0
702 922
703 923 self.xmin = None
704 924 self.xmax = None
705 925
706 926 def getSubplots(self):
707 927 ncol = 1
708 928 nrow = self.nplots*2
709 929
710 930 return nrow, ncol
711 931
712 932 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
713 933 self.__showprofile = showprofile
714 934 self.nplots = nplots
715 935
716 936 ncolspan = 1
717 937 colspan = 1
718 938 if showprofile:
719 939 ncolspan = 7
720 940 colspan = 6
721 941 self.__nsubplots = 2
722 942
723 943 self.createFigure(id = id,
724 944 wintitle = wintitle,
725 945 widthplot = self.WIDTH + self.WIDTHPROF,
726 946 heightplot = self.HEIGHT + self.HEIGHTPROF,
727 947 show=True)
728 948
729 949 nrow, ncol = self.getSubplots()
730 950
731 951 for y in range(nrow):
732 952 for x in range(ncol):
733 953
734 954 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
735 955
736 956 if showprofile:
737 957 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
738 958
739 959 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
740 960 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
741 961 timerange=None, phase_min=None, phase_max=None,
742 962 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
743 963 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
744 964 server=None, folder=None, username=None, password=None,
745 965 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
746 966
747 967
748 if dataOut.flagNoData:
968 if dataOut.flagNoData:
749 969 return dataOut
750 970
751 971 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
752 972 return
753 973
754 974 if pairsList == None:
755 975 pairsIndexList = dataOut.pairsIndexList
756 976 else:
757 977 pairsIndexList = []
758 978 for pair in pairsList:
759 979 if pair not in dataOut.pairsList:
760 980 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
761 981 pairsIndexList.append(dataOut.pairsList.index(pair))
762 982
763 983 if pairsIndexList == []:
764 984 return
765 985
766 986 if len(pairsIndexList) > 4:
767 987 pairsIndexList = pairsIndexList[0:4]
768 988
769 989 if phase_min == None:
770 990 phase_min = -180
771 991 if phase_max == None:
772 992 phase_max = 180
773 993
774 994 x = dataOut.getTimeRange()
775 995 y = dataOut.getHeiRange()
776 996
777 997 thisDatetime = dataOut.datatime
778 998
779 999 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
780 1000 xlabel = ""
781 1001 ylabel = "Range (Km)"
782 1002 update_figfile = False
783 1003
784 1004 if not self.isConfig:
785 1005 nplots = len(pairsIndexList)
786 1006 self.setup(id=id,
787 1007 nplots=nplots,
788 1008 wintitle=wintitle,
789 1009 showprofile=showprofile,
790 1010 show=show)
791 1011
792 1012 if timerange != None:
793 1013 self.timerange = timerange
794 1014
795 1015 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
796 1016
797 1017 if ymin == None: ymin = numpy.nanmin(y)
798 1018 if ymax == None: ymax = numpy.nanmax(y)
799 1019 if zmin == None: zmin = 0.
800 1020 if zmax == None: zmax = 1.
801 1021
802 1022 self.FTP_WEI = ftp_wei
803 1023 self.EXP_CODE = exp_code
804 1024 self.SUB_EXP_CODE = sub_exp_code
805 1025 self.PLOT_POS = plot_pos
806 1026
807 1027 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
808 1028
809 1029 self.isConfig = True
810 1030 update_figfile = True
811 1031
812 1032 self.setWinTitle(title)
813 1033
814 1034 for i in range(self.nplots):
815 1035
816 1036 pair = dataOut.pairsList[pairsIndexList[i]]
817 1037
818 1038 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
819 1039 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
820 1040 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
821 1041
822 1042
823 1043 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
824 1044 coherence = numpy.abs(avgcoherenceComplex)
825 1045
826 1046 z = coherence.reshape((1,-1))
827 1047
828 1048 counter = 0
829 1049
830 1050 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
831 1051 axes = self.axesList[i*self.__nsubplots*2]
832 1052 axes.pcolorbuffer(x, y, z,
833 1053 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
834 1054 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
835 1055 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
836 1056
837 1057 if self.__showprofile:
838 1058 counter += 1
839 1059 axes = self.axesList[i*self.__nsubplots*2 + counter]
840 1060 axes.pline(coherence, y,
841 1061 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
842 1062 xlabel='', ylabel='', title='', ticksize=7,
843 1063 ytick_visible=False, nxticks=5,
844 1064 grid='x')
845 1065
846 1066 counter += 1
847 1067
848 1068 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
849 1069
850 1070 z = phase.reshape((1,-1))
851 1071
852 1072 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
853 1073 axes = self.axesList[i*self.__nsubplots*2 + counter]
854 1074 axes.pcolorbuffer(x, y, z,
855 1075 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
856 1076 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
857 1077 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
858 1078
859 1079 if self.__showprofile:
860 1080 counter += 1
861 1081 axes = self.axesList[i*self.__nsubplots*2 + counter]
862 1082 axes.pline(phase, y,
863 1083 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
864 1084 xlabel='', ylabel='', title='', ticksize=7,
865 1085 ytick_visible=False, nxticks=4,
866 1086 grid='x')
867 1087
868 1088 self.draw()
869 1089
870 1090 if dataOut.ltctime >= self.xmax:
871 1091 self.counter_imagwr = wr_period
872 1092 self.isConfig = False
873 1093 update_figfile = True
874 1094
875 1095 self.save(figpath=figpath,
876 1096 figfile=figfile,
877 1097 save=save,
878 1098 ftp=ftp,
879 1099 wr_period=wr_period,
880 1100 thisDatetime=thisDatetime,
881 1101 update_figfile=update_figfile)
882 1102
883 1103 return dataOut
884 1104
885 1105 @MPDecorator
886 1106 class PowerProfilePlot_(Figure):
887 1107
888 1108 isConfig = None
889 1109 __nsubplots = None
890 1110
891 1111 WIDTHPROF = None
892 1112 HEIGHTPROF = None
893 1113 PREFIX = 'spcprofile'
894 1114
895 1115 def __init__(self):
896 1116 Figure.__init__(self)
897 1117 self.isConfig = False
898 1118 self.__nsubplots = 1
899 1119
900 1120 self.PLOT_CODE = POWER_CODE
901 1121
902 1122 self.WIDTH = 300
903 1123 self.HEIGHT = 500
904 1124 self.counter_imagwr = 0
905 1125
906 1126 def getSubplots(self):
907 1127 ncol = 1
908 1128 nrow = 1
909 1129
910 1130 return nrow, ncol
911 1131
912 1132 def setup(self, id, nplots, wintitle, show):
913 1133
914 1134 self.nplots = nplots
915 1135
916 1136 ncolspan = 1
917 1137 colspan = 1
918 1138
919 1139 self.createFigure(id = id,
920 1140 wintitle = wintitle,
921 1141 widthplot = self.WIDTH,
922 1142 heightplot = self.HEIGHT,
923 1143 show=show)
924 1144
925 1145 nrow, ncol = self.getSubplots()
926 1146
927 1147 counter = 0
928 1148 for y in range(nrow):
929 1149 for x in range(ncol):
930 1150 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
931 1151
932 1152 def run(self, dataOut, id, wintitle="", channelList=None,
933 1153 xmin=None, xmax=None, ymin=None, ymax=None,
934 1154 save=False, figpath='./', figfile=None, show=True,
935 1155 ftp=False, wr_period=1, server=None,
936 1156 folder=None, username=None, password=None):
937 1157
938 if dataOut.flagNoData:
1158 if dataOut.flagNoData:
939 1159 return dataOut
940 1160
941 1161
942 1162 if channelList == None:
943 1163 channelIndexList = dataOut.channelIndexList
944 1164 channelList = dataOut.channelList
945 1165 else:
946 1166 channelIndexList = []
947 1167 for channel in channelList:
948 1168 if channel not in dataOut.channelList:
949 1169 raise ValueError("Channel %d is not in dataOut.channelList")
950 1170 channelIndexList.append(dataOut.channelList.index(channel))
951 1171
952 1172 factor = dataOut.normFactor
953 1173
954 1174 y = dataOut.getHeiRange()
955 1175
956 1176 #for voltage
957 1177 if dataOut.type == 'Voltage':
958 1178 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
959 1179 x = x.real
960 1180 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
961 1181
962 1182 #for spectra
963 1183 if dataOut.type == 'Spectra':
964 1184 x = dataOut.data_spc[channelIndexList,:,:]/factor
965 1185 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
966 1186 x = numpy.average(x, axis=1)
967 1187
968 1188
969 1189 xdB = 10*numpy.log10(x)
970 1190
971 1191 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
972 1192 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
973 1193 xlabel = "dB"
974 1194 ylabel = "Range (Km)"
975 1195
976 1196 if not self.isConfig:
977 1197
978 1198 nplots = 1
979 1199
980 1200 self.setup(id=id,
981 1201 nplots=nplots,
982 1202 wintitle=wintitle,
983 1203 show=show)
984 1204
985 1205 if ymin == None: ymin = numpy.nanmin(y)
986 1206 if ymax == None: ymax = numpy.nanmax(y)
987 1207 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
988 1208 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
989 1209
990 1210 self.isConfig = True
991 1211
992 1212 self.setWinTitle(title)
993 1213
994 1214 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
995 1215 axes = self.axesList[0]
996 1216
997 1217 legendlabels = ["channel %d"%x for x in channelList]
998 1218 axes.pmultiline(xdB, y,
999 1219 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1000 1220 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1001 1221 ytick_visible=True, nxticks=5,
1002 1222 grid='x')
1003 1223
1004 1224 self.draw()
1005 1225
1006 1226 self.save(figpath=figpath,
1007 1227 figfile=figfile,
1008 1228 save=save,
1009 1229 ftp=ftp,
1010 1230 wr_period=wr_period,
1011 1231 thisDatetime=thisDatetime)
1012
1232
1013 1233 return dataOut
1014 1234
1015 1235 @MPDecorator
1016 1236 class SpectraCutPlot_(Figure):
1017 1237
1018 1238 isConfig = None
1019 1239 __nsubplots = None
1020 1240
1021 1241 WIDTHPROF = None
1022 1242 HEIGHTPROF = None
1023 1243 PREFIX = 'spc_cut'
1024 1244
1025 1245 def __init__(self):
1026 1246 Figure.__init__(self)
1027 1247 self.isConfig = False
1028 1248 self.__nsubplots = 1
1029 1249
1030 1250 self.PLOT_CODE = POWER_CODE
1031 1251
1032 1252 self.WIDTH = 700
1033 1253 self.HEIGHT = 500
1034 1254 self.counter_imagwr = 0
1035 1255
1036 1256 def getSubplots(self):
1037 1257 ncol = 1
1038 1258 nrow = 1
1039 1259
1040 1260 return nrow, ncol
1041 1261
1042 1262 def setup(self, id, nplots, wintitle, show):
1043 1263
1044 1264 self.nplots = nplots
1045 1265
1046 1266 ncolspan = 1
1047 1267 colspan = 1
1048 1268
1049 1269 self.createFigure(id = id,
1050 1270 wintitle = wintitle,
1051 1271 widthplot = self.WIDTH,
1052 1272 heightplot = self.HEIGHT,
1053 1273 show=show)
1054 1274
1055 1275 nrow, ncol = self.getSubplots()
1056 1276
1057 1277 counter = 0
1058 1278 for y in range(nrow):
1059 1279 for x in range(ncol):
1060 1280 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1061 1281
1062 1282 def run(self, dataOut, id, wintitle="", channelList=None,
1063 1283 xmin=None, xmax=None, ymin=None, ymax=None,
1064 1284 save=False, figpath='./', figfile=None, show=True,
1065 1285 ftp=False, wr_period=1, server=None,
1066 1286 folder=None, username=None, password=None,
1067 1287 xaxis="frequency"):
1068 1288
1069 if dataOut.flagNoData:
1289 if dataOut.flagNoData:
1070 1290 return dataOut
1071 1291
1072 1292 if channelList == None:
1073 1293 channelIndexList = dataOut.channelIndexList
1074 1294 channelList = dataOut.channelList
1075 1295 else:
1076 1296 channelIndexList = []
1077 1297 for channel in channelList:
1078 1298 if channel not in dataOut.channelList:
1079 1299 raise ValueError("Channel %d is not in dataOut.channelList")
1080 1300 channelIndexList.append(dataOut.channelList.index(channel))
1081 1301
1082 1302 factor = dataOut.normFactor
1083 1303
1084 1304 y = dataOut.getHeiRange()
1085 1305
1086 1306 z = dataOut.data_spc/factor
1087 1307 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1088 1308
1089 1309 hei_index = numpy.arange(25)*3 + 20
1090 1310
1091 1311 if xaxis == "frequency":
1092 1312 x = dataOut.getFreqRange()/1000.
1093 1313 zdB = 10*numpy.log10(z[0,:,hei_index])
1094 1314 xlabel = "Frequency (kHz)"
1095 1315 ylabel = "Power (dB)"
1096 1316
1097 1317 elif xaxis == "time":
1098 1318 x = dataOut.getAcfRange()
1099 1319 zdB = z[0,:,hei_index]
1100 1320 xlabel = "Time (ms)"
1101 1321 ylabel = "ACF"
1102 1322
1103 1323 else:
1104 1324 x = dataOut.getVelRange()
1105 1325 zdB = 10*numpy.log10(z[0,:,hei_index])
1106 1326 xlabel = "Velocity (m/s)"
1107 1327 ylabel = "Power (dB)"
1108 1328
1109 1329 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1110 1330 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1111 1331
1112 1332 if not self.isConfig:
1113 1333
1114 1334 nplots = 1
1115 1335
1116 1336 self.setup(id=id,
1117 1337 nplots=nplots,
1118 1338 wintitle=wintitle,
1119 1339 show=show)
1120 1340
1121 1341 if xmin == None: xmin = numpy.nanmin(x)*0.9
1122 1342 if xmax == None: xmax = numpy.nanmax(x)*1.1
1123 1343 if ymin == None: ymin = numpy.nanmin(zdB)
1124 1344 if ymax == None: ymax = numpy.nanmax(zdB)
1125 1345
1126 1346 self.isConfig = True
1127 1347
1128 1348 self.setWinTitle(title)
1129 1349
1130 1350 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1131 1351 axes = self.axesList[0]
1132 1352
1133 1353 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1134 1354
1135 1355 axes.pmultilineyaxis( x, zdB,
1136 1356 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1137 1357 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1138 1358 ytick_visible=True, nxticks=5,
1139 1359 grid='x')
1140 1360
1141 1361 self.draw()
1142 1362
1143 1363 self.save(figpath=figpath,
1144 1364 figfile=figfile,
1145 1365 save=save,
1146 1366 ftp=ftp,
1147 1367 wr_period=wr_period,
1148 1368 thisDatetime=thisDatetime)
1149 1369
1150 1370 return dataOut
1151 1371
1152 1372 @MPDecorator
1153 1373 class Noise_(Figure):
1154 1374
1155 1375 isConfig = None
1156 1376 __nsubplots = None
1157 1377
1158 1378 PREFIX = 'noise'
1159 1379
1160 1380
1161 1381 def __init__(self):
1162 1382 Figure.__init__(self)
1163 1383 self.timerange = 24*60*60
1164 1384 self.isConfig = False
1165 1385 self.__nsubplots = 1
1166 1386 self.counter_imagwr = 0
1167 1387 self.WIDTH = 800
1168 1388 self.HEIGHT = 400
1169 1389 self.WIDTHPROF = 120
1170 1390 self.HEIGHTPROF = 0
1171 1391 self.xdata = None
1172 1392 self.ydata = None
1173 1393
1174 1394 self.PLOT_CODE = NOISE_CODE
1175 1395
1176 1396 self.FTP_WEI = None
1177 1397 self.EXP_CODE = None
1178 1398 self.SUB_EXP_CODE = None
1179 1399 self.PLOT_POS = None
1180 1400 self.figfile = None
1181 1401
1182 1402 self.xmin = None
1183 1403 self.xmax = None
1184 1404
1185 1405 def getSubplots(self):
1186 1406
1187 1407 ncol = 1
1188 1408 nrow = 1
1189 1409
1190 1410 return nrow, ncol
1191 1411
1192 1412 def openfile(self, filename):
1193 1413 dirname = os.path.dirname(filename)
1194 1414
1195 1415 if not os.path.exists(dirname):
1196 1416 os.mkdir(dirname)
1197 1417
1198 1418 f = open(filename,'w+')
1199 1419 f.write('\n\n')
1200 1420 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1201 1421 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1202 1422 f.close()
1203 1423
1204 1424 def save_data(self, filename_phase, data, data_datetime):
1205 1425
1206 1426 f=open(filename_phase,'a')
1207 1427
1208 1428 timetuple_data = data_datetime.timetuple()
1209 1429 day = str(timetuple_data.tm_mday)
1210 1430 month = str(timetuple_data.tm_mon)
1211 1431 year = str(timetuple_data.tm_year)
1212 1432 hour = str(timetuple_data.tm_hour)
1213 1433 minute = str(timetuple_data.tm_min)
1214 1434 second = str(timetuple_data.tm_sec)
1215 1435
1216 1436 data_msg = ''
1217 1437 for i in range(len(data)):
1218 1438 data_msg += str(data[i]) + ' '
1219 1439
1220 1440 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1221 1441 f.close()
1222 1442
1223 1443
1224 1444 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1225 1445
1226 1446 self.__showprofile = showprofile
1227 1447 self.nplots = nplots
1228 1448
1229 1449 ncolspan = 7
1230 1450 colspan = 6
1231 1451 self.__nsubplots = 2
1232 1452
1233 1453 self.createFigure(id = id,
1234 1454 wintitle = wintitle,
1235 1455 widthplot = self.WIDTH+self.WIDTHPROF,
1236 1456 heightplot = self.HEIGHT+self.HEIGHTPROF,
1237 1457 show=show)
1238 1458
1239 1459 nrow, ncol = self.getSubplots()
1240 1460
1241 1461 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1242 1462
1243 1463
1244 1464 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1245 1465 xmin=None, xmax=None, ymin=None, ymax=None,
1246 1466 timerange=None,
1247 1467 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1248 1468 server=None, folder=None, username=None, password=None,
1249 1469 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1250 1470
1251 if dataOut.flagNoData:
1471 if dataOut.flagNoData:
1252 1472 return dataOut
1253 1473
1254 1474 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1255 1475 return
1256 1476
1257 1477 if channelList == None:
1258 1478 channelIndexList = dataOut.channelIndexList
1259 1479 channelList = dataOut.channelList
1260 1480 else:
1261 1481 channelIndexList = []
1262 1482 for channel in channelList:
1263 1483 if channel not in dataOut.channelList:
1264 1484 raise ValueError("Channel %d is not in dataOut.channelList")
1265 1485 channelIndexList.append(dataOut.channelList.index(channel))
1266 1486
1267 1487 x = dataOut.getTimeRange()
1268 1488 #y = dataOut.getHeiRange()
1269 1489 factor = dataOut.normFactor
1270 1490 noise = dataOut.noise[channelIndexList]/factor
1271 1491 noisedB = 10*numpy.log10(noise)
1272 1492
1273 1493 thisDatetime = dataOut.datatime
1274 1494
1275 1495 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1276 1496 xlabel = ""
1277 1497 ylabel = "Intensity (dB)"
1278 1498 update_figfile = False
1279 1499
1280 1500 if not self.isConfig:
1281 1501
1282 1502 nplots = 1
1283 1503
1284 1504 self.setup(id=id,
1285 1505 nplots=nplots,
1286 1506 wintitle=wintitle,
1287 1507 showprofile=showprofile,
1288 1508 show=show)
1289 1509
1290 1510 if timerange != None:
1291 1511 self.timerange = timerange
1292 1512
1293 1513 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1294 1514
1295 1515 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1296 1516 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1297 1517
1298 1518 self.FTP_WEI = ftp_wei
1299 1519 self.EXP_CODE = exp_code
1300 1520 self.SUB_EXP_CODE = sub_exp_code
1301 1521 self.PLOT_POS = plot_pos
1302 1522
1303 1523
1304 1524 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1305 1525 self.isConfig = True
1306 1526 self.figfile = figfile
1307 1527 self.xdata = numpy.array([])
1308 1528 self.ydata = numpy.array([])
1309 1529
1310 1530 update_figfile = True
1311 1531
1312 1532 #open file beacon phase
1313 1533 path = '%s%03d' %(self.PREFIX, self.id)
1314 1534 noise_file = os.path.join(path,'%s.txt'%self.name)
1315 1535 self.filename_noise = os.path.join(figpath,noise_file)
1316 1536
1317 1537 self.setWinTitle(title)
1318 1538
1319 1539 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1320 1540
1321 1541 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1322 1542 axes = self.axesList[0]
1323 1543
1324 1544 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1325 1545
1326 1546 if len(self.ydata)==0:
1327 1547 self.ydata = noisedB.reshape(-1,1)
1328 1548 else:
1329 1549 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1330 1550
1331 1551
1332 1552 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1333 1553 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1334 1554 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1335 1555 XAxisAsTime=True, grid='both'
1336 1556 )
1337 1557
1338 1558 self.draw()
1339 1559
1340 1560 if dataOut.ltctime >= self.xmax:
1341 1561 self.counter_imagwr = wr_period
1342 1562 self.isConfig = False
1343 1563 update_figfile = True
1344 1564
1345 1565 self.save(figpath=figpath,
1346 1566 figfile=figfile,
1347 1567 save=save,
1348 1568 ftp=ftp,
1349 1569 wr_period=wr_period,
1350 1570 thisDatetime=thisDatetime,
1351 1571 update_figfile=update_figfile)
1352 1572
1353 1573 #store data beacon phase
1354 1574 if save:
1355 1575 self.save_data(self.filename_noise, noisedB, thisDatetime)
1356 1576
1357 1577 return dataOut
1358 1578
1359 1579 @MPDecorator
1360 1580 class BeaconPhase_(Figure):
1361 1581
1362 1582 __isConfig = None
1363 1583 __nsubplots = None
1364 1584
1365 1585 PREFIX = 'beacon_phase'
1366 1586
1367 1587 def __init__(self):
1368 1588 Figure.__init__(self)
1369 1589 self.timerange = 24*60*60
1370 1590 self.isConfig = False
1371 1591 self.__nsubplots = 1
1372 1592 self.counter_imagwr = 0
1373 1593 self.WIDTH = 800
1374 1594 self.HEIGHT = 400
1375 1595 self.WIDTHPROF = 120
1376 1596 self.HEIGHTPROF = 0
1377 1597 self.xdata = None
1378 1598 self.ydata = None
1379 1599
1380 1600 self.PLOT_CODE = BEACON_CODE
1381 1601
1382 1602 self.FTP_WEI = None
1383 1603 self.EXP_CODE = None
1384 1604 self.SUB_EXP_CODE = None
1385 1605 self.PLOT_POS = None
1386 1606
1387 1607 self.filename_phase = None
1388 1608
1389 1609 self.figfile = None
1390 1610
1391 1611 self.xmin = None
1392 1612 self.xmax = None
1393 1613
1394 1614 def getSubplots(self):
1395 1615
1396 1616 ncol = 1
1397 1617 nrow = 1
1398 1618
1399 1619 return nrow, ncol
1400 1620
1401 1621 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1402 1622
1403 1623 self.__showprofile = showprofile
1404 1624 self.nplots = nplots
1405 1625
1406 1626 ncolspan = 7
1407 1627 colspan = 6
1408 1628 self.__nsubplots = 2
1409 1629
1410 1630 self.createFigure(id = id,
1411 1631 wintitle = wintitle,
1412 1632 widthplot = self.WIDTH+self.WIDTHPROF,
1413 1633 heightplot = self.HEIGHT+self.HEIGHTPROF,
1414 1634 show=show)
1415 1635
1416 1636 nrow, ncol = self.getSubplots()
1417 1637
1418 1638 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1419 1639
1420 1640 def save_phase(self, filename_phase):
1421 1641 f = open(filename_phase,'w+')
1422 1642 f.write('\n\n')
1423 1643 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1424 1644 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1425 1645 f.close()
1426 1646
1427 1647 def save_data(self, filename_phase, data, data_datetime):
1428 1648 f=open(filename_phase,'a')
1429 1649 timetuple_data = data_datetime.timetuple()
1430 1650 day = str(timetuple_data.tm_mday)
1431 1651 month = str(timetuple_data.tm_mon)
1432 1652 year = str(timetuple_data.tm_year)
1433 1653 hour = str(timetuple_data.tm_hour)
1434 1654 minute = str(timetuple_data.tm_min)
1435 1655 second = str(timetuple_data.tm_sec)
1436 1656 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1437 1657 f.close()
1438 1658
1439 1659
1440 1660 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1441 1661 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1442 1662 timerange=None,
1443 1663 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1444 1664 server=None, folder=None, username=None, password=None,
1445 1665 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1446 1666
1447 if dataOut.flagNoData:
1667 if dataOut.flagNoData:
1448 1668 return dataOut
1449 1669
1450 1670 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1451 1671 return
1452 1672
1453 1673 if pairsList == None:
1454 1674 pairsIndexList = dataOut.pairsIndexList[:10]
1455 1675 else:
1456 1676 pairsIndexList = []
1457 1677 for pair in pairsList:
1458 1678 if pair not in dataOut.pairsList:
1459 1679 raise ValueError("Pair %s is not in dataOut.pairsList" %(pair))
1460 1680 pairsIndexList.append(dataOut.pairsList.index(pair))
1461 1681
1462 1682 if pairsIndexList == []:
1463 1683 return
1464 1684
1465 1685 # if len(pairsIndexList) > 4:
1466 1686 # pairsIndexList = pairsIndexList[0:4]
1467 1687
1468 1688 hmin_index = None
1469 1689 hmax_index = None
1470 1690
1471 1691 if hmin != None and hmax != None:
1472 1692 indexes = numpy.arange(dataOut.nHeights)
1473 1693 hmin_list = indexes[dataOut.heightList >= hmin]
1474 1694 hmax_list = indexes[dataOut.heightList <= hmax]
1475 1695
1476 1696 if hmin_list.any():
1477 1697 hmin_index = hmin_list[0]
1478 1698
1479 1699 if hmax_list.any():
1480 1700 hmax_index = hmax_list[-1]+1
1481 1701
1482 1702 x = dataOut.getTimeRange()
1483 1703 #y = dataOut.getHeiRange()
1484 1704
1485 1705
1486 1706 thisDatetime = dataOut.datatime
1487 1707
1488 1708 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1489 1709 xlabel = "Local Time"
1490 1710 ylabel = "Phase (degrees)"
1491 1711
1492 1712 update_figfile = False
1493 1713
1494 1714 nplots = len(pairsIndexList)
1495 1715 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1496 1716 phase_beacon = numpy.zeros(len(pairsIndexList))
1497 1717 for i in range(nplots):
1498 1718 pair = dataOut.pairsList[pairsIndexList[i]]
1499 1719 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1500 1720 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1501 1721 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1502 1722 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1503 1723 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1504 1724
1505 1725 if dataOut.beacon_heiIndexList:
1506 1726 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1507 1727 else:
1508 1728 phase_beacon[i] = numpy.average(phase)
1509 1729
1510 1730 if not self.isConfig:
1511 1731
1512 1732 nplots = len(pairsIndexList)
1513 1733
1514 1734 self.setup(id=id,
1515 1735 nplots=nplots,
1516 1736 wintitle=wintitle,
1517 1737 showprofile=showprofile,
1518 1738 show=show)
1519 1739
1520 1740 if timerange != None:
1521 1741 self.timerange = timerange
1522 1742
1523 1743 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1524 1744
1525 1745 if ymin == None: ymin = 0
1526 1746 if ymax == None: ymax = 360
1527 1747
1528 1748 self.FTP_WEI = ftp_wei
1529 1749 self.EXP_CODE = exp_code
1530 1750 self.SUB_EXP_CODE = sub_exp_code
1531 1751 self.PLOT_POS = plot_pos
1532 1752
1533 1753 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1534 1754 self.isConfig = True
1535 1755 self.figfile = figfile
1536 1756 self.xdata = numpy.array([])
1537 1757 self.ydata = numpy.array([])
1538 1758
1539 1759 update_figfile = True
1540 1760
1541 1761 #open file beacon phase
1542 1762 path = '%s%03d' %(self.PREFIX, self.id)
1543 1763 beacon_file = os.path.join(path,'%s.txt'%self.name)
1544 1764 self.filename_phase = os.path.join(figpath,beacon_file)
1545 1765 #self.save_phase(self.filename_phase)
1546 1766
1547 1767
1548 1768 #store data beacon phase
1549 1769 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1550 1770
1551 1771 self.setWinTitle(title)
1552 1772
1553 1773
1554 1774 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1555 1775
1556 1776 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1557 1777
1558 1778 axes = self.axesList[0]
1559 1779
1560 1780 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1561 1781
1562 1782 if len(self.ydata)==0:
1563 1783 self.ydata = phase_beacon.reshape(-1,1)
1564 1784 else:
1565 1785 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1566 1786
1567 1787
1568 1788 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1569 1789 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1570 1790 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1571 1791 XAxisAsTime=True, grid='both'
1572 1792 )
1573 1793
1574 1794 self.draw()
1575 1795
1576 1796 if dataOut.ltctime >= self.xmax:
1577 1797 self.counter_imagwr = wr_period
1578 1798 self.isConfig = False
1579 1799 update_figfile = True
1580 1800
1581 1801 self.save(figpath=figpath,
1582 1802 figfile=figfile,
1583 1803 save=save,
1584 1804 ftp=ftp,
1585 1805 wr_period=wr_period,
1586 1806 thisDatetime=thisDatetime,
1587 1807 update_figfile=update_figfile)
1588 1808
1589 return dataOut No newline at end of file
1809 return dataOut
@@ -1,232 +1,294
1 1 '''
2 2 Created on Jul 9, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import datetime
8 8 import numpy
9 9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator #YONG
10 10 from schainpy.utils import log
11 11 from .figure import Figure
12 12
13 13
14 14 @MPDecorator
15 15 class Scope_(Figure):
16
16
17 17 isConfig = None
18
18
19 19 def __init__(self):#, **kwargs): #YONG
20 20 Figure.__init__(self)#, **kwargs)
21 21 self.isConfig = False
22 22 self.WIDTH = 300
23 23 self.HEIGHT = 200
24 24 self.counter_imagwr = 0
25
25
26 26 def getSubplots(self):
27
27
28 28 nrow = self.nplots
29 29 ncol = 3
30 30 return nrow, ncol
31
31
32 32 def setup(self, id, nplots, wintitle, show):
33
33
34 34 self.nplots = nplots
35
36 self.createFigure(id=id,
37 wintitle=wintitle,
35
36 self.createFigure(id=id,
37 wintitle=wintitle,
38 38 show=show)
39
39
40 40 nrow,ncol = self.getSubplots()
41 41 colspan = 3
42 42 rowspan = 1
43
43
44 44 for i in range(nplots):
45 45 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
46
46
47 47 def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
48 48 yreal = y[channelIndexList,:].real
49 49 yimag = y[channelIndexList,:].imag
50
50
51 51 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
52 52 xlabel = "Range (Km)"
53 53 ylabel = "Intensity - IQ"
54
54
55 55 if not self.isConfig:
56 56 nplots = len(channelIndexList)
57
57
58 58 self.setup(id=id,
59 59 nplots=nplots,
60 60 wintitle='',
61 61 show=show)
62
62
63 63 if xmin == None: xmin = numpy.nanmin(x)
64 64 if xmax == None: xmax = numpy.nanmax(x)
65 65 if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag))
66 66 if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag))
67
67
68 68 self.isConfig = True
69
69
70 70 self.setWinTitle(title)
71
71
72 72 for i in range(len(self.axesList)):
73 73 title = "Channel %d" %(i)
74 74 axes = self.axesList[i]
75 75
76 76 axes.pline(x, yreal[i,:],
77 77 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
78 78 xlabel=xlabel, ylabel=ylabel, title=title)
79 79
80 80 axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2)
81
81
82 82 def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
83 83 y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:])
84 84 yreal = y.real
85
85
86 86 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
87 87 xlabel = "Range (Km)"
88 88 ylabel = "Intensity"
89
89
90 90 if not self.isConfig:
91 91 nplots = len(channelIndexList)
92
92
93 93 self.setup(id=id,
94 94 nplots=nplots,
95 95 wintitle='',
96 96 show=show)
97
97
98 98 if xmin == None: xmin = numpy.nanmin(x)
99 99 if xmax == None: xmax = numpy.nanmax(x)
100 100 if ymin == None: ymin = numpy.nanmin(yreal)
101 101 if ymax == None: ymax = numpy.nanmax(yreal)
102
102
103 103 self.isConfig = True
104
104
105 105 self.setWinTitle(title)
106
106
107 107 for i in range(len(self.axesList)):
108 108 title = "Channel %d" %(i)
109 109 axes = self.axesList[i]
110 110 ychannel = yreal[i,:]
111 111 axes.pline(x, ychannel,
112 112 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
113 113 xlabel=xlabel, ylabel=ylabel, title=title)
114 114
115
115 def plot_weatherpower(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
116 y = y[channelIndexList,:]
117 yreal = y
118
119 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
120 xlabel = "Range (Km)"
121 ylabel = "Intensity"
122
123 if not self.isConfig:
124 nplots = len(channelIndexList)
125
126 self.setup(id=id,
127 nplots=nplots,
128 wintitle='',
129 show=show)
130
131 if xmin == None: xmin = numpy.nanmin(x)
132 if xmax == None: xmax = numpy.nanmax(x)
133 if ymin == None: ymin = numpy.nanmin(yreal)
134 if ymax == None: ymax = numpy.nanmax(yreal)
135
136 self.isConfig = True
137
138 self.setWinTitle(title)
139
140 for i in range(len(self.axesList)):
141 title = "Channel %d" %(i)
142 axes = self.axesList[i]
143 ychannel = yreal[i,:]
144 axes.pline(x, ychannel,
145 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
146 xlabel=xlabel, ylabel=ylabel, title=title)
147
148
149
116 150 def run(self, dataOut, id, wintitle="", channelList=None,
117 151 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
118 152 figpath='./', figfile=None, show=True, wr_period=1,
119 153 ftp=False, server=None, folder=None, username=None, password=None, type='power', **kwargs):
120
154
121 155 """
122
156
123 157 Input:
124 158 dataOut :
125 159 id :
126 160 wintitle :
127 161 channelList :
128 162 xmin : None,
129 163 xmax : None,
130 164 ymin : None,
131 165 ymax : None,
132 166 """
133 if dataOut.flagNoData:
167 if dataOut.flagNoData:
134 168 return dataOut
135
169
136 170 if channelList == None:
137 171 channelIndexList = dataOut.channelIndexList
138 172 else:
139 173 channelIndexList = []
140 174 for channel in channelList:
141 175 if channel not in dataOut.channelList:
142 176 raise ValueError("Channel %d is not in dataOut.channelList")
143 177 channelIndexList.append(dataOut.channelList.index(channel))
144
178
145 179 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
146
180 ### print("***************** PLOTEO **************************")
181 ### print(dataOut.nProfiles)
182 ### print(dataOut.heightList.shape)
147 183 if dataOut.flagDataAsBlock:
148
184
149 185 for i in range(dataOut.nProfiles):
150
186
151 187 wintitle1 = wintitle + " [Profile = %d] " %i
152
188
153 189 if type == "power":
154 self.plot_power(dataOut.heightList,
190 self.plot_power(dataOut.heightList,
155 191 dataOut.data[:,i,:],
156 id,
157 channelIndexList,
192 id,
193 channelIndexList,
158 194 thisDatetime,
159 195 wintitle1,
160 196 show,
161 197 xmin,
162 198 xmax,
163 199 ymin,
164 200 ymax)
165
201
202 if type == "weatherpower":
203 self.plot_weatherpower(dataOut.heightList,
204 dataOut.data[:,i,:],
205 id,
206 channelIndexList,
207 thisDatetime,
208 wintitle1,
209 show,
210 xmin,
211 xmax,
212 ymin,
213 ymax)
214
215 if type == "weathervelocity":
216 self.plot_weatherpower(dataOut.heightList,
217 dataOut.data_velocity[:,i,:],
218 id,
219 channelIndexList,
220 thisDatetime,
221 wintitle1,
222 show,
223 xmin,
224 xmax,
225 ymin,
226 ymax)
227
166 228 if type == "iq":
167 self.plot_iq(dataOut.heightList,
229 self.plot_iq(dataOut.heightList,
168 230 dataOut.data[:,i,:],
169 id,
170 channelIndexList,
231 id,
232 channelIndexList,
171 233 thisDatetime,
172 234 wintitle1,
173 235 show,
174 236 xmin,
175 237 xmax,
176 238 ymin,
177 239 ymax)
178
240
179 241 self.draw()
180
242
181 243 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
182 244 figfile = self.getFilename(name = str_datetime) + "_" + str(i)
183
245
184 246 self.save(figpath=figpath,
185 247 figfile=figfile,
186 248 save=save,
187 249 ftp=ftp,
188 250 wr_period=wr_period,
189 251 thisDatetime=thisDatetime)
190
252
191 253 else:
192 254 wintitle += " [Profile = %d] " %dataOut.profileIndex
193
255
194 256 if type == "power":
195 self.plot_power(dataOut.heightList,
257 self.plot_power(dataOut.heightList,
196 258 dataOut.data,
197 id,
198 channelIndexList,
259 id,
260 channelIndexList,
199 261 thisDatetime,
200 262 wintitle,
201 263 show,
202 264 xmin,
203 265 xmax,
204 266 ymin,
205 267 ymax)
206
268
207 269 if type == "iq":
208 self.plot_iq(dataOut.heightList,
270 self.plot_iq(dataOut.heightList,
209 271 dataOut.data,
210 id,
211 channelIndexList,
272 id,
273 channelIndexList,
212 274 thisDatetime,
213 275 wintitle,
214 276 show,
215 277 xmin,
216 278 xmax,
217 279 ymin,
218 280 ymax)
219
281
220 282 self.draw()
221
283
222 284 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") + "_" + str(dataOut.profileIndex)
223 figfile = self.getFilename(name = str_datetime)
224
285 figfile = self.getFilename(name = str_datetime)
286
225 287 self.save(figpath=figpath,
226 288 figfile=figfile,
227 289 save=save,
228 290 ftp=ftp,
229 291 wr_period=wr_period,
230 292 thisDatetime=thisDatetime)
231 293
232 return dataOut No newline at end of file
294 return dataOut
@@ -1,28 +1,30
1 1 '''
2 2 @author: roj-idl71
3 3 '''
4 4 #USED IN jroplot_spectra.py
5 5 RTI_CODE = 0 #Range time intensity (RTI).
6 6 SPEC_CODE = 1 #Spectra (and Cross-spectra) information.
7 7 CROSS_CODE = 2 #Cross-Correlation information.
8 8 COH_CODE = 3 #Coherence map.
9 9 BASE_CODE = 4 #Base lines graphic.
10 10 ROW_CODE = 5 #Row Spectra.
11 11 TOTAL_CODE = 6 #Total Power.
12 12 DRIFT_CODE = 7 #Drifts graphics.
13 13 HEIGHT_CODE = 8 #Height profile.
14 14 PHASE_CODE = 9 #Signal Phase.
15 15
16 16 POWER_CODE = 16
17 17 NOISE_CODE = 17
18 18 BEACON_CODE = 18
19 19
20 20 #USED IN jroplot_parameters.py
21 21 WIND_CODE = 22
22 22 MSKYMAP_CODE = 23
23 23 MPHASE_CODE = 24
24 24
25 25 MOMENTS_CODE = 25
26 PARMS_CODE = 26
26 PARMS_CODE = 26
27 27 SPECFIT_CODE = 27
28 28 EWDRIFT_CODE = 28
29
30 WPO_CODE = 29 #Weather Intensity - Power
@@ -1,1435 +1,1458
1 1 import numpy
2 2 import time
3 3 import os
4 4 import h5py
5 5 import re
6 6 import datetime
7 7
8 8 import schainpy.admin
9 9 from schainpy.model.data.jrodata import *
10 10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
11 11 from schainpy.model.io.jroIO_base import *
12 12 from schainpy.utils import log
13 13
14 14 @MPDecorator
15 15 class ParamReader(JRODataReader,ProcessingUnit):
16 16 '''
17 17 Reads HDF5 format files
18 18 path
19 19 startDate
20 20 endDate
21 21 startTime
22 22 endTime
23 23 '''
24 24
25 25 ext = ".hdf5"
26 26 optchar = "D"
27 27 timezone = None
28 28 startTime = None
29 29 endTime = None
30 30 fileIndex = None
31 31 utcList = None #To select data in the utctime list
32 32 blockList = None #List to blocks to be read from the file
33 33 blocksPerFile = None #Number of blocks to be read
34 34 blockIndex = None
35 35 path = None
36 36 #List of Files
37 37 filenameList = None
38 38 datetimeList = None
39 39 #Hdf5 File
40 40 listMetaname = None
41 41 listMeta = None
42 42 listDataname = None
43 43 listData = None
44 44 listShapes = None
45 45 fp = None
46 46 #dataOut reconstruction
47 47 dataOut = None
48 48
49 49 def __init__(self):#, **kwargs):
50 50 ProcessingUnit.__init__(self) #, **kwargs)
51 51 self.dataOut = Parameters()
52 52 return
53 53
54 54 def setup(self, **kwargs):
55 55
56 56 path = kwargs['path']
57 57 startDate = kwargs['startDate']
58 58 endDate = kwargs['endDate']
59 59 startTime = kwargs['startTime']
60 60 endTime = kwargs['endTime']
61 61 walk = kwargs['walk']
62 62 if 'ext' in kwargs:
63 63 ext = kwargs['ext']
64 64 else:
65 65 ext = '.hdf5'
66 66 if 'timezone' in kwargs:
67 67 self.timezone = kwargs['timezone']
68 68 else:
69 69 self.timezone = 'lt'
70 70
71 71 print("[Reading] Searching files in offline mode ...")
72 72 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
73 73 startTime=startTime, endTime=endTime,
74 74 ext=ext, walk=walk)
75 75
76 76 if not(filenameList):
77 77 print("There is no files into the folder: %s"%(path))
78 78 sys.exit(-1)
79 79
80 80 self.fileIndex = -1
81 81 self.startTime = startTime
82 82 self.endTime = endTime
83 83
84 84 self.__readMetadata()
85 85
86 86 self.__setNextFileOffline()
87 87
88 88 return
89 89
90 90 def searchFilesOffLine(self,
91 91 path,
92 92 startDate=None,
93 93 endDate=None,
94 94 startTime=datetime.time(0,0,0),
95 95 endTime=datetime.time(23,59,59),
96 96 ext='.hdf5',
97 97 walk=True):
98 98
99 99 expLabel = ''
100 100 self.filenameList = []
101 101 self.datetimeList = []
102 102
103 103 pathList = []
104 104
105 105 JRODataObj = JRODataReader()
106 106 dateList, pathList = JRODataObj.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
107 107
108 108 if dateList == []:
109 109 print("[Reading] No *%s files in %s from %s to %s)"%(ext, path,
110 110 datetime.datetime.combine(startDate,startTime).ctime(),
111 111 datetime.datetime.combine(endDate,endTime).ctime()))
112 112
113 113 return None, None
114 114
115 115 if len(dateList) > 1:
116 116 print("[Reading] %d days were found in date range: %s - %s" %(len(dateList), startDate, endDate))
117 117 else:
118 118 print("[Reading] data was found for the date %s" %(dateList[0]))
119 119
120 120 filenameList = []
121 121 datetimeList = []
122 122
123 123 #----------------------------------------------------------------------------------
124 124
125 125 for thisPath in pathList:
126 126
127 127 fileList = glob.glob1(thisPath, "*%s" %ext)
128 128 fileList.sort()
129 129
130 130 for file in fileList:
131 131
132 132 filename = os.path.join(thisPath,file)
133 133
134 134 if not isFileInDateRange(filename, startDate, endDate):
135 135 continue
136 136
137 137 thisDatetime = self.__isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
138 138
139 139 if not(thisDatetime):
140 140 continue
141 141
142 142 filenameList.append(filename)
143 143 datetimeList.append(thisDatetime)
144 144
145 145 if not(filenameList):
146 146 print("[Reading] Any file was found int time range %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()))
147 147 return None, None
148 148
149 149 print("[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime))
150 150 print()
151 151
152 152 self.filenameList = filenameList
153 153 self.datetimeList = datetimeList
154 154
155 155 return pathList, filenameList
156 156
157 157 def __isFileInTimeRange(self,filename, startDate, endDate, startTime, endTime):
158 158
159 159 """
160 160 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
161 161
162 162 Inputs:
163 163 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
164 164 startDate : fecha inicial del rango seleccionado en formato datetime.date
165 165 endDate : fecha final del rango seleccionado en formato datetime.date
166 166 startTime : tiempo inicial del rango seleccionado en formato datetime.time
167 167 endTime : tiempo final del rango seleccionado en formato datetime.time
168 168
169 169 Return:
170 170 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
171 171 fecha especificado, de lo contrario retorna False.
172 172
173 173 Excepciones:
174 174 Si el archivo no existe o no puede ser abierto
175 175 Si la cabecera no puede ser leida.
176 176
177 177 """
178 178
179 179 try:
180 180 fp = h5py.File(filename,'r')
181 181 grp1 = fp['Data']
182 182
183 183 except IOError:
184 184 traceback.print_exc()
185 185 raise IOError("The file %s can't be opened" %(filename))
186
186
187 187 #In case has utctime attribute
188 188 grp2 = grp1['utctime']
189 189 # thisUtcTime = grp2.value[0] - 5*3600 #To convert to local time
190 190 thisUtcTime = grp2.value[0]
191 191
192 192 fp.close()
193 193
194 194 if self.timezone == 'lt':
195 195 thisUtcTime -= 5*3600
196 196
197 197 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
198 198 thisDate = thisDatetime.date()
199 199 thisTime = thisDatetime.time()
200 200
201 201 startUtcTime = (datetime.datetime.combine(thisDate,startTime)- datetime.datetime(1970, 1, 1)).total_seconds()
202 202 endUtcTime = (datetime.datetime.combine(thisDate,endTime)- datetime.datetime(1970, 1, 1)).total_seconds()
203 203
204 204 #General case
205 205 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
206 206 #-----------o----------------------------o-----------
207 207 # startTime endTime
208 208
209 209 if endTime >= startTime:
210 210 thisUtcLog = numpy.logical_and(thisUtcTime > startUtcTime, thisUtcTime < endUtcTime)
211 211 if numpy.any(thisUtcLog): #If there is one block between the hours mentioned
212 212 return thisDatetime
213 213 return None
214 214
215 215 #If endTime < startTime then endTime belongs to the next day
216 216 #<<<<<<<<<<<o o>>>>>>>>>>>
217 217 #-----------o----------------------------o-----------
218 218 # endTime startTime
219 219
220 220 if (thisDate == startDate) and numpy.all(thisUtcTime < startUtcTime):
221 221 return None
222 222
223 223 if (thisDate == endDate) and numpy.all(thisUtcTime > endUtcTime):
224 224 return None
225 225
226 226 if numpy.all(thisUtcTime < startUtcTime) and numpy.all(thisUtcTime > endUtcTime):
227 227 return None
228 228
229 229 return thisDatetime
230 230
231 231 def __setNextFileOffline(self):
232 232
233 233 self.fileIndex += 1
234 234 idFile = self.fileIndex
235 235
236 236 if not(idFile < len(self.filenameList)):
237 237 raise schainpy.admin.SchainError("No more Files")
238 238 return 0
239 239
240 240 filename = self.filenameList[idFile]
241 241 filePointer = h5py.File(filename,'r')
242 242 self.filename = filename
243 243 self.fp = filePointer
244 244
245 245 print("Setting the file: %s"%self.filename)
246 246
247 247 self.__setBlockList()
248 248 self.__readData()
249 249 self.blockIndex = 0
250 250 return 1
251 251
252 252 def __setBlockList(self):
253 253 '''
254 254 Selects the data within the times defined
255 255
256 256 self.fp
257 257 self.startTime
258 258 self.endTime
259 259
260 260 self.blockList
261 261 self.blocksPerFile
262 262
263 263 '''
264 264 fp = self.fp
265 265 startTime = self.startTime
266 266 endTime = self.endTime
267 267
268 268 grp = fp['Data']
269 269 thisUtcTime = grp['utctime'].value.astype(numpy.float)[0]
270 270
271 271 #ERROOOOR
272 272 if self.timezone == 'lt':
273 273 thisUtcTime -= 5*3600
274 274
275 275 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
276 276
277 277 thisDate = thisDatetime.date()
278 278 thisTime = thisDatetime.time()
279 279
280 280 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
281 281 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
282 282
283 283 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
284 284
285 285 self.blockList = ind
286 286 self.blocksPerFile = len(ind)
287 287
288 288 return
289 289
290 290 def __readMetadata(self):
291 291 '''
292 292 Reads Metadata
293 293
294 294 self.pathMeta
295 295 self.listShapes
296 296 self.listMetaname
297 297 self.listMeta
298 298
299 299 '''
300 300
301 301 filename = self.filenameList[0]
302 302 fp = h5py.File(filename,'r')
303 303 gp = fp['Metadata']
304 304
305 305 listMetaname = []
306 306 listMetadata = []
307 307 for item in list(gp.items()):
308 308 name = item[0]
309 309
310 310 if name=='array dimensions':
311 311 table = gp[name][:]
312 312 listShapes = {}
313 313 for shapes in table:
314 314 listShapes[shapes[0]] = numpy.array([shapes[1],shapes[2],shapes[3],shapes[4],shapes[5]])
315 315 else:
316 316 data = gp[name].value
317 317 listMetaname.append(name)
318 318 listMetadata.append(data)
319 319
320 320 self.listShapes = listShapes
321 321 self.listMetaname = listMetaname
322 322 self.listMeta = listMetadata
323 323
324 324 fp.close()
325 325 return
326 326
327 327 def __readData(self):
328 328 grp = self.fp['Data']
329 329 listdataname = []
330 330 listdata = []
331 331
332 332 for item in list(grp.items()):
333 333 name = item[0]
334 334 listdataname.append(name)
335 335
336 336 array = self.__setDataArray(grp[name],self.listShapes[name])
337 337 listdata.append(array)
338 338
339 339 self.listDataname = listdataname
340 340 self.listData = listdata
341 341 return
342 342
343 343 def __setDataArray(self, dataset, shapes):
344 344
345 345 nDims = shapes[0]
346 346 nDim2 = shapes[1] #Dimension 0
347 347 nDim1 = shapes[2] #Dimension 1, number of Points or Parameters
348 348 nDim0 = shapes[3] #Dimension 2, number of samples or ranges
349 349 mode = shapes[4] #Mode of storing
350 350 blockList = self.blockList
351 351 blocksPerFile = self.blocksPerFile
352 352
353 353 #Depending on what mode the data was stored
354 354 if mode == 0: #Divided in channels
355 355 arrayData = dataset.value.astype(numpy.float)[0][blockList]
356 356 if mode == 1: #Divided in parameter
357 357 strds = 'table'
358 358 nDatas = nDim1
359 359 newShapes = (blocksPerFile,nDim2,nDim0)
360 360 elif mode==2: #Concatenated in a table
361 361 strds = 'table0'
362 362 arrayData = dataset[strds].value
363 363 #Selecting part of the dataset
364 364 utctime = arrayData[:,0]
365 365 u, indices = numpy.unique(utctime, return_index=True)
366 366
367 367 if blockList.size != indices.size:
368 368 indMin = indices[blockList[0]]
369 369 if blockList[1] + 1 >= indices.size:
370 370 arrayData = arrayData[indMin:,:]
371 371 else:
372 372 indMax = indices[blockList[1] + 1]
373 373 arrayData = arrayData[indMin:indMax,:]
374 374 return arrayData
375 375
376 376 # One dimension
377 377 if nDims == 0:
378 378 arrayData = dataset.value.astype(numpy.float)[0][blockList]
379 379
380 380 # Two dimensions
381 381 elif nDims == 2:
382 382 arrayData = numpy.zeros((blocksPerFile,nDim1,nDim0))
383 383 newShapes = (blocksPerFile,nDim0)
384 384 nDatas = nDim1
385 385
386 386 for i in range(nDatas):
387 387 data = dataset[strds + str(i)].value
388 388 arrayData[:,i,:] = data[blockList,:]
389 389
390 390 # Three dimensions
391 391 else:
392 392 arrayData = numpy.zeros((blocksPerFile,nDim2,nDim1,nDim0))
393 393 for i in range(nDatas):
394 394
395 395 data = dataset[strds + str(i)].value
396 396
397 397 for b in range(blockList.size):
398 398 arrayData[b,:,i,:] = data[:,:,blockList[b]]
399 399
400 400 return arrayData
401 401
402 402 def __setDataOut(self):
403 403 listMeta = self.listMeta
404 404 listMetaname = self.listMetaname
405 405 listDataname = self.listDataname
406 406 listData = self.listData
407 407 listShapes = self.listShapes
408 408
409 409 blockIndex = self.blockIndex
410 410 # blockList = self.blockList
411 411
412 412 for i in range(len(listMeta)):
413 413 setattr(self.dataOut,listMetaname[i],listMeta[i])
414 414
415 415 for j in range(len(listData)):
416 416 nShapes = listShapes[listDataname[j]][0]
417 417 mode = listShapes[listDataname[j]][4]
418 418 if nShapes == 1:
419 419 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
420 420 elif nShapes > 1:
421 421 setattr(self.dataOut,listDataname[j],listData[j][blockIndex,:])
422 422 elif mode==0:
423 423 setattr(self.dataOut,listDataname[j],listData[j][blockIndex])
424 424 #Mode Meteors
425 425 elif mode ==2:
426 426 selectedData = self.__selectDataMode2(listData[j], blockIndex)
427 427 setattr(self.dataOut, listDataname[j], selectedData)
428 428 return
429 429
430 430 def __selectDataMode2(self, data, blockIndex):
431 431 utctime = data[:,0]
432 432 aux, indices = numpy.unique(utctime, return_inverse=True)
433 433 selInd = numpy.where(indices == blockIndex)[0]
434 434 selData = data[selInd,:]
435 435
436 436 return selData
437 437
438 438 def getData(self):
439 439
440 440 if self.blockIndex==self.blocksPerFile:
441 441 if not( self.__setNextFileOffline() ):
442 442 self.dataOut.flagNoData = True
443 443 return 0
444 444
445 445 self.__setDataOut()
446 446 self.dataOut.flagNoData = False
447 447
448 448 self.blockIndex += 1
449 449
450 450 return
451 451
452 452 def run(self, **kwargs):
453 453
454 454 if not(self.isConfig):
455 455 self.setup(**kwargs)
456 456 self.isConfig = True
457 457
458 458 self.getData()
459 459
460 460 return
461 461
462 462 @MPDecorator
463 463 class ParamWriter(Operation):
464 464 '''
465 465 HDF5 Writer, stores parameters data in HDF5 format files
466 466
467 467 path: path where the files will be stored
468 468 blocksPerFile: number of blocks that will be saved in per HDF5 format file
469 469 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
470 470 metadataList: list of attributes that will be stored as metadata
471 471 dataList: list of attributes that will be stores as data
472 472 '''
473 473
474 474 ext = ".hdf5"
475 475 optchar = "D"
476 476 metaoptchar = "M"
477 477 metaFile = None
478 478 filename = None
479 479 path = None
480 480 setFile = None
481 481 fp = None
482 482 grp = None
483 483 ds = None
484 484 firsttime = True
485 485 #Configurations
486 486 blocksPerFile = None
487 487 blockIndex = None
488 488 dataOut = None
489 489 #Data Arrays
490 490 dataList = None
491 491 metadataList = None
492 492 dsList = None #List of dictionaries with dataset properties
493 493 tableDim = None
494 494 dtype = [('arrayName', 'S20'),('nDimensions', 'i'), ('dim2', 'i'), ('dim1', 'i'),('dim0', 'i'),('mode', 'b')]
495 495 currentDay = None
496 496 lastTime = None
497 497 setType = None
498 498
499 499 def __init__(self):
500
500
501 501 Operation.__init__(self)
502 502 return
503 503
504 504 def setup(self, dataOut, path=None, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
505 505 self.path = path
506 506 self.blocksPerFile = blocksPerFile
507 507 self.metadataList = metadataList
508 508 self.dataList = dataList
509 509 self.dataOut = dataOut
510 510 self.mode = mode
511 511 if self.mode is not None:
512 512 self.mode = numpy.zeros(len(self.dataList)) + mode
513 513 else:
514 514 self.mode = numpy.ones(len(self.dataList))
515 515
516 516 self.setType = setType
517 517
518 518 arrayDim = numpy.zeros((len(self.dataList),5))
519 519
520 520 #Table dimensions
521 521 dtype0 = self.dtype
522 522 tableList = []
523 523
524 524 #Dictionary and list of tables
525 525 dsList = []
526 526
527 527 for i in range(len(self.dataList)):
528 528 dsDict = {}
529 529 dataAux = getattr(self.dataOut, self.dataList[i])
530 530 dsDict['variable'] = self.dataList[i]
531 531 #--------------------- Conditionals ------------------------
532 532 #There is no data
533
533
534 534 if dataAux is None:
535
535
536 536 return 0
537 537
538 538 if isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
539 539 dsDict['mode'] = 0
540 540 dsDict['nDim'] = 0
541 541 arrayDim[i,0] = 0
542 542 dsList.append(dsDict)
543 543
544 544 #Mode 2: meteors
545 545 elif self.mode[i] == 2:
546 546 dsDict['dsName'] = 'table0'
547 547 dsDict['mode'] = 2 # Mode meteors
548 548 dsDict['shape'] = dataAux.shape[-1]
549 549 dsDict['nDim'] = 0
550 550 dsDict['dsNumber'] = 1
551 551 arrayDim[i,3] = dataAux.shape[-1]
552 552 arrayDim[i,4] = self.mode[i] #Mode the data was stored
553 553 dsList.append(dsDict)
554 554
555 555 #Mode 1
556 556 else:
557 557 arrayDim0 = dataAux.shape #Data dimensions
558 558 arrayDim[i,0] = len(arrayDim0) #Number of array dimensions
559 559 arrayDim[i,4] = self.mode[i] #Mode the data was stored
560 560 strtable = 'table'
561 561 dsDict['mode'] = 1 # Mode parameters
562 562
563 563 # Three-dimension arrays
564 564 if len(arrayDim0) == 3:
565 565 arrayDim[i,1:-1] = numpy.array(arrayDim0)
566 566 nTables = int(arrayDim[i,2])
567 567 dsDict['dsNumber'] = nTables
568 568 dsDict['shape'] = arrayDim[i,2:4]
569 569 dsDict['nDim'] = 3
570 570
571 571 for j in range(nTables):
572 572 dsDict = dsDict.copy()
573 573 dsDict['dsName'] = strtable + str(j)
574 574 dsList.append(dsDict)
575 575
576 576 # Two-dimension arrays
577 577 elif len(arrayDim0) == 2:
578 578 arrayDim[i,2:-1] = numpy.array(arrayDim0)
579 579 nTables = int(arrayDim[i,2])
580 580 dsDict['dsNumber'] = nTables
581 581 dsDict['shape'] = arrayDim[i,3]
582 582 dsDict['nDim'] = 2
583 583
584 584 for j in range(nTables):
585 585 dsDict = dsDict.copy()
586 586 dsDict['dsName'] = strtable + str(j)
587 587 dsList.append(dsDict)
588 588
589 589 # One-dimension arrays
590 590 elif len(arrayDim0) == 1:
591 591 arrayDim[i,3] = arrayDim0[0]
592 592 dsDict['shape'] = arrayDim0[0]
593 593 dsDict['dsNumber'] = 1
594 594 dsDict['dsName'] = strtable + str(0)
595 595 dsDict['nDim'] = 1
596 596 dsList.append(dsDict)
597 597
598 598 table = numpy.array((self.dataList[i],) + tuple(arrayDim[i,:]),dtype = dtype0)
599 599 tableList.append(table)
600 600
601 601 self.dsList = dsList
602 602 self.tableDim = numpy.array(tableList, dtype = dtype0)
603 603 self.blockIndex = 0
604 604 timeTuple = time.localtime(dataOut.utctime)
605 605 self.currentDay = timeTuple.tm_yday
606 606
607 607 def putMetadata(self):
608 608
609 609 fp = self.createMetadataFile()
610 610 self.writeMetadata(fp)
611 611 fp.close()
612 612 return
613 613
614 614 def createMetadataFile(self):
615 615 ext = self.ext
616 616 path = self.path
617 617 setFile = self.setFile
618 618
619 619 timeTuple = time.localtime(self.dataOut.utctime)
620 620
621 621 subfolder = ''
622 622 fullpath = os.path.join( path, subfolder )
623 623
624 624 if not( os.path.exists(fullpath) ):
625 625 os.mkdir(fullpath)
626 626 setFile = -1 #inicializo mi contador de seteo
627 627
628 628 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
629 629 fullpath = os.path.join( path, subfolder )
630 630
631 631 if not( os.path.exists(fullpath) ):
632 632 os.mkdir(fullpath)
633 633 setFile = -1 #inicializo mi contador de seteo
634 634
635 635 else:
636 636 filesList = os.listdir( fullpath )
637 637 filesList = sorted( filesList, key=str.lower )
638 638 if len( filesList ) > 0:
639 639 filesList = [k for k in filesList if k.startswith(self.metaoptchar)]
640 640 filen = filesList[-1]
641 641 # el filename debera tener el siguiente formato
642 642 # 0 1234 567 89A BCDE (hex)
643 643 # x YYYY DDD SSS .ext
644 644 if isNumber( filen[8:11] ):
645 645 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
646 646 else:
647 647 setFile = -1
648 648 else:
649 649 setFile = -1 #inicializo mi contador de seteo
650 650
651 651 if self.setType is None:
652 652 setFile += 1
653 653 file = '%s%4.4d%3.3d%03d%s' % (self.metaoptchar,
654 654 timeTuple.tm_year,
655 655 timeTuple.tm_yday,
656 656 setFile,
657 657 ext )
658 658 else:
659 659 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
660 660 file = '%s%4.4d%3.3d%04d%s' % (self.metaoptchar,
661 661 timeTuple.tm_year,
662 662 timeTuple.tm_yday,
663 663 setFile,
664 664 ext )
665 665
666 666 filename = os.path.join( path, subfolder, file )
667 667 self.metaFile = file
668 668 #Setting HDF5 File
669 669 fp = h5py.File(filename,'w')
670 670
671 671 return fp
672 672
673 673 def writeMetadata(self, fp):
674 674
675 675 grp = fp.create_group("Metadata")
676 676 grp.create_dataset('array dimensions', data = self.tableDim, dtype = self.dtype)
677 677
678 678 for i in range(len(self.metadataList)):
679 679 grp.create_dataset(self.metadataList[i], data=getattr(self.dataOut, self.metadataList[i]))
680 680 return
681 681
682 682 def timeFlag(self):
683 683 currentTime = self.dataOut.utctime
684 684
685 685 if self.lastTime is None:
686 686 self.lastTime = currentTime
687 687
688 688 #Day
689 689 timeTuple = time.localtime(currentTime)
690 690 dataDay = timeTuple.tm_yday
691 691
692 692 #Time
693 693 timeDiff = currentTime - self.lastTime
694 694
695 695 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
696 696 if dataDay != self.currentDay:
697 697 self.currentDay = dataDay
698 698 return True
699 699 elif timeDiff > 3*60*60:
700 700 self.lastTime = currentTime
701 701 return True
702 702 else:
703 703 self.lastTime = currentTime
704 704 return False
705 705
706 706 def setNextFile(self):
707
707
708 708 ext = self.ext
709 709 path = self.path
710 710 setFile = self.setFile
711 711 mode = self.mode
712 712
713 713 timeTuple = time.localtime(self.dataOut.utctime)
714 714 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
715 715
716 716 fullpath = os.path.join( path, subfolder )
717 717
718 718 if os.path.exists(fullpath):
719 719 filesList = os.listdir( fullpath )
720 720 filesList = [k for k in filesList if 'M' in k]
721 721 if len( filesList ) > 0:
722 722 filesList = sorted( filesList, key=str.lower )
723 723 filen = filesList[-1]
724 724 # el filename debera tener el siguiente formato
725 725 # 0 1234 567 89A BCDE (hex)
726 726 # x YYYY DDD SSS .ext
727 727 if isNumber( filen[8:11] ):
728 728 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
729 729 else:
730 730 setFile = -1
731 731 else:
732 732 setFile = -1 #inicializo mi contador de seteo
733 733 else:
734 734 os.makedirs(fullpath)
735 735 setFile = -1 #inicializo mi contador de seteo
736 736
737 737 if self.setType is None:
738 738 setFile += 1
739 739 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
740 740 timeTuple.tm_year,
741 741 timeTuple.tm_yday,
742 742 setFile,
743 743 ext )
744 744 else:
745 745 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
746 746 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
747 747 timeTuple.tm_year,
748 748 timeTuple.tm_yday,
749 749 setFile,
750 750 ext )
751 751
752 752 filename = os.path.join( path, subfolder, file )
753 753
754 754 #Setting HDF5 File
755 755 fp = h5py.File(filename,'w')
756 756 #write metadata
757 757 self.writeMetadata(fp)
758 758 #Write data
759 759 grp = fp.create_group("Data")
760 760 ds = []
761 761 data = []
762 762 dsList = self.dsList
763 763 i = 0
764 764 while i < len(dsList):
765 765 dsInfo = dsList[i]
766 766 #One-dimension data
767 767 if dsInfo['mode'] == 0:
768 768 ds0 = grp.create_dataset(dsInfo['variable'], (1,1), maxshape=(1,self.blocksPerFile) , chunks = True, dtype=numpy.float64)
769 769 ds.append(ds0)
770 770 data.append([])
771 771 i += 1
772 772 continue
773 773
774 774 elif dsInfo['mode'] == 2:
775 775 grp0 = grp.create_group(dsInfo['variable'])
776 776 ds0 = grp0.create_dataset(dsInfo['dsName'], (1,dsInfo['shape']), data = numpy.zeros((1,dsInfo['shape'])) , maxshape=(None,dsInfo['shape']), chunks=True)
777 777 ds.append(ds0)
778 778 data.append([])
779 779 i += 1
780 780 continue
781 781
782 782 elif dsInfo['mode'] == 1:
783 783 grp0 = grp.create_group(dsInfo['variable'])
784 784
785 785 for j in range(dsInfo['dsNumber']):
786 786 dsInfo = dsList[i]
787 787 tableName = dsInfo['dsName']
788
788
789 789
790 790 if dsInfo['nDim'] == 3:
791 791 shape = dsInfo['shape'].astype(int)
792 792 ds0 = grp0.create_dataset(tableName, (shape[0],shape[1],1) , data = numpy.zeros((shape[0],shape[1],1)), maxshape = (None,shape[1],None), chunks=True)
793 793 else:
794 794 shape = int(dsInfo['shape'])
795 795 ds0 = grp0.create_dataset(tableName, (1,shape), data = numpy.zeros((1,shape)) , maxshape=(None,shape), chunks=True)
796 796
797 797 ds.append(ds0)
798 798 data.append([])
799 799 i += 1
800 800
801 801 fp.flush()
802 802 fp.close()
803 803
804 804 log.log('creating file: {}'.format(filename), 'Writing')
805 805 self.filename = filename
806 806 self.ds = ds
807 807 self.data = data
808 808 self.firsttime = True
809 809 self.blockIndex = 0
810 810 return
811 811
812 812 def putData(self):
813 813
814 814 if self.blockIndex == self.blocksPerFile or self.timeFlag():
815 815 self.setNextFile()
816 816
817 817 self.readBlock()
818 818 self.setBlock() #Prepare data to be written
819 819 self.writeBlock() #Write data
820 820
821 821 return
822 822
823 823 def readBlock(self):
824 824
825 825 '''
826 826 data Array configured
827 827
828 828
829 829 self.data
830 830 '''
831 831 dsList = self.dsList
832 832 ds = self.ds
833 833 #Setting HDF5 File
834 834 fp = h5py.File(self.filename,'r+')
835 835 grp = fp["Data"]
836 836 ind = 0
837 837
838 838 while ind < len(dsList):
839 839 dsInfo = dsList[ind]
840 840
841 841 if dsInfo['mode'] == 0:
842 842 ds0 = grp[dsInfo['variable']]
843 843 ds[ind] = ds0
844 844 ind += 1
845 845 else:
846 846
847 847 grp0 = grp[dsInfo['variable']]
848 848
849 849 for j in range(dsInfo['dsNumber']):
850 850 dsInfo = dsList[ind]
851 851 ds0 = grp0[dsInfo['dsName']]
852 852 ds[ind] = ds0
853 853 ind += 1
854 854
855 855 self.fp = fp
856 856 self.grp = grp
857 857 self.ds = ds
858 858
859 859 return
860 860
861 861 def setBlock(self):
862 862 '''
863 863 data Array configured
864 864
865 865
866 866 self.data
867 867 '''
868 868 #Creating Arrays
869 869 dsList = self.dsList
870 870 data = self.data
871 871 ind = 0
872
872 #print("dsList ",dsList)
873 #print("len ",len(dsList))
873 874 while ind < len(dsList):
874 875 dsInfo = dsList[ind]
875 876 dataAux = getattr(self.dataOut, dsInfo['variable'])
876 877
877 878 mode = dsInfo['mode']
878 879 nDim = dsInfo['nDim']
879 880
880 881 if mode == 0 or mode == 2 or nDim == 1:
881 882 data[ind] = dataAux
882 883 ind += 1
883 884 # elif nDim == 1:
884 885 # data[ind] = numpy.reshape(dataAux,(numpy.size(dataAux),1))
885 886 # ind += 1
886 887 elif nDim == 2:
887 888 for j in range(dsInfo['dsNumber']):
888 889 data[ind] = dataAux[j,:]
889 890 ind += 1
890 891 elif nDim == 3:
891 892 for j in range(dsInfo['dsNumber']):
892 893 data[ind] = dataAux[:,j,:]
893 894 ind += 1
894 895
895 896 self.data = data
896 897 return
897 898
898 899 def writeBlock(self):
899 900 '''
900 901 Saves the block in the HDF5 file
901 902 '''
902 903 dsList = self.dsList
903 904
904 905 for i in range(len(self.ds)):
906 print("#############", i , "#######################")
905 907 dsInfo = dsList[i]
906 908 nDim = dsInfo['nDim']
907 909 mode = dsInfo['mode']
908
910 print("dsInfo",dsInfo)
911 print("nDim",nDim)
912 print("mode",mode)
909 913 # First time
910 914 if self.firsttime:
915 print("ENTRE FIRSTIME")
911 916 if type(self.data[i]) == numpy.ndarray:
912 917
913 918 if nDim == 3:
919 print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
920 print("ndim","dentro del primer if 3")
914 921 self.data[i] = self.data[i].reshape((self.data[i].shape[0],self.data[i].shape[1],1))
922 print(self.data[i].shape)
923 print(type(self.data[i]))
915 924 self.ds[i].resize(self.data[i].shape)
925 print(self.ds[i].shape)
926 print(type(self.ds[i]))
916 927 if mode == 2:
917 928 self.ds[i].resize(self.data[i].shape)
918 self.ds[i][:] = self.data[i]
919 else:
929 try:
930 print("PTM ODIO ESTO")
931 print(self.ds[i][:].shape)
932 self.ds[i][:] = self.data[i]
933 print("*****___________********______******")
920 934
935 except:
936 print("q habra pasaado")
937 return
938 print("LLEGUE Y CUMPLI EL IF")
939 else:
940 print("ELSE -----------------------")
921 941 # From second time
922 942 # Meteors!
923 943 if mode == 2:
924 944 dataShape = self.data[i].shape
925 945 dsShape = self.ds[i].shape
926 946 self.ds[i].resize((self.ds[i].shape[0] + dataShape[0],self.ds[i].shape[1]))
927 947 self.ds[i][dsShape[0]:,:] = self.data[i]
928 948 # No dimension
929 949 elif mode == 0:
930 950 self.ds[i].resize((self.ds[i].shape[0], self.ds[i].shape[1] + 1))
931 951 self.ds[i][0,-1] = self.data[i]
932 952 # One dimension
933 953 elif nDim == 1:
934 954 self.ds[i].resize((self.ds[i].shape[0] + 1, self.ds[i].shape[1]))
935 955 self.ds[i][-1,:] = self.data[i]
936 956 # Two dimension
937 957 elif nDim == 2:
938 958 self.ds[i].resize((self.ds[i].shape[0] + 1,self.ds[i].shape[1]))
939 959 self.ds[i][self.blockIndex,:] = self.data[i]
940 960 # Three dimensions
941 961 elif nDim == 3:
942 962 self.ds[i].resize((self.ds[i].shape[0],self.ds[i].shape[1],self.ds[i].shape[2]+1))
943 963 self.ds[i][:,:,-1] = self.data[i]
944 964
945 965 self.firsttime = False
946 966 self.blockIndex += 1
947
967 print("HOLA AMIGOS COMO ESTAN LLEGUE")
968 print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
948 969 #Close to save changes
949 970 self.fp.flush()
950 971 self.fp.close()
951 972 return
952 973
953 974 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, mode=None, setType=None):
954 975
955 976 self.dataOut = dataOut
956 977 if not(self.isConfig):
957 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
978 self.setup(dataOut, path=path, blocksPerFile=blocksPerFile,
958 979 metadataList=metadataList, dataList=dataList, mode=mode,
959 980 setType=setType)
960 981
961 982 self.isConfig = True
962 983 self.setNextFile()
963 984
964 985 self.putData()
965 986 return
966
987
967 988
968 989 @MPDecorator
969 990 class ParameterReader(Reader, ProcessingUnit):
970 991 '''
971 992 Reads HDF5 format files
972 993 '''
973 994
974 995 def __init__(self):
975 996 ProcessingUnit.__init__(self)
976 997 self.dataOut = Parameters()
977 998 self.ext = ".hdf5"
978 999 self.optchar = "D"
979 1000 self.timezone = "lt"
980 1001 self.listMetaname = []
981 1002 self.listMeta = []
982 1003 self.listDataname = []
983 1004 self.listData = []
984 1005 self.listShapes = []
985 1006 self.open_file = h5py.File
986 1007 self.open_mode = 'r'
987 1008 self.metadata = False
988 1009 self.filefmt = "*%Y%j***"
989 1010 self.folderfmt = "*%Y%j"
990 1011
991 1012 def setup(self, **kwargs):
992 1013
993 1014 self.set_kwargs(**kwargs)
994 1015 if not self.ext.startswith('.'):
995 self.ext = '.{}'.format(self.ext)
1016 self.ext = '.{}'.format(self.ext)
996 1017
997 1018 if self.online:
998 1019 log.log("Searching files in online mode...", self.name)
999 1020
1000 1021 for nTries in range(self.nTries):
1001 1022 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1002 self.endDate, self.expLabel, self.ext, self.walk,
1023 self.endDate, self.expLabel, self.ext, self.walk,
1003 1024 self.filefmt, self.folderfmt)
1004 1025
1005 1026 try:
1006 1027 fullpath = next(fullpath)
1007 1028 except:
1008 1029 fullpath = None
1009
1030
1010 1031 if fullpath:
1011 1032 break
1012 1033
1013 1034 log.warning(
1014 1035 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1015 self.delay, self.path, nTries + 1),
1036 self.delay, self.path, nTries + 1),
1016 1037 self.name)
1017 1038 time.sleep(self.delay)
1018 1039
1019 1040 if not(fullpath):
1020 1041 raise schainpy.admin.SchainError(
1021 'There isn\'t any valid file in {}'.format(self.path))
1042 'There isn\'t any valid file in {}'.format(self.path))
1022 1043
1023 1044 pathname, filename = os.path.split(fullpath)
1024 1045 self.year = int(filename[1:5])
1025 1046 self.doy = int(filename[5:8])
1026 self.set = int(filename[8:11]) - 1
1047 self.set = int(filename[8:11]) - 1
1027 1048 else:
1028 1049 log.log("Searching files in {}".format(self.path), self.name)
1029 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1050 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1030 1051 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1031
1052
1032 1053 self.setNextFile()
1033 1054
1034 1055 return
1035 1056
1036 1057 def readFirstHeader(self):
1037 1058 '''Read metadata and data'''
1038 1059
1039 self.__readMetadata()
1060 self.__readMetadata()
1040 1061 self.__readData()
1041 1062 self.__setBlockList()
1042 1063 self.blockIndex = 0
1043
1064
1044 1065 return
1045 1066
1046 1067 def __setBlockList(self):
1047 1068 '''
1048 1069 Selects the data within the times defined
1049 1070
1050 1071 self.fp
1051 1072 self.startTime
1052 1073 self.endTime
1053 1074 self.blockList
1054 1075 self.blocksPerFile
1055 1076
1056 1077 '''
1057 1078
1058 1079 startTime = self.startTime
1059 1080 endTime = self.endTime
1060 1081
1061 1082 index = self.listDataname.index('utctime')
1062 1083 thisUtcTime = self.listData[index]
1063 1084 self.interval = numpy.min(thisUtcTime[1:] - thisUtcTime[:-1])
1064 1085
1065 1086 if self.timezone == 'lt':
1066 1087 thisUtcTime -= 5*3600
1067 1088
1068 1089 thisDatetime = datetime.datetime.fromtimestamp(thisUtcTime[0] + 5*3600)
1069 1090
1070 1091 thisDate = thisDatetime.date()
1071 1092 thisTime = thisDatetime.time()
1072 1093
1073 1094 startUtcTime = (datetime.datetime.combine(thisDate,startTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1074 1095 endUtcTime = (datetime.datetime.combine(thisDate,endTime) - datetime.datetime(1970, 1, 1)).total_seconds()
1075 1096
1076 1097 ind = numpy.where(numpy.logical_and(thisUtcTime >= startUtcTime, thisUtcTime < endUtcTime))[0]
1077 1098
1078 1099 self.blockList = ind
1079 1100 self.blocksPerFile = len(ind)
1080 1101 return
1081 1102
1082 1103 def __readMetadata(self):
1083 1104 '''
1084 1105 Reads Metadata
1085 1106 '''
1086 1107
1087 1108 listMetaname = []
1088 1109 listMetadata = []
1089 1110 if 'Metadata' in self.fp:
1090 1111 gp = self.fp['Metadata']
1091 1112 for item in list(gp.items()):
1092 1113 name = item[0]
1093 1114
1094 1115 if name=='variables':
1095 1116 table = gp[name][:]
1096 1117 listShapes = {}
1097 1118 for shapes in table:
1098 1119 listShapes[shapes[0].decode()] = numpy.array([shapes[1]])
1099 1120 else:
1100 1121 data = gp[name].value
1101 1122 listMetaname.append(name)
1102 listMetadata.append(data)
1123 listMetadata.append(data)
1103 1124 elif self.metadata:
1104 1125 metadata = json.loads(self.metadata)
1105 1126 listShapes = {}
1106 1127 for tup in metadata:
1107 1128 name, values, dim = tup
1108 1129 if dim == -1:
1109 1130 listMetaname.append(name)
1110 1131 listMetadata.append(self.fp[values].value)
1111 1132 else:
1112 1133 listShapes[name] = numpy.array([dim])
1113 1134 else:
1114 1135 raise IOError('Missing Metadata group in file or metadata info')
1115 1136
1116 1137 self.listShapes = listShapes
1117 1138 self.listMetaname = listMetaname
1118 self.listMeta = listMetadata
1139 self.listMeta = listMetadata
1119 1140
1120 1141 return
1121 1142
1122 1143 def __readData(self):
1123 1144
1124 1145 listdataname = []
1125 1146 listdata = []
1126
1147
1127 1148 if 'Data' in self.fp:
1128 1149 grp = self.fp['Data']
1129 1150 for item in list(grp.items()):
1130 1151 name = item[0]
1131 1152 listdataname.append(name)
1132 1153 dim = self.listShapes[name][0]
1133 1154 if dim == 0:
1134 1155 array = grp[name].value
1135 1156 else:
1136 1157 array = []
1137 1158 for i in range(dim):
1138 1159 array.append(grp[name]['table{:02d}'.format(i)].value)
1139 1160 array = numpy.array(array)
1140
1161
1141 1162 listdata.append(array)
1142 1163 elif self.metadata:
1143 1164 metadata = json.loads(self.metadata)
1144 1165 for tup in metadata:
1145 1166 name, values, dim = tup
1146 1167 listdataname.append(name)
1147 1168 if dim == -1:
1148 1169 continue
1149 1170 elif dim == 0:
1150 1171 array = self.fp[values].value
1151 1172 else:
1152 1173 array = []
1153 1174 for var in values:
1154 1175 array.append(self.fp[var].value)
1155 1176 array = numpy.array(array)
1156 1177 listdata.append(array)
1157 1178 else:
1158 1179 raise IOError('Missing Data group in file or metadata info')
1159 1180
1160 1181 self.listDataname = listdataname
1161 1182 self.listData = listdata
1162 1183 return
1163
1184
1164 1185 def getData(self):
1165 1186
1166 1187 for i in range(len(self.listMeta)):
1167 1188 setattr(self.dataOut, self.listMetaname[i], self.listMeta[i])
1168 1189
1169 1190 for j in range(len(self.listData)):
1170 1191 dim = self.listShapes[self.listDataname[j]][0]
1171 1192 if dim == 0:
1172 1193 setattr(self.dataOut, self.listDataname[j], self.listData[j][self.blockIndex])
1173 1194 else:
1174 1195 setattr(self.dataOut, self.listDataname[j], self.listData[j][:,self.blockIndex])
1175 1196
1176 1197 self.dataOut.paramInterval = self.interval
1177 1198 self.dataOut.flagNoData = False
1178 1199 self.blockIndex += 1
1179 1200
1180 1201 return
1181 1202
1182 1203 def run(self, **kwargs):
1183 1204
1184 1205 if not(self.isConfig):
1185 1206 self.setup(**kwargs)
1186 1207 self.isConfig = True
1187 1208
1188 1209 if self.blockIndex == self.blocksPerFile:
1189 1210 self.setNextFile()
1190 1211
1191 1212 self.getData()
1192 1213
1193 1214 return
1194 1215
1195 1216 @MPDecorator
1196 1217 class ParameterWriter(Operation):
1197 1218 '''
1198 1219 HDF5 Writer, stores parameters data in HDF5 format files
1199 1220
1200 1221 path: path where the files will be stored
1201 1222 blocksPerFile: number of blocks that will be saved in per HDF5 format file
1202 1223 mode: selects the data stacking mode: '0' channels, '1' parameters, '3' table (for meteors)
1203 1224 metadataList: list of attributes that will be stored as metadata
1204 1225 dataList: list of attributes that will be stores as data
1205 1226 '''
1206 1227
1207 1228
1208 1229 ext = ".hdf5"
1209 1230 optchar = "D"
1210 1231 metaoptchar = "M"
1211 1232 metaFile = None
1212 1233 filename = None
1213 1234 path = None
1214 1235 setFile = None
1215 1236 fp = None
1216 1237 grp = None
1217 1238 ds = None
1218 1239 firsttime = True
1219 1240 #Configurations
1220 1241 blocksPerFile = None
1221 1242 blockIndex = None
1222 1243 dataOut = None
1223 1244 #Data Arrays
1224 1245 dataList = None
1225 1246 metadataList = None
1226 1247 dsList = None #List of dictionaries with dataset properties
1227 1248 tableDim = None
1228 1249 dtype = [('name', 'S20'),('nDim', 'i')]
1229 1250 currentDay = None
1230 1251 lastTime = None
1231 1252
1232 1253 def __init__(self):
1233
1254
1234 1255 Operation.__init__(self)
1235 1256 return
1236 1257
1237 1258 def setup(self, path=None, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1238 1259 self.path = path
1239 1260 self.blocksPerFile = blocksPerFile
1240 1261 self.metadataList = metadataList
1241 1262 self.dataList = dataList
1242 1263 self.setType = setType
1243 1264
1244 1265 tableList = []
1245 1266 dsList = []
1246 1267
1247 1268 for i in range(len(self.dataList)):
1248 1269 dsDict = {}
1249 1270 dataAux = getattr(self.dataOut, self.dataList[i])
1250 1271 dsDict['variable'] = self.dataList[i]
1251 1272
1252 1273 if dataAux is None:
1253 1274 continue
1254 1275 elif isinstance(dataAux, (int, float, numpy.integer, numpy.float)):
1255 1276 dsDict['nDim'] = 0
1256 1277 else:
1257 1278 dsDict['nDim'] = len(dataAux.shape)
1258 1279 dsDict['shape'] = dataAux.shape
1259 1280 dsDict['dsNumber'] = dataAux.shape[0]
1260
1281
1261 1282 dsList.append(dsDict)
1262 1283 tableList.append((self.dataList[i], dsDict['nDim']))
1263 1284
1264 1285 self.dsList = dsList
1265 1286 self.tableDim = numpy.array(tableList, dtype=self.dtype)
1266 1287 self.currentDay = self.dataOut.datatime.date()
1267 1288
1268 1289 def timeFlag(self):
1269 1290 currentTime = self.dataOut.utctime
1270 1291 timeTuple = time.localtime(currentTime)
1271 1292 dataDay = timeTuple.tm_yday
1272 1293
1273 1294 if self.lastTime is None:
1274 1295 self.lastTime = currentTime
1275 1296 self.currentDay = dataDay
1276 1297 return False
1277
1298
1278 1299 timeDiff = currentTime - self.lastTime
1279 1300
1280 1301 #Si el dia es diferente o si la diferencia entre un dato y otro supera la hora
1281 1302 if dataDay != self.currentDay:
1282 1303 self.currentDay = dataDay
1283 1304 return True
1284 1305 elif timeDiff > 3*60*60:
1285 1306 self.lastTime = currentTime
1286 1307 return True
1287 1308 else:
1288 1309 self.lastTime = currentTime
1289 1310 return False
1290 1311
1291 1312 def run(self, dataOut, path, blocksPerFile=10, metadataList=None, dataList=None, setType=None):
1292 1313
1293 1314 self.dataOut = dataOut
1294 1315 if not(self.isConfig):
1295 self.setup(path=path, blocksPerFile=blocksPerFile,
1316 self.setup(path=path, blocksPerFile=blocksPerFile,
1296 1317 metadataList=metadataList, dataList=dataList,
1297 1318 setType=setType)
1298 1319
1299 1320 self.isConfig = True
1300 1321 self.setNextFile()
1301 1322
1302 1323 self.putData()
1303 1324 return
1304
1325
1305 1326 def setNextFile(self):
1306
1327
1307 1328 ext = self.ext
1308 1329 path = self.path
1309 1330 setFile = self.setFile
1310 1331
1311 1332 timeTuple = time.localtime(self.dataOut.utctime)
1312 1333 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1313 1334 fullpath = os.path.join(path, subfolder)
1314 1335
1315 1336 if os.path.exists(fullpath):
1316 1337 filesList = os.listdir(fullpath)
1317 1338 filesList = [k for k in filesList if k.startswith(self.optchar)]
1318 1339 if len( filesList ) > 0:
1319 1340 filesList = sorted(filesList, key=str.lower)
1320 1341 filen = filesList[-1]
1321 1342 # el filename debera tener el siguiente formato
1322 1343 # 0 1234 567 89A BCDE (hex)
1323 1344 # x YYYY DDD SSS .ext
1324 1345 if isNumber(filen[8:11]):
1325 1346 setFile = int(filen[8:11]) #inicializo mi contador de seteo al seteo del ultimo file
1326 1347 else:
1327 1348 setFile = -1
1328 1349 else:
1329 1350 setFile = -1 #inicializo mi contador de seteo
1330 1351 else:
1331 1352 os.makedirs(fullpath)
1332 1353 setFile = -1 #inicializo mi contador de seteo
1333 1354
1334 1355 if self.setType is None:
1335 1356 setFile += 1
1336 1357 file = '%s%4.4d%3.3d%03d%s' % (self.optchar,
1337 1358 timeTuple.tm_year,
1338 1359 timeTuple.tm_yday,
1339 1360 setFile,
1340 1361 ext )
1341 1362 else:
1342 1363 setFile = timeTuple.tm_hour*60+timeTuple.tm_min
1343 1364 file = '%s%4.4d%3.3d%04d%s' % (self.optchar,
1344 1365 timeTuple.tm_year,
1345 1366 timeTuple.tm_yday,
1346 1367 setFile,
1347 1368 ext )
1348 1369
1349 1370 self.filename = os.path.join( path, subfolder, file )
1350 1371
1351 1372 #Setting HDF5 File
1352 1373 self.fp = h5py.File(self.filename, 'w')
1353 1374 #write metadata
1354 1375 self.writeMetadata(self.fp)
1355 1376 #Write data
1356 1377 self.writeData(self.fp)
1357 1378
1358 1379 def writeMetadata(self, fp):
1359 1380
1360 1381 grp = fp.create_group("Metadata")
1361 1382 grp.create_dataset('variables', data=self.tableDim, dtype=self.dtype)
1362 1383
1363 1384 for i in range(len(self.metadataList)):
1364 1385 if not hasattr(self.dataOut, self.metadataList[i]):
1365 1386 log.warning('Metadata: `{}` not found'.format(self.metadataList[i]), self.name)
1366 1387 continue
1367 1388 value = getattr(self.dataOut, self.metadataList[i])
1368 1389 grp.create_dataset(self.metadataList[i], data=value)
1369 1390 return
1370 1391
1371 1392 def writeData(self, fp):
1372
1393
1373 1394 grp = fp.create_group("Data")
1374 1395 dtsets = []
1375 1396 data = []
1376
1397
1377 1398 for dsInfo in self.dsList:
1378 1399 if dsInfo['nDim'] == 0:
1379 1400 ds = grp.create_dataset(
1380 dsInfo['variable'],
1401 dsInfo['variable'],
1381 1402 (self.blocksPerFile, ),
1382 chunks=True,
1403 chunks=True,
1383 1404 dtype=numpy.float64)
1384 1405 dtsets.append(ds)
1385 1406 data.append((dsInfo['variable'], -1))
1386 1407 else:
1387 1408 sgrp = grp.create_group(dsInfo['variable'])
1388 1409 for i in range(dsInfo['dsNumber']):
1389 1410 ds = sgrp.create_dataset(
1390 'table{:02d}'.format(i),
1411 'table{:02d}'.format(i),
1391 1412 (self.blocksPerFile, ) + dsInfo['shape'][1:],
1392 1413 chunks=True)
1393 1414 dtsets.append(ds)
1394 1415 data.append((dsInfo['variable'], i))
1395 1416 fp.flush()
1396 1417
1397 1418 log.log('Creating file: {}'.format(fp.filename), self.name)
1398
1419
1399 1420 self.ds = dtsets
1400 1421 self.data = data
1401 1422 self.firsttime = True
1402 1423 self.blockIndex = 0
1403 1424 return
1404 1425
1405 1426 def putData(self):
1406 1427
1407 1428 if (self.blockIndex == self.blocksPerFile) or self.timeFlag():
1408 1429 self.closeFile()
1409 1430 self.setNextFile()
1410 1431
1411 1432 for i, ds in enumerate(self.ds):
1433 print(i,ds)
1412 1434 attr, ch = self.data[i]
1413 1435 if ch == -1:
1414 1436 ds[self.blockIndex] = getattr(self.dataOut, attr)
1415 1437 else:
1438 print(ch, getattr(self.dataOut, attr).shape)
1416 1439 ds[self.blockIndex] = getattr(self.dataOut, attr)[ch]
1417 1440
1418 1441 self.fp.flush()
1419 1442 self.blockIndex += 1
1420 1443 log.log('Block No. {}/{}'.format(self.blockIndex, self.blocksPerFile), self.name)
1421 1444
1422 1445 return
1423 1446
1424 1447 def closeFile(self):
1425 1448
1426 1449 if self.blockIndex != self.blocksPerFile:
1427 1450 for ds in self.ds:
1428 1451 ds.resize(self.blockIndex, axis=0)
1429 1452
1430 1453 self.fp.flush()
1431 1454 self.fp.close()
1432 1455
1433 1456 def close(self):
1434 1457
1435 1458 self.closeFile()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,1056 +1,1260
1 1 import itertools
2 2
3 3 import numpy
4 4
5 5 from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation
6 6 from schainpy.model.data.jrodata import Spectra
7 7 from schainpy.model.data.jrodata import hildebrand_sekhon
8 8 from schainpy.utils import log
9 9
10 10 @MPDecorator
11 11 class SpectraProc(ProcessingUnit):
12 12
13 13
14 14 def __init__(self):
15 15
16 16 ProcessingUnit.__init__(self)
17 17
18 18 self.buffer = None
19 19 self.firstdatatime = None
20 20 self.profIndex = 0
21 21 self.dataOut = Spectra()
22 22 self.id_min = None
23 23 self.id_max = None
24 24 self.setupReq = False #Agregar a todas las unidades de proc
25 25
26 26 def __updateSpecFromVoltage(self):
27 27
28 28 self.dataOut.timeZone = self.dataIn.timeZone
29 29 self.dataOut.dstFlag = self.dataIn.dstFlag
30 30 self.dataOut.errorCount = self.dataIn.errorCount
31 31 self.dataOut.useLocalTime = self.dataIn.useLocalTime
32 32 try:
33 33 self.dataOut.processingHeaderObj = self.dataIn.processingHeaderObj.copy()
34 34 except:
35 35 pass
36 36 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
37 37 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
38 38 self.dataOut.channelList = self.dataIn.channelList
39 39 self.dataOut.heightList = self.dataIn.heightList
40 40 self.dataOut.dtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
41 41
42 42 self.dataOut.nBaud = self.dataIn.nBaud
43 43 self.dataOut.nCode = self.dataIn.nCode
44 44 self.dataOut.code = self.dataIn.code
45 45 self.dataOut.nProfiles = self.dataOut.nFFTPoints
46 46
47 47 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
48 48 self.dataOut.utctime = self.firstdatatime
49 49 # asumo q la data esta decodificada
50 50 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData
51 51 # asumo q la data esta sin flip
52 52 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData
53 53 self.dataOut.flagShiftFFT = False
54 54
55 55 self.dataOut.nCohInt = self.dataIn.nCohInt
56 56 self.dataOut.nIncohInt = 1
57 57
58 58 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
59 59
60 60 self.dataOut.frequency = self.dataIn.frequency
61 61 self.dataOut.realtime = self.dataIn.realtime
62 62
63 63 self.dataOut.azimuth = self.dataIn.azimuth
64 64 self.dataOut.zenith = self.dataIn.zenith
65 65
66 66 self.dataOut.beam.codeList = self.dataIn.beam.codeList
67 67 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
68 68 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
69 69
70 70 def __getFft(self):
71 71 """
72 72 Convierte valores de Voltaje a Spectra
73 73
74 74 Affected:
75 75 self.dataOut.data_spc
76 76 self.dataOut.data_cspc
77 77 self.dataOut.data_dc
78 78 self.dataOut.heightList
79 79 self.profIndex
80 80 self.buffer
81 81 self.dataOut.flagNoData
82 82 """
83 83 fft_volt = numpy.fft.fft(
84 84 self.buffer, n=self.dataOut.nFFTPoints, axis=1)
85 85 fft_volt = fft_volt.astype(numpy.dtype('complex'))
86 86 dc = fft_volt[:, 0, :]
87 87
88 88 # calculo de self-spectra
89 89 fft_volt = numpy.fft.fftshift(fft_volt, axes=(1,))
90 90 spc = fft_volt * numpy.conjugate(fft_volt)
91 91 spc = spc.real
92 92
93 93 blocksize = 0
94 94 blocksize += dc.size
95 95 blocksize += spc.size
96 96
97 #print("spc :",spc.shape)
98 data_wr = None
99 if self.dataOut.flagWR:
100 data_wr = fft_volt
101 blocksize = fft_volt.size
102
97 103 cspc = None
98 104 pairIndex = 0
99 105 if self.dataOut.pairsList != None:
100 106 # calculo de cross-spectra
101 107 cspc = numpy.zeros(
102 108 (self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
103 109 for pair in self.dataOut.pairsList:
104 110 if pair[0] not in self.dataOut.channelList:
105 111 raise ValueError("Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" % (
106 112 str(pair), str(self.dataOut.channelList)))
107 113 if pair[1] not in self.dataOut.channelList:
108 114 raise ValueError("Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" % (
109 115 str(pair), str(self.dataOut.channelList)))
110 116
111 117 cspc[pairIndex, :, :] = fft_volt[pair[0], :, :] * \
112 118 numpy.conjugate(fft_volt[pair[1], :, :])
113 119 pairIndex += 1
114 120 blocksize += cspc.size
115 121
116 self.dataOut.data_spc = spc
117 self.dataOut.data_cspc = cspc
118 self.dataOut.data_dc = dc
119 self.dataOut.blockSize = blocksize
122 self.dataOut.data_spc = spc
123 self.dataOut.data_cspc = cspc
124 self.dataOut.data_wr = data_wr
125 self.dataOut.data_dc = dc
126 self.dataOut.blockSize = blocksize
120 127 self.dataOut.flagShiftFFT = False
121 128
122 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None, shift_fft=False):
129 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None, shift_fft=False,flagWR= 0):
130
131 self.dataOut.flagWR = flagWR
123 132
124 133 if self.dataIn.type == "Spectra":
125 134 self.dataOut.copy(self.dataIn)
135
126 136 if shift_fft:
127 137 #desplaza a la derecha en el eje 2 determinadas posiciones
128 138 shift = int(self.dataOut.nFFTPoints/2)
129 139 self.dataOut.data_spc = numpy.roll(self.dataOut.data_spc, shift , axis=1)
130 140
131 141 if self.dataOut.data_cspc is not None:
132 142 #desplaza a la derecha en el eje 2 determinadas posiciones
133 143 self.dataOut.data_cspc = numpy.roll(self.dataOut.data_cspc, shift, axis=1)
134 144
135 145 return True
136 146
137 147 if self.dataIn.type == "Voltage":
138
148 #print("VOLTAGE INPUT SPECTRA")
139 149 self.dataOut.flagNoData = True
140 150
141 151 if nFFTPoints == None:
142 152 raise ValueError("This SpectraProc.run() need nFFTPoints input variable")
143 153
144 154 if nProfiles == None:
145 155 nProfiles = nFFTPoints
146 156
147 157 if ippFactor == None:
148 158 ippFactor = 1
149 159
150 160 self.dataOut.ippFactor = ippFactor
151 161
152 162 self.dataOut.nFFTPoints = nFFTPoints
153 163 self.dataOut.pairsList = pairsList
154 164
155 165 if self.buffer is None:
156 166 self.buffer = numpy.zeros((self.dataIn.nChannels,
157 167 nProfiles,
158 168 self.dataIn.nHeights),
159 169 dtype='complex')
170 #print("buffer :",self.buffer.shape)
160 171
161 172 if self.dataIn.flagDataAsBlock:
162 173 nVoltProfiles = self.dataIn.data.shape[1]
163 174
164 175 if nVoltProfiles == nProfiles:
165 176 self.buffer = self.dataIn.data.copy()
166 177 self.profIndex = nVoltProfiles
167 178
168 179 elif nVoltProfiles < nProfiles:
169 180
170 181 if self.profIndex == 0:
171 182 self.id_min = 0
172 183 self.id_max = nVoltProfiles
173 184
174 185 self.buffer[:, self.id_min:self.id_max,
175 186 :] = self.dataIn.data
176 187 self.profIndex += nVoltProfiles
177 188 self.id_min += nVoltProfiles
178 189 self.id_max += nVoltProfiles
179 190 else:
180 191 raise ValueError("The type object %s has %d profiles, it should just has %d profiles" % (
181 192 self.dataIn.type, self.dataIn.data.shape[1], nProfiles))
182 193 self.dataOut.flagNoData = True
183 194 return 0
184 195 else:
196 #print("Spectra ",self.profIndex)
185 197 self.buffer[:, self.profIndex, :] = self.dataIn.data.copy()
186 198 self.profIndex += 1
187 199
188 200 if self.firstdatatime == None:
189 201 self.firstdatatime = self.dataIn.utctime
190 202
191 203 if self.profIndex == nProfiles:
192 204 self.__updateSpecFromVoltage()
193 205 self.__getFft()
206 #print(" DATAOUT SHAPE SPEC",self.dataOut.data_spc.shape)
194 207
195 208 self.dataOut.flagNoData = False
196 209 self.firstdatatime = None
197 210 self.profIndex = 0
198 211
199 212 return True
200 213
201 214 raise ValueError("The type of input object '%s' is not valid" % (
202 215 self.dataIn.type))
203 216
204 217 def __selectPairs(self, pairsList):
205 218
206 219 if not pairsList:
207 220 return
208 221
209 222 pairs = []
210 223 pairsIndex = []
211 224
212 225 for pair in pairsList:
213 226 if pair[0] not in self.dataOut.channelList or pair[1] not in self.dataOut.channelList:
214 227 continue
215 228 pairs.append(pair)
216 229 pairsIndex.append(pairs.index(pair))
217 230
218 231 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndex]
219 232 self.dataOut.pairsList = pairs
220 233
221 234 return
222 235
223 236 def __selectPairsByChannel(self, channelList=None):
224 237
225 238 if channelList == None:
226 239 return
227 240
228 241 pairsIndexListSelected = []
229 242 for pairIndex in self.dataOut.pairsIndexList:
230 243 # First pair
231 244 if self.dataOut.pairsList[pairIndex][0] not in channelList:
232 245 continue
233 246 # Second pair
234 247 if self.dataOut.pairsList[pairIndex][1] not in channelList:
235 248 continue
236 249
237 250 pairsIndexListSelected.append(pairIndex)
238 251
239 252 if not pairsIndexListSelected:
240 253 self.dataOut.data_cspc = None
241 254 self.dataOut.pairsList = []
242 255 return
243 256
244 257 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
245 258 self.dataOut.pairsList = [self.dataOut.pairsList[i]
246 259 for i in pairsIndexListSelected]
247 260
248 261 return
249 262
250 263 def selectChannels(self, channelList):
251 264
252 265 channelIndexList = []
253 266
254 267 for channel in channelList:
255 268 if channel not in self.dataOut.channelList:
256 269 raise ValueError("Error selecting channels, Channel %d is not valid.\nAvailable channels = %s" % (
257 270 channel, str(self.dataOut.channelList)))
258 271
259 272 index = self.dataOut.channelList.index(channel)
260 273 channelIndexList.append(index)
261 274
262 275 self.selectChannelsByIndex(channelIndexList)
263 276
264 277 def selectChannelsByIndex(self, channelIndexList):
265 278 """
266 279 Selecciona un bloque de datos en base a canales segun el channelIndexList
267 280
268 281 Input:
269 282 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
270 283
271 284 Affected:
272 285 self.dataOut.data_spc
273 286 self.dataOut.channelIndexList
274 287 self.dataOut.nChannels
275 288
276 289 Return:
277 290 None
278 291 """
279 292
280 293 for channelIndex in channelIndexList:
281 294 if channelIndex not in self.dataOut.channelIndexList:
282 295 raise ValueError("Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " % (
283 296 channelIndex, self.dataOut.channelIndexList))
284 297
285 298 data_spc = self.dataOut.data_spc[channelIndexList, :]
286 299 data_dc = self.dataOut.data_dc[channelIndexList, :]
287 300
288 301 self.dataOut.data_spc = data_spc
289 302 self.dataOut.data_dc = data_dc
290 303
291 304 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
292 305 self.dataOut.channelList = range(len(channelIndexList))
293 306 self.__selectPairsByChannel(channelIndexList)
294
307
295 308 return 1
296
297
309
310
298 311 def selectFFTs(self, minFFT, maxFFT ):
299 312 """
300 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
313 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
301 314 minFFT<= FFT <= maxFFT
302 315 """
303
316
304 317 if (minFFT > maxFFT):
305 318 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT))
306 319
307 320 if (minFFT < self.dataOut.getFreqRange()[0]):
308 321 minFFT = self.dataOut.getFreqRange()[0]
309 322
310 323 if (maxFFT > self.dataOut.getFreqRange()[-1]):
311 324 maxFFT = self.dataOut.getFreqRange()[-1]
312 325
313 326 minIndex = 0
314 327 maxIndex = 0
315 328 FFTs = self.dataOut.getFreqRange()
316 329
317 330 inda = numpy.where(FFTs >= minFFT)
318 331 indb = numpy.where(FFTs <= maxFFT)
319 332
320 333 try:
321 334 minIndex = inda[0][0]
322 335 except:
323 336 minIndex = 0
324 337
325 338 try:
326 339 maxIndex = indb[0][-1]
327 340 except:
328 341 maxIndex = len(FFTs)
329 342
330 343 self.selectFFTsByIndex(minIndex, maxIndex)
331 344
332 345 return 1
333
334
346
347
335 348 def setH0(self, h0, deltaHeight = None):
336
349
337 350 if not deltaHeight:
338 351 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
339
352
340 353 nHeights = self.dataOut.nHeights
341
354
342 355 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
343
356
344 357 self.dataOut.heightList = newHeiRange
345
346
358
359
347 360 def selectHeights(self, minHei, maxHei):
348 361 """
349 362 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
350 363 minHei <= height <= maxHei
351 364
352 365 Input:
353 366 minHei : valor minimo de altura a considerar
354 367 maxHei : valor maximo de altura a considerar
355 368
356 369 Affected:
357 370 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
358 371
359 372 Return:
360 373 1 si el metodo se ejecuto con exito caso contrario devuelve 0
361 374 """
362 375
363
376
364 377 if (minHei > maxHei):
365 378 raise ValueError("Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei))
366 379
367 380 if (minHei < self.dataOut.heightList[0]):
368 381 minHei = self.dataOut.heightList[0]
369 382
370 383 if (maxHei > self.dataOut.heightList[-1]):
371 384 maxHei = self.dataOut.heightList[-1]
372 385
373 386 minIndex = 0
374 387 maxIndex = 0
375 388 heights = self.dataOut.heightList
376 389
377 390 inda = numpy.where(heights >= minHei)
378 391 indb = numpy.where(heights <= maxHei)
379 392
380 393 try:
381 394 minIndex = inda[0][0]
382 395 except:
383 396 minIndex = 0
384 397
385 398 try:
386 399 maxIndex = indb[0][-1]
387 400 except:
388 401 maxIndex = len(heights)
389 402
390 403 self.selectHeightsByIndex(minIndex, maxIndex)
391
404
392 405
393 406 return 1
394 407
395 408 def getBeaconSignal(self, tauindex=0, channelindex=0, hei_ref=None):
396 409 newheis = numpy.where(
397 410 self.dataOut.heightList > self.dataOut.radarControllerHeaderObj.Taus[tauindex])
398 411
399 412 if hei_ref != None:
400 413 newheis = numpy.where(self.dataOut.heightList > hei_ref)
401 414
402 415 minIndex = min(newheis[0])
403 416 maxIndex = max(newheis[0])
404 417 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
405 418 heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
406 419
407 420 # determina indices
408 421 nheis = int(self.dataOut.radarControllerHeaderObj.txB /
409 422 (self.dataOut.heightList[1] - self.dataOut.heightList[0]))
410 423 avg_dB = 10 * \
411 424 numpy.log10(numpy.sum(data_spc[channelindex, :, :], axis=0))
412 425 beacon_dB = numpy.sort(avg_dB)[-nheis:]
413 426 beacon_heiIndexList = []
414 427 for val in avg_dB.tolist():
415 428 if val >= beacon_dB[0]:
416 429 beacon_heiIndexList.append(avg_dB.tolist().index(val))
417 430
418 431 #data_spc = data_spc[:,:,beacon_heiIndexList]
419 432 data_cspc = None
420 433 if self.dataOut.data_cspc is not None:
421 434 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
422 435 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
423 436
424 437 data_dc = None
425 438 if self.dataOut.data_dc is not None:
426 439 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
427 440 #data_dc = data_dc[:,beacon_heiIndexList]
428 441
429 442 self.dataOut.data_spc = data_spc
430 443 self.dataOut.data_cspc = data_cspc
431 444 self.dataOut.data_dc = data_dc
432 445 self.dataOut.heightList = heightList
433 446 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
434 447
435 448 return 1
436 449
437 450 def selectFFTsByIndex(self, minIndex, maxIndex):
438 451 """
439
452
440 453 """
441 454
442 455 if (minIndex < 0) or (minIndex > maxIndex):
443 456 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex))
444 457
445 458 if (maxIndex >= self.dataOut.nProfiles):
446 459 maxIndex = self.dataOut.nProfiles-1
447 460
448 461 #Spectra
449 462 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
450 463
451 464 data_cspc = None
452 465 if self.dataOut.data_cspc is not None:
453 466 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
454 467
455 468 data_dc = None
456 469 if self.dataOut.data_dc is not None:
457 470 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
458 471
459 472 self.dataOut.data_spc = data_spc
460 473 self.dataOut.data_cspc = data_cspc
461 474 self.dataOut.data_dc = data_dc
462
475
463 476 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
464 477 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
465 478 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
466 479
467 480 return 1
468 481
469 482
470 483
471 484 def selectHeightsByIndex(self, minIndex, maxIndex):
472 485 """
473 486 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
474 487 minIndex <= index <= maxIndex
475 488
476 489 Input:
477 490 minIndex : valor de indice minimo de altura a considerar
478 491 maxIndex : valor de indice maximo de altura a considerar
479 492
480 493 Affected:
481 494 self.dataOut.data_spc
482 495 self.dataOut.data_cspc
483 496 self.dataOut.data_dc
484 497 self.dataOut.heightList
485 498
486 499 Return:
487 500 1 si el metodo se ejecuto con exito caso contrario devuelve 0
488 501 """
489 502
490 503 if (minIndex < 0) or (minIndex > maxIndex):
491 504 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
492 505 minIndex, maxIndex))
493 506
494 507 if (maxIndex >= self.dataOut.nHeights):
495 508 maxIndex = self.dataOut.nHeights - 1
496 509
497 510 # Spectra
498 511 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
499 512
500 513 data_cspc = None
501 514 if self.dataOut.data_cspc is not None:
502 515 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
503 516
504 517 data_dc = None
505 518 if self.dataOut.data_dc is not None:
506 519 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
507 520
508 521 self.dataOut.data_spc = data_spc
509 522 self.dataOut.data_cspc = data_cspc
510 523 self.dataOut.data_dc = data_dc
511 524
512 525 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
513 526
514 527 return 1
515 528
516 529 def removeDC(self, mode=2):
517 530 jspectra = self.dataOut.data_spc
518 531 jcspectra = self.dataOut.data_cspc
519 532
520 533 num_chan = jspectra.shape[0]
521 534 num_hei = jspectra.shape[2]
522 535
523 536 if jcspectra is not None:
524 537 jcspectraExist = True
525 538 num_pairs = jcspectra.shape[0]
526 539 else:
527 540 jcspectraExist = False
528 541
529 542 freq_dc = int(jspectra.shape[1] / 2)
530 543 ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
531 544 ind_vel = ind_vel.astype(int)
532 545
533 546 if ind_vel[0] < 0:
534 547 ind_vel[list(range(0, 1))] = ind_vel[list(range(0, 1))] + self.num_prof
535 548
536 549 if mode == 1:
537 550 jspectra[:, freq_dc, :] = (
538 551 jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
539 552
540 553 if jcspectraExist:
541 554 jcspectra[:, freq_dc, :] = (
542 555 jcspectra[:, ind_vel[1], :] + jcspectra[:, ind_vel[2], :]) / 2
543 556
544 557 if mode == 2:
545 558
546 559 vel = numpy.array([-2, -1, 1, 2])
547 560 xx = numpy.zeros([4, 4])
548 561
549 562 for fil in range(4):
550 563 xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
551 564
552 565 xx_inv = numpy.linalg.inv(xx)
553 566 xx_aux = xx_inv[0, :]
554 567
555 for ich in range(num_chan):
568 for ich in range(num_chan):
556 569 yy = jspectra[ich, ind_vel, :]
557 570 jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
558 571
559 572 junkid = jspectra[ich, freq_dc, :] <= 0
560 573 cjunkid = sum(junkid)
561 574
562 575 if cjunkid.any():
563 576 jspectra[ich, freq_dc, junkid.nonzero()] = (
564 577 jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
565 578
566 579 if jcspectraExist:
567 580 for ip in range(num_pairs):
568 581 yy = jcspectra[ip, ind_vel, :]
569 582 jcspectra[ip, freq_dc, :] = numpy.dot(xx_aux, yy)
570 583
571 584 self.dataOut.data_spc = jspectra
572 585 self.dataOut.data_cspc = jcspectra
573 586
574 587 return 1
575 588
576 589 def removeInterference2(self):
577
590
578 591 cspc = self.dataOut.data_cspc
579 592 spc = self.dataOut.data_spc
580 Heights = numpy.arange(cspc.shape[2])
593 Heights = numpy.arange(cspc.shape[2])
581 594 realCspc = numpy.abs(cspc)
582
595
583 596 for i in range(cspc.shape[0]):
584 597 LinePower= numpy.sum(realCspc[i], axis=0)
585 598 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
586 599 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
587 600 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
588 601 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
589 602 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
590
591
603
604
592 605 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
593 606 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
594 607 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
595 608 cspc[i,InterferenceRange,:] = numpy.NaN
596
597
598
609
610
611
599 612 self.dataOut.data_cspc = cspc
600
613
601 614 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
602 615
603 616 jspectra = self.dataOut.data_spc
604 617 jcspectra = self.dataOut.data_cspc
605 618 jnoise = self.dataOut.getNoise()
606 619 num_incoh = self.dataOut.nIncohInt
607 620
608 621 num_channel = jspectra.shape[0]
609 622 num_prof = jspectra.shape[1]
610 623 num_hei = jspectra.shape[2]
611 624
612 625 # hei_interf
613 626 if hei_interf is None:
614 627 count_hei = int(num_hei / 2)
615 628 hei_interf = numpy.asmatrix(list(range(count_hei))) + num_hei - count_hei
616 629 hei_interf = numpy.asarray(hei_interf)[0]
617 630 # nhei_interf
618 631 if (nhei_interf == None):
619 632 nhei_interf = 5
620 633 if (nhei_interf < 1):
621 634 nhei_interf = 1
622 635 if (nhei_interf > count_hei):
623 636 nhei_interf = count_hei
624 637 if (offhei_interf == None):
625 638 offhei_interf = 0
626 639
627 640 ind_hei = list(range(num_hei))
628 641 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
629 642 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
630 643 mask_prof = numpy.asarray(list(range(num_prof)))
631 644 num_mask_prof = mask_prof.size
632 645 comp_mask_prof = [0, num_prof / 2]
633 646
634 647 # noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
635 648 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
636 649 jnoise = numpy.nan
637 650 noise_exist = jnoise[0] < numpy.Inf
638 651
639 652 # Subrutina de Remocion de la Interferencia
640 653 for ich in range(num_channel):
641 654 # Se ordena los espectros segun su potencia (menor a mayor)
642 655 power = jspectra[ich, mask_prof, :]
643 656 power = power[:, hei_interf]
644 657 power = power.sum(axis=0)
645 658 psort = power.ravel().argsort()
646 659
647 660 # Se estima la interferencia promedio en los Espectros de Potencia empleando
648 661 junkspc_interf = jspectra[ich, :, hei_interf[psort[list(range(
649 662 offhei_interf, nhei_interf + offhei_interf))]]]
650 663
651 664 if noise_exist:
652 665 # tmp_noise = jnoise[ich] / num_prof
653 666 tmp_noise = jnoise[ich]
654 667 junkspc_interf = junkspc_interf - tmp_noise
655 668 #junkspc_interf[:,comp_mask_prof] = 0
656 669
657 670 jspc_interf = junkspc_interf.sum(axis=0) / nhei_interf
658 671 jspc_interf = jspc_interf.transpose()
659 672 # Calculando el espectro de interferencia promedio
660 673 noiseid = numpy.where(
661 674 jspc_interf <= tmp_noise / numpy.sqrt(num_incoh))
662 675 noiseid = noiseid[0]
663 676 cnoiseid = noiseid.size
664 677 interfid = numpy.where(
665 678 jspc_interf > tmp_noise / numpy.sqrt(num_incoh))
666 679 interfid = interfid[0]
667 680 cinterfid = interfid.size
668 681
669 682 if (cnoiseid > 0):
670 683 jspc_interf[noiseid] = 0
671 684
672 685 # Expandiendo los perfiles a limpiar
673 686 if (cinterfid > 0):
674 687 new_interfid = (
675 688 numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof) % num_prof
676 689 new_interfid = numpy.asarray(new_interfid)
677 690 new_interfid = {x for x in new_interfid}
678 691 new_interfid = numpy.array(list(new_interfid))
679 692 new_cinterfid = new_interfid.size
680 693 else:
681 694 new_cinterfid = 0
682 695
683 696 for ip in range(new_cinterfid):
684 697 ind = junkspc_interf[:, new_interfid[ip]].ravel().argsort()
685 698 jspc_interf[new_interfid[ip]
686 699 ] = junkspc_interf[ind[nhei_interf // 2], new_interfid[ip]]
687 700
688 701 jspectra[ich, :, ind_hei] = jspectra[ich, :,
689 702 ind_hei] - jspc_interf # Corregir indices
690 703
691 704 # Removiendo la interferencia del punto de mayor interferencia
692 705 ListAux = jspc_interf[mask_prof].tolist()
693 706 maxid = ListAux.index(max(ListAux))
694 707
695 708 if cinterfid > 0:
696 709 for ip in range(cinterfid * (interf == 2) - 1):
697 710 ind = (jspectra[ich, interfid[ip], :] < tmp_noise *
698 711 (1 + 1 / numpy.sqrt(num_incoh))).nonzero()
699 712 cind = len(ind)
700 713
701 714 if (cind > 0):
702 715 jspectra[ich, interfid[ip], ind] = tmp_noise * \
703 716 (1 + (numpy.random.uniform(cind) - 0.5) /
704 717 numpy.sqrt(num_incoh))
705 718
706 719 ind = numpy.array([-2, -1, 1, 2])
707 720 xx = numpy.zeros([4, 4])
708 721
709 722 for id1 in range(4):
710 723 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
711 724
712 725 xx_inv = numpy.linalg.inv(xx)
713 726 xx = xx_inv[:, 0]
714 727 ind = (ind + maxid + num_mask_prof) % num_mask_prof
715 728 yy = jspectra[ich, mask_prof[ind], :]
716 729 jspectra[ich, mask_prof[maxid], :] = numpy.dot(
717 730 yy.transpose(), xx)
718 731
719 732 indAux = (jspectra[ich, :, :] < tmp_noise *
720 733 (1 - 1 / numpy.sqrt(num_incoh))).nonzero()
721 734 jspectra[ich, indAux[0], indAux[1]] = tmp_noise * \
722 735 (1 - 1 / numpy.sqrt(num_incoh))
723 736
724 737 # Remocion de Interferencia en el Cross Spectra
725 738 if jcspectra is None:
726 739 return jspectra, jcspectra
727 740 num_pairs = int(jcspectra.size / (num_prof * num_hei))
728 741 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
729 742
730 743 for ip in range(num_pairs):
731 744
732 745 #-------------------------------------------
733 746
734 747 cspower = numpy.abs(jcspectra[ip, mask_prof, :])
735 748 cspower = cspower[:, hei_interf]
736 749 cspower = cspower.sum(axis=0)
737 750
738 751 cspsort = cspower.ravel().argsort()
739 752 junkcspc_interf = jcspectra[ip, :, hei_interf[cspsort[list(range(
740 753 offhei_interf, nhei_interf + offhei_interf))]]]
741 754 junkcspc_interf = junkcspc_interf.transpose()
742 755 jcspc_interf = junkcspc_interf.sum(axis=1) / nhei_interf
743 756
744 757 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
745 758
746 759 median_real = int(numpy.median(numpy.real(
747 760 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
748 761 median_imag = int(numpy.median(numpy.imag(
749 762 junkcspc_interf[mask_prof[ind[list(range(3 * num_prof // 4))]], :])))
750 763 comp_mask_prof = [int(e) for e in comp_mask_prof]
751 764 junkcspc_interf[comp_mask_prof, :] = numpy.complex(
752 765 median_real, median_imag)
753 766
754 767 for iprof in range(num_prof):
755 768 ind = numpy.abs(junkcspc_interf[iprof, :]).ravel().argsort()
756 769 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf // 2]]
757 770
758 771 # Removiendo la Interferencia
759 772 jcspectra[ip, :, ind_hei] = jcspectra[ip,
760 773 :, ind_hei] - jcspc_interf
761 774
762 775 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
763 776 maxid = ListAux.index(max(ListAux))
764 777
765 778 ind = numpy.array([-2, -1, 1, 2])
766 779 xx = numpy.zeros([4, 4])
767 780
768 781 for id1 in range(4):
769 782 xx[:, id1] = ind[id1]**numpy.asarray(list(range(4)))
770 783
771 784 xx_inv = numpy.linalg.inv(xx)
772 785 xx = xx_inv[:, 0]
773 786
774 787 ind = (ind + maxid + num_mask_prof) % num_mask_prof
775 788 yy = jcspectra[ip, mask_prof[ind], :]
776 789 jcspectra[ip, mask_prof[maxid], :] = numpy.dot(yy.transpose(), xx)
777 790
778 791 # Guardar Resultados
779 792 self.dataOut.data_spc = jspectra
780 793 self.dataOut.data_cspc = jcspectra
781 794
782 795 return 1
783 796
784 797 def setRadarFrequency(self, frequency=None):
785 798
786 799 if frequency != None:
787 800 self.dataOut.frequency = frequency
788 801
789 802 return 1
790 803
791 804 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
792 805 # validacion de rango
793 806 if minHei == None:
794 807 minHei = self.dataOut.heightList[0]
795 808
796 809 if maxHei == None:
797 810 maxHei = self.dataOut.heightList[-1]
798 811
799 812 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
800 813 print('minHei: %.2f is out of the heights range' % (minHei))
801 814 print('minHei is setting to %.2f' % (self.dataOut.heightList[0]))
802 815 minHei = self.dataOut.heightList[0]
803 816
804 817 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
805 818 print('maxHei: %.2f is out of the heights range' % (maxHei))
806 819 print('maxHei is setting to %.2f' % (self.dataOut.heightList[-1]))
807 820 maxHei = self.dataOut.heightList[-1]
808 821
809 822 # validacion de velocidades
810 823 velrange = self.dataOut.getVelRange(1)
811 824
812 825 if minVel == None:
813 826 minVel = velrange[0]
814 827
815 828 if maxVel == None:
816 829 maxVel = velrange[-1]
817 830
818 831 if (minVel < velrange[0]) or (minVel > maxVel):
819 832 print('minVel: %.2f is out of the velocity range' % (minVel))
820 833 print('minVel is setting to %.2f' % (velrange[0]))
821 834 minVel = velrange[0]
822 835
823 836 if (maxVel > velrange[-1]) or (maxVel < minVel):
824 837 print('maxVel: %.2f is out of the velocity range' % (maxVel))
825 838 print('maxVel is setting to %.2f' % (velrange[-1]))
826 839 maxVel = velrange[-1]
827 840
828 841 # seleccion de indices para rango
829 842 minIndex = 0
830 843 maxIndex = 0
831 844 heights = self.dataOut.heightList
832 845
833 846 inda = numpy.where(heights >= minHei)
834 847 indb = numpy.where(heights <= maxHei)
835 848
836 849 try:
837 850 minIndex = inda[0][0]
838 851 except:
839 852 minIndex = 0
840 853
841 854 try:
842 855 maxIndex = indb[0][-1]
843 856 except:
844 857 maxIndex = len(heights)
845 858
846 859 if (minIndex < 0) or (minIndex > maxIndex):
847 860 raise ValueError("some value in (%d,%d) is not valid" % (
848 861 minIndex, maxIndex))
849 862
850 863 if (maxIndex >= self.dataOut.nHeights):
851 864 maxIndex = self.dataOut.nHeights - 1
852 865
853 866 # seleccion de indices para velocidades
854 867 indminvel = numpy.where(velrange >= minVel)
855 868 indmaxvel = numpy.where(velrange <= maxVel)
856 869 try:
857 870 minIndexVel = indminvel[0][0]
858 871 except:
859 872 minIndexVel = 0
860 873
861 874 try:
862 875 maxIndexVel = indmaxvel[0][-1]
863 876 except:
864 877 maxIndexVel = len(velrange)
865 878
866 879 # seleccion del espectro
867 880 data_spc = self.dataOut.data_spc[:,
868 881 minIndexVel:maxIndexVel + 1, minIndex:maxIndex + 1]
869 882 # estimacion de ruido
870 883 noise = numpy.zeros(self.dataOut.nChannels)
871 884
872 885 for channel in range(self.dataOut.nChannels):
873 886 daux = data_spc[channel, :, :]
874 887 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
875 888
876 889 self.dataOut.noise_estimation = noise.copy()
877 890
878 891 return 1
879 892
880 893
881 894 class IncohInt(Operation):
882 895
883 896 __profIndex = 0
884 897 __withOverapping = False
885 898
886 899 __byTime = False
887 900 __initime = None
888 901 __lastdatatime = None
889 902 __integrationtime = None
890 903
891 904 __buffer_spc = None
892 905 __buffer_cspc = None
893 906 __buffer_dc = None
894 907
895 908 __dataReady = False
896 909
897 910 __timeInterval = None
898 911
899 912 n = None
900 913
901 914 def __init__(self):
902 915
903 916 Operation.__init__(self)
904 917
905 918 def setup(self, n=None, timeInterval=None, overlapping=False):
906 919 """
907 920 Set the parameters of the integration class.
908 921
909 922 Inputs:
910 923
911 924 n : Number of coherent integrations
912 925 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
913 926 overlapping :
914 927
915 928 """
916 929
917 930 self.__initime = None
918 931 self.__lastdatatime = 0
919 932
920 933 self.__buffer_spc = 0
921 934 self.__buffer_cspc = 0
922 935 self.__buffer_dc = 0
923 936
924 937 self.__profIndex = 0
925 938 self.__dataReady = False
926 939 self.__byTime = False
927 940
928 941 if n is None and timeInterval is None:
929 942 raise ValueError("n or timeInterval should be specified ...")
930 943
931 944 if n is not None:
932 945 self.n = int(n)
933 946 else:
934
947
935 948 self.__integrationtime = int(timeInterval)
936 949 self.n = None
937 950 self.__byTime = True
938 951
939 952 def putData(self, data_spc, data_cspc, data_dc):
940 953 """
941 954 Add a profile to the __buffer_spc and increase in one the __profileIndex
942 955
943 956 """
957 print("profIndex: ",self.__profIndex)
958 print("data_spc.shape: ",data_spc.shape)
959 print("data_spc.shape: ",data_spc[0,0,:])
944 960
945 961 self.__buffer_spc += data_spc
946 962
947 963 if data_cspc is None:
948 964 self.__buffer_cspc = None
949 965 else:
950 966 self.__buffer_cspc += data_cspc
951 967
952 968 if data_dc is None:
953 969 self.__buffer_dc = None
954 970 else:
955 971 self.__buffer_dc += data_dc
956 972
957 973 self.__profIndex += 1
958 974
959 975 return
960 976
961 977 def pushData(self):
962 978 """
963 979 Return the sum of the last profiles and the profiles used in the sum.
964 980
965 981 Affected:
966 982
967 983 self.__profileIndex
968 984
969 985 """
970 986
971 987 data_spc = self.__buffer_spc
972 988 data_cspc = self.__buffer_cspc
973 989 data_dc = self.__buffer_dc
974 990 n = self.__profIndex
975 991
976 992 self.__buffer_spc = 0
977 993 self.__buffer_cspc = 0
978 994 self.__buffer_dc = 0
979 995 self.__profIndex = 0
980 996
981 997 return data_spc, data_cspc, data_dc, n
982 998
983 999 def byProfiles(self, *args):
984 1000
985 1001 self.__dataReady = False
986 1002 avgdata_spc = None
987 1003 avgdata_cspc = None
988 1004 avgdata_dc = None
989 1005
990 1006 self.putData(*args)
991 1007
992 1008 if self.__profIndex == self.n:
993 1009
994 1010 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
995 1011 self.n = n
996 1012 self.__dataReady = True
997 1013
998 1014 return avgdata_spc, avgdata_cspc, avgdata_dc
999 1015
1000 1016 def byTime(self, datatime, *args):
1001 1017
1002 1018 self.__dataReady = False
1003 1019 avgdata_spc = None
1004 1020 avgdata_cspc = None
1005 1021 avgdata_dc = None
1006 1022
1007 1023 self.putData(*args)
1008 1024
1009 1025 if (datatime - self.__initime) >= self.__integrationtime:
1010 1026 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1011 1027 self.n = n
1012 1028 self.__dataReady = True
1013 1029
1014 1030 return avgdata_spc, avgdata_cspc, avgdata_dc
1015 1031
1016 1032 def integrate(self, datatime, *args):
1017 1033
1018 1034 if self.__profIndex == 0:
1019 1035 self.__initime = datatime
1020 1036
1021 1037 if self.__byTime:
1022 1038 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(
1023 1039 datatime, *args)
1024 1040 else:
1025 1041 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1026 1042
1027 1043 if not self.__dataReady:
1028 1044 return None, None, None, None
1029 1045
1030 1046 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
1031 1047
1032 1048 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1033 1049 if n == 1:
1034 1050 return
1035
1051
1036 1052 dataOut.flagNoData = True
1037 1053
1038 1054 if not self.isConfig:
1039 1055 self.setup(n, timeInterval, overlapping)
1040 1056 self.isConfig = True
1041 1057
1042 1058 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1043 1059 dataOut.data_spc,
1044 1060 dataOut.data_cspc,
1045 1061 dataOut.data_dc)
1046 1062
1047 1063 if self.__dataReady:
1048 1064
1049 1065 dataOut.data_spc = avgdata_spc
1050 1066 dataOut.data_cspc = avgdata_cspc
1051 dataOut.data_dc = avgdata_dc
1067 dataOut.data_dc = avgdata_dc
1052 1068 dataOut.nIncohInt *= self.n
1053 1069 dataOut.utctime = avgdatatime
1054 1070 dataOut.flagNoData = False
1055 1071
1056 return dataOut No newline at end of file
1072 return dataOut
1073
1074
1075 class PulsePair(Operation):
1076 isConfig = False
1077 __profIndex = 0
1078 __profIndex2 = 0
1079 __initime = None
1080 __lastdatatime = None
1081 __buffer = None
1082 __buffer2 = []
1083 __buffer3 = None
1084 __dataReady = False
1085 n = None
1086
1087 __nch =0
1088 __nProf =0
1089 __nHeis =0
1090
1091 def __init__(self,**kwargs):
1092 Operation.__init__(self,**kwargs)
1093
1094 def setup(self,dataOut,n =None, m = None):
1095
1096 self.__initime = None
1097 self.__lastdatatime = 0
1098 self.__buffer = 0
1099 self.__bufferV = 0
1100 #self.__buffer2 = []
1101 self.__buffer3 = 0
1102 self.__dataReady = False
1103 self.__profIndex = 0
1104 self.__profIndex2 = 0
1105 self.count = 0
1106
1107
1108 self.__nch = dataOut.nChannels
1109 self.__nHeis = dataOut.nHeights
1110 self.__nProf = dataOut.nProfiles
1111 self.__nFFT = dataOut.nFFTPoints
1112 #print("Valores de Ch,Samples,Perfiles,nFFT",self.__nch,self.__nHeis,self.__nProf, self.__nFFT)
1113 #print("EL VALOR DE n es:",n)
1114 if n == None:
1115 raise ValueError("n Should be specified.")
1116
1117 if n != None:
1118 if n<2:
1119 raise ValueError("n Should be greather than 2 ")
1120 self.n = n
1121 if m == None:
1122 m = n
1123 if m != None:
1124 if m<2:
1125 raise ValueError("n Should be greather than 2 ")
1126
1127 self.m = m
1128 self.__buffer2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1129 self.__bufferV2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1130
1131
1132
1133 def putData(self,data):
1134 #print("###################################################")
1135 '''
1136 data_tmp = numpy.zeros(self.__nch,self.n,self.__nHeis, dtype= complex)
1137 if self.count < self.__nProf:
1138
1139 for i in range(self.n):
1140 data_tmp[:,i,:] = data[:,i+self.count,:]
1141
1142 self.__buffer = data_tmp*numpy.conjugate(data_tmp)
1143
1144
1145 #####self.__buffer = data*numpy.conjugate(data)
1146 #####self.__bufferV = data[:,(self.__nProf-1):,:]*numpy.conjugate(data[:,1:,:])
1147
1148 #self.__buffer2.append(numpy.conjugate(data))
1149
1150 #####self.__profIndex = data.shape[1]
1151 self.count = self.count + self.n -1
1152 self.__profIndex = self.n
1153 '''
1154 self.__buffer = data*numpy.conjugate(data)
1155 self.__bufferV = data[:,(self.__nProf-1):,:]*numpy.conjugate(data[:,1:,:])
1156 self.__profIndex = self.n
1157 return
1158
1159 def pushData(self):
1160
1161 data_I = numpy.zeros((self.__nch,self.__nHeis))
1162 data_IV = numpy.zeros((self.__nch,self.__nHeis))
1163
1164 for i in range(self.__nch):
1165 data_I[i,:] = numpy.sum(numpy.sum(self.__buffer[i],axis=0),axis=0)/self.n
1166 data_IV[i,:] = numpy.sum(numpy.sum(self.__bufferV[i],axis=0),axis=0)/(self.n-1)
1167
1168 n = self.__profIndex
1169 ####data_intensity = numpy.sum(numpy.sum(self.__buffer,axis=0),axis=0)/self.n
1170 #print("data_intensity push data",data_intensity.shape)
1171 #data_velocity = self.__buffer3/(self.n-1)
1172 ####n = self.__profIndex
1173
1174 self.__buffer = 0
1175 self.__buffer3 = 0
1176 self.__profIndex = 0
1177
1178 #return data_intensity,data_velocity,n
1179 return data_I,data_IV,n
1180
1181 def pulsePairbyProfiles(self,data):
1182 self.__dataReady = False
1183 data_intensity = None
1184 data_velocity = None
1185
1186 self.putData(data)
1187
1188 if self.__profIndex == self.n:
1189 #data_intensity,data_velocity,n = self.pushData()
1190 data_intensity,data_velocity,n = self.pushData()
1191 #print(data_intensity.shape)
1192 #print("self.__profIndex2", self.__profIndex2)
1193 if self.__profIndex2 == 0:
1194 #print("PRIMERA VEZ")
1195 #print("self.__buffer2",self.__buffer2)
1196 for i in range(self.__nch):
1197 self.__buffer2[i][self.__profIndex2] = data_intensity[i]
1198 self.__bufferV2[i][self.__profIndex2] = data_velocity[i]
1199 self.__profIndex2 += 1
1200 return None,None
1201
1202 if self.__profIndex2 > 0:
1203 for i in range(self.__nch):
1204 self.__buffer2[i][self.__profIndex2] = data_intensity[i]
1205 self.__bufferV2[i][self.__profIndex2] = data_velocity[i]
1206 #print("Dentro del bucle",self.__buffer2)
1207 self.__profIndex2 += 1
1208 if self.__profIndex2 == self.m :
1209 data_i = self.__buffer2
1210 data_v = self.__bufferV2
1211 #print(data_i.shape)
1212 self.__dataReady = True
1213 self.__profIndex2 = 0
1214 self.__buffer2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1215 self.__bufferV2 = numpy.zeros((self.__nch,self.m,self.__nHeis))
1216 return data_i,data_v
1217 return None,None
1218
1219 def pulsePairOp(self,data,datatime=None):
1220 if self.__initime == None:
1221 self.__initime = datatime
1222
1223 data_intensity,data_velocity = self.pulsePairbyProfiles(data)
1224 self.__lastdatatime = datatime
1225
1226 if data_intensity is None:
1227 return None,None,None
1228
1229 avgdatatime = self.__initime
1230 self.__initime = datatime
1231
1232 return data_intensity,data_velocity,avgdatatime
1233
1234 def run(self,dataOut,n =None,m=None):
1235
1236 if not self.isConfig:
1237 self.setup(dataOut = dataOut, n = n, m = m)
1238 self.isConfig = True
1239
1240 data_intensity,data_velocity,avgdatatime = self.pulsePairOp(dataOut.data_wr,dataOut.utctime)
1241 dataOut.flagNoData = True
1242
1243 if self.__dataReady:
1244 #print(" DATA " , data_intensity.shape)
1245 #dataOut.data = numpy.array([data_intensity])#aqui amigo revisa
1246 #tmp = numpy.zeros([1,data_intensity.shape[0],data_intensity.shape[1]])
1247 #tmp[0] = data_intensity
1248 dataOut.data = data_intensity
1249 dataOut.data_velocity = data_velocity
1250 #dataOut.data = tmp
1251 #print(" DATA " , dataOut.data.shape)
1252 dataOut.nIncohInt *= self.n
1253 dataOut.nProfiles = self.m
1254 dataOut.nFFTPoints = self.m
1255 #dataOut.data_intensity = data_intensity
1256 dataOut.PRFbyAngle = self.n
1257 dataOut.utctime = avgdatatime
1258 dataOut.flagNoData = False
1259 #####print("TIEMPO: ",dataOut.utctime)
1260 return dataOut
@@ -1,1328 +1,1623
1 1 import sys
2 2 import numpy
3 3 from scipy import interpolate
4 4 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
5 5 from schainpy.model.data.jrodata import Voltage
6 6 from schainpy.utils import log
7 7 from time import time
8 8
9 9
10 10 @MPDecorator
11 class VoltageProc(ProcessingUnit):
12
11 class VoltageProc(ProcessingUnit):
12
13 13 def __init__(self):
14 14
15 15 ProcessingUnit.__init__(self)
16 16
17 17 self.dataOut = Voltage()
18 18 self.flip = 1
19 19 self.setupReq = False
20 20
21 21 def run(self):
22 22
23 23 if self.dataIn.type == 'AMISR':
24 24 self.__updateObjFromAmisrInput()
25 25
26 26 if self.dataIn.type == 'Voltage':
27 27 self.dataOut.copy(self.dataIn)
28 28
29 29 # self.dataOut.copy(self.dataIn)
30 30
31 31 def __updateObjFromAmisrInput(self):
32 32
33 33 self.dataOut.timeZone = self.dataIn.timeZone
34 34 self.dataOut.dstFlag = self.dataIn.dstFlag
35 35 self.dataOut.errorCount = self.dataIn.errorCount
36 36 self.dataOut.useLocalTime = self.dataIn.useLocalTime
37 37
38 38 self.dataOut.flagNoData = self.dataIn.flagNoData
39 39 self.dataOut.data = self.dataIn.data
40 40 self.dataOut.utctime = self.dataIn.utctime
41 41 self.dataOut.channelList = self.dataIn.channelList
42 42 #self.dataOut.timeInterval = self.dataIn.timeInterval
43 43 self.dataOut.heightList = self.dataIn.heightList
44 44 self.dataOut.nProfiles = self.dataIn.nProfiles
45 45
46 46 self.dataOut.nCohInt = self.dataIn.nCohInt
47 47 self.dataOut.ippSeconds = self.dataIn.ippSeconds
48 48 self.dataOut.frequency = self.dataIn.frequency
49 49
50 50 self.dataOut.azimuth = self.dataIn.azimuth
51 51 self.dataOut.zenith = self.dataIn.zenith
52 52
53 53 self.dataOut.beam.codeList = self.dataIn.beam.codeList
54 54 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
55 55 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
56 56 #
57 57 # pass#
58 58 #
59 59 # def init(self):
60 60 #
61 61 #
62 62 # if self.dataIn.type == 'AMISR':
63 63 # self.__updateObjFromAmisrInput()
64 64 #
65 65 # if self.dataIn.type == 'Voltage':
66 66 # self.dataOut.copy(self.dataIn)
67 67 # # No necesita copiar en cada init() los atributos de dataIn
68 68 # # la copia deberia hacerse por cada nuevo bloque de datos
69 69
70 70 def selectChannels(self, channelList):
71 71
72 72 channelIndexList = []
73 73
74 74 for channel in channelList:
75 75 if channel not in self.dataOut.channelList:
76 76 raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList)))
77 77
78 78 index = self.dataOut.channelList.index(channel)
79 79 channelIndexList.append(index)
80 80
81 81 self.selectChannelsByIndex(channelIndexList)
82 82
83 83 def selectChannelsByIndex(self, channelIndexList):
84 84 """
85 85 Selecciona un bloque de datos en base a canales segun el channelIndexList
86 86
87 87 Input:
88 88 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
89 89
90 90 Affected:
91 91 self.dataOut.data
92 92 self.dataOut.channelIndexList
93 93 self.dataOut.nChannels
94 94 self.dataOut.m_ProcessingHeader.totalSpectra
95 95 self.dataOut.systemHeaderObj.numChannels
96 96 self.dataOut.m_ProcessingHeader.blockSize
97 97
98 98 Return:
99 99 None
100 100 """
101 101
102 102 for channelIndex in channelIndexList:
103 103 if channelIndex not in self.dataOut.channelIndexList:
104 104 print(channelIndexList)
105 105 raise ValueError("The value %d in channelIndexList is not valid" %channelIndex)
106 106
107 107 if self.dataOut.flagDataAsBlock:
108 108 """
109 109 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
110 110 """
111 111 data = self.dataOut.data[channelIndexList,:,:]
112 112 else:
113 113 data = self.dataOut.data[channelIndexList,:]
114 114
115 115 self.dataOut.data = data
116 116 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
117 117 self.dataOut.channelList = range(len(channelIndexList))
118
118
119 119 return 1
120 120
121 121 def selectHeights(self, minHei=None, maxHei=None):
122 122 """
123 123 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
124 124 minHei <= height <= maxHei
125 125
126 126 Input:
127 127 minHei : valor minimo de altura a considerar
128 128 maxHei : valor maximo de altura a considerar
129 129
130 130 Affected:
131 131 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
132 132
133 133 Return:
134 134 1 si el metodo se ejecuto con exito caso contrario devuelve 0
135 135 """
136 136
137 137 if minHei == None:
138 138 minHei = self.dataOut.heightList[0]
139 139
140 140 if maxHei == None:
141 141 maxHei = self.dataOut.heightList[-1]
142 142
143 143 if (minHei < self.dataOut.heightList[0]):
144 144 minHei = self.dataOut.heightList[0]
145 145
146 146 if (maxHei > self.dataOut.heightList[-1]):
147 147 maxHei = self.dataOut.heightList[-1]
148 148
149 149 minIndex = 0
150 150 maxIndex = 0
151 151 heights = self.dataOut.heightList
152 152
153 153 inda = numpy.where(heights >= minHei)
154 154 indb = numpy.where(heights <= maxHei)
155 155
156 156 try:
157 157 minIndex = inda[0][0]
158 158 except:
159 159 minIndex = 0
160 160
161 161 try:
162 162 maxIndex = indb[0][-1]
163 163 except:
164 164 maxIndex = len(heights)
165 165
166 166 self.selectHeightsByIndex(minIndex, maxIndex)
167 167
168 168 return 1
169 169
170 170
171 171 def selectHeightsByIndex(self, minIndex, maxIndex):
172 172 """
173 173 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
174 174 minIndex <= index <= maxIndex
175 175
176 176 Input:
177 177 minIndex : valor de indice minimo de altura a considerar
178 178 maxIndex : valor de indice maximo de altura a considerar
179 179
180 180 Affected:
181 181 self.dataOut.data
182 182 self.dataOut.heightList
183 183
184 184 Return:
185 185 1 si el metodo se ejecuto con exito caso contrario devuelve 0
186 186 """
187 187
188 188 if (minIndex < 0) or (minIndex > maxIndex):
189 189 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
190 190
191 191 if (maxIndex >= self.dataOut.nHeights):
192 192 maxIndex = self.dataOut.nHeights
193 193
194 194 #voltage
195 195 if self.dataOut.flagDataAsBlock:
196 196 """
197 197 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
198 198 """
199 199 data = self.dataOut.data[:,:, minIndex:maxIndex]
200 200 else:
201 201 data = self.dataOut.data[:, minIndex:maxIndex]
202 202
203 203 # firstHeight = self.dataOut.heightList[minIndex]
204 204
205 205 self.dataOut.data = data
206 206 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
207 207
208 208 if self.dataOut.nHeights <= 1:
209 209 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights))
210 210
211 211 return 1
212 212
213 213
214 214 def filterByHeights(self, window):
215 215
216 216 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
217 217
218 218 if window == None:
219 219 window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
220 220
221 221 newdelta = deltaHeight * window
222 222 r = self.dataOut.nHeights % window
223 223 newheights = (self.dataOut.nHeights-r)/window
224 224
225 225 if newheights <= 1:
226 226 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window))
227 227
228 228 if self.dataOut.flagDataAsBlock:
229 229 """
230 230 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
231 231 """
232 buffer = self.dataOut.data[:, :, 0:int(self.dataOut.nHeights-r)]
232 buffer = self.dataOut.data[:, :, 0:int(self.dataOut.nHeights-r)]
233 233 buffer = buffer.reshape(self.dataOut.nChannels, self.dataOut.nProfiles, int(self.dataOut.nHeights/window), window)
234 234 buffer = numpy.sum(buffer,3)
235 235
236 236 else:
237 237 buffer = self.dataOut.data[:,0:int(self.dataOut.nHeights-r)]
238 238 buffer = buffer.reshape(self.dataOut.nChannels,int(self.dataOut.nHeights/window),int(window))
239 239 buffer = numpy.sum(buffer,2)
240 240
241 241 self.dataOut.data = buffer
242 242 self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta
243 243 self.dataOut.windowOfFilter = window
244 244
245 245 def setH0(self, h0, deltaHeight = None):
246 246
247 247 if not deltaHeight:
248 248 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
249 249
250 250 nHeights = self.dataOut.nHeights
251 251
252 252 newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight
253 253
254 254 self.dataOut.heightList = newHeiRange
255 255
256 256 def deFlip(self, channelList = []):
257 257
258 258 data = self.dataOut.data.copy()
259 259
260 260 if self.dataOut.flagDataAsBlock:
261 261 flip = self.flip
262 262 profileList = list(range(self.dataOut.nProfiles))
263 263
264 264 if not channelList:
265 265 for thisProfile in profileList:
266 266 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
267 267 flip *= -1.0
268 268 else:
269 269 for thisChannel in channelList:
270 270 if thisChannel not in self.dataOut.channelList:
271 271 continue
272 272
273 273 for thisProfile in profileList:
274 274 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
275 275 flip *= -1.0
276 276
277 277 self.flip = flip
278 278
279 279 else:
280 280 if not channelList:
281 281 data[:,:] = data[:,:]*self.flip
282 282 else:
283 283 for thisChannel in channelList:
284 284 if thisChannel not in self.dataOut.channelList:
285 285 continue
286 286
287 287 data[thisChannel,:] = data[thisChannel,:]*self.flip
288 288
289 289 self.flip *= -1.
290 290
291 291 self.dataOut.data = data
292 292
293 293 def setRadarFrequency(self, frequency=None):
294 294
295 295 if frequency != None:
296 296 self.dataOut.frequency = frequency
297 297
298 298 return 1
299 299
300 300 def interpolateHeights(self, topLim, botLim):
301 301 #69 al 72 para julia
302 302 #82-84 para meteoros
303 303 if len(numpy.shape(self.dataOut.data))==2:
304 304 sampInterp = (self.dataOut.data[:,botLim-1] + self.dataOut.data[:,topLim+1])/2
305 305 sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1)))
306 306 #self.dataOut.data[:,botLim:limSup+1] = sampInterp
307 307 self.dataOut.data[:,botLim:topLim+1] = sampInterp
308 308 else:
309 309 nHeights = self.dataOut.data.shape[2]
310 310 x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights)))
311 311 y = self.dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))]
312 312 f = interpolate.interp1d(x, y, axis = 2)
313 313 xnew = numpy.arange(botLim,topLim+1)
314 314 ynew = f(xnew)
315 315
316 316 self.dataOut.data[:,:,botLim:topLim+1] = ynew
317 317
318 318 # import collections
319 319
320 320 class CohInt(Operation):
321 321
322 322 isConfig = False
323 323 __profIndex = 0
324 324 __byTime = False
325 325 __initime = None
326 326 __lastdatatime = None
327 327 __integrationtime = None
328 328 __buffer = None
329 329 __bufferStride = []
330 330 __dataReady = False
331 331 __profIndexStride = 0
332 332 __dataToPutStride = False
333 333 n = None
334 334
335 335 def __init__(self, **kwargs):
336 336
337 337 Operation.__init__(self, **kwargs)
338 338
339 339 # self.isConfig = False
340 340
341 341 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
342 342 """
343 343 Set the parameters of the integration class.
344 344
345 345 Inputs:
346 346
347 347 n : Number of coherent integrations
348 348 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
349 349 overlapping :
350 350 """
351 351
352 352 self.__initime = None
353 353 self.__lastdatatime = 0
354 354 self.__buffer = None
355 355 self.__dataReady = False
356 356 self.byblock = byblock
357 357 self.stride = stride
358 358
359 359 if n == None and timeInterval == None:
360 360 raise ValueError("n or timeInterval should be specified ...")
361 361
362 362 if n != None:
363 363 self.n = n
364 364 self.__byTime = False
365 365 else:
366 366 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
367 367 self.n = 9999
368 368 self.__byTime = True
369 369
370 370 if overlapping:
371 371 self.__withOverlapping = True
372 372 self.__buffer = None
373 373 else:
374 374 self.__withOverlapping = False
375 375 self.__buffer = 0
376 376
377 377 self.__profIndex = 0
378 378
379 379 def putData(self, data):
380 380
381 381 """
382 382 Add a profile to the __buffer and increase in one the __profileIndex
383 383
384 384 """
385 385
386 386 if not self.__withOverlapping:
387 print("inside over")
387 388 self.__buffer += data.copy()
388 389 self.__profIndex += 1
389 390 return
390 391
391 392 #Overlapping data
392 393 nChannels, nHeis = data.shape
394 print("show me the light",data.shape)
393 395 data = numpy.reshape(data, (1, nChannels, nHeis))
394
396 print(data.shape)
395 397 #If the buffer is empty then it takes the data value
396 398 if self.__buffer is None:
397 399 self.__buffer = data
398 400 self.__profIndex += 1
399 401 return
400 402
401 403 #If the buffer length is lower than n then stakcing the data value
402 404 if self.__profIndex < self.n:
403 405 self.__buffer = numpy.vstack((self.__buffer, data))
404 406 self.__profIndex += 1
405 407 return
406 408
407 409 #If the buffer length is equal to n then replacing the last buffer value with the data value
408 410 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
409 411 self.__buffer[self.n-1] = data
410 412 self.__profIndex = self.n
411 413 return
412 414
413 415
414 416 def pushData(self):
415 417 """
416 418 Return the sum of the last profiles and the profiles used in the sum.
417 419
418 420 Affected:
419 421
420 422 self.__profileIndex
421 423
422 424 """
423 425
424 426 if not self.__withOverlapping:
427 #print("ahora que fue")
425 428 data = self.__buffer
426 429 n = self.__profIndex
427 430
428 431 self.__buffer = 0
429 432 self.__profIndex = 0
430 433
431 434 return data, n
432 435
436 #print("cual funciona")
433 437 #Integration with Overlapping
434 438 data = numpy.sum(self.__buffer, axis=0)
435 439 # print data
436 440 # raise
437 441 n = self.__profIndex
438 442
439 443 return data, n
440 444
441 445 def byProfiles(self, data):
442 446
443 447 self.__dataReady = False
444 448 avgdata = None
445 449 # n = None
446 450 # print data
447 451 # raise
452 #print("beforeputdata")
448 453 self.putData(data)
449 454
450 455 if self.__profIndex == self.n:
451 456 avgdata, n = self.pushData()
452 457 self.__dataReady = True
453 458
454 459 return avgdata
455 460
456 461 def byTime(self, data, datatime):
457 462
458 463 self.__dataReady = False
459 464 avgdata = None
460 465 n = None
461 466
462 467 self.putData(data)
463 468
464 469 if (datatime - self.__initime) >= self.__integrationtime:
465 470 avgdata, n = self.pushData()
466 471 self.n = n
467 472 self.__dataReady = True
468 473
469 474 return avgdata
470 475
471 476 def integrateByStride(self, data, datatime):
472 477 # print data
473 478 if self.__profIndex == 0:
474 479 self.__buffer = [[data.copy(), datatime]]
475 480 else:
476 481 self.__buffer.append([data.copy(),datatime])
477 482 self.__profIndex += 1
478 483 self.__dataReady = False
479 484
480 485 if self.__profIndex == self.n * self.stride :
481 486 self.__dataToPutStride = True
482 487 self.__profIndexStride = 0
483 488 self.__profIndex = 0
484 489 self.__bufferStride = []
485 490 for i in range(self.stride):
486 491 current = self.__buffer[i::self.stride]
487 492 data = numpy.sum([t[0] for t in current], axis=0)
488 493 avgdatatime = numpy.average([t[1] for t in current])
489 494 # print data
490 495 self.__bufferStride.append((data, avgdatatime))
491 496
492 497 if self.__dataToPutStride:
493 498 self.__dataReady = True
494 499 self.__profIndexStride += 1
495 500 if self.__profIndexStride == self.stride:
496 501 self.__dataToPutStride = False
497 502 # print self.__bufferStride[self.__profIndexStride - 1]
498 503 # raise
499 504 return self.__bufferStride[self.__profIndexStride - 1]
500
501
505
506
502 507 return None, None
503 508
504 509 def integrate(self, data, datatime=None):
505 510
506 511 if self.__initime == None:
507 512 self.__initime = datatime
508 513
509 514 if self.__byTime:
510 515 avgdata = self.byTime(data, datatime)
511 516 else:
512 517 avgdata = self.byProfiles(data)
513 518
514 519
515 520 self.__lastdatatime = datatime
516 521
517 522 if avgdata is None:
518 523 return None, None
519 524
520 525 avgdatatime = self.__initime
521 526
522 527 deltatime = datatime - self.__lastdatatime
523
528
524 529 if not self.__withOverlapping:
525 530 self.__initime = datatime
526 531 else:
527 532 self.__initime += deltatime
528 533
529 534 return avgdata, avgdatatime
530 535
531 536 def integrateByBlock(self, dataOut):
532 537
533 538 times = int(dataOut.data.shape[1]/self.n)
534 539 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex)
535 540
536 541 id_min = 0
537 542 id_max = self.n
538 543
539 544 for i in range(times):
540 545 junk = dataOut.data[:,id_min:id_max,:]
541 546 avgdata[:,i,:] = junk.sum(axis=1)
542 547 id_min += self.n
543 548 id_max += self.n
544 549
545 550 timeInterval = dataOut.ippSeconds*self.n
546 551 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
547 552 self.__dataReady = True
548 553 return avgdata, avgdatatime
549
554
550 555 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
551 556
552 557 if not self.isConfig:
553 558 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
554 559 self.isConfig = True
555 560
556 561 if dataOut.flagDataAsBlock:
557 562 """
558 563 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
559 564 """
560 565 avgdata, avgdatatime = self.integrateByBlock(dataOut)
561 566 dataOut.nProfiles /= self.n
562 567 else:
563 if stride is None:
568 if stride is None:
564 569 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
565 570 else:
566 571 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
567 572
568
573
569 574 # dataOut.timeInterval *= n
570 575 dataOut.flagNoData = True
571 576
572 577 if self.__dataReady:
573 578 dataOut.data = avgdata
574 579 dataOut.nCohInt *= self.n
575 580 dataOut.utctime = avgdatatime
576 581 # print avgdata, avgdatatime
577 582 # raise
578 583 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
579 584 dataOut.flagNoData = False
580 585 return dataOut
581 586
582 587 class Decoder(Operation):
583 588
584 589 isConfig = False
585 590 __profIndex = 0
586 591
587 592 code = None
588 593
589 594 nCode = None
590 595 nBaud = None
591 596
592 597 def __init__(self, **kwargs):
593 598
594 599 Operation.__init__(self, **kwargs)
595 600
596 601 self.times = None
597 602 self.osamp = None
598 603 # self.__setValues = False
599 604 self.isConfig = False
600 605 self.setupReq = False
601 606 def setup(self, code, osamp, dataOut):
602 607
603 608 self.__profIndex = 0
604 609
605 610 self.code = code
606 611
607 612 self.nCode = len(code)
608 613 self.nBaud = len(code[0])
609 614
610 615 if (osamp != None) and (osamp >1):
611 616 self.osamp = osamp
612 617 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
613 618 self.nBaud = self.nBaud*self.osamp
614 619
615 620 self.__nChannels = dataOut.nChannels
616 621 self.__nProfiles = dataOut.nProfiles
617 622 self.__nHeis = dataOut.nHeights
618 623
619 624 if self.__nHeis < self.nBaud:
620 625 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
621 626
622 627 #Frequency
623 628 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex)
624 629
625 630 __codeBuffer[:,0:self.nBaud] = self.code
626 631
627 632 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
628 633
629 634 if dataOut.flagDataAsBlock:
630 635
631 636 self.ndatadec = self.__nHeis #- self.nBaud + 1
632 637
633 638 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex)
634 639
635 640 else:
636 641
637 642 #Time
638 643 self.ndatadec = self.__nHeis #- self.nBaud + 1
639 644
640 645 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex)
641 646
642 647 def __convolutionInFreq(self, data):
643 648
644 649 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
645 650
646 651 fft_data = numpy.fft.fft(data, axis=1)
647 652
648 653 conv = fft_data*fft_code
649 654
650 655 data = numpy.fft.ifft(conv,axis=1)
651 656
652 657 return data
653 658
654 659 def __convolutionInFreqOpt(self, data):
655 660
656 661 raise NotImplementedError
657 662
658 663 def __convolutionInTime(self, data):
659 664
660 665 code = self.code[self.__profIndex]
661 666 for i in range(self.__nChannels):
662 667 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
663 668
664 669 return self.datadecTime
665 670
666 671 def __convolutionByBlockInTime(self, data):
667 672
668 673 repetitions = int(self.__nProfiles / self.nCode)
669 674 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
670 675 junk = junk.flatten()
671 676 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
672 677 profilesList = range(self.__nProfiles)
673
674 for i in range(self.__nChannels):
675 for j in profilesList:
676 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
677 return self.datadecTime
678
679 for i in range(self.__nChannels):
680 for j in profilesList:
681 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
682 return self.datadecTime
678 683
679 684 def __convolutionByBlockInFreq(self, data):
680 685
681 686 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
682 687
683 688
684 689 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
685 690
686 691 fft_data = numpy.fft.fft(data, axis=2)
687 692
688 693 conv = fft_data*fft_code
689 694
690 695 data = numpy.fft.ifft(conv,axis=2)
691 696
692 697 return data
693 698
694
699
695 700 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
696 701
697 702 if dataOut.flagDecodeData:
698 703 print("This data is already decoded, recoding again ...")
699 704
700 705 if not self.isConfig:
701 706
702 707 if code is None:
703 708 if dataOut.code is None:
704 709 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
705 710
706 711 code = dataOut.code
707 712 else:
708 713 code = numpy.array(code).reshape(nCode,nBaud)
709 714 self.setup(code, osamp, dataOut)
710 715
711 716 self.isConfig = True
712 717
713 718 if mode == 3:
714 719 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
715 720
716 721 if times != None:
717 722 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
718 723
719 724 if self.code is None:
720 725 print("Fail decoding: Code is not defined.")
721 726 return
722 727
723 728 self.__nProfiles = dataOut.nProfiles
724 729 datadec = None
725
730
726 731 if mode == 3:
727 732 mode = 0
728 733
729 734 if dataOut.flagDataAsBlock:
730 735 """
731 736 Decoding when data have been read as block,
732 737 """
733 738
734 739 if mode == 0:
735 740 datadec = self.__convolutionByBlockInTime(dataOut.data)
736 741 if mode == 1:
737 742 datadec = self.__convolutionByBlockInFreq(dataOut.data)
738 743 else:
739 744 """
740 745 Decoding when data have been read profile by profile
741 746 """
742 747 if mode == 0:
743 748 datadec = self.__convolutionInTime(dataOut.data)
744 749
745 750 if mode == 1:
746 751 datadec = self.__convolutionInFreq(dataOut.data)
747 752
748 753 if mode == 2:
749 754 datadec = self.__convolutionInFreqOpt(dataOut.data)
750 755
751 756 if datadec is None:
752 757 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
753 758
754 759 dataOut.code = self.code
755 760 dataOut.nCode = self.nCode
756 761 dataOut.nBaud = self.nBaud
757 762
758 763 dataOut.data = datadec
759 764
760 765 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
761 766
762 767 dataOut.flagDecodeData = True #asumo q la data esta decodificada
763 768
764 769 if self.__profIndex == self.nCode-1:
765 770 self.__profIndex = 0
766 771 return dataOut
767 772
768 773 self.__profIndex += 1
769 774
770 775 return dataOut
771 776 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
772 777
773 778
774 779 class ProfileConcat(Operation):
775 780
776 781 isConfig = False
777 782 buffer = None
778 783
779 784 def __init__(self, **kwargs):
780 785
781 786 Operation.__init__(self, **kwargs)
782 787 self.profileIndex = 0
783 788
784 789 def reset(self):
785 790 self.buffer = numpy.zeros_like(self.buffer)
786 791 self.start_index = 0
787 792 self.times = 1
788 793
789 794 def setup(self, data, m, n=1):
790 795 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
791 796 self.nHeights = data.shape[1]#.nHeights
792 797 self.start_index = 0
793 798 self.times = 1
794 799
795 800 def concat(self, data):
796 801
797 802 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
798 803 self.start_index = self.start_index + self.nHeights
799 804
800 805 def run(self, dataOut, m):
801 806 dataOut.flagNoData = True
802 807
803 808 if not self.isConfig:
804 809 self.setup(dataOut.data, m, 1)
805 810 self.isConfig = True
806 811
807 812 if dataOut.flagDataAsBlock:
808 813 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
809 814
810 815 else:
811 816 self.concat(dataOut.data)
812 817 self.times += 1
813 818 if self.times > m:
814 819 dataOut.data = self.buffer
815 820 self.reset()
816 821 dataOut.flagNoData = False
817 822 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
818 823 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
819 824 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
820 825 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
821 826 dataOut.ippSeconds *= m
822 827 return dataOut
823 828
824 829 class ProfileSelector(Operation):
825 830
826 831 profileIndex = None
827 832 # Tamanho total de los perfiles
828 833 nProfiles = None
829 834
830 835 def __init__(self, **kwargs):
831 836
832 837 Operation.__init__(self, **kwargs)
833 838 self.profileIndex = 0
834 839
835 840 def incProfileIndex(self):
836 841
837 842 self.profileIndex += 1
838 843
839 844 if self.profileIndex >= self.nProfiles:
840 845 self.profileIndex = 0
841 846
842 847 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
843 848
844 849 if profileIndex < minIndex:
845 850 return False
846 851
847 852 if profileIndex > maxIndex:
848 853 return False
849 854
850 855 return True
851 856
852 857 def isThisProfileInList(self, profileIndex, profileList):
853 858
854 859 if profileIndex not in profileList:
855 860 return False
856 861
857 862 return True
858 863
859 864 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
860 865
861 866 """
862 867 ProfileSelector:
863 868
864 869 Inputs:
865 870 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
866 871
867 872 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
868 873
869 874 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
870 875
871 876 """
872 877
873 878 if rangeList is not None:
874 879 if type(rangeList[0]) not in (tuple, list):
875 880 rangeList = [rangeList]
876 881
877 882 dataOut.flagNoData = True
878 883
879 884 if dataOut.flagDataAsBlock:
880 885 """
881 886 data dimension = [nChannels, nProfiles, nHeis]
882 887 """
883 888 if profileList != None:
884 889 dataOut.data = dataOut.data[:,profileList,:]
885 890
886 891 if profileRangeList != None:
887 892 minIndex = profileRangeList[0]
888 893 maxIndex = profileRangeList[1]
889 894 profileList = list(range(minIndex, maxIndex+1))
890 895
891 896 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
892 897
893 898 if rangeList != None:
894 899
895 900 profileList = []
896 901
897 902 for thisRange in rangeList:
898 903 minIndex = thisRange[0]
899 904 maxIndex = thisRange[1]
900 905
901 906 profileList.extend(list(range(minIndex, maxIndex+1)))
902 907
903 908 dataOut.data = dataOut.data[:,profileList,:]
904 909
905 910 dataOut.nProfiles = len(profileList)
906 911 dataOut.profileIndex = dataOut.nProfiles - 1
907 912 dataOut.flagNoData = False
908 913
909 914 return dataOut
910 915
911 916 """
912 917 data dimension = [nChannels, nHeis]
913 918 """
914 919
915 920 if profileList != None:
916 921
917 922 if self.isThisProfileInList(dataOut.profileIndex, profileList):
918 923
919 924 self.nProfiles = len(profileList)
920 925 dataOut.nProfiles = self.nProfiles
921 926 dataOut.profileIndex = self.profileIndex
922 927 dataOut.flagNoData = False
923 928
924 929 self.incProfileIndex()
925 930 return dataOut
926 931
927 932 if profileRangeList != None:
928 933
929 934 minIndex = profileRangeList[0]
930 935 maxIndex = profileRangeList[1]
931 936
932 937 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
933 938
934 939 self.nProfiles = maxIndex - minIndex + 1
935 940 dataOut.nProfiles = self.nProfiles
936 941 dataOut.profileIndex = self.profileIndex
937 942 dataOut.flagNoData = False
938 943
939 944 self.incProfileIndex()
940 945 return dataOut
941 946
942 947 if rangeList != None:
943 948
944 949 nProfiles = 0
945 950
946 951 for thisRange in rangeList:
947 952 minIndex = thisRange[0]
948 953 maxIndex = thisRange[1]
949 954
950 955 nProfiles += maxIndex - minIndex + 1
951 956
952 957 for thisRange in rangeList:
953 958
954 959 minIndex = thisRange[0]
955 960 maxIndex = thisRange[1]
956 961
957 962 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
958 963
959 964 self.nProfiles = nProfiles
960 965 dataOut.nProfiles = self.nProfiles
961 966 dataOut.profileIndex = self.profileIndex
962 967 dataOut.flagNoData = False
963 968
964 969 self.incProfileIndex()
965 970
966 971 break
967 972
968 973 return dataOut
969 974
970 975
971 976 if beam != None: #beam is only for AMISR data
972 977 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
973 978 dataOut.flagNoData = False
974 979 dataOut.profileIndex = self.profileIndex
975 980
976 981 self.incProfileIndex()
977 982
978 983 return dataOut
979 984
980 985 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
981 986
982 987 #return False
983 988 return dataOut
984 989
985 990 class Reshaper(Operation):
986 991
987 992 def __init__(self, **kwargs):
988 993
989 994 Operation.__init__(self, **kwargs)
990 995
991 996 self.__buffer = None
992 997 self.__nitems = 0
993 998
994 999 def __appendProfile(self, dataOut, nTxs):
995 1000
996 1001 if self.__buffer is None:
997 1002 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
998 1003 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
999 1004
1000 1005 ini = dataOut.nHeights * self.__nitems
1001 1006 end = ini + dataOut.nHeights
1002 1007
1003 1008 self.__buffer[:, ini:end] = dataOut.data
1004 1009
1005 1010 self.__nitems += 1
1006 1011
1007 1012 return int(self.__nitems*nTxs)
1008 1013
1009 1014 def __getBuffer(self):
1010 1015
1011 1016 if self.__nitems == int(1./self.__nTxs):
1012 1017
1013 1018 self.__nitems = 0
1014 1019
1015 1020 return self.__buffer.copy()
1016 1021
1017 1022 return None
1018 1023
1019 1024 def __checkInputs(self, dataOut, shape, nTxs):
1020 1025
1021 1026 if shape is None and nTxs is None:
1022 1027 raise ValueError("Reshaper: shape of factor should be defined")
1023 1028
1024 1029 if nTxs:
1025 1030 if nTxs < 0:
1026 1031 raise ValueError("nTxs should be greater than 0")
1027 1032
1028 1033 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
1029 1034 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
1030 1035
1031 1036 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
1032 1037
1033 1038 return shape, nTxs
1034 1039
1035 1040 if len(shape) != 2 and len(shape) != 3:
1036 1041 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
1037 1042
1038 1043 if len(shape) == 2:
1039 1044 shape_tuple = [dataOut.nChannels]
1040 1045 shape_tuple.extend(shape)
1041 1046 else:
1042 1047 shape_tuple = list(shape)
1043 1048
1044 1049 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
1045 1050
1046 1051 return shape_tuple, nTxs
1047 1052
1048 1053 def run(self, dataOut, shape=None, nTxs=None):
1049 1054
1050 1055 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
1051 1056
1052 1057 dataOut.flagNoData = True
1053 1058 profileIndex = None
1054 1059
1055 1060 if dataOut.flagDataAsBlock:
1056 1061
1057 1062 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
1058 1063 dataOut.flagNoData = False
1059 1064
1060 1065 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
1061 1066
1062 1067 else:
1063 1068
1064 1069 if self.__nTxs < 1:
1065 1070
1066 1071 self.__appendProfile(dataOut, self.__nTxs)
1067 1072 new_data = self.__getBuffer()
1068 1073
1069 1074 if new_data is not None:
1070 1075 dataOut.data = new_data
1071 1076 dataOut.flagNoData = False
1072 1077
1073 1078 profileIndex = dataOut.profileIndex*nTxs
1074 1079
1075 1080 else:
1076 1081 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
1077 1082
1078 1083 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1079 1084
1080 1085 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
1081 1086
1082 1087 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
1083 1088
1084 1089 dataOut.profileIndex = profileIndex
1085 1090
1086 1091 dataOut.ippSeconds /= self.__nTxs
1087 1092
1088 1093 return dataOut
1089 1094
1090 1095 class SplitProfiles(Operation):
1091 1096
1092 1097 def __init__(self, **kwargs):
1093 1098
1094 1099 Operation.__init__(self, **kwargs)
1095 1100
1096 1101 def run(self, dataOut, n):
1097 1102
1098 1103 dataOut.flagNoData = True
1099 1104 profileIndex = None
1100 1105
1101 1106 if dataOut.flagDataAsBlock:
1102 1107
1103 1108 #nchannels, nprofiles, nsamples
1104 1109 shape = dataOut.data.shape
1105 1110
1106 1111 if shape[2] % n != 0:
1107 1112 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
1108
1113
1109 1114 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
1110
1115
1111 1116 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1112 1117 dataOut.flagNoData = False
1113 1118
1114 1119 profileIndex = int(dataOut.nProfiles/n) - 1
1115 1120
1116 1121 else:
1117 1122
1118 1123 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
1119 1124
1120 1125 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1121 1126
1122 1127 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
1123 1128
1124 1129 dataOut.nProfiles = int(dataOut.nProfiles*n)
1125 1130
1126 1131 dataOut.profileIndex = profileIndex
1127 1132
1128 1133 dataOut.ippSeconds /= n
1129 1134
1130 1135 return dataOut
1131 1136
1132 1137 class CombineProfiles(Operation):
1133 1138 def __init__(self, **kwargs):
1134 1139
1135 1140 Operation.__init__(self, **kwargs)
1136 1141
1137 1142 self.__remData = None
1138 1143 self.__profileIndex = 0
1139 1144
1140 1145 def run(self, dataOut, n):
1141 1146
1142 1147 dataOut.flagNoData = True
1143 1148 profileIndex = None
1144 1149
1145 1150 if dataOut.flagDataAsBlock:
1146 1151
1147 1152 #nchannels, nprofiles, nsamples
1148 1153 shape = dataOut.data.shape
1149 1154 new_shape = shape[0], shape[1]/n, shape[2]*n
1150 1155
1151 1156 if shape[1] % n != 0:
1152 1157 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
1153 1158
1154 1159 dataOut.data = numpy.reshape(dataOut.data, new_shape)
1155 1160 dataOut.flagNoData = False
1156 1161
1157 1162 profileIndex = int(dataOut.nProfiles*n) - 1
1158 1163
1159 1164 else:
1160 1165
1161 1166 #nchannels, nsamples
1162 1167 if self.__remData is None:
1163 1168 newData = dataOut.data
1164 1169 else:
1165 1170 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
1166 1171
1167 1172 self.__profileIndex += 1
1168 1173
1169 1174 if self.__profileIndex < n:
1170 1175 self.__remData = newData
1171 1176 #continue
1172 1177 return
1173 1178
1174 1179 self.__profileIndex = 0
1175 1180 self.__remData = None
1176 1181
1177 1182 dataOut.data = newData
1178 1183 dataOut.flagNoData = False
1179 1184
1180 1185 profileIndex = dataOut.profileIndex/n
1181 1186
1182 1187
1183 1188 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1184 1189
1185 1190 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
1186 1191
1187 1192 dataOut.nProfiles = int(dataOut.nProfiles/n)
1188 1193
1189 1194 dataOut.profileIndex = profileIndex
1190 1195
1191 1196 dataOut.ippSeconds *= n
1192 1197
1193 1198 return dataOut
1199
1200
1201
1202 class CreateBlockVoltage(Operation):
1203
1204 isConfig = False
1205 __Index = 0
1206 bufferShape = None
1207 buffer = None
1208 firstdatatime = None
1209
1210 def __init__(self,**kwargs):
1211 Operation.__init__(self,**kwargs)
1212 self.isConfig = False
1213 self.__Index = 0
1214 self.firstdatatime = None
1215
1216 def setup(self,dataOut, m = None ):
1217 '''
1218 m= Numero perfiles
1219 '''
1220 #print("CONFIGURANDO CBV")
1221 self.__nChannels = dataOut.nChannels
1222 self.__nHeis = dataOut.nHeights
1223 shape = dataOut.data.shape #nchannels, nprofiles, nsamples
1224 #print("input nChannels",self.__nChannels)
1225 #print("input nHeis",self.__nHeis)
1226 #print("SETUP CREATE BLOCK VOLTAGE")
1227 #print("input Shape",shape)
1228 #print("dataOut.nProfiles",dataOut.nProfiles)
1229 numberSamples = self.__nHeis
1230 numberProfile = int(m)
1231 dataOut.nProfiles = numberProfile
1232 #print("new numberProfile",numberProfile)
1233 #print("new numberSamples",numberSamples)
1234
1235 self.bufferShape = shape[0], numberProfile, numberSamples # nchannels,nprofiles,nsamples
1236 self.buffer = numpy.zeros((self.bufferShape))
1237 self.bufferVel = numpy.zeros((self.bufferShape))
1238
1239 def run(self, dataOut, m=None):
1240 #print("RUN")
1241 dataOut.flagNoData = True
1242 dataOut.flagDataAsBlock = False
1243 #print("BLOCK INDEX ",self.__Index)
1244
1245 if not self.isConfig:
1246 self.setup(dataOut, m= m)
1247 self.isConfig = True
1248 if self.__Index < m:
1249 #print("PROFINDEX BLOCK CBV",self.__Index)
1250 self.buffer[:,self.__Index,:] = dataOut.data
1251 self.bufferVel[:,self.__Index,:] = dataOut.data_velocity
1252 self.__Index += 1
1253 dataOut.flagNoData = True
1254
1255 if self.firstdatatime == None:
1256 self.firstdatatime = dataOut.utctime
1257
1258 if self.__Index == m:
1259 #print("**********************************************")
1260 #print("self.buffer.shape ",self.buffer.shape)
1261 #print("##############",self.firstdatatime)
1262 ##print("*********************************************")
1263 ##print("*********************************************")
1264 ##print("******* nProfiles *******", dataOut.nProfiles)
1265 ##print("*********************************************")
1266 ##print("*********************************************")
1267 dataOut.data = self.buffer
1268 dataOut.data_velocity = self.bufferVel
1269 dataOut.utctime = self.firstdatatime
1270 dataOut.nProfiles = m
1271 self.firstdatatime = None
1272 dataOut.flagNoData = False
1273 dataOut.flagDataAsBlock = True
1274 self.__Index = 0
1275 dataOut.identifierWR = True
1276 return dataOut
1277
1278 class PulsePairVoltage(Operation):
1279 '''
1280 Function PulsePair(Signal Power, Velocity)
1281 The real component of Lag[0] provides Intensity Information
1282 The imag component of Lag[1] Phase provides Velocity Information
1283
1284 Configuration Parameters:
1285 nPRF = Number of Several PRF
1286 theta = Degree Azimuth angel Boundaries
1287
1288 Input:
1289 self.dataOut
1290 lag[N]
1291 Affected:
1292 self.dataOut.spc
1293 '''
1294 isConfig = False
1295 __profIndex = 0
1296 __initime = None
1297 __lastdatatime = None
1298 __buffer = None
1299 __buffer2 = []
1300 __buffer3 = None
1301 __dataReady = False
1302 n = None
1303 __nch = 0
1304 __nHeis = 0
1305
1306 def __init__(self,**kwargs):
1307 Operation.__init__(self,**kwargs)
1308
1309 def setup(self, dataOut, n = None ):
1310 '''
1311 n= Numero de PRF's de entrada
1312 '''
1313 self.__initime = None
1314 self.__lastdatatime = 0
1315 self.__dataReady = False
1316 self.__buffer = 0
1317 self.__buffer2 = []
1318 self.__buffer3 = 0
1319 self.__profIndex = 0
1320
1321 self.__nch = dataOut.nChannels
1322 self.__nHeis = dataOut.nHeights
1323
1324 print("ELVALOR DE n es:", n)
1325 if n == None:
1326 raise ValueError("n should be specified.")
1327
1328 if n != None:
1329 if n<2:
1330 raise ValueError("n should be greater than 2")
1331
1332 self.n = n
1333 self.__nProf = n
1334 '''
1335 if overlapping:
1336 self.__withOverlapping = True
1337 self.__buffer = None
1338
1339 else:
1340 #print ("estoy sin __withO")
1341 self.__withOverlapping = False
1342 self.__buffer = 0
1343 self.__buffer2 = []
1344 self.__buffer3 = 0
1345 '''
1346
1347 def putData(self,data):
1348 '''
1349 Add a profile to he __buffer and increase in one the __profiel Index
1350 '''
1351 #print("self.__profIndex :",self.__profIndex)
1352 self.__buffer += data*numpy.conjugate(data)
1353 self.__buffer2.append(numpy.conjugate(data))
1354 if self.__profIndex > 0:
1355 self.__buffer3 += self.__buffer2[self.__profIndex-1]*data
1356 self.__profIndex += 1
1357 return
1358 '''
1359 if not self.__withOverlapping:
1360 #print("Putdata inside over")
1361 self.__buffer += data* numpy.conjugate(data)
1362 self.__buffer2.append(numpy.conjugate(data))
1363
1364 if self.__profIndex >0:
1365 self.__buffer3 += self.__buffer2[self.__profIndex-1]*data
1366 self.__profIndex += 1
1367 return
1368
1369 if self.__buffer is None:
1370 #print("aqui bro")
1371 self.__buffer = data* numpy.conjugate(data)
1372 self.__buffer2.append(numpy.conjugate(data))
1373 self.__profIndex += 1
1374
1375 return
1376
1377 if self.__profIndex < self.n:
1378 self.__buffer = numpy.vstack(self.__buffer,data* numpy.conjugate(data))
1379 self.__buffer2.append(numpy.conjugate(data))
1380
1381 if self.__profIndex == 1:
1382 self.__buffer3 = self.__buffer2[self.__profIndex -1] * data
1383 else:
1384 self.__buffer3 = numpy.vstack(self.__buffer3, self.__buffer2[self.profIndex-1]*data)
1385
1386 self.__profIndex += 1
1387 return
1388 '''
1389
1390 def pushData(self):
1391 '''
1392 Return the PULSEPAIR and the profiles used in the operation
1393 Affected : self.__profileIndex
1394 '''
1395 #print("************************************************")
1396 #print("push data int vel n")
1397 data_intensity = self.__buffer/self.n
1398 data_velocity = self.__buffer3/(self.n-1)
1399 n = self.__profIndex
1400
1401 self.__buffer = 0
1402 self.__buffer2 = []
1403 self.__buffer3 = 0
1404 self.__profIndex = 0
1405
1406 return data_intensity, data_velocity,n
1407 '''
1408 if not self.__withOverlapping:
1409 #print("ahora que fue")
1410 data_intensity = self.__buffer/self.n
1411 data_velocity = self.__buffer3/(self.n-1)
1412 n = self.__profIndex
1413
1414 self.__buffer = 0
1415 self.__buffer2 = []
1416 self.__buffer3 = 0
1417 self.__profIndex = 0
1418 return data_intensity, data_velocity,n
1419
1420 data_intensity = numpy.sum(self.__buffer,axis = 0)
1421 data_velocity = numpy.sum(self.__buffer3,axis = 0)
1422 n = self.__profIndex
1423 #self.__buffer = 0
1424 #self.__buffer2 = []
1425 #self.__buffer3 = 0
1426 #self.__profIndex = 0
1427 return data_intensity, data_velocity,n
1428 '''
1429
1430 def pulsePairbyProfiles(self,data):
1431
1432 self.__dataReady = False
1433 data_intensity = None
1434 data_velocity = None
1435 #print("beforeputada")
1436 self.putData(data)
1437 #print("ProfileIndex:",self.__profIndex)
1438 if self.__profIndex == self.n:
1439 data_intensity, data_velocity, n = self.pushData()
1440 self.__dataReady = True
1441 #print("-----------------------------------------------")
1442 #print("data_intensity",data_intensity.shape,"data_velocity",data_velocity.shape)
1443 return data_intensity, data_velocity
1444
1445 def pulsePairOp(self, data, datatime= None):
1446
1447 if self.__initime == None:
1448 self.__initime = datatime
1449
1450 data_intensity, data_velocity = self.pulsePairbyProfiles(data)
1451 self.__lastdatatime = datatime
1452
1453 if data_intensity is None:
1454 return None, None, None
1455
1456 avgdatatime = self.__initime
1457 deltatime = datatime - self.__lastdatatime
1458 self.__initime = datatime
1459 '''
1460 if not self.__withOverlapping:
1461 self.__initime = datatime
1462 else:
1463 self.__initime += deltatime
1464 '''
1465 return data_intensity, data_velocity, avgdatatime
1466
1467 def run(self, dataOut,n = None, overlapping= False,**kwargs):
1468
1469 if not self.isConfig:
1470 self.setup(dataOut = dataOut, n = n , **kwargs)
1471 self.isConfig = True
1472 #print("*******************")
1473 #print("print Shape input data:",dataOut.data.shape)
1474 data_intensity, data_velocity, avgdatatime = self.pulsePairOp(dataOut.data, dataOut.utctime)
1475 dataOut.flagNoData = True
1476
1477 if self.__dataReady:
1478 #print("#------------------------------------------------------")
1479 #print("data_ready",data_intensity.shape)
1480 dataOut.data = data_intensity #valor para plotear RTI
1481 dataOut.nCohInt *= self.n
1482 dataOut.data_intensity = data_intensity #valor para intensidad
1483 dataOut.data_velocity = data_velocity #valor para velocidad
1484 dataOut.PRFbyAngle = self.n #numero de PRF*cada angulo rotado que equivale a un tiempo.
1485 dataOut.utctime = avgdatatime
1486 dataOut.flagNoData = False
1487 return dataOut
1488
1194 1489 # import collections
1195 1490 # from scipy.stats import mode
1196 1491 #
1197 1492 # class Synchronize(Operation):
1198 1493 #
1199 1494 # isConfig = False
1200 1495 # __profIndex = 0
1201 1496 #
1202 1497 # def __init__(self, **kwargs):
1203 1498 #
1204 1499 # Operation.__init__(self, **kwargs)
1205 1500 # # self.isConfig = False
1206 1501 # self.__powBuffer = None
1207 1502 # self.__startIndex = 0
1208 1503 # self.__pulseFound = False
1209 1504 #
1210 1505 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
1211 1506 #
1212 1507 # #Read data
1213 1508 #
1214 1509 # powerdB = dataOut.getPower(channel = channel)
1215 1510 # noisedB = dataOut.getNoise(channel = channel)[0]
1216 1511 #
1217 1512 # self.__powBuffer.extend(powerdB.flatten())
1218 1513 #
1219 1514 # dataArray = numpy.array(self.__powBuffer)
1220 1515 #
1221 1516 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
1222 1517 #
1223 1518 # maxValue = numpy.nanmax(filteredPower)
1224 1519 #
1225 1520 # if maxValue < noisedB + 10:
1226 1521 # #No se encuentra ningun pulso de transmision
1227 1522 # return None
1228 1523 #
1229 1524 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
1230 1525 #
1231 1526 # if len(maxValuesIndex) < 2:
1232 1527 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
1233 1528 # return None
1234 1529 #
1235 1530 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
1236 1531 #
1237 1532 # #Seleccionar solo valores con un espaciamiento de nSamples
1238 1533 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
1239 1534 #
1240 1535 # if len(pulseIndex) < 2:
1241 1536 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1242 1537 # return None
1243 1538 #
1244 1539 # spacing = pulseIndex[1:] - pulseIndex[:-1]
1245 1540 #
1246 1541 # #remover senales que se distancien menos de 10 unidades o muestras
1247 1542 # #(No deberian existir IPP menor a 10 unidades)
1248 1543 #
1249 1544 # realIndex = numpy.where(spacing > 10 )[0]
1250 1545 #
1251 1546 # if len(realIndex) < 2:
1252 1547 # #Solo se encontro un pulso de transmision con ancho mayor a 1
1253 1548 # return None
1254 1549 #
1255 1550 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
1256 1551 # realPulseIndex = pulseIndex[realIndex]
1257 1552 #
1258 1553 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
1259 1554 #
1260 1555 # print "IPP = %d samples" %period
1261 1556 #
1262 1557 # self.__newNSamples = dataOut.nHeights #int(period)
1263 1558 # self.__startIndex = int(realPulseIndex[0])
1264 1559 #
1265 1560 # return 1
1266 1561 #
1267 1562 #
1268 1563 # def setup(self, nSamples, nChannels, buffer_size = 4):
1269 1564 #
1270 1565 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
1271 1566 # maxlen = buffer_size*nSamples)
1272 1567 #
1273 1568 # bufferList = []
1274 1569 #
1275 1570 # for i in range(nChannels):
1276 1571 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN,
1277 1572 # maxlen = buffer_size*nSamples)
1278 1573 #
1279 1574 # bufferList.append(bufferByChannel)
1280 1575 #
1281 1576 # self.__nSamples = nSamples
1282 1577 # self.__nChannels = nChannels
1283 1578 # self.__bufferList = bufferList
1284 1579 #
1285 1580 # def run(self, dataOut, channel = 0):
1286 1581 #
1287 1582 # if not self.isConfig:
1288 1583 # nSamples = dataOut.nHeights
1289 1584 # nChannels = dataOut.nChannels
1290 1585 # self.setup(nSamples, nChannels)
1291 1586 # self.isConfig = True
1292 1587 #
1293 1588 # #Append new data to internal buffer
1294 1589 # for thisChannel in range(self.__nChannels):
1295 1590 # bufferByChannel = self.__bufferList[thisChannel]
1296 1591 # bufferByChannel.extend(dataOut.data[thisChannel])
1297 1592 #
1298 1593 # if self.__pulseFound:
1299 1594 # self.__startIndex -= self.__nSamples
1300 1595 #
1301 1596 # #Finding Tx Pulse
1302 1597 # if not self.__pulseFound:
1303 1598 # indexFound = self.__findTxPulse(dataOut, channel)
1304 1599 #
1305 1600 # if indexFound == None:
1306 1601 # dataOut.flagNoData = True
1307 1602 # return
1308 1603 #
1309 1604 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex)
1310 1605 # self.__pulseFound = True
1311 1606 # self.__startIndex = indexFound
1312 1607 #
1313 1608 # #If pulse was found ...
1314 1609 # for thisChannel in range(self.__nChannels):
1315 1610 # bufferByChannel = self.__bufferList[thisChannel]
1316 1611 # #print self.__startIndex
1317 1612 # x = numpy.array(bufferByChannel)
1318 1613 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
1319 1614 #
1320 1615 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
1321 1616 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
1322 1617 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
1323 1618 #
1324 1619 # dataOut.data = self.__arrayBuffer
1325 1620 #
1326 1621 # self.__startIndex += self.__newNSamples
1327 1622 #
1328 1623 # return
@@ -1,183 +1,203
1 1 #!python
2 2 '''
3 3 '''
4 4
5 5 import os, sys
6 6 import datetime
7 7 import time
8 8
9 9 #path = os.path.dirname(os.getcwd())
10 10 #path = os.path.dirname(path)
11 11 #sys.path.insert(0, path)
12 12
13 13 from schainpy.controller import Project
14 14
15 15 desc = "USRP_test"
16 16 filename = "USRP_processing.xml"
17 17 controllerObj = Project()
18 18 controllerObj.setup(id = '191', name='Test_USRP', description=desc)
19 19
20 20 ############## USED TO PLOT IQ VOLTAGE, POWER AND SPECTRA #############
21 21
22 22 #######################################################################
23 23 ######PATH DE LECTURA, ESCRITURA, GRAFICOS Y ENVIO WEB#################
24 24 #######################################################################
25 25 #path = '/media/data/data/vientos/57.2063km/echoes/NCO_Woodman'
26 26
27 27
28 path = '/home/soporte/data_hdf5' #### with clock 35.16 db noise
29
30 figpath = '/home/soporte/data_hdf5_imag'
28 #path = '/home/soporte/data_hdf5' #### with clock 35.16 db noise
29 path = '/home/alex/WEATHER_DATA/DATA'
30 figpath = '/home/alex/WEATHER_DATA/DATA/pic'
31 #figpath = '/home/soporte/data_hdf5_imag'
31 32 #remotefolder = "/home/wmaster/graficos"
32 33 #######################################################################
33 34 ################# RANGO DE PLOTEO######################################
34 35 #######################################################################
35 36 dBmin = '30'
36 37 dBmax = '60'
37 38 xmin = '0'
38 39 xmax ='24'
39 40 ymin = '0'
40 41 ymax = '600'
41 42 #######################################################################
42 43 ########################FECHA##########################################
43 44 #######################################################################
44 45 str = datetime.date.today()
45 46 today = str.strftime("%Y/%m/%d")
46 47 str2 = str - datetime.timedelta(days=1)
47 48 yesterday = str2.strftime("%Y/%m/%d")
48 49 #######################################################################
49 50 ######################## UNIDAD DE LECTURA#############################
50 51 #######################################################################
51 52 readUnitConfObj = controllerObj.addReadUnit(datatype='DigitalRFReader',
52 53 path=path,
53 54 startDate="2019/01/01",#today,
54 55 endDate="2109/12/30",#today,
55 56 startTime='00:00:00',
56 57 endTime='23:59:59',
57 58 delay=0,
58 59 #set=0,
59 60 online=0,
60 61 walk=1,
61 62 ippKm = 1000)
62 63
63 64 opObj11 = readUnitConfObj.addOperation(name='printInfo')
64 65 opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
65 66 #######################################################################
66 67 ################ OPERACIONES DOMINIO DEL TIEMPO########################
67 68 #######################################################################
68 69
69 70 procUnitConfObjA = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId())
70 71 #
71 72 # codigo64='1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,'+\
72 73 # '1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1'
73 74
74 75 #opObj11 = procUnitConfObjA.addOperation(name='setRadarFrequency')
75 76 #opObj11.addParameter(name='frequency', value='30e6', format='float')
76 77
77 78 #opObj10 = procUnitConfObjA.addOperation(name='Scope', optype='external')
78 79 #opObj10.addParameter(name='id', value='10', format='int')
79 80 ##opObj10.addParameter(name='xmin', value='0', format='int')
80 81 ##opObj10.addParameter(name='xmax', value='50', format='int')
81 82 #opObj10.addParameter(name='type', value='iq')
82 83 #opObj10.addParameter(name='ymin', value='-5000', format='int')
83 84 ##opObj10.addParameter(name='ymax', value='8500', format='int')
84 85
85 86 #opObj10 = procUnitConfObjA.addOperation(name='setH0')
86 87 #opObj10.addParameter(name='h0', value='-5000', format='float')
87 88
88 89 #opObj11 = procUnitConfObjA.addOperation(name='filterByHeights')
89 90 #opObj11.addParameter(name='window', value='1', format='int')
90 91
91 92 #codigo='1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,-1'
92 93 #opObj11 = procUnitConfObjSousy.addOperation(name='Decoder', optype='other')
93 94 #opObj11.addParameter(name='code', value=codigo, format='floatlist')
94 95 #opObj11.addParameter(name='nCode', value='1', format='int')
95 96 #opObj11.addParameter(name='nBaud', value='28', format='int')
96 97
97 98 #opObj11 = procUnitConfObjA.addOperation(name='CohInt', optype='other')
98 #opObj11.addParameter(name='n', value='100', format='int')
99 #opObj11.addParameter(name='n', value='10', format='int')
100
101
102 opObj11 = procUnitConfObjA.addOperation(name='PulsePair', optype='other')
103 opObj11.addParameter(name='n', value='10', format='int')
104
105 opObj11 = procUnitConfObjA.addOperation(name='CreateBlockVoltage', optype='other')
106 opObj11.addParameter(name='m', value='16', format='int')
107
108 procUnitConfObj2 = controllerObj.addProcUnit(datatype='ParametersProc', inputId=procUnitConfObjA.getId())
99 109
110 #Not used because the RGB data is obtained directly from the HF Reader.
111 #opObj21 = procUnitConfObj2.addOperation(name='GetRGBData')
112
113 opObj21 = procUnitConfObj2.addOperation(name='ParamWriter', optype='external')
114 opObj21.addParameter(name='path', value=figpath+'/NEWData')
115 opObj21.addParameter(name='blocksPerFile', value='1', format='int')
116 opObj21.addParameter(name='metadataList',value='heightList',format='list')
117 opObj21.addParameter(name='dataList',value='data_intensity',format='list')
118
119 '''
100 120 #######################################################################
101 121 ########## OPERACIONES DOMINIO DE LA FRECUENCIA########################
102 122 #######################################################################
103 123 procUnitConfObjSousySpectra = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObjA.getId())
104 procUnitConfObjSousySpectra.addParameter(name='nFFTPoints', value='100', format='int')
105 procUnitConfObjSousySpectra.addParameter(name='nProfiles', value='100', format='int')
124 procUnitConfObjSousySpectra.addParameter(name='nFFTPoints', value='16', format='int')
125 procUnitConfObjSousySpectra.addParameter(name='nProfiles', value='16', format='int')
106 126 #procUnitConfObjSousySpectra.addParameter(name='pairsList', value='(0,0),(1,1),(0,1)', format='pairsList')
107 127
108 128 #opObj13 = procUnitConfObjSousySpectra.addOperation(name='removeDC')
109 129 #opObj13.addParameter(name='mode', value='2', format='int')
110 130
111 131 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='IncohInt', optype='other')
112 132 #opObj11.addParameter(name='n', value='60', format='float')
113 133 #######################################################################
114 134 ########## PLOTEO DOMINIO DE LA FRECUENCIA#############################
115 135 #######################################################################
116 136 #SpectraPlot
117 137
118 138 opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraPlot', optype='external')
119 139 opObj11.addParameter(name='id', value='1', format='int')
120 140 opObj11.addParameter(name='wintitle', value='Spectra', format='str')
121 141 #opObj11.addParameter(name='xmin', value=-0.01, format='float')
122 142 #opObj11.addParameter(name='xmax', value=0.01, format='float')
123 143 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
124 144 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
125 145 #opObj11.addParameter(name='ymin', value=ymin, format='int')
126 146 #opObj11.addParameter(name='ymax', value=ymax, format='int')
127 147 opObj11.addParameter(name='showprofile', value='1', format='int')
128 148 opObj11.addParameter(name='save', value=figpath, format='str')
129 149 opObj11.addParameter(name='save_period', value=10, format='int')
130 150
131 151
132 152 #RTIPLOT
133 153
134 154 opObj11 = procUnitConfObjSousySpectra.addOperation(name='RTIPlot', optype='external')
135 155 opObj11.addParameter(name='id', value='2', format='int')
136 156 opObj11.addParameter(name='wintitle', value='RTIPlot', format='str')
137 157 #opObj11.addParameter(name='zmin', value=dBmin, format='int')
138 158 #opObj11.addParameter(name='zmax', value=dBmax, format='int')
139 159 #opObj11.addParameter(name='ymin', value=ymin, format='int')
140 160 #opObj11.addParameter(name='ymax', value=ymax, format='int')
141 161 opObj11.addParameter(name='xmin', value=0, format='int')
142 162 opObj11.addParameter(name='xmax', value=23, format='int')
143 163
144 164 opObj11.addParameter(name='showprofile', value='1', format='int')
145 165 opObj11.addParameter(name='save', value=figpath, format='str')
146 166 opObj11.addParameter(name='save_period', value=10, format='int')
147 167
148 168
149 169 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CrossSpectraPlot', optype='other')
150 170 # opObj11.addParameter(name='id', value='3', format='int')
151 171 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
152 172 # opObj11.addParameter(name='ymin', value=ymin, format='int')
153 173 # opObj11.addParameter(name='ymax', value=ymax, format='int')
154 174 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
155 175 # opObj11.addParameter(name='zmin', value=dBmin, format='int')
156 176 # opObj11.addParameter(name='zmax', value=dBmax, format='int')
157 177 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
158 178 # opObj11.addParameter(name='save', value=0, format='bool')
159 179 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
160 180 # #
161 181 # opObj11 = procUnitConfObjSousySpectra.addOperation(name='CoherenceMap', optype='other')
162 182 # opObj11.addParameter(name='id', value='4', format='int')
163 183 # opObj11.addParameter(name='wintitle', value='Coherence', format='str')
164 184 # opObj11.addParameter(name='phase_cmap', value='jet', format='str')
165 185 # opObj11.addParameter(name='xmin', value=xmin, format='float')
166 186 # opObj11.addParameter(name='xmax', value=xmax, format='float')
167 187 # opObj11.addParameter(name='figpath', value=figures_path, format='str')
168 188 # opObj11.addParameter(name='save', value=0, format='bool')
169 189 # opObj11.addParameter(name='pairsList', value='(0,1)', format='pairsList')
170 190 #
171 191 #######################################################################
172 192 ############### UNIDAD DE ESCRITURA ###################################
173 193 #######################################################################
174 194 #opObj11 = procUnitConfObjSousySpectra.addOperation(name='SpectraWriter', optype='other')
175 195 #opObj11.addParameter(name='path', value=wr_path)
176 196 #opObj11.addParameter(name='blocksPerFile', value='50', format='int')
197 '''
177 198 print ("Escribiendo el archivo XML")
178 199 print ("Leyendo el archivo XML")
179 200
180 201
181 202
182 203 controllerObj.start()
183
General Comments 0
You need to be logged in to leave comments. Login now