##// END OF EJS Templates
23/11/2017
ebocanegra -
r1123:72ed20327727
parent child
Show More

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

@@ -1,1321 +1,1321
1 1 '''
2 2 Created on September , 2012
3 3 @author:
4 4 '''
5 5
6 6 import sys
7 7 import ast
8 8 import datetime
9 9 import traceback
10 10 import math
11 11 import time
12 12 from multiprocessing import Process, Queue, cpu_count
13 13
14 14 import schainpy
15 15 import schainpy.admin
16 16
17 17 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
18 18 from xml.dom import minidom
19 19
20 20 from schainpy.model import *
21 21 from time import sleep
22 22
23 23 def prettify(elem):
24 24 """Return a pretty-printed XML string for the Element.
25 25 """
26 26 rough_string = tostring(elem, 'utf-8')
27 27 reparsed = minidom.parseString(rough_string)
28 28 return reparsed.toprettyxml(indent=" ")
29 29
30 30 def multiSchain(child, nProcess=cpu_count(), startDate=None, endDate=None, by_day=False):
31 31 skip = 0
32 32 cursor = 0
33 33 nFiles = None
34 34 processes = []
35 35 dt1 = datetime.datetime.strptime(startDate, '%Y/%m/%d')
36 36 dt2 = datetime.datetime.strptime(endDate, '%Y/%m/%d')
37 37 days = (dt2 - dt1).days
38 38
39 39 for day in range(days+1):
40 40 skip = 0
41 41 cursor = 0
42 42 q = Queue()
43 43 processes = []
44 44 dt = (dt1 + datetime.timedelta(day)).strftime('%Y/%m/%d')
45 45 firstProcess = Process(target=child, args=(cursor, skip, q, dt))
46 46 firstProcess.start()
47 47 if by_day:
48 48 continue
49 49 nFiles = q.get()
50 50 firstProcess.terminate()
51 51 skip = int(math.ceil(nFiles/nProcess))
52 52 while True:
53 53 processes.append(Process(target=child, args=(cursor, skip, q, dt)))
54 54 processes[cursor].start()
55 55 if nFiles < cursor*skip:
56 56 break
57 57 cursor += 1
58 58
59 59 def beforeExit(exctype, value, trace):
60 60 for process in processes:
61 61 process.terminate()
62 62 process.join()
63 63 print traceback.print_tb(trace)
64 64
65 65 sys.excepthook = beforeExit
66 66
67 67 for process in processes:
68 68 process.join()
69 69 process.terminate()
70 70 time.sleep(3)
71 71
72 72 class ParameterConf():
73 73
74 74 id = None
75 75 name = None
76 76 value = None
77 77 format = None
78 78
79 79 __formated_value = None
80 80
81 81 ELEMENTNAME = 'Parameter'
82 82
83 83 def __init__(self):
84 84
85 85 self.format = 'str'
86 86
87 87 def getElementName(self):
88 88
89 89 return self.ELEMENTNAME
90 90
91 91 def getValue(self):
92 92
93 93 value = self.value
94 94 format = self.format
95 95
96 96 if self.__formated_value != None:
97 97
98 98 return self.__formated_value
99 99
100 100 if format == 'obj':
101 101 return value
102 102
103 103 if format == 'str':
104 104 self.__formated_value = str(value)
105 105 return self.__formated_value
106 106
107 107 if value == '':
108 108 raise ValueError, "%s: This parameter value is empty" %self.name
109 109
110 110 if format == 'list':
111 111 strList = value.split(',')
112 112
113 113 self.__formated_value = strList
114 114
115 115 return self.__formated_value
116 116
117 117 if format == 'intlist':
118 118 """
119 119 Example:
120 120 value = (0,1,2)
121 121 """
122 122
123 123 new_value = ast.literal_eval(value)
124 124
125 125 if type(new_value) not in (tuple, list):
126 126 new_value = [int(new_value)]
127 127
128 128 self.__formated_value = new_value
129 129
130 130 return self.__formated_value
131 131
132 132 if format == 'floatlist':
133 133 """
134 134 Example:
135 135 value = (0.5, 1.4, 2.7)
136 136 """
137 137
138 138 new_value = ast.literal_eval(value)
139 139
140 140 if type(new_value) not in (tuple, list):
141 141 new_value = [float(new_value)]
142 142
143 143 self.__formated_value = new_value
144 144
145 145 return self.__formated_value
146 146
147 147 if format == 'date':
148 148 strList = value.split('/')
149 149 intList = [int(x) for x in strList]
150 150 date = datetime.date(intList[0], intList[1], intList[2])
151 151
152 152 self.__formated_value = date
153 153
154 154 return self.__formated_value
155 155
156 156 if format == 'time':
157 157 strList = value.split(':')
158 158 intList = [int(x) for x in strList]
159 159 time = datetime.time(intList[0], intList[1], intList[2])
160 160
161 161 self.__formated_value = time
162 162
163 163 return self.__formated_value
164 164
165 165 if format == 'pairslist':
166 166 """
167 167 Example:
168 168 value = (0,1),(1,2)
169 169 """
170 170
171 171 new_value = ast.literal_eval(value)
172 172
173 173 if type(new_value) not in (tuple, list):
174 174 raise ValueError, "%s has to be a tuple or list of pairs" %value
175 175
176 176 if type(new_value[0]) not in (tuple, list):
177 177 if len(new_value) != 2:
178 178 raise ValueError, "%s has to be a tuple or list of pairs" %value
179 179 new_value = [new_value]
180 180
181 181 for thisPair in new_value:
182 182 if len(thisPair) != 2:
183 183 raise ValueError, "%s has to be a tuple or list of pairs" %value
184 184
185 185 self.__formated_value = new_value
186 186
187 187 return self.__formated_value
188 188
189 189 if format == 'multilist':
190 190 """
191 191 Example:
192 192 value = (0,1,2),(3,4,5)
193 193 """
194 194 multiList = ast.literal_eval(value)
195 195
196 196 if type(multiList[0]) == int:
197 197 multiList = ast.literal_eval("(" + value + ")")
198 198
199 199 self.__formated_value = multiList
200 200
201 201 return self.__formated_value
202 202
203 203 if format == 'bool':
204 204 value = int(value)
205 205
206 206 if format == 'int':
207 207 value = float(value)
208 208
209 209 format_func = eval(format)
210 210
211 211 self.__formated_value = format_func(value)
212 212
213 213 return self.__formated_value
214 214
215 215 def updateId(self, new_id):
216 216
217 217 self.id = str(new_id)
218 218
219 219 def setup(self, id, name, value, format='str'):
220 220
221 221 self.id = str(id)
222 222 self.name = name
223 223 if format == 'obj':
224 224 self.value = value
225 225 else:
226 226 self.value = str(value)
227 227 self.format = str.lower(format)
228 228
229 229 self.getValue()
230 230
231 231 return 1
232 232
233 233 def update(self, name, value, format='str'):
234 234
235 235 self.name = name
236 236 self.value = str(value)
237 237 self.format = format
238 238
239 239 def makeXml(self, opElement):
240 240 if self.name not in ('queue',):
241 241 parmElement = SubElement(opElement, self.ELEMENTNAME)
242 242 parmElement.set('id', str(self.id))
243 243 parmElement.set('name', self.name)
244 244 parmElement.set('value', self.value)
245 245 parmElement.set('format', self.format)
246 246
247 247 def readXml(self, parmElement):
248 248
249 249 self.id = parmElement.get('id')
250 250 self.name = parmElement.get('name')
251 251 self.value = parmElement.get('value')
252 252 self.format = str.lower(parmElement.get('format'))
253 253
254 254 #Compatible with old signal chain version
255 255 if self.format == 'int' and self.name == 'idfigure':
256 256 self.name = 'id'
257 257
258 258 def printattr(self):
259 259
260 260 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
261 261
262 262 class OperationConf():
263 263
264 264 id = None
265 265 name = None
266 266 priority = None
267 267 type = None
268 268
269 269 parmConfObjList = []
270 270
271 271 ELEMENTNAME = 'Operation'
272 272
273 273 def __init__(self):
274 274
275 275 self.id = '0'
276 276 self.name = None
277 277 self.priority = None
278 278 self.type = 'self'
279 279
280 280
281 281 def __getNewId(self):
282 282
283 283 return int(self.id)*10 + len(self.parmConfObjList) + 1
284 284
285 285 def updateId(self, new_id):
286 286
287 287 self.id = str(new_id)
288 288
289 289 n = 1
290 290 for parmObj in self.parmConfObjList:
291 291
292 292 idParm = str(int(new_id)*10 + n)
293 293 parmObj.updateId(idParm)
294 294
295 295 n += 1
296 296
297 297 def getElementName(self):
298 298
299 299 return self.ELEMENTNAME
300 300
301 301 def getParameterObjList(self):
302 302
303 303 return self.parmConfObjList
304 304
305 305 def getParameterObj(self, parameterName):
306 306
307 307 for parmConfObj in self.parmConfObjList:
308 308
309 309 if parmConfObj.name != parameterName:
310 310 continue
311 311
312 312 return parmConfObj
313 313
314 314 return None
315 315
316 316 def getParameterObjfromValue(self, parameterValue):
317 317
318 318 for parmConfObj in self.parmConfObjList:
319 319
320 320 if parmConfObj.getValue() != parameterValue:
321 321 continue
322 322
323 323 return parmConfObj.getValue()
324 324
325 325 return None
326 326
327 327 def getParameterValue(self, parameterName):
328 328
329 329 parameterObj = self.getParameterObj(parameterName)
330 330
331 331 # if not parameterObj:
332 332 # return None
333 333
334 334 value = parameterObj.getValue()
335 335
336 336 return value
337 337
338 338
339 339 def getKwargs(self):
340 340
341 341 kwargs = {}
342 342
343 343 for parmConfObj in self.parmConfObjList:
344 344 if self.name == 'run' and parmConfObj.name == 'datatype':
345 345 continue
346 346
347 347 kwargs[parmConfObj.name] = parmConfObj.getValue()
348 348
349 349 return kwargs
350 350
351 351 def setup(self, id, name, priority, type):
352 352
353 353 self.id = str(id)
354 354 self.name = name
355 355 self.type = type
356 356 self.priority = priority
357 357
358 358 self.parmConfObjList = []
359 359
360 360 def removeParameters(self):
361 361
362 362 for obj in self.parmConfObjList:
363 363 del obj
364 364
365 365 self.parmConfObjList = []
366 366
367 367 def addParameter(self, name, value, format='str'):
368 368
369 369 id = self.__getNewId()
370 370
371 371 parmConfObj = ParameterConf()
372 372 if not parmConfObj.setup(id, name, value, format):
373 373 return None
374 374
375 375 self.parmConfObjList.append(parmConfObj)
376 376
377 377 return parmConfObj
378 378
379 379 def changeParameter(self, name, value, format='str'):
380 380
381 381 parmConfObj = self.getParameterObj(name)
382 382 parmConfObj.update(name, value, format)
383 383
384 384 return parmConfObj
385 385
386 386 def makeXml(self, procUnitElement):
387 387
388 388 opElement = SubElement(procUnitElement, self.ELEMENTNAME)
389 389 opElement.set('id', str(self.id))
390 390 opElement.set('name', self.name)
391 391 opElement.set('type', self.type)
392 392 opElement.set('priority', str(self.priority))
393 393
394 394 for parmConfObj in self.parmConfObjList:
395 395 parmConfObj.makeXml(opElement)
396 396
397 397 def readXml(self, opElement):
398 398
399 399 self.id = opElement.get('id')
400 400 self.name = opElement.get('name')
401 401 self.type = opElement.get('type')
402 402 self.priority = opElement.get('priority')
403 403
404 404 #Compatible with old signal chain version
405 405 #Use of 'run' method instead 'init'
406 406 if self.type == 'self' and self.name == 'init':
407 407 self.name = 'run'
408 408
409 409 self.parmConfObjList = []
410 410
411 411 parmElementList = opElement.iter(ParameterConf().getElementName())
412 412
413 413 for parmElement in parmElementList:
414 414 parmConfObj = ParameterConf()
415 415 parmConfObj.readXml(parmElement)
416 416
417 417 #Compatible with old signal chain version
418 418 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
419 419 if self.type != 'self' and self.name == 'Plot':
420 420 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
421 421 self.name = parmConfObj.value
422 422 continue
423 423
424 424 self.parmConfObjList.append(parmConfObj)
425 425
426 426 def printattr(self):
427 427
428 428 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
429 429 self.id,
430 430 self.name,
431 431 self.type,
432 432 self.priority)
433 433
434 434 for parmConfObj in self.parmConfObjList:
435 435 parmConfObj.printattr()
436 436
437 437 def createObject(self, plotter_queue=None):
438 438
439 439
440 440 if self.type == 'self':
441 441 raise ValueError, "This operation type cannot be created"
442 442
443 443 if self.type == 'plotter':
444 444 #Plotter(plotter_name)
445 445 if not plotter_queue:
446 446 raise ValueError, "plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)"
447 447
448 448 opObj = Plotter(self.name, plotter_queue)
449 449
450 450 if self.type == 'external' or self.type == 'other':
451 451
452 452 className = eval(self.name)
453 453 kwargs = self.getKwargs()
454 454
455 455 opObj = className(**kwargs)
456 456
457 457 return opObj
458 458
459 459
460 460 class ProcUnitConf():
461 461
462 462 id = None
463 463 name = None
464 464 datatype = None
465 465 inputId = None
466 466 parentId = None
467 467
468 468 opConfObjList = []
469 469
470 470 procUnitObj = None
471 471 opObjList = []
472 472
473 473 ELEMENTNAME = 'ProcUnit'
474 474
475 475 def __init__(self):
476 476
477 477 self.id = None
478 478 self.datatype = None
479 479 self.name = None
480 480 self.inputId = None
481 481
482 482 self.opConfObjList = []
483 483
484 484 self.procUnitObj = None
485 485 self.opObjDict = {}
486 486
487 487 def __getPriority(self):
488 488
489 489 return len(self.opConfObjList)+1
490 490
491 491 def __getNewId(self):
492 492
493 493 return int(self.id)*10 + len(self.opConfObjList) + 1
494 494
495 495 def getElementName(self):
496 496
497 497 return self.ELEMENTNAME
498 498
499 499 def getId(self):
500 500
501 501 return self.id
502 502
503 503 def updateId(self, new_id, parentId=parentId):
504 504
505 505
506 506 new_id = int(parentId)*10 + (int(self.id) % 10)
507 507 new_inputId = int(parentId)*10 + (int(self.inputId) % 10)
508 508
509 509 #If this proc unit has not inputs
510 510 if self.inputId == '0':
511 511 new_inputId = 0
512 512
513 513 n = 1
514 514 for opConfObj in self.opConfObjList:
515 515
516 516 idOp = str(int(new_id)*10 + n)
517 517 opConfObj.updateId(idOp)
518 518
519 519 n += 1
520 520
521 521 self.parentId = str(parentId)
522 522 self.id = str(new_id)
523 523 self.inputId = str(new_inputId)
524 524
525 525
526 526 def getInputId(self):
527 527
528 528 return self.inputId
529 529
530 530 def getOperationObjList(self):
531 531
532 532 return self.opConfObjList
533 533
534 534 def getOperationObj(self, name=None):
535 535
536 536 for opConfObj in self.opConfObjList:
537 537
538 538 if opConfObj.name != name:
539 539 continue
540 540
541 541 return opConfObj
542 542
543 543 return None
544 544
545 545 def getOpObjfromParamValue(self, value=None):
546 546
547 547 for opConfObj in self.opConfObjList:
548 548 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
549 549 continue
550 550 return opConfObj
551 551 return None
552 552
553 553 def getProcUnitObj(self):
554 554
555 555 return self.procUnitObj
556 556
557 557 def setup(self, id, name, datatype, inputId, parentId=None):
558 558
559 559 #Compatible with old signal chain version
560 560 if datatype==None and name==None:
561 561 raise ValueError, "datatype or name should be defined"
562 562
563 563 if name==None:
564 564 if 'Proc' in datatype:
565 565 name = datatype
566 566 else:
567 567 name = '%sProc' %(datatype)
568 568
569 569 if datatype==None:
570 570 datatype = name.replace('Proc','')
571 571
572 572 self.id = str(id)
573 573 self.name = name
574 574 self.datatype = datatype
575 575 self.inputId = inputId
576 576 self.parentId = parentId
577 577
578 578 self.opConfObjList = []
579 579
580 580 self.addOperation(name='run', optype='self')
581 581
582 582 def removeOperations(self):
583 583
584 584 for obj in self.opConfObjList:
585 585 del obj
586 586
587 587 self.opConfObjList = []
588 588 self.addOperation(name='run')
589 589
590 590 def addParameter(self, **kwargs):
591 591 '''
592 592 Add parameters to "run" operation
593 593 '''
594 594 opObj = self.opConfObjList[0]
595 595
596 596 opObj.addParameter(**kwargs)
597 597
598 598 return opObj
599 599
600 600 def addOperation(self, name, optype='self'):
601 601
602 602 id = self.__getNewId()
603 603 priority = self.__getPriority()
604 604
605 605 opConfObj = OperationConf()
606 606 opConfObj.setup(id, name=name, priority=priority, type=optype)
607 607
608 608 self.opConfObjList.append(opConfObj)
609 609
610 610 return opConfObj
611 611
612 612 def makeXml(self, projectElement):
613 613
614 614 procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
615 615 procUnitElement.set('id', str(self.id))
616 616 procUnitElement.set('name', self.name)
617 617 procUnitElement.set('datatype', self.datatype)
618 618 procUnitElement.set('inputId', str(self.inputId))
619 619
620 620 for opConfObj in self.opConfObjList:
621 621 opConfObj.makeXml(procUnitElement)
622 622
623 623 def readXml(self, upElement):
624 624
625 625 self.id = upElement.get('id')
626 626 self.name = upElement.get('name')
627 627 self.datatype = upElement.get('datatype')
628 628 self.inputId = upElement.get('inputId')
629 629
630 630 if self.ELEMENTNAME == "ReadUnit":
631 631 self.datatype = self.datatype.replace("Reader", "")
632 632
633 633 if self.ELEMENTNAME == "ProcUnit":
634 634 self.datatype = self.datatype.replace("Proc", "")
635 635
636 636 if self.inputId == 'None':
637 637 self.inputId = '0'
638 638
639 639 self.opConfObjList = []
640 640
641 641 opElementList = upElement.iter(OperationConf().getElementName())
642 642
643 643 for opElement in opElementList:
644 644 opConfObj = OperationConf()
645 645 opConfObj.readXml(opElement)
646 646 self.opConfObjList.append(opConfObj)
647 647
648 648 def printattr(self):
649 649
650 650 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
651 651 self.id,
652 652 self.name,
653 653 self.datatype,
654 654 self.inputId)
655 655
656 656 for opConfObj in self.opConfObjList:
657 657 opConfObj.printattr()
658 658
659 659
660 660 def getKwargs(self):
661 661
662 662 opObj = self.opConfObjList[0]
663 663 kwargs = opObj.getKwargs()
664 664
665 665 return kwargs
666 666
667 667 def createObjects(self, plotter_queue=None):
668 668
669 669 className = eval(self.name)
670 670 kwargs = self.getKwargs()
671 671 procUnitObj = className(**kwargs)
672 672
673 673 for opConfObj in self.opConfObjList:
674 674
675 675 if opConfObj.type=='self' and self.name=='run':
676 676 continue
677 677 elif opConfObj.type=='self':
678 678 procUnitObj.addOperationKwargs(opConfObj.id, **opConfObj.getKwargs())
679 679 continue
680 680
681 681 opObj = opConfObj.createObject(plotter_queue)
682 682
683 683 self.opObjDict[opConfObj.id] = opObj
684 684
685 685 procUnitObj.addOperation(opObj, opConfObj.id)
686 686
687 687 self.procUnitObj = procUnitObj
688 688
689 689 return procUnitObj
690 690
691 691 def run(self):
692 692
693 693 is_ok = False
694 694
695 695 for opConfObj in self.opConfObjList:
696 696
697 697 kwargs = {}
698 698 for parmConfObj in opConfObj.getParameterObjList():
699 699 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
700 700 continue
701 701
702 702 kwargs[parmConfObj.name] = parmConfObj.getValue()
703 703
704 704 #ini = time.time()
705 705
706 706 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
707 707 sts = self.procUnitObj.call(opType = opConfObj.type,
708 708 opName = opConfObj.name,
709 opId = opConfObj.id,
709 opId = opConfObj.id
710 710 )
711 711
712 712 # total_time = time.time() - ini
713 713 #
714 714 # if total_time > 0.002:
715 715 # print "%s::%s took %f seconds" %(self.name, opConfObj.name, total_time)
716 716
717 717 is_ok = is_ok or sts
718 718
719 719 return is_ok
720 720
721 721 def close(self):
722 722
723 723 for opConfObj in self.opConfObjList:
724 724 if opConfObj.type == 'self':
725 725 continue
726 726
727 727 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
728 728 opObj.close()
729 729
730 730 self.procUnitObj.close()
731 731
732 732 return
733 733
734 734 class ReadUnitConf(ProcUnitConf):
735 735
736 736 path = None
737 737 startDate = None
738 738 endDate = None
739 739 startTime = None
740 740 endTime = None
741 741
742 742 ELEMENTNAME = 'ReadUnit'
743 743
744 744 def __init__(self):
745 745
746 746 self.id = None
747 747 self.datatype = None
748 748 self.name = None
749 749 self.inputId = None
750 750
751 751 self.parentId = None
752 752
753 753 self.opConfObjList = []
754 754 self.opObjList = []
755 755
756 756 def getElementName(self):
757 757
758 758 return self.ELEMENTNAME
759 759
760 760 def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, queue=None, **kwargs):
761 761
762 762 #Compatible with old signal chain version
763 763 if datatype==None and name==None:
764 764 raise ValueError, "datatype or name should be defined"
765 765
766 766 if name==None:
767 767 if 'Reader' in datatype:
768 768 name = datatype
769 769 else:
770 770 name = '%sReader' %(datatype)
771 771
772 772 if datatype==None:
773 773 datatype = name.replace('Reader','')
774 774
775 775 self.id = id
776 776 self.name = name
777 777 self.datatype = datatype
778 778
779 779 self.path = os.path.abspath(path)
780 780 self.startDate = startDate
781 781 self.endDate = endDate
782 782 self.startTime = startTime
783 783 self.endTime = endTime
784 784
785 785 self.inputId = '0'
786 786 self.parentId = parentId
787 787 self.queue = queue
788 788 self.addRunOperation(**kwargs)
789 789
790 790 def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs):
791 791
792 792 #Compatible with old signal chain version
793 793 if datatype==None and name==None:
794 794 raise ValueError, "datatype or name should be defined"
795 795
796 796 if name==None:
797 797 if 'Reader' in datatype:
798 798 name = datatype
799 799 else:
800 800 name = '%sReader' %(datatype)
801 801
802 802 if datatype==None:
803 803 datatype = name.replace('Reader','')
804 804
805 805 self.datatype = datatype
806 806 self.name = name
807 807 self.path = path
808 808 self.startDate = startDate
809 809 self.endDate = endDate
810 810 self.startTime = startTime
811 811 self.endTime = endTime
812 812
813 813 self.inputId = '0'
814 814 self.parentId = parentId
815 815
816 816 self.updateRunOperation(**kwargs)
817 817
818 818 def removeOperations(self):
819 819
820 820 for obj in self.opConfObjList:
821 821 del obj
822 822
823 823 self.opConfObjList = []
824 824
825 825 def addRunOperation(self, **kwargs):
826 826
827 827 opObj = self.addOperation(name = 'run', optype = 'self')
828 828
829 829 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
830 830 opObj.addParameter(name='path' , value=self.path, format='str')
831 831 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
832 832 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
833 833 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
834 834 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
835 835 opObj.addParameter(name='queue' , value=self.queue, format='obj')
836 836
837 837 for key, value in kwargs.items():
838 838 opObj.addParameter(name=key, value=value, format=type(value).__name__)
839 839
840 840 return opObj
841 841
842 842 def updateRunOperation(self, **kwargs):
843 843
844 844 opObj = self.getOperationObj(name = 'run')
845 845 opObj.removeParameters()
846 846
847 847 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
848 848 opObj.addParameter(name='path' , value=self.path, format='str')
849 849 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
850 850 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
851 851 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
852 852 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
853 853
854 854 for key, value in kwargs.items():
855 855 opObj.addParameter(name=key, value=value, format=type(value).__name__)
856 856
857 857 return opObj
858 858
859 859 # def makeXml(self, projectElement):
860 860 #
861 861 # procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
862 862 # procUnitElement.set('id', str(self.id))
863 863 # procUnitElement.set('name', self.name)
864 864 # procUnitElement.set('datatype', self.datatype)
865 865 # procUnitElement.set('inputId', str(self.inputId))
866 866 #
867 867 # for opConfObj in self.opConfObjList:
868 868 # opConfObj.makeXml(procUnitElement)
869 869
870 870 def readXml(self, upElement):
871 871
872 872 self.id = upElement.get('id')
873 873 self.name = upElement.get('name')
874 874 self.datatype = upElement.get('datatype')
875 875 self.inputId = upElement.get('inputId')
876 876
877 877 if self.ELEMENTNAME == "ReadUnit":
878 878 self.datatype = self.datatype.replace("Reader", "")
879 879
880 880 if self.inputId == 'None':
881 881 self.inputId = '0'
882 882
883 883 self.opConfObjList = []
884 884
885 885 opElementList = upElement.iter(OperationConf().getElementName())
886 886
887 887 for opElement in opElementList:
888 888 opConfObj = OperationConf()
889 889 opConfObj.readXml(opElement)
890 890 self.opConfObjList.append(opConfObj)
891 891
892 892 if opConfObj.name == 'run':
893 893 self.path = opConfObj.getParameterValue('path')
894 894 self.startDate = opConfObj.getParameterValue('startDate')
895 895 self.endDate = opConfObj.getParameterValue('endDate')
896 896 self.startTime = opConfObj.getParameterValue('startTime')
897 897 self.endTime = opConfObj.getParameterValue('endTime')
898 898
899 899 class Project():
900 900
901 901 id = None
902 902 name = None
903 903 description = None
904 904 filename = None
905 905
906 906 procUnitConfObjDict = None
907 907
908 908 ELEMENTNAME = 'Project'
909 909
910 910 plotterQueue = None
911 911
912 912 def __init__(self, plotter_queue=None):
913 913
914 914 self.id = None
915 915 self.name = None
916 916 self.description = None
917 917
918 918 self.plotterQueue = plotter_queue
919 919
920 920 self.procUnitConfObjDict = {}
921 921
922 922 def __getNewId(self):
923 923
924 924 idList = self.procUnitConfObjDict.keys()
925 925
926 926 id = int(self.id)*10
927 927
928 928 while True:
929 929 id += 1
930 930
931 931 if str(id) in idList:
932 932 continue
933 933
934 934 break
935 935
936 936 return str(id)
937 937
938 938 def getElementName(self):
939 939
940 940 return self.ELEMENTNAME
941 941
942 942 def getId(self):
943 943
944 944 return self.id
945 945
946 946 def updateId(self, new_id):
947 947
948 948 self.id = str(new_id)
949 949
950 950 keyList = self.procUnitConfObjDict.keys()
951 951 keyList.sort()
952 952
953 953 n = 1
954 954 newProcUnitConfObjDict = {}
955 955
956 956 for procKey in keyList:
957 957
958 958 procUnitConfObj = self.procUnitConfObjDict[procKey]
959 959 idProcUnit = str(int(self.id)*10 + n)
960 960 procUnitConfObj.updateId(idProcUnit, parentId = self.id)
961 961
962 962 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
963 963 n += 1
964 964
965 965 self.procUnitConfObjDict = newProcUnitConfObjDict
966 966
967 967 def setup(self, id, name, description):
968 968
969 969 self.id = str(id)
970 970 self.name = name
971 971 self.description = description
972 972
973 973 def update(self, name, description):
974 974
975 975 self.name = name
976 976 self.description = description
977 977
978 978 def addReadUnit(self, id=None, datatype=None, name=None, **kwargs):
979 979
980 980 if id is None:
981 981 idReadUnit = self.__getNewId()
982 982 else:
983 983 idReadUnit = str(id)
984 984
985 985 readUnitConfObj = ReadUnitConf()
986 986 readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs)
987 987
988 988 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
989 989
990 990 return readUnitConfObj
991 991
992 992 def addProcUnit(self, inputId='0', datatype=None, name=None):
993 993
994 994 idProcUnit = self.__getNewId()
995 995
996 996 procUnitConfObj = ProcUnitConf()
997 997 procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id)
998 998
999 999 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1000 1000
1001 1001 return procUnitConfObj
1002 1002
1003 1003 def removeProcUnit(self, id):
1004 1004
1005 1005 if id in self.procUnitConfObjDict.keys():
1006 1006 self.procUnitConfObjDict.pop(id)
1007 1007
1008 1008 def getReadUnitId(self):
1009 1009
1010 1010 readUnitConfObj = self.getReadUnitObj()
1011 1011
1012 1012 return readUnitConfObj.id
1013 1013
1014 1014 def getReadUnitObj(self):
1015 1015
1016 1016 for obj in self.procUnitConfObjDict.values():
1017 1017 if obj.getElementName() == "ReadUnit":
1018 1018 return obj
1019 1019
1020 1020 return None
1021 1021
1022 1022 def getProcUnitObj(self, id=None, name=None):
1023 1023
1024 1024 if id != None:
1025 1025 return self.procUnitConfObjDict[id]
1026 1026
1027 1027 if name != None:
1028 1028 return self.getProcUnitObjByName(name)
1029 1029
1030 1030 return None
1031 1031
1032 1032 def getProcUnitObjByName(self, name):
1033 1033
1034 1034 for obj in self.procUnitConfObjDict.values():
1035 1035 if obj.name == name:
1036 1036 return obj
1037 1037
1038 1038 return None
1039 1039
1040 1040 def procUnitItems(self):
1041 1041
1042 1042 return self.procUnitConfObjDict.items()
1043 1043
1044 1044 def makeXml(self):
1045 1045
1046 1046 projectElement = Element('Project')
1047 1047 projectElement.set('id', str(self.id))
1048 1048 projectElement.set('name', self.name)
1049 1049 projectElement.set('description', self.description)
1050 1050
1051 1051 for procUnitConfObj in self.procUnitConfObjDict.values():
1052 1052 procUnitConfObj.makeXml(projectElement)
1053 1053
1054 1054 self.projectElement = projectElement
1055 1055
1056 1056 def writeXml(self, filename=None):
1057 1057
1058 1058 if filename == None:
1059 1059 if self.filename:
1060 1060 filename = self.filename
1061 1061 else:
1062 1062 filename = "schain.xml"
1063 1063
1064 1064 if not filename:
1065 1065 print "filename has not been defined. Use setFilename(filename) for do it."
1066 1066 return 0
1067 1067
1068 1068 abs_file = os.path.abspath(filename)
1069 1069
1070 1070 if not os.access(os.path.dirname(abs_file), os.W_OK):
1071 1071 print "No write permission on %s" %os.path.dirname(abs_file)
1072 1072 return 0
1073 1073
1074 1074 if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)):
1075 1075 print "File %s already exists and it could not be overwriten" %abs_file
1076 1076 return 0
1077 1077
1078 1078 self.makeXml()
1079 1079
1080 1080 ElementTree(self.projectElement).write(abs_file, method='xml')
1081 1081
1082 1082 self.filename = abs_file
1083 1083
1084 1084 return 1
1085 1085
1086 1086 def readXml(self, filename = None):
1087 1087
1088 1088 if not filename:
1089 1089 print "filename is not defined"
1090 1090 return 0
1091 1091
1092 1092 abs_file = os.path.abspath(filename)
1093 1093
1094 1094 if not os.path.isfile(abs_file):
1095 1095 print "%s file does not exist" %abs_file
1096 1096 return 0
1097 1097
1098 1098 self.projectElement = None
1099 1099 self.procUnitConfObjDict = {}
1100 1100
1101 1101 try:
1102 1102 self.projectElement = ElementTree().parse(abs_file)
1103 1103 except:
1104 1104 print "Error reading %s, verify file format" %filename
1105 1105 return 0
1106 1106
1107 1107 self.project = self.projectElement.tag
1108 1108
1109 1109 self.id = self.projectElement.get('id')
1110 1110 self.name = self.projectElement.get('name')
1111 1111 self.description = self.projectElement.get('description')
1112 1112
1113 1113 readUnitElementList = self.projectElement.iter(ReadUnitConf().getElementName())
1114 1114
1115 1115 for readUnitElement in readUnitElementList:
1116 1116 readUnitConfObj = ReadUnitConf()
1117 1117 readUnitConfObj.readXml(readUnitElement)
1118 1118
1119 1119 if readUnitConfObj.parentId == None:
1120 1120 readUnitConfObj.parentId = self.id
1121 1121
1122 1122 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
1123 1123
1124 1124 procUnitElementList = self.projectElement.iter(ProcUnitConf().getElementName())
1125 1125
1126 1126 for procUnitElement in procUnitElementList:
1127 1127 procUnitConfObj = ProcUnitConf()
1128 1128 procUnitConfObj.readXml(procUnitElement)
1129 1129
1130 1130 if procUnitConfObj.parentId == None:
1131 1131 procUnitConfObj.parentId = self.id
1132 1132
1133 1133 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1134 1134
1135 1135 self.filename = abs_file
1136 1136
1137 1137 return 1
1138 1138
1139 1139 def printattr(self):
1140 1140
1141 1141 print "Project[%s]: name = %s, description = %s" %(self.id,
1142 1142 self.name,
1143 1143 self.description)
1144 1144
1145 1145 for procUnitConfObj in self.procUnitConfObjDict.values():
1146 1146 procUnitConfObj.printattr()
1147 1147
1148 1148 def createObjects(self):
1149 1149
1150 1150 for procUnitConfObj in self.procUnitConfObjDict.values():
1151 1151 procUnitConfObj.createObjects(self.plotterQueue)
1152 1152
1153 1153 def __connect(self, objIN, thisObj):
1154 1154
1155 1155 thisObj.setInput(objIN.getOutputObj())
1156 1156
1157 1157 def connectObjects(self):
1158 1158
1159 1159 for thisPUConfObj in self.procUnitConfObjDict.values():
1160 1160
1161 1161 inputId = thisPUConfObj.getInputId()
1162 1162
1163 1163 if int(inputId) == 0:
1164 1164 continue
1165 1165
1166 1166 #Get input object
1167 1167 puConfINObj = self.procUnitConfObjDict[inputId]
1168 1168 puObjIN = puConfINObj.getProcUnitObj()
1169 1169
1170 1170 #Get current object
1171 1171 thisPUObj = thisPUConfObj.getProcUnitObj()
1172 1172
1173 1173 self.__connect(puObjIN, thisPUObj)
1174 1174
1175 1175 def __handleError(self, procUnitConfObj, send_email=True):
1176 1176
1177 1177 import socket
1178 1178
1179 1179 err = traceback.format_exception(sys.exc_info()[0],
1180 1180 sys.exc_info()[1],
1181 1181 sys.exc_info()[2])
1182 1182
1183 1183 print "***** Error occurred in %s *****" %(procUnitConfObj.name)
1184 1184 print "***** %s" %err[-1]
1185 1185
1186 1186 message = "".join(err)
1187 1187
1188 1188 sys.stderr.write(message)
1189 1189
1190 1190 if not send_email:
1191 1191 return
1192 1192
1193 1193 subject = "SChain v%s: Error running %s\n" %(schainpy.__version__, procUnitConfObj.name)
1194 1194
1195 1195 subtitle = "%s: %s\n" %(procUnitConfObj.getElementName() ,procUnitConfObj.name)
1196 1196 subtitle += "Hostname: %s\n" %socket.gethostbyname(socket.gethostname())
1197 1197 subtitle += "Working directory: %s\n" %os.path.abspath("./")
1198 1198 subtitle += "Configuration file: %s\n" %self.filename
1199 1199 subtitle += "Time: %s\n" %str(datetime.datetime.now())
1200 1200
1201 1201 readUnitConfObj = self.getReadUnitObj()
1202 1202 if readUnitConfObj:
1203 1203 subtitle += "\nInput parameters:\n"
1204 1204 subtitle += "[Data path = %s]\n" %readUnitConfObj.path
1205 1205 subtitle += "[Data type = %s]\n" %readUnitConfObj.datatype
1206 1206 subtitle += "[Start date = %s]\n" %readUnitConfObj.startDate
1207 1207 subtitle += "[End date = %s]\n" %readUnitConfObj.endDate
1208 1208 subtitle += "[Start time = %s]\n" %readUnitConfObj.startTime
1209 1209 subtitle += "[End time = %s]\n" %readUnitConfObj.endTime
1210 1210
1211 1211 adminObj = schainpy.admin.SchainNotify()
1212 1212 adminObj.sendAlert(message=message,
1213 1213 subject=subject,
1214 1214 subtitle=subtitle,
1215 1215 filename=self.filename)
1216 1216
1217 1217 def isPaused(self):
1218 1218 return 0
1219 1219
1220 1220 def isStopped(self):
1221 1221 return 0
1222 1222
1223 1223 def runController(self):
1224 1224 """
1225 1225 returns 0 when this process has been stopped, 1 otherwise
1226 1226 """
1227 1227
1228 1228 if self.isPaused():
1229 1229 print "Process suspended"
1230 1230
1231 1231 while True:
1232 1232 sleep(0.1)
1233 1233
1234 1234 if not self.isPaused():
1235 1235 break
1236 1236
1237 1237 if self.isStopped():
1238 1238 break
1239 1239
1240 1240 print "Process reinitialized"
1241 1241
1242 1242 if self.isStopped():
1243 1243 print "Process stopped"
1244 1244 return 0
1245 1245
1246 1246 return 1
1247 1247
1248 1248 def setFilename(self, filename):
1249 1249
1250 1250 self.filename = filename
1251 1251
1252 1252 def setPlotterQueue(self, plotter_queue):
1253 1253
1254 1254 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1255 1255
1256 1256 def getPlotterQueue(self):
1257 1257
1258 1258 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1259 1259
1260 1260 def useExternalPlotter(self):
1261 1261
1262 1262 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1263 1263
1264 1264 def run(self):
1265 1265
1266 1266 print
1267 1267 print "*"*60
1268 1268 print " Starting SIGNAL CHAIN PROCESSING v%s " %schainpy.__version__
1269 1269 print "*"*60
1270 1270 print
1271 1271
1272 1272 keyList = self.procUnitConfObjDict.keys()
1273 1273 keyList.sort()
1274 1274
1275 1275 while(True):
1276 1276
1277 1277 is_ok = False
1278 1278
1279 1279 for procKey in keyList:
1280 1280 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
1281 1281
1282 1282 procUnitConfObj = self.procUnitConfObjDict[procKey]
1283 1283
1284 1284 try:
1285 1285 sts = procUnitConfObj.run()
1286 1286 is_ok = is_ok or sts
1287 1287 except KeyboardInterrupt:
1288 1288 is_ok = False
1289 1289 break
1290 1290 except ValueError, e:
1291 1291 sleep(0.5)
1292 1292 self.__handleError(procUnitConfObj, send_email=True)
1293 1293 is_ok = False
1294 1294 break
1295 1295 except:
1296 1296 sleep(0.5)
1297 1297 self.__handleError(procUnitConfObj)
1298 1298 is_ok = False
1299 1299 break
1300 1300
1301 1301 #If every process unit finished so end process
1302 1302 if not(is_ok):
1303 1303 # print "Every process unit have finished"
1304 1304 break
1305 1305
1306 1306 if not self.runController():
1307 1307 break
1308 1308
1309 1309 #Closing every process
1310 1310 for procKey in keyList:
1311 1311 procUnitConfObj = self.procUnitConfObjDict[procKey]
1312 1312 procUnitConfObj.close()
1313 1313
1314 1314 print "Process finished"
1315 1315
1316 1316 def start(self, filename=None):
1317 1317
1318 1318 self.writeXml(filename)
1319 1319 self.createObjects()
1320 1320 self.connectObjects()
1321 1321 self.run()
@@ -1,2154 +1,2155
1 1 import os
2 2 import datetime
3 3 import numpy
4 4 import inspect
5 5 from figure import Figure, isRealtime, isTimeInHourRange
6 6 from plotting_codes import *
7 7
8 8
9 9 class FitGauPlot(Figure):
10 10
11 11 isConfig = None
12 12 __nsubplots = None
13 13
14 14 WIDTHPROF = None
15 15 HEIGHTPROF = None
16 16 PREFIX = 'fitgau'
17 17
18 18 def __init__(self, **kwargs):
19 19 Figure.__init__(self, **kwargs)
20 20 self.isConfig = False
21 21 self.__nsubplots = 1
22 22
23 23 self.WIDTH = 250
24 24 self.HEIGHT = 250
25 25 self.WIDTHPROF = 120
26 26 self.HEIGHTPROF = 0
27 27 self.counter_imagwr = 0
28 28
29 29 self.PLOT_CODE = SPEC_CODE
30 30
31 31 self.FTP_WEI = None
32 32 self.EXP_CODE = None
33 33 self.SUB_EXP_CODE = None
34 34 self.PLOT_POS = None
35 35
36 36 self.__xfilter_ena = False
37 37 self.__yfilter_ena = False
38 38
39 39 def getSubplots(self):
40 40
41 41 ncol = int(numpy.sqrt(self.nplots)+0.9)
42 42 nrow = int(self.nplots*1./ncol + 0.9)
43 43
44 44 return nrow, ncol
45 45
46 46 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
47 47
48 48 self.__showprofile = showprofile
49 49 self.nplots = nplots
50 50
51 51 ncolspan = 1
52 52 colspan = 1
53 53 if showprofile:
54 54 ncolspan = 3
55 55 colspan = 2
56 56 self.__nsubplots = 2
57 57
58 58 self.createFigure(id = id,
59 59 wintitle = wintitle,
60 60 widthplot = self.WIDTH + self.WIDTHPROF,
61 61 heightplot = self.HEIGHT + self.HEIGHTPROF,
62 62 show=show)
63 63
64 64 nrow, ncol = self.getSubplots()
65 65
66 66 counter = 0
67 67 for y in range(nrow):
68 68 for x in range(ncol):
69 69
70 70 if counter >= self.nplots:
71 71 break
72 72
73 73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
74 74
75 75 if showprofile:
76 76 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
77 77
78 78 counter += 1
79 79
80 80 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
81 81 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
82 82 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
83 83 server=None, folder=None, username=None, password=None,
84 84 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
85 xaxis="frequency", colormap='jet', normFactor=None , GauSelector = 1):
85 xaxis="frequency", colormap='jet', normFactor=None , GauSelector = 0):
86 86
87 87 """
88 88
89 89 Input:
90 90 dataOut :
91 91 id :
92 92 wintitle :
93 93 channelList :
94 94 showProfile :
95 95 xmin : None,
96 96 xmax : None,
97 97 ymin : None,
98 98 ymax : None,
99 99 zmin : None,
100 100 zmax : None
101 101 """
102 102 if realtime:
103 103 if not(isRealtime(utcdatatime = dataOut.utctime)):
104 104 print 'Skipping this plot function'
105 105 return
106 106
107 107 if channelList == None:
108 108 channelIndexList = dataOut.channelIndexList
109 109 else:
110 110 channelIndexList = []
111 111 for channel in channelList:
112 112 if channel not in dataOut.channelList:
113 113 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
114 114 channelIndexList.append(dataOut.channelList.index(channel))
115 115
116 116 # if normFactor is None:
117 117 # factor = dataOut.normFactor
118 118 # else:
119 119 # factor = normFactor
120 120 if xaxis == "frequency":
121 121 x = dataOut.spc_range[0]
122 122 xlabel = "Frequency (kHz)"
123 123
124 124 elif xaxis == "time":
125 125 x = dataOut.spc_range[1]
126 126 xlabel = "Time (ms)"
127 127
128 else:
128 else:
129 129 x = dataOut.spc_range[2]
130 130 xlabel = "Velocity (m/s)"
131 131
132 132 ylabel = "Range (Km)"
133 133
134 134 y = dataOut.getHeiRange()
135 135
136 136 z = dataOut.GauSPC[:,GauSelector,:,:] #GauSelector] #dataOut.data_spc/factor
137 137 print 'GausSPC', z[0,32,10:40]
138 138 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
139 139 zdB = 10*numpy.log10(z)
140 140
141 141 avg = numpy.average(z, axis=1)
142 142 avgdB = 10*numpy.log10(avg)
143 143
144 144 noise = dataOut.spc_noise
145 145 noisedB = 10*numpy.log10(noise)
146 146
147 147 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
148 148 title = wintitle + " Spectra"
149 149 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
150 150 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
151 151
152 152 if not self.isConfig:
153 153
154 154 nplots = len(channelIndexList)
155 155
156 156 self.setup(id=id,
157 157 nplots=nplots,
158 158 wintitle=wintitle,
159 159 showprofile=showprofile,
160 160 show=show)
161 161
162 162 if xmin == None: xmin = numpy.nanmin(x)
163 163 if xmax == None: xmax = numpy.nanmax(x)
164 164 if ymin == None: ymin = numpy.nanmin(y)
165 165 if ymax == None: ymax = numpy.nanmax(y)
166 166 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
167 167 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
168 168
169 169 self.FTP_WEI = ftp_wei
170 170 self.EXP_CODE = exp_code
171 171 self.SUB_EXP_CODE = sub_exp_code
172 172 self.PLOT_POS = plot_pos
173 173
174 174 self.isConfig = True
175 175
176 176 self.setWinTitle(title)
177 177
178 178 for i in range(self.nplots):
179 179 index = channelIndexList[i]
180 180 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
181 181 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
182 182 if len(dataOut.beam.codeList) != 0:
183 183 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)
184 184
185 185 axes = self.axesList[i*self.__nsubplots]
186 186 axes.pcolor(x, y, zdB[index,:,:],
187 187 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
188 188 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
189 189 ticksize=9, cblabel='')
190 190
191 191 if self.__showprofile:
192 192 axes = self.axesList[i*self.__nsubplots +1]
193 193 axes.pline(avgdB[index,:], y,
194 194 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
195 195 xlabel='dB', ylabel='', title='',
196 196 ytick_visible=False,
197 197 grid='x')
198 198
199 199 noiseline = numpy.repeat(noisedB[index], len(y))
200 200 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
201 201
202 202 self.draw()
203 203
204 204 if figfile == None:
205 205 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
206 206 name = str_datetime
207 207 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
208 208 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
209 209 figfile = self.getFilename(name)
210 210
211 211 self.save(figpath=figpath,
212 212 figfile=figfile,
213 213 save=save,
214 214 ftp=ftp,
215 215 wr_period=wr_period,
216 216 thisDatetime=thisDatetime)
217 217
218 218
219 219
220 220 class MomentsPlot(Figure):
221 221
222 222 isConfig = None
223 223 __nsubplots = None
224 224
225 225 WIDTHPROF = None
226 226 HEIGHTPROF = None
227 227 PREFIX = 'prm'
228 228
229 229 def __init__(self, **kwargs):
230 230 Figure.__init__(self, **kwargs)
231 231 self.isConfig = False
232 232 self.__nsubplots = 1
233 233
234 234 self.WIDTH = 280
235 235 self.HEIGHT = 250
236 236 self.WIDTHPROF = 120
237 237 self.HEIGHTPROF = 0
238 238 self.counter_imagwr = 0
239 239
240 240 self.PLOT_CODE = MOMENTS_CODE
241 241
242 242 self.FTP_WEI = None
243 243 self.EXP_CODE = None
244 244 self.SUB_EXP_CODE = None
245 245 self.PLOT_POS = None
246 246
247 247 def getSubplots(self):
248 248
249 249 ncol = int(numpy.sqrt(self.nplots)+0.9)
250 250 nrow = int(self.nplots*1./ncol + 0.9)
251 251
252 252 return nrow, ncol
253 253
254 254 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
255 255
256 256 self.__showprofile = showprofile
257 257 self.nplots = nplots
258 258
259 259 ncolspan = 1
260 260 colspan = 1
261 261 if showprofile:
262 262 ncolspan = 3
263 263 colspan = 2
264 264 self.__nsubplots = 2
265 265
266 266 self.createFigure(id = id,
267 267 wintitle = wintitle,
268 268 widthplot = self.WIDTH + self.WIDTHPROF,
269 269 heightplot = self.HEIGHT + self.HEIGHTPROF,
270 270 show=show)
271 271
272 272 nrow, ncol = self.getSubplots()
273 273
274 274 counter = 0
275 275 for y in range(nrow):
276 276 for x in range(ncol):
277 277
278 278 if counter >= self.nplots:
279 279 break
280 280
281 281 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
282 282
283 283 if showprofile:
284 284 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
285 285
286 286 counter += 1
287 287
288 288 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
289 289 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
290 290 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
291 291 server=None, folder=None, username=None, password=None,
292 292 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
293 293
294 294 """
295 295
296 296 Input:
297 297 dataOut :
298 298 id :
299 299 wintitle :
300 300 channelList :
301 301 showProfile :
302 302 xmin : None,
303 303 xmax : None,
304 304 ymin : None,
305 305 ymax : None,
306 306 zmin : None,
307 307 zmax : None
308 308 """
309 309
310 310 if dataOut.flagNoData:
311 311 return None
312 312
313 313 if realtime:
314 314 if not(isRealtime(utcdatatime = dataOut.utctime)):
315 315 print 'Skipping this plot function'
316 316 return
317 317
318 318 if channelList == None:
319 319 channelIndexList = dataOut.channelIndexList
320 320 else:
321 321 channelIndexList = []
322 322 for channel in channelList:
323 323 if channel not in dataOut.channelList:
324 324 raise ValueError, "Channel %d is not in dataOut.channelList"
325 325 channelIndexList.append(dataOut.channelList.index(channel))
326 326
327 327 factor = dataOut.normFactor
328 328 x = dataOut.abscissaList
329 329 y = dataOut.heightList
330 330
331 331 z = dataOut.data_pre[channelIndexList,:,:]/factor
332 332 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
333 333 avg = numpy.average(z, axis=1)
334 334 noise = dataOut.noise/factor
335 335
336 336 zdB = 10*numpy.log10(z)
337 337 avgdB = 10*numpy.log10(avg)
338 338 noisedB = 10*numpy.log10(noise)
339 339
340 340 #thisDatetime = dataOut.datatime
341 341 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
342 342 title = wintitle + " Parameters"
343 343 xlabel = "Velocity (m/s)"
344 344 ylabel = "Range (Km)"
345 345
346 346 update_figfile = False
347 347
348 348 if not self.isConfig:
349 349
350 350 nplots = len(channelIndexList)
351 351
352 352 self.setup(id=id,
353 353 nplots=nplots,
354 354 wintitle=wintitle,
355 355 showprofile=showprofile,
356 356 show=show)
357 357
358 358 if xmin == None: xmin = numpy.nanmin(x)
359 359 if xmax == None: xmax = numpy.nanmax(x)
360 360 if ymin == None: ymin = numpy.nanmin(y)
361 361 if ymax == None: ymax = numpy.nanmax(y)
362 362 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
363 363 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
364 364
365 365 self.FTP_WEI = ftp_wei
366 366 self.EXP_CODE = exp_code
367 367 self.SUB_EXP_CODE = sub_exp_code
368 368 self.PLOT_POS = plot_pos
369 369
370 370 self.isConfig = True
371 371 update_figfile = True
372 372
373 373 self.setWinTitle(title)
374 374
375 375 for i in range(self.nplots):
376 376 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
377 377 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
378 378 axes = self.axesList[i*self.__nsubplots]
379 379 axes.pcolor(x, y, zdB[i,:,:],
380 380 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
381 381 xlabel=xlabel, ylabel=ylabel, title=title,
382 382 ticksize=9, cblabel='')
383 383 #Mean Line
384 384 mean = dataOut.data_param[i, 1, :]
385 385 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
386 386
387 387 if self.__showprofile:
388 388 axes = self.axesList[i*self.__nsubplots +1]
389 389 axes.pline(avgdB[i], y,
390 390 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
391 391 xlabel='dB', ylabel='', title='',
392 392 ytick_visible=False,
393 393 grid='x')
394 394
395 395 noiseline = numpy.repeat(noisedB[i], len(y))
396 396 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
397 397
398 398 self.draw()
399 399
400 400 self.save(figpath=figpath,
401 401 figfile=figfile,
402 402 save=save,
403 403 ftp=ftp,
404 404 wr_period=wr_period,
405 405 thisDatetime=thisDatetime)
406 406
407 407
408 408
409 409 class SkyMapPlot(Figure):
410 410
411 411 __isConfig = None
412 412 __nsubplots = None
413 413
414 414 WIDTHPROF = None
415 415 HEIGHTPROF = None
416 416 PREFIX = 'mmap'
417 417
418 418 def __init__(self, **kwargs):
419 419 Figure.__init__(self, **kwargs)
420 420 self.isConfig = False
421 421 self.__nsubplots = 1
422 422
423 423 # self.WIDTH = 280
424 424 # self.HEIGHT = 250
425 425 self.WIDTH = 600
426 426 self.HEIGHT = 600
427 427 self.WIDTHPROF = 120
428 428 self.HEIGHTPROF = 0
429 429 self.counter_imagwr = 0
430 430
431 431 self.PLOT_CODE = MSKYMAP_CODE
432 432
433 433 self.FTP_WEI = None
434 434 self.EXP_CODE = None
435 435 self.SUB_EXP_CODE = None
436 436 self.PLOT_POS = None
437 437
438 438 def getSubplots(self):
439 439
440 440 ncol = int(numpy.sqrt(self.nplots)+0.9)
441 441 nrow = int(self.nplots*1./ncol + 0.9)
442 442
443 443 return nrow, ncol
444 444
445 445 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
446 446
447 447 self.__showprofile = showprofile
448 448 self.nplots = nplots
449 449
450 450 ncolspan = 1
451 451 colspan = 1
452 452
453 453 self.createFigure(id = id,
454 454 wintitle = wintitle,
455 455 widthplot = self.WIDTH, #+ self.WIDTHPROF,
456 456 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
457 457 show=show)
458 458
459 459 nrow, ncol = 1,1
460 460 counter = 0
461 461 x = 0
462 462 y = 0
463 463 self.addAxes(1, 1, 0, 0, 1, 1, True)
464 464
465 465 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
466 466 tmin=0, tmax=24, timerange=None,
467 467 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
468 468 server=None, folder=None, username=None, password=None,
469 469 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
470 470
471 471 """
472 472
473 473 Input:
474 474 dataOut :
475 475 id :
476 476 wintitle :
477 477 channelList :
478 478 showProfile :
479 479 xmin : None,
480 480 xmax : None,
481 481 ymin : None,
482 482 ymax : None,
483 483 zmin : None,
484 484 zmax : None
485 485 """
486 486
487 487 arrayParameters = dataOut.data_param
488 488 error = arrayParameters[:,-1]
489 489 indValid = numpy.where(error == 0)[0]
490 490 finalMeteor = arrayParameters[indValid,:]
491 491 finalAzimuth = finalMeteor[:,3]
492 492 finalZenith = finalMeteor[:,4]
493 493
494 494 x = finalAzimuth*numpy.pi/180
495 495 y = finalZenith
496 496 x1 = [dataOut.ltctime, dataOut.ltctime]
497 497
498 498 #thisDatetime = dataOut.datatime
499 499 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
500 500 title = wintitle + " Parameters"
501 501 xlabel = "Zonal Zenith Angle (deg) "
502 502 ylabel = "Meridional Zenith Angle (deg)"
503 503 update_figfile = False
504 504
505 505 if not self.isConfig:
506 506
507 507 nplots = 1
508 508
509 509 self.setup(id=id,
510 510 nplots=nplots,
511 511 wintitle=wintitle,
512 512 showprofile=showprofile,
513 513 show=show)
514 514
515 515 if self.xmin is None and self.xmax is None:
516 516 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
517 517
518 518 if timerange != None:
519 519 self.timerange = timerange
520 520 else:
521 521 self.timerange = self.xmax - self.xmin
522 522
523 523 self.FTP_WEI = ftp_wei
524 524 self.EXP_CODE = exp_code
525 525 self.SUB_EXP_CODE = sub_exp_code
526 526 self.PLOT_POS = plot_pos
527 527 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
528 528 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
529 529 self.isConfig = True
530 530 update_figfile = True
531 531
532 532 self.setWinTitle(title)
533 533
534 534 i = 0
535 535 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
536 536
537 537 axes = self.axesList[i*self.__nsubplots]
538 538 nevents = axes.x_buffer.shape[0] + x.shape[0]
539 539 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
540 540 axes.polar(x, y,
541 541 title=title, xlabel=xlabel, ylabel=ylabel,
542 542 ticksize=9, cblabel='')
543 543
544 544 self.draw()
545 545
546 546 self.save(figpath=figpath,
547 547 figfile=figfile,
548 548 save=save,
549 549 ftp=ftp,
550 550 wr_period=wr_period,
551 551 thisDatetime=thisDatetime,
552 552 update_figfile=update_figfile)
553 553
554 554 if dataOut.ltctime >= self.xmax:
555 555 self.isConfigmagwr = wr_period
556 556 self.isConfig = False
557 557 update_figfile = True
558 558 axes.__firsttime = True
559 559 self.xmin += self.timerange
560 560 self.xmax += self.timerange
561 561
562 562
563 563
564 564
565 565 class WindProfilerPlot(Figure):
566 566
567 567 __isConfig = None
568 568 __nsubplots = None
569 569
570 570 WIDTHPROF = None
571 571 HEIGHTPROF = None
572 572 PREFIX = 'wind'
573 573
574 574 def __init__(self, **kwargs):
575 575 Figure.__init__(self, **kwargs)
576 576 self.timerange = None
577 577 self.isConfig = False
578 578 self.__nsubplots = 1
579 579
580 580 self.WIDTH = 800
581 581 self.HEIGHT = 300
582 582 self.WIDTHPROF = 120
583 583 self.HEIGHTPROF = 0
584 584 self.counter_imagwr = 0
585 585
586 586 self.PLOT_CODE = WIND_CODE
587 587
588 588 self.FTP_WEI = None
589 589 self.EXP_CODE = None
590 590 self.SUB_EXP_CODE = None
591 591 self.PLOT_POS = None
592 592 self.tmin = None
593 593 self.tmax = None
594 594
595 595 self.xmin = None
596 596 self.xmax = None
597 597
598 598 self.figfile = None
599 599
600 600 def getSubplots(self):
601 601
602 602 ncol = 1
603 603 nrow = self.nplots
604 604
605 605 return nrow, ncol
606 606
607 607 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
608 608
609 609 self.__showprofile = showprofile
610 610 self.nplots = nplots
611 611
612 612 ncolspan = 1
613 613 colspan = 1
614 614
615 615 self.createFigure(id = id,
616 616 wintitle = wintitle,
617 617 widthplot = self.WIDTH + self.WIDTHPROF,
618 618 heightplot = self.HEIGHT + self.HEIGHTPROF,
619 619 show=show)
620 620
621 621 nrow, ncol = self.getSubplots()
622 622
623 623 counter = 0
624 624 for y in range(nrow):
625 625 if counter >= self.nplots:
626 626 break
627 627
628 628 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
629 629 counter += 1
630 630
631 631 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
632 632 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
633 633 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
634 634 timerange=None, SNRthresh = None,
635 635 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
636 636 server=None, folder=None, username=None, password=None,
637 637 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
638 638 """
639 639
640 640 Input:
641 641 dataOut :
642 642 id :
643 643 wintitle :
644 644 channelList :
645 645 showProfile :
646 646 xmin : None,
647 647 xmax : None,
648 648 ymin : None,
649 649 ymax : None,
650 650 zmin : None,
651 651 zmax : None
652 652 """
653 653
654 654 # if timerange is not None:
655 655 # self.timerange = timerange
656 656 #
657 657 # tmin = None
658 658 # tmax = None
659 659
660 660 x = dataOut.getTimeRange1(dataOut.paramInterval)
661 661 y = dataOut.heightList
662 662 z = dataOut.data_output.copy()
663 663 nplots = z.shape[0] #Number of wind dimensions estimated
664 664 nplotsw = nplots
665 665
666 666
667 667 #If there is a SNR function defined
668 668 if dataOut.data_SNR is not None:
669 669 nplots += 1
670 SNR = dataOut.data_SNR
671 SNRavg = numpy.average(SNR, axis=0)
670 SNR = dataOut.data_SNR[0]
671 SNRavg = SNR#numpy.average(SNR, axis=0)
672 672
673 673 SNRdB = 10*numpy.log10(SNR)
674 674 SNRavgdB = 10*numpy.log10(SNRavg)
675 675
676 if SNRthresh == None: SNRthresh = -5.0
676 if SNRthresh == None:
677 SNRthresh = -5.0
677 678 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
678 679
679 680 for i in range(nplotsw):
680 681 z[i,ind] = numpy.nan
681 682
682 683 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
683 684 #thisDatetime = datetime.datetime.now()
684 685 title = wintitle + "Wind"
685 686 xlabel = ""
686 687 ylabel = "Height (km)"
687 688 update_figfile = False
688 689
689 690 if not self.isConfig:
690 691
691 692 self.setup(id=id,
692 693 nplots=nplots,
693 694 wintitle=wintitle,
694 695 showprofile=showprofile,
695 696 show=show)
696 697
697 698 if timerange is not None:
698 699 self.timerange = timerange
699 700
700 701 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
701 702
702 703 if ymin == None: ymin = numpy.nanmin(y)
703 704 if ymax == None: ymax = numpy.nanmax(y)
704 705
705 706 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
706 707 #if numpy.isnan(zmax): zmax = 50
707 708 if zmin == None: zmin = -zmax
708 709
709 710 if nplotsw == 3:
710 711 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
711 712 if zmin_ver == None: zmin_ver = -zmax_ver
712 713
713 714 if dataOut.data_SNR is not None:
714 715 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
715 716 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
716 717
717 718
718 719 self.FTP_WEI = ftp_wei
719 720 self.EXP_CODE = exp_code
720 721 self.SUB_EXP_CODE = sub_exp_code
721 722 self.PLOT_POS = plot_pos
722 723
723 724 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
724 725 self.isConfig = True
725 726 self.figfile = figfile
726 727 update_figfile = True
727 728
728 729 self.setWinTitle(title)
729 730
730 731 if ((self.xmax - x[1]) < (x[1]-x[0])):
731 732 x[1] = self.xmax
732 733
733 734 strWind = ['Zonal', 'Meridional', 'Vertical']
734 735 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
735 736 zmaxVector = [zmax, zmax, zmax_ver]
736 737 zminVector = [zmin, zmin, zmin_ver]
737 738 windFactor = [1,1,100]
738 739
739 740 for i in range(nplotsw):
740 741
741 742 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
742 743 axes = self.axesList[i*self.__nsubplots]
743 744
744 745 z1 = z[i,:].reshape((1,-1))*windFactor[i]
745 746 #z1=numpy.ma.masked_where(z1==0.,z1)
746 747
747 748 axes.pcolorbuffer(x, y, z1,
748 749 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
749 750 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
750 751 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
751 752
752 753 if dataOut.data_SNR is not None:
753 754 i += 1
754 755 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
755 756 axes = self.axesList[i*self.__nsubplots]
756 757 SNRavgdB = SNRavgdB.reshape((1,-1))
757 758 axes.pcolorbuffer(x, y, SNRavgdB,
758 759 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
759 760 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
760 761 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
761 762
762 763 self.draw()
763 764
764 765 self.save(figpath=figpath,
765 766 figfile=figfile,
766 767 save=save,
767 768 ftp=ftp,
768 769 wr_period=wr_period,
769 770 thisDatetime=thisDatetime,
770 771 update_figfile=update_figfile)
771 772
772 773 if dataOut.ltctime + dataOut.paramInterval >= self.xmax:
773 774 self.counter_imagwr = wr_period
774 775 self.isConfig = False
775 776 update_figfile = True
776 777
777 778
778 779 class ParametersPlot(Figure):
779 780
780 781 __isConfig = None
781 782 __nsubplots = None
782 783
783 784 WIDTHPROF = None
784 785 HEIGHTPROF = None
785 786 PREFIX = 'param'
786 787
787 788 nplots = None
788 789 nchan = None
789 790
790 791 def __init__(self, **kwargs):
791 792 Figure.__init__(self, **kwargs)
792 793 self.timerange = None
793 794 self.isConfig = False
794 795 self.__nsubplots = 1
795 796
796 797 self.WIDTH = 800
797 798 self.HEIGHT = 180
798 799 self.WIDTHPROF = 120
799 800 self.HEIGHTPROF = 0
800 801 self.counter_imagwr = 0
801 802
802 803 self.PLOT_CODE = RTI_CODE
803 804
804 805 self.FTP_WEI = None
805 806 self.EXP_CODE = None
806 807 self.SUB_EXP_CODE = None
807 808 self.PLOT_POS = None
808 809 self.tmin = None
809 810 self.tmax = None
810 811
811 812 self.xmin = None
812 813 self.xmax = None
813 814
814 815 self.figfile = None
815 816
816 817 def getSubplots(self):
817 818
818 819 ncol = 1
819 820 nrow = self.nplots
820 821
821 822 return nrow, ncol
822 823
823 824 def setup(self, id, nplots, wintitle, show=True):
824 825
825 826 self.nplots = nplots
826 827
827 828 ncolspan = 1
828 829 colspan = 1
829 830
830 831 self.createFigure(id = id,
831 832 wintitle = wintitle,
832 833 widthplot = self.WIDTH + self.WIDTHPROF,
833 834 heightplot = self.HEIGHT + self.HEIGHTPROF,
834 835 show=show)
835 836
836 837 nrow, ncol = self.getSubplots()
837 838
838 839 counter = 0
839 840 for y in range(nrow):
840 841 for x in range(ncol):
841 842
842 843 if counter >= self.nplots:
843 844 break
844 845
845 846 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
846 847
847 848 counter += 1
848 849
849 850 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap="jet",
850 851 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
851 852 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
852 853 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
853 854 server=None, folder=None, username=None, password=None,
854 855 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, HEIGHT=None):
855 856 """
856 857
857 858 Input:
858 859 dataOut :
859 860 id :
860 861 wintitle :
861 862 channelList :
862 863 showProfile :
863 864 xmin : None,
864 865 xmax : None,
865 866 ymin : None,
866 867 ymax : None,
867 868 zmin : None,
868 869 zmax : None
869 870 """
870 871
871 872 if HEIGHT is not None:
872 873 self.HEIGHT = HEIGHT
873 874
874 875
875 876 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
876 877 return
877 878
878 879 if channelList == None:
879 880 channelIndexList = range(dataOut.data_param.shape[0])
880 881 else:
881 882 channelIndexList = []
882 883 for channel in channelList:
883 884 if channel not in dataOut.channelList:
884 885 raise ValueError, "Channel %d is not in dataOut.channelList"
885 886 channelIndexList.append(dataOut.channelList.index(channel))
886 887
887 888 x = dataOut.getTimeRange1(dataOut.paramInterval)
888 889 y = dataOut.getHeiRange()
889 890
890 891 if dataOut.data_param.ndim == 3:
891 892 z = dataOut.data_param[channelIndexList,paramIndex,:]
892 893 else:
893 894 z = dataOut.data_param[channelIndexList,:]
894 895
895 896 if showSNR:
896 897 #SNR data
897 898 SNRarray = dataOut.data_SNR[channelIndexList,:]
898 899 SNRdB = 10*numpy.log10(SNRarray)
899 900 ind = numpy.where(SNRdB < SNRthresh)
900 901 z[ind] = numpy.nan
901 902
902 903 thisDatetime = dataOut.datatime
903 904 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
904 905 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
905 906 xlabel = ""
906 907 ylabel = "Range (Km)"
907 908
908 909 update_figfile = False
909 910
910 911 if not self.isConfig:
911 912
912 913 nchan = len(channelIndexList)
913 914 self.nchan = nchan
914 915 self.plotFact = 1
915 916 nplots = nchan
916 917
917 918 if showSNR:
918 919 nplots = nchan*2
919 920 self.plotFact = 2
920 921 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
921 922 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
922 923
923 924 self.setup(id=id,
924 925 nplots=nplots,
925 926 wintitle=wintitle,
926 927 show=show)
927 928
928 929 if timerange != None:
929 930 self.timerange = timerange
930 931
931 932 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
932 933
933 934 if ymin == None: ymin = numpy.nanmin(y)
934 935 if ymax == None: ymax = numpy.nanmax(y)
935 936 if zmin == None: zmin = numpy.nanmin(z)
936 937 if zmax == None: zmax = numpy.nanmax(z)
937 938
938 939 self.FTP_WEI = ftp_wei
939 940 self.EXP_CODE = exp_code
940 941 self.SUB_EXP_CODE = sub_exp_code
941 942 self.PLOT_POS = plot_pos
942 943
943 944 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
944 945 self.isConfig = True
945 946 self.figfile = figfile
946 947 update_figfile = True
947 948
948 949 self.setWinTitle(title)
949 950
950 951 for i in range(self.nchan):
951 952 index = channelIndexList[i]
952 953 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
953 954 axes = self.axesList[i*self.plotFact]
954 955 z1 = z[i,:].reshape((1,-1))
955 956 axes.pcolorbuffer(x, y, z1,
956 957 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
957 958 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
958 959 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
959 960
960 961 if showSNR:
961 962 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
962 963 axes = self.axesList[i*self.plotFact + 1]
963 964 SNRdB1 = SNRdB[i,:].reshape((1,-1))
964 965 axes.pcolorbuffer(x, y, SNRdB1,
965 966 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
966 967 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
967 968 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
968 969
969 970
970 971 self.draw()
971 972
972 973 if dataOut.ltctime >= self.xmax:
973 974 self.counter_imagwr = wr_period
974 975 self.isConfig = False
975 976 update_figfile = True
976 977
977 978 self.save(figpath=figpath,
978 979 figfile=figfile,
979 980 save=save,
980 981 ftp=ftp,
981 982 wr_period=wr_period,
982 983 thisDatetime=thisDatetime,
983 984 update_figfile=update_figfile)
984 985
985 986
986 987
987 988 class Parameters1Plot(Figure):
988 989
989 990 __isConfig = None
990 991 __nsubplots = None
991 992
992 993 WIDTHPROF = None
993 994 HEIGHTPROF = None
994 995 PREFIX = 'prm'
995 996
996 997 def __init__(self, **kwargs):
997 998 Figure.__init__(self, **kwargs)
998 999 self.timerange = 2*60*60
999 1000 self.isConfig = False
1000 1001 self.__nsubplots = 1
1001 1002
1002 1003 self.WIDTH = 800
1003 1004 self.HEIGHT = 180
1004 1005 self.WIDTHPROF = 120
1005 1006 self.HEIGHTPROF = 0
1006 1007 self.counter_imagwr = 0
1007 1008
1008 1009 self.PLOT_CODE = PARMS_CODE
1009 1010
1010 1011 self.FTP_WEI = None
1011 1012 self.EXP_CODE = None
1012 1013 self.SUB_EXP_CODE = None
1013 1014 self.PLOT_POS = None
1014 1015 self.tmin = None
1015 1016 self.tmax = None
1016 1017
1017 1018 self.xmin = None
1018 1019 self.xmax = None
1019 1020
1020 1021 self.figfile = None
1021 1022
1022 1023 def getSubplots(self):
1023 1024
1024 1025 ncol = 1
1025 1026 nrow = self.nplots
1026 1027
1027 1028 return nrow, ncol
1028 1029
1029 1030 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1030 1031
1031 1032 self.__showprofile = showprofile
1032 1033 self.nplots = nplots
1033 1034
1034 1035 ncolspan = 1
1035 1036 colspan = 1
1036 1037
1037 1038 self.createFigure(id = id,
1038 1039 wintitle = wintitle,
1039 1040 widthplot = self.WIDTH + self.WIDTHPROF,
1040 1041 heightplot = self.HEIGHT + self.HEIGHTPROF,
1041 1042 show=show)
1042 1043
1043 1044 nrow, ncol = self.getSubplots()
1044 1045
1045 1046 counter = 0
1046 1047 for y in range(nrow):
1047 1048 for x in range(ncol):
1048 1049
1049 1050 if counter >= self.nplots:
1050 1051 break
1051 1052
1052 1053 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1053 1054
1054 1055 if showprofile:
1055 1056 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1056 1057
1057 1058 counter += 1
1058 1059
1059 1060 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
1060 1061 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
1061 1062 parameterIndex = None, onlyPositive = False,
1062 1063 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
1063 1064 DOP = True,
1064 1065 zlabel = "", parameterName = "", parameterObject = "data_param",
1065 1066 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1066 1067 server=None, folder=None, username=None, password=None,
1067 1068 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1068 1069 #print inspect.getargspec(self.run).args
1069 1070 """
1070 1071
1071 1072 Input:
1072 1073 dataOut :
1073 1074 id :
1074 1075 wintitle :
1075 1076 channelList :
1076 1077 showProfile :
1077 1078 xmin : None,
1078 1079 xmax : None,
1079 1080 ymin : None,
1080 1081 ymax : None,
1081 1082 zmin : None,
1082 1083 zmax : None
1083 1084 """
1084 1085
1085 1086 data_param = getattr(dataOut, parameterObject)
1086 1087
1087 1088 if channelList == None:
1088 1089 channelIndexList = numpy.arange(data_param.shape[0])
1089 1090 else:
1090 1091 channelIndexList = numpy.array(channelList)
1091 1092
1092 1093 nchan = len(channelIndexList) #Number of channels being plotted
1093 1094
1094 1095 if nchan < 1:
1095 1096 return
1096 1097
1097 1098 nGraphsByChannel = 0
1098 1099
1099 1100 if SNR:
1100 1101 nGraphsByChannel += 1
1101 1102 if DOP:
1102 1103 nGraphsByChannel += 1
1103 1104
1104 1105 if nGraphsByChannel < 1:
1105 1106 return
1106 1107
1107 1108 nplots = nGraphsByChannel*nchan
1108 1109
1109 1110 if timerange is not None:
1110 1111 self.timerange = timerange
1111 1112
1112 1113 #tmin = None
1113 1114 #tmax = None
1114 1115 if parameterIndex == None:
1115 1116 parameterIndex = 1
1116 1117
1117 1118 x = dataOut.getTimeRange1(dataOut.paramInterval)
1118 1119 y = dataOut.heightList
1119 1120 z = data_param[channelIndexList,parameterIndex,:].copy()
1120 1121
1121 1122 zRange = dataOut.abscissaList
1122 1123 # nChannels = z.shape[0] #Number of wind dimensions estimated
1123 1124 # thisDatetime = dataOut.datatime
1124 1125
1125 1126 if dataOut.data_SNR is not None:
1126 1127 SNRarray = dataOut.data_SNR[channelIndexList,:]
1127 1128 SNRdB = 10*numpy.log10(SNRarray)
1128 1129 # SNRavgdB = 10*numpy.log10(SNRavg)
1129 1130 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
1130 1131 z[ind] = numpy.nan
1131 1132
1132 1133 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1133 1134 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
1134 1135 xlabel = ""
1135 1136 ylabel = "Range (Km)"
1136 1137
1137 1138 if (SNR and not onlySNR): nplots = 2*nplots
1138 1139
1139 1140 if onlyPositive:
1140 1141 colormap = "jet"
1141 1142 zmin = 0
1142 1143 else: colormap = "RdBu_r"
1143 1144
1144 1145 if not self.isConfig:
1145 1146
1146 1147 self.setup(id=id,
1147 1148 nplots=nplots,
1148 1149 wintitle=wintitle,
1149 1150 showprofile=showprofile,
1150 1151 show=show)
1151 1152
1152 1153 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1153 1154
1154 1155 if ymin == None: ymin = numpy.nanmin(y)
1155 1156 if ymax == None: ymax = numpy.nanmax(y)
1156 1157 if zmin == None: zmin = numpy.nanmin(zRange)
1157 1158 if zmax == None: zmax = numpy.nanmax(zRange)
1158 1159
1159 1160 if SNR:
1160 1161 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
1161 1162 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
1162 1163
1163 1164 self.FTP_WEI = ftp_wei
1164 1165 self.EXP_CODE = exp_code
1165 1166 self.SUB_EXP_CODE = sub_exp_code
1166 1167 self.PLOT_POS = plot_pos
1167 1168
1168 1169 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1169 1170 self.isConfig = True
1170 1171 self.figfile = figfile
1171 1172
1172 1173 self.setWinTitle(title)
1173 1174
1174 1175 if ((self.xmax - x[1]) < (x[1]-x[0])):
1175 1176 x[1] = self.xmax
1176 1177
1177 1178 for i in range(nchan):
1178 1179
1179 1180 if (SNR and not onlySNR): j = 2*i
1180 1181 else: j = i
1181 1182
1182 1183 j = nGraphsByChannel*i
1183 1184
1184 1185 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1185 1186 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1186 1187
1187 1188 if not onlySNR:
1188 1189 axes = self.axesList[j*self.__nsubplots]
1189 1190 z1 = z[i,:].reshape((1,-1))
1190 1191 axes.pcolorbuffer(x, y, z1,
1191 1192 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1192 1193 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1193 1194 ticksize=9, cblabel=zlabel, cbsize="1%")
1194 1195
1195 1196 if DOP:
1196 1197 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1197 1198
1198 1199 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1199 1200 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
1200 1201 axes = self.axesList[j]
1201 1202 z1 = z[i,:].reshape((1,-1))
1202 1203 axes.pcolorbuffer(x, y, z1,
1203 1204 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
1204 1205 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
1205 1206 ticksize=9, cblabel=zlabel, cbsize="1%")
1206 1207
1207 1208 if SNR:
1208 1209 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1209 1210 axes = self.axesList[(j)*self.__nsubplots]
1210 1211 if not onlySNR:
1211 1212 axes = self.axesList[(j + 1)*self.__nsubplots]
1212 1213
1213 1214 axes = self.axesList[(j + nGraphsByChannel-1)]
1214 1215
1215 1216 z1 = SNRdB[i,:].reshape((1,-1))
1216 1217 axes.pcolorbuffer(x, y, z1,
1217 1218 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1218 1219 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1219 1220 ticksize=9, cblabel=zlabel, cbsize="1%")
1220 1221
1221 1222
1222 1223
1223 1224 self.draw()
1224 1225
1225 1226 if x[1] >= self.axesList[0].xmax:
1226 1227 self.counter_imagwr = wr_period
1227 1228 self.isConfig = False
1228 1229 self.figfile = None
1229 1230
1230 1231 self.save(figpath=figpath,
1231 1232 figfile=figfile,
1232 1233 save=save,
1233 1234 ftp=ftp,
1234 1235 wr_period=wr_period,
1235 1236 thisDatetime=thisDatetime,
1236 1237 update_figfile=False)
1237 1238
1238 1239 class SpectralFittingPlot(Figure):
1239 1240
1240 1241 __isConfig = None
1241 1242 __nsubplots = None
1242 1243
1243 1244 WIDTHPROF = None
1244 1245 HEIGHTPROF = None
1245 1246 PREFIX = 'prm'
1246 1247
1247 1248
1248 1249 N = None
1249 1250 ippSeconds = None
1250 1251
1251 1252 def __init__(self, **kwargs):
1252 1253 Figure.__init__(self, **kwargs)
1253 1254 self.isConfig = False
1254 1255 self.__nsubplots = 1
1255 1256
1256 1257 self.PLOT_CODE = SPECFIT_CODE
1257 1258
1258 1259 self.WIDTH = 450
1259 1260 self.HEIGHT = 250
1260 1261 self.WIDTHPROF = 0
1261 1262 self.HEIGHTPROF = 0
1262 1263
1263 1264 def getSubplots(self):
1264 1265
1265 1266 ncol = int(numpy.sqrt(self.nplots)+0.9)
1266 1267 nrow = int(self.nplots*1./ncol + 0.9)
1267 1268
1268 1269 return nrow, ncol
1269 1270
1270 1271 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1271 1272
1272 1273 showprofile = False
1273 1274 self.__showprofile = showprofile
1274 1275 self.nplots = nplots
1275 1276
1276 1277 ncolspan = 5
1277 1278 colspan = 4
1278 1279 if showprofile:
1279 1280 ncolspan = 5
1280 1281 colspan = 4
1281 1282 self.__nsubplots = 2
1282 1283
1283 1284 self.createFigure(id = id,
1284 1285 wintitle = wintitle,
1285 1286 widthplot = self.WIDTH + self.WIDTHPROF,
1286 1287 heightplot = self.HEIGHT + self.HEIGHTPROF,
1287 1288 show=show)
1288 1289
1289 1290 nrow, ncol = self.getSubplots()
1290 1291
1291 1292 counter = 0
1292 1293 for y in range(nrow):
1293 1294 for x in range(ncol):
1294 1295
1295 1296 if counter >= self.nplots:
1296 1297 break
1297 1298
1298 1299 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1299 1300
1300 1301 if showprofile:
1301 1302 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1302 1303
1303 1304 counter += 1
1304 1305
1305 1306 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1306 1307 xmin=None, xmax=None, ymin=None, ymax=None,
1307 1308 save=False, figpath='./', figfile=None, show=True):
1308 1309
1309 1310 """
1310 1311
1311 1312 Input:
1312 1313 dataOut :
1313 1314 id :
1314 1315 wintitle :
1315 1316 channelList :
1316 1317 showProfile :
1317 1318 xmin : None,
1318 1319 xmax : None,
1319 1320 zmin : None,
1320 1321 zmax : None
1321 1322 """
1322 1323
1323 1324 if cutHeight==None:
1324 1325 h=270
1325 1326 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1326 1327 cutHeight = dataOut.heightList[heightindex]
1327 1328
1328 1329 factor = dataOut.normFactor
1329 1330 x = dataOut.abscissaList[:-1]
1330 1331 #y = dataOut.getHeiRange()
1331 1332
1332 1333 z = dataOut.data_pre[:,:,heightindex]/factor
1333 1334 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1334 1335 avg = numpy.average(z, axis=1)
1335 1336 listChannels = z.shape[0]
1336 1337
1337 1338 #Reconstruct Function
1338 1339 if fit==True:
1339 1340 groupArray = dataOut.groupList
1340 1341 listChannels = groupArray.reshape((groupArray.size))
1341 1342 listChannels.sort()
1342 1343 spcFitLine = numpy.zeros(z.shape)
1343 1344 constants = dataOut.constants
1344 1345
1345 1346 nGroups = groupArray.shape[0]
1346 1347 nChannels = groupArray.shape[1]
1347 1348 nProfiles = z.shape[1]
1348 1349
1349 1350 for f in range(nGroups):
1350 1351 groupChann = groupArray[f,:]
1351 1352 p = dataOut.data_param[f,:,heightindex]
1352 1353 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1353 1354 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1354 1355 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1355 1356 spcFitLine[groupChann,:] = fitLineAux
1356 1357 # spcFitLine = spcFitLine/factor
1357 1358
1358 1359 z = z[listChannels,:]
1359 1360 spcFitLine = spcFitLine[listChannels,:]
1360 1361 spcFitLinedB = 10*numpy.log10(spcFitLine)
1361 1362
1362 1363 zdB = 10*numpy.log10(z)
1363 1364 #thisDatetime = dataOut.datatime
1364 1365 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1365 1366 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1366 1367 xlabel = "Velocity (m/s)"
1367 1368 ylabel = "Spectrum"
1368 1369
1369 1370 if not self.isConfig:
1370 1371
1371 1372 nplots = listChannels.size
1372 1373
1373 1374 self.setup(id=id,
1374 1375 nplots=nplots,
1375 1376 wintitle=wintitle,
1376 1377 showprofile=showprofile,
1377 1378 show=show)
1378 1379
1379 1380 if xmin == None: xmin = numpy.nanmin(x)
1380 1381 if xmax == None: xmax = numpy.nanmax(x)
1381 1382 if ymin == None: ymin = numpy.nanmin(zdB)
1382 1383 if ymax == None: ymax = numpy.nanmax(zdB)+2
1383 1384
1384 1385 self.isConfig = True
1385 1386
1386 1387 self.setWinTitle(title)
1387 1388 for i in range(self.nplots):
1388 1389 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1389 1390 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1390 1391 axes = self.axesList[i*self.__nsubplots]
1391 1392 if fit == False:
1392 1393 axes.pline(x, zdB[i,:],
1393 1394 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1394 1395 xlabel=xlabel, ylabel=ylabel, title=title
1395 1396 )
1396 1397 if fit == True:
1397 1398 fitline=spcFitLinedB[i,:]
1398 1399 y=numpy.vstack([zdB[i,:],fitline] )
1399 1400 legendlabels=['Data','Fitting']
1400 1401 axes.pmultilineyaxis(x, y,
1401 1402 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1402 1403 xlabel=xlabel, ylabel=ylabel, title=title,
1403 1404 legendlabels=legendlabels, marker=None,
1404 1405 linestyle='solid', grid='both')
1405 1406
1406 1407 self.draw()
1407 1408
1408 1409 self.save(figpath=figpath,
1409 1410 figfile=figfile,
1410 1411 save=save,
1411 1412 ftp=ftp,
1412 1413 wr_period=wr_period,
1413 1414 thisDatetime=thisDatetime)
1414 1415
1415 1416
1416 1417 class EWDriftsPlot(Figure):
1417 1418
1418 1419 __isConfig = None
1419 1420 __nsubplots = None
1420 1421
1421 1422 WIDTHPROF = None
1422 1423 HEIGHTPROF = None
1423 1424 PREFIX = 'drift'
1424 1425
1425 1426 def __init__(self, **kwargs):
1426 1427 Figure.__init__(self, **kwargs)
1427 1428 self.timerange = 2*60*60
1428 1429 self.isConfig = False
1429 1430 self.__nsubplots = 1
1430 1431
1431 1432 self.WIDTH = 800
1432 1433 self.HEIGHT = 150
1433 1434 self.WIDTHPROF = 120
1434 1435 self.HEIGHTPROF = 0
1435 1436 self.counter_imagwr = 0
1436 1437
1437 1438 self.PLOT_CODE = EWDRIFT_CODE
1438 1439
1439 1440 self.FTP_WEI = None
1440 1441 self.EXP_CODE = None
1441 1442 self.SUB_EXP_CODE = None
1442 1443 self.PLOT_POS = None
1443 1444 self.tmin = None
1444 1445 self.tmax = None
1445 1446
1446 1447 self.xmin = None
1447 1448 self.xmax = None
1448 1449
1449 1450 self.figfile = None
1450 1451
1451 1452 def getSubplots(self):
1452 1453
1453 1454 ncol = 1
1454 1455 nrow = self.nplots
1455 1456
1456 1457 return nrow, ncol
1457 1458
1458 1459 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1459 1460
1460 1461 self.__showprofile = showprofile
1461 1462 self.nplots = nplots
1462 1463
1463 1464 ncolspan = 1
1464 1465 colspan = 1
1465 1466
1466 1467 self.createFigure(id = id,
1467 1468 wintitle = wintitle,
1468 1469 widthplot = self.WIDTH + self.WIDTHPROF,
1469 1470 heightplot = self.HEIGHT + self.HEIGHTPROF,
1470 1471 show=show)
1471 1472
1472 1473 nrow, ncol = self.getSubplots()
1473 1474
1474 1475 counter = 0
1475 1476 for y in range(nrow):
1476 1477 if counter >= self.nplots:
1477 1478 break
1478 1479
1479 1480 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1480 1481 counter += 1
1481 1482
1482 1483 def run(self, dataOut, id, wintitle="", channelList=None,
1483 1484 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1484 1485 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1485 1486 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1486 1487 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1487 1488 server=None, folder=None, username=None, password=None,
1488 1489 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1489 1490 """
1490 1491
1491 1492 Input:
1492 1493 dataOut :
1493 1494 id :
1494 1495 wintitle :
1495 1496 channelList :
1496 1497 showProfile :
1497 1498 xmin : None,
1498 1499 xmax : None,
1499 1500 ymin : None,
1500 1501 ymax : None,
1501 1502 zmin : None,
1502 1503 zmax : None
1503 1504 """
1504 1505
1505 1506 if timerange is not None:
1506 1507 self.timerange = timerange
1507 1508
1508 1509 tmin = None
1509 1510 tmax = None
1510 1511
1511 1512 x = dataOut.getTimeRange1(dataOut.outputInterval)
1512 1513 # y = dataOut.heightList
1513 1514 y = dataOut.heightList
1514 1515
1515 1516 z = dataOut.data_output
1516 1517 nplots = z.shape[0] #Number of wind dimensions estimated
1517 1518 nplotsw = nplots
1518 1519
1519 1520 #If there is a SNR function defined
1520 1521 if dataOut.data_SNR is not None:
1521 1522 nplots += 1
1522 1523 SNR = dataOut.data_SNR
1523 1524
1524 1525 if SNR_1:
1525 1526 SNR += 1
1526 1527
1527 1528 SNRavg = numpy.average(SNR, axis=0)
1528 1529
1529 1530 SNRdB = 10*numpy.log10(SNR)
1530 1531 SNRavgdB = 10*numpy.log10(SNRavg)
1531 1532
1532 1533 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1533 1534
1534 1535 for i in range(nplotsw):
1535 1536 z[i,ind] = numpy.nan
1536 1537
1537 1538
1538 1539 showprofile = False
1539 1540 # thisDatetime = dataOut.datatime
1540 1541 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1541 1542 title = wintitle + " EW Drifts"
1542 1543 xlabel = ""
1543 1544 ylabel = "Height (Km)"
1544 1545
1545 1546 if not self.isConfig:
1546 1547
1547 1548 self.setup(id=id,
1548 1549 nplots=nplots,
1549 1550 wintitle=wintitle,
1550 1551 showprofile=showprofile,
1551 1552 show=show)
1552 1553
1553 1554 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1554 1555
1555 1556 if ymin == None: ymin = numpy.nanmin(y)
1556 1557 if ymax == None: ymax = numpy.nanmax(y)
1557 1558
1558 1559 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1559 1560 if zminZonal == None: zminZonal = -zmaxZonal
1560 1561 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1561 1562 if zminVertical == None: zminVertical = -zmaxVertical
1562 1563
1563 1564 if dataOut.data_SNR is not None:
1564 1565 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1565 1566 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1566 1567
1567 1568 self.FTP_WEI = ftp_wei
1568 1569 self.EXP_CODE = exp_code
1569 1570 self.SUB_EXP_CODE = sub_exp_code
1570 1571 self.PLOT_POS = plot_pos
1571 1572
1572 1573 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1573 1574 self.isConfig = True
1574 1575
1575 1576
1576 1577 self.setWinTitle(title)
1577 1578
1578 1579 if ((self.xmax - x[1]) < (x[1]-x[0])):
1579 1580 x[1] = self.xmax
1580 1581
1581 1582 strWind = ['Zonal','Vertical']
1582 1583 strCb = 'Velocity (m/s)'
1583 1584 zmaxVector = [zmaxZonal, zmaxVertical]
1584 1585 zminVector = [zminZonal, zminVertical]
1585 1586
1586 1587 for i in range(nplotsw):
1587 1588
1588 1589 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1589 1590 axes = self.axesList[i*self.__nsubplots]
1590 1591
1591 1592 z1 = z[i,:].reshape((1,-1))
1592 1593
1593 1594 axes.pcolorbuffer(x, y, z1,
1594 1595 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1595 1596 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1596 1597 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1597 1598
1598 1599 if dataOut.data_SNR is not None:
1599 1600 i += 1
1600 1601 if SNR_1:
1601 1602 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1602 1603 else:
1603 1604 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1604 1605 axes = self.axesList[i*self.__nsubplots]
1605 1606 SNRavgdB = SNRavgdB.reshape((1,-1))
1606 1607
1607 1608 axes.pcolorbuffer(x, y, SNRavgdB,
1608 1609 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1609 1610 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1610 1611 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1611 1612
1612 1613 self.draw()
1613 1614
1614 1615 if x[1] >= self.axesList[0].xmax:
1615 1616 self.counter_imagwr = wr_period
1616 1617 self.isConfig = False
1617 1618 self.figfile = None
1618 1619
1619 1620
1620 1621
1621 1622
1622 1623 class PhasePlot(Figure):
1623 1624
1624 1625 __isConfig = None
1625 1626 __nsubplots = None
1626 1627
1627 1628 PREFIX = 'mphase'
1628 1629
1629 1630 def __init__(self, **kwargs):
1630 1631 Figure.__init__(self, **kwargs)
1631 1632 self.timerange = 24*60*60
1632 1633 self.isConfig = False
1633 1634 self.__nsubplots = 1
1634 1635 self.counter_imagwr = 0
1635 1636 self.WIDTH = 600
1636 1637 self.HEIGHT = 300
1637 1638 self.WIDTHPROF = 120
1638 1639 self.HEIGHTPROF = 0
1639 1640 self.xdata = None
1640 1641 self.ydata = None
1641 1642
1642 1643 self.PLOT_CODE = MPHASE_CODE
1643 1644
1644 1645 self.FTP_WEI = None
1645 1646 self.EXP_CODE = None
1646 1647 self.SUB_EXP_CODE = None
1647 1648 self.PLOT_POS = None
1648 1649
1649 1650
1650 1651 self.filename_phase = None
1651 1652
1652 1653 self.figfile = None
1653 1654
1654 1655 def getSubplots(self):
1655 1656
1656 1657 ncol = 1
1657 1658 nrow = 1
1658 1659
1659 1660 return nrow, ncol
1660 1661
1661 1662 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1662 1663
1663 1664 self.__showprofile = showprofile
1664 1665 self.nplots = nplots
1665 1666
1666 1667 ncolspan = 7
1667 1668 colspan = 6
1668 1669 self.__nsubplots = 2
1669 1670
1670 1671 self.createFigure(id = id,
1671 1672 wintitle = wintitle,
1672 1673 widthplot = self.WIDTH+self.WIDTHPROF,
1673 1674 heightplot = self.HEIGHT+self.HEIGHTPROF,
1674 1675 show=show)
1675 1676
1676 1677 nrow, ncol = self.getSubplots()
1677 1678
1678 1679 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1679 1680
1680 1681
1681 1682 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1682 1683 xmin=None, xmax=None, ymin=None, ymax=None,
1683 1684 timerange=None,
1684 1685 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1685 1686 server=None, folder=None, username=None, password=None,
1686 1687 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1687 1688
1688 1689
1689 1690 tmin = None
1690 1691 tmax = None
1691 1692 x = dataOut.getTimeRange1(dataOut.outputInterval)
1692 1693 y = dataOut.getHeiRange()
1693 1694
1694 1695
1695 1696 #thisDatetime = dataOut.datatime
1696 1697 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1697 1698 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1698 1699 xlabel = "Local Time"
1699 1700 ylabel = "Phase"
1700 1701
1701 1702
1702 1703 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1703 1704 phase_beacon = dataOut.data_output
1704 1705 update_figfile = False
1705 1706
1706 1707 if not self.isConfig:
1707 1708
1708 1709 self.nplots = phase_beacon.size
1709 1710
1710 1711 self.setup(id=id,
1711 1712 nplots=self.nplots,
1712 1713 wintitle=wintitle,
1713 1714 showprofile=showprofile,
1714 1715 show=show)
1715 1716
1716 1717 if timerange is not None:
1717 1718 self.timerange = timerange
1718 1719
1719 1720 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1720 1721
1721 1722 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1722 1723 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1723 1724
1724 1725 self.FTP_WEI = ftp_wei
1725 1726 self.EXP_CODE = exp_code
1726 1727 self.SUB_EXP_CODE = sub_exp_code
1727 1728 self.PLOT_POS = plot_pos
1728 1729
1729 1730 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1730 1731 self.isConfig = True
1731 1732 self.figfile = figfile
1732 1733 self.xdata = numpy.array([])
1733 1734 self.ydata = numpy.array([])
1734 1735
1735 1736 #open file beacon phase
1736 1737 path = '%s%03d' %(self.PREFIX, self.id)
1737 1738 beacon_file = os.path.join(path,'%s.txt'%self.name)
1738 1739 self.filename_phase = os.path.join(figpath,beacon_file)
1739 1740 update_figfile = True
1740 1741
1741 1742
1742 1743 #store data beacon phase
1743 1744 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1744 1745
1745 1746 self.setWinTitle(title)
1746 1747
1747 1748
1748 1749 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1749 1750
1750 1751 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1751 1752
1752 1753 axes = self.axesList[0]
1753 1754
1754 1755 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1755 1756
1756 1757 if len(self.ydata)==0:
1757 1758 self.ydata = phase_beacon.reshape(-1,1)
1758 1759 else:
1759 1760 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1760 1761
1761 1762
1762 1763 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1763 1764 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1764 1765 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1765 1766 XAxisAsTime=True, grid='both'
1766 1767 )
1767 1768
1768 1769 self.draw()
1769 1770
1770 1771 self.save(figpath=figpath,
1771 1772 figfile=figfile,
1772 1773 save=save,
1773 1774 ftp=ftp,
1774 1775 wr_period=wr_period,
1775 1776 thisDatetime=thisDatetime,
1776 1777 update_figfile=update_figfile)
1777 1778
1778 1779 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1779 1780 self.counter_imagwr = wr_period
1780 1781 self.isConfig = False
1781 1782 update_figfile = True
1782 1783
1783 1784
1784 1785
1785 1786 class NSMeteorDetection1Plot(Figure):
1786 1787
1787 1788 isConfig = None
1788 1789 __nsubplots = None
1789 1790
1790 1791 WIDTHPROF = None
1791 1792 HEIGHTPROF = None
1792 1793 PREFIX = 'nsm'
1793 1794
1794 1795 zminList = None
1795 1796 zmaxList = None
1796 1797 cmapList = None
1797 1798 titleList = None
1798 1799 nPairs = None
1799 1800 nChannels = None
1800 1801 nParam = None
1801 1802
1802 1803 def __init__(self, **kwargs):
1803 1804 Figure.__init__(self, **kwargs)
1804 1805 self.isConfig = False
1805 1806 self.__nsubplots = 1
1806 1807
1807 1808 self.WIDTH = 750
1808 1809 self.HEIGHT = 250
1809 1810 self.WIDTHPROF = 120
1810 1811 self.HEIGHTPROF = 0
1811 1812 self.counter_imagwr = 0
1812 1813
1813 1814 self.PLOT_CODE = SPEC_CODE
1814 1815
1815 1816 self.FTP_WEI = None
1816 1817 self.EXP_CODE = None
1817 1818 self.SUB_EXP_CODE = None
1818 1819 self.PLOT_POS = None
1819 1820
1820 1821 self.__xfilter_ena = False
1821 1822 self.__yfilter_ena = False
1822 1823
1823 1824 def getSubplots(self):
1824 1825
1825 1826 ncol = 3
1826 1827 nrow = int(numpy.ceil(self.nplots/3.0))
1827 1828
1828 1829 return nrow, ncol
1829 1830
1830 1831 def setup(self, id, nplots, wintitle, show=True):
1831 1832
1832 1833 self.nplots = nplots
1833 1834
1834 1835 ncolspan = 1
1835 1836 colspan = 1
1836 1837
1837 1838 self.createFigure(id = id,
1838 1839 wintitle = wintitle,
1839 1840 widthplot = self.WIDTH + self.WIDTHPROF,
1840 1841 heightplot = self.HEIGHT + self.HEIGHTPROF,
1841 1842 show=show)
1842 1843
1843 1844 nrow, ncol = self.getSubplots()
1844 1845
1845 1846 counter = 0
1846 1847 for y in range(nrow):
1847 1848 for x in range(ncol):
1848 1849
1849 1850 if counter >= self.nplots:
1850 1851 break
1851 1852
1852 1853 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1853 1854
1854 1855 counter += 1
1855 1856
1856 1857 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1857 1858 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1858 1859 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1859 1860 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1860 1861 server=None, folder=None, username=None, password=None,
1861 1862 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1862 1863 xaxis="frequency"):
1863 1864
1864 1865 """
1865 1866
1866 1867 Input:
1867 1868 dataOut :
1868 1869 id :
1869 1870 wintitle :
1870 1871 channelList :
1871 1872 showProfile :
1872 1873 xmin : None,
1873 1874 xmax : None,
1874 1875 ymin : None,
1875 1876 ymax : None,
1876 1877 zmin : None,
1877 1878 zmax : None
1878 1879 """
1879 1880 #SEPARAR EN DOS PLOTS
1880 1881 nParam = dataOut.data_param.shape[1] - 3
1881 1882
1882 1883 utctime = dataOut.data_param[0,0]
1883 1884 tmet = dataOut.data_param[:,1].astype(int)
1884 1885 hmet = dataOut.data_param[:,2].astype(int)
1885 1886
1886 1887 x = dataOut.abscissaList
1887 1888 y = dataOut.heightList
1888 1889
1889 1890 z = numpy.zeros((nParam, y.size, x.size - 1))
1890 1891 z[:,:] = numpy.nan
1891 1892 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1892 1893 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1893 1894
1894 1895 xlabel = "Time (s)"
1895 1896 ylabel = "Range (km)"
1896 1897
1897 1898 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1898 1899
1899 1900 if not self.isConfig:
1900 1901
1901 1902 nplots = nParam
1902 1903
1903 1904 self.setup(id=id,
1904 1905 nplots=nplots,
1905 1906 wintitle=wintitle,
1906 1907 show=show)
1907 1908
1908 1909 if xmin is None: xmin = numpy.nanmin(x)
1909 1910 if xmax is None: xmax = numpy.nanmax(x)
1910 1911 if ymin is None: ymin = numpy.nanmin(y)
1911 1912 if ymax is None: ymax = numpy.nanmax(y)
1912 1913 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1913 1914 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1914 1915 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1915 1916 if vmin is None: vmin = -vmax
1916 1917 if wmin is None: wmin = 0
1917 1918 if wmax is None: wmax = 50
1918 1919
1919 1920 pairsList = dataOut.groupList
1920 1921 self.nPairs = len(dataOut.groupList)
1921 1922
1922 1923 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1923 1924 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1924 1925 titleList = ["SNR","Radial Velocity","Coherence"]
1925 1926 cmapList = ["jet","RdBu_r","jet"]
1926 1927
1927 1928 for i in range(self.nPairs):
1928 1929 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1929 1930 titleList = titleList + [strAux1]
1930 1931 cmapList = cmapList + ["RdBu_r"]
1931 1932
1932 1933 self.zminList = zminList
1933 1934 self.zmaxList = zmaxList
1934 1935 self.cmapList = cmapList
1935 1936 self.titleList = titleList
1936 1937
1937 1938 self.FTP_WEI = ftp_wei
1938 1939 self.EXP_CODE = exp_code
1939 1940 self.SUB_EXP_CODE = sub_exp_code
1940 1941 self.PLOT_POS = plot_pos
1941 1942
1942 1943 self.isConfig = True
1943 1944
1944 1945 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1945 1946
1946 1947 for i in range(nParam):
1947 1948 title = self.titleList[i] + ": " +str_datetime
1948 1949 axes = self.axesList[i]
1949 1950 axes.pcolor(x, y, z[i,:].T,
1950 1951 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1951 1952 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1952 1953 self.draw()
1953 1954
1954 1955 if figfile == None:
1955 1956 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1956 1957 name = str_datetime
1957 1958 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1958 1959 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1959 1960 figfile = self.getFilename(name)
1960 1961
1961 1962 self.save(figpath=figpath,
1962 1963 figfile=figfile,
1963 1964 save=save,
1964 1965 ftp=ftp,
1965 1966 wr_period=wr_period,
1966 1967 thisDatetime=thisDatetime)
1967 1968
1968 1969
1969 1970 class NSMeteorDetection2Plot(Figure):
1970 1971
1971 1972 isConfig = None
1972 1973 __nsubplots = None
1973 1974
1974 1975 WIDTHPROF = None
1975 1976 HEIGHTPROF = None
1976 1977 PREFIX = 'nsm'
1977 1978
1978 1979 zminList = None
1979 1980 zmaxList = None
1980 1981 cmapList = None
1981 1982 titleList = None
1982 1983 nPairs = None
1983 1984 nChannels = None
1984 1985 nParam = None
1985 1986
1986 1987 def __init__(self, **kwargs):
1987 1988 Figure.__init__(self, **kwargs)
1988 1989 self.isConfig = False
1989 1990 self.__nsubplots = 1
1990 1991
1991 1992 self.WIDTH = 750
1992 1993 self.HEIGHT = 250
1993 1994 self.WIDTHPROF = 120
1994 1995 self.HEIGHTPROF = 0
1995 1996 self.counter_imagwr = 0
1996 1997
1997 1998 self.PLOT_CODE = SPEC_CODE
1998 1999
1999 2000 self.FTP_WEI = None
2000 2001 self.EXP_CODE = None
2001 2002 self.SUB_EXP_CODE = None
2002 2003 self.PLOT_POS = None
2003 2004
2004 2005 self.__xfilter_ena = False
2005 2006 self.__yfilter_ena = False
2006 2007
2007 2008 def getSubplots(self):
2008 2009
2009 2010 ncol = 3
2010 2011 nrow = int(numpy.ceil(self.nplots/3.0))
2011 2012
2012 2013 return nrow, ncol
2013 2014
2014 2015 def setup(self, id, nplots, wintitle, show=True):
2015 2016
2016 2017 self.nplots = nplots
2017 2018
2018 2019 ncolspan = 1
2019 2020 colspan = 1
2020 2021
2021 2022 self.createFigure(id = id,
2022 2023 wintitle = wintitle,
2023 2024 widthplot = self.WIDTH + self.WIDTHPROF,
2024 2025 heightplot = self.HEIGHT + self.HEIGHTPROF,
2025 2026 show=show)
2026 2027
2027 2028 nrow, ncol = self.getSubplots()
2028 2029
2029 2030 counter = 0
2030 2031 for y in range(nrow):
2031 2032 for x in range(ncol):
2032 2033
2033 2034 if counter >= self.nplots:
2034 2035 break
2035 2036
2036 2037 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
2037 2038
2038 2039 counter += 1
2039 2040
2040 2041 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
2041 2042 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
2042 2043 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
2043 2044 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
2044 2045 server=None, folder=None, username=None, password=None,
2045 2046 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
2046 2047 xaxis="frequency"):
2047 2048
2048 2049 """
2049 2050
2050 2051 Input:
2051 2052 dataOut :
2052 2053 id :
2053 2054 wintitle :
2054 2055 channelList :
2055 2056 showProfile :
2056 2057 xmin : None,
2057 2058 xmax : None,
2058 2059 ymin : None,
2059 2060 ymax : None,
2060 2061 zmin : None,
2061 2062 zmax : None
2062 2063 """
2063 2064 #Rebuild matrix
2064 2065 utctime = dataOut.data_param[0,0]
2065 2066 cmet = dataOut.data_param[:,1].astype(int)
2066 2067 tmet = dataOut.data_param[:,2].astype(int)
2067 2068 hmet = dataOut.data_param[:,3].astype(int)
2068 2069
2069 2070 nParam = 3
2070 2071 nChan = len(dataOut.groupList)
2071 2072 x = dataOut.abscissaList
2072 2073 y = dataOut.heightList
2073 2074
2074 2075 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
2075 2076 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
2076 2077 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
2077 2078 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
2078 2079
2079 2080 xlabel = "Time (s)"
2080 2081 ylabel = "Range (km)"
2081 2082
2082 2083 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
2083 2084
2084 2085 if not self.isConfig:
2085 2086
2086 2087 nplots = nParam*nChan
2087 2088
2088 2089 self.setup(id=id,
2089 2090 nplots=nplots,
2090 2091 wintitle=wintitle,
2091 2092 show=show)
2092 2093
2093 2094 if xmin is None: xmin = numpy.nanmin(x)
2094 2095 if xmax is None: xmax = numpy.nanmax(x)
2095 2096 if ymin is None: ymin = numpy.nanmin(y)
2096 2097 if ymax is None: ymax = numpy.nanmax(y)
2097 2098 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
2098 2099 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
2099 2100 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
2100 2101 if vmin is None: vmin = -vmax
2101 2102 if wmin is None: wmin = 0
2102 2103 if wmax is None: wmax = 50
2103 2104
2104 2105 self.nChannels = nChan
2105 2106
2106 2107 zminList = []
2107 2108 zmaxList = []
2108 2109 titleList = []
2109 2110 cmapList = []
2110 2111 for i in range(self.nChannels):
2111 2112 strAux1 = "SNR Channel "+ str(i)
2112 2113 strAux2 = "Radial Velocity Channel "+ str(i)
2113 2114 strAux3 = "Spectral Width Channel "+ str(i)
2114 2115
2115 2116 titleList = titleList + [strAux1,strAux2,strAux3]
2116 2117 cmapList = cmapList + ["jet","RdBu_r","jet"]
2117 2118 zminList = zminList + [SNRmin,vmin,wmin]
2118 2119 zmaxList = zmaxList + [SNRmax,vmax,wmax]
2119 2120
2120 2121 self.zminList = zminList
2121 2122 self.zmaxList = zmaxList
2122 2123 self.cmapList = cmapList
2123 2124 self.titleList = titleList
2124 2125
2125 2126 self.FTP_WEI = ftp_wei
2126 2127 self.EXP_CODE = exp_code
2127 2128 self.SUB_EXP_CODE = sub_exp_code
2128 2129 self.PLOT_POS = plot_pos
2129 2130
2130 2131 self.isConfig = True
2131 2132
2132 2133 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
2133 2134
2134 2135 for i in range(self.nplots):
2135 2136 title = self.titleList[i] + ": " +str_datetime
2136 2137 axes = self.axesList[i]
2137 2138 axes.pcolor(x, y, z[i,:].T,
2138 2139 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
2139 2140 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
2140 2141 self.draw()
2141 2142
2142 2143 if figfile == None:
2143 2144 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
2144 2145 name = str_datetime
2145 2146 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
2146 2147 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
2147 2148 figfile = self.getFilename(name)
2148 2149
2149 2150 self.save(figpath=figpath,
2150 2151 figfile=figfile,
2151 2152 save=save,
2152 2153 ftp=ftp,
2153 2154 wr_period=wr_period,
2154 2155 thisDatetime=thisDatetime)
@@ -1,1584 +1,1609
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 import matplotlib.pyplot as plt
11 11
12 12 from figure import Figure, isRealtime, isTimeInHourRange
13 13 from plotting_codes import *
14 14 from matplotlib.pyplot import savefig
15 15
16 16 class SpectraPlot(Figure):
17 17
18 18 isConfig = None
19 19 __nsubplots = None
20 20
21 21 WIDTHPROF = None
22 22 HEIGHTPROF = None
23 23 PREFIX = 'spc'
24 24
25 25 def __init__(self, **kwargs):
26 26 Figure.__init__(self, **kwargs)
27 27 self.isConfig = False
28 28 self.__nsubplots = 1
29 29
30 self.WIDTH = 250
31 self.HEIGHT = 250
30 self.WIDTH = 300
31 self.HEIGHT = 300
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 realtime:
112 112 if not(isRealtime(utcdatatime = dataOut.utctime)):
113 113 print 'Skipping this plot function'
114 114 return
115 115
116 116 if channelList == None:
117 117 channelIndexList = dataOut.channelIndexList
118 118 else:
119 119 channelIndexList = []
120 120 for channel in channelList:
121 121 if channel not in dataOut.channelList:
122 122 raise ValueError, "Channel %d is not in dataOut.channelList" %channel
123 123 channelIndexList.append(dataOut.channelList.index(channel))
124 124
125 125 if normFactor is None:
126 126 factor = dataOut.normFactor
127 127 else:
128 128 factor = normFactor
129 129 if xaxis == "frequency":
130 130 x = dataOut.getFreqRange(1)/1000.
131 print '#######################################################'
132 print 'xlen', len(x)
133 print x
134 print '#######################################################'
131 135 xlabel = "Frequency (kHz)"
132 136
133 137 elif xaxis == "time":
134 138 x = dataOut.getAcfRange(1)
135 139 xlabel = "Time (ms)"
136 140
137 141 else:
138 142 x = dataOut.getVelRange(1)
139 143 xlabel = "Velocity (m/s)"
140 144
141 145 ylabel = "Range (Km)"
142 146
143 147 y = dataOut.getHeiRange()
144 148
145 149 z = dataOut.data_spc/factor
146 150 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
147 151 zdB = 10*numpy.log10(z)
148 152
149 153 avg = numpy.average(z, axis=1)
150 154 avgdB = 10*numpy.log10(avg)
151 155
152 156 noise = dataOut.getNoise()/factor
153 157 noisedB = 10*numpy.log10(noise)
154 158
155 159 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
156 160 title = wintitle + " Spectra"
157 161
158 162
159 163
160 164 print 'len de X',len(x), numpy.shape(x), 'len de spc line',len(dataOut.data_spc[1,:,15]), numpy.shape(dataOut.data_spc)
161 165 print 'Altura:', y[0], y[1], y[13], y[14], y[10]
162 166 #a=z[1,:,15]
163 167
164 168 # fig = plt.figure(10+self.indice)
165 169 # plt.plot( x[0:128], zdB[0,:,10] )
166 170 # plt.axis([-12, 12, 15, 50])
167 171 # plt.title(" %s" %( '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))) )
168 172 # plt.ylabel('Intensidad [dB]')
169 173 # plt.xlabel('Velocidad [m/s]')
170 174 # fig.savefig('/home/erick/Documents/Pics/to{}.png'.format(self.indice))
171 175 #
172 176 # plt.show()
173 177 #
174 178 # self.indice=self.indice+1
175 179
176 180
177 181
178 182 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
179 183 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
180 184
181 185 if not self.isConfig:
182 186
183 187 nplots = len(channelIndexList)
184 188
185 189 self.setup(id=id,
186 190 nplots=nplots,
187 191 wintitle=wintitle,
188 192 showprofile=showprofile,
189 193 show=show)
190 194
191 195 if xmin == None: xmin = numpy.nanmin(x)
192 196 if xmax == None: xmax = numpy.nanmax(x)
193 197 if ymin == None: ymin = numpy.nanmin(y)
194 198 if ymax == None: ymax = numpy.nanmax(y)
195 199 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
196 200 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
197 201
198 202 self.FTP_WEI = ftp_wei
199 203 self.EXP_CODE = exp_code
200 204 self.SUB_EXP_CODE = sub_exp_code
201 205 self.PLOT_POS = plot_pos
202 206
203 207 self.isConfig = True
204 208
205 209 self.setWinTitle(title)
206 210
207 211 for i in range(self.nplots):
208 212 index = channelIndexList[i]
209 213 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
210 214 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[index], noisedB[index], str_datetime)
211 215 if len(dataOut.beam.codeList) != 0:
212 216 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)
213 217
214 218 axes = self.axesList[i*self.__nsubplots]
215 219 axes.pcolor(x, y, zdB[index,:,:],
216 220 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
217 221 xlabel=xlabel, ylabel=ylabel, title=title, colormap=colormap,
218 222 ticksize=9, cblabel='')
219 223
220 224 if self.__showprofile:
221 225 axes = self.axesList[i*self.__nsubplots +1]
222 226 axes.pline(avgdB[index,:], y,
223 227 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
224 228 xlabel='dB', ylabel='', title='',
225 229 ytick_visible=False,
226 230 grid='x')
227 231
228 232 noiseline = numpy.repeat(noisedB[index], len(y))
229 233 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
230 234
231 235 self.draw()
232 236
233 237 if figfile == None:
234 238 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
235 239 name = str_datetime
236 240 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
237 241 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
238 242 figfile = self.getFilename(name)
239 243
240 244 self.save(figpath=figpath,
241 245 figfile=figfile,
242 246 save=save,
243 247 ftp=ftp,
244 248 wr_period=wr_period,
245 249 thisDatetime=thisDatetime)
246 250
247 251
248 252 class CrossSpectraPlot(Figure):
249 253
250 254 isConfig = None
251 255 __nsubplots = None
252 256
253 257 WIDTH = None
254 258 HEIGHT = None
255 259 WIDTHPROF = None
256 260 HEIGHTPROF = None
257 261 PREFIX = 'cspc'
258 262
259 263 def __init__(self, **kwargs):
260 264 Figure.__init__(self, **kwargs)
261 265 self.isConfig = False
262 266 self.__nsubplots = 4
263 267 self.counter_imagwr = 0
264 268 self.WIDTH = 250
265 269 self.HEIGHT = 250
266 270 self.WIDTHPROF = 0
267 271 self.HEIGHTPROF = 0
268 272
269 273 self.PLOT_CODE = CROSS_CODE
270 274 self.FTP_WEI = None
271 275 self.EXP_CODE = None
272 276 self.SUB_EXP_CODE = None
273 277 self.PLOT_POS = None
274 278
275 279 self.indice=0
276 280
277 281 def getSubplots(self):
278 282
279 283 ncol = 4
280 284 nrow = self.nplots
281 285
282 286 return nrow, ncol
283 287
284 288 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
285 289
286 290 self.__showprofile = showprofile
287 291 self.nplots = nplots
288 292
289 293 ncolspan = 1
290 294 colspan = 1
291 295
292 296 self.createFigure(id = id,
293 297 wintitle = wintitle,
294 298 widthplot = self.WIDTH + self.WIDTHPROF,
295 299 heightplot = self.HEIGHT + self.HEIGHTPROF,
296 300 show=True)
297 301
298 302 nrow, ncol = self.getSubplots()
299 303
300 304 counter = 0
301 305 for y in range(nrow):
302 306 for x in range(ncol):
303 307 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
304 308
305 309 counter += 1
306 310
307 311 def run(self, dataOut, id, wintitle="", pairsList=None,
308 312 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
309 313 coh_min=None, coh_max=None, phase_min=None, phase_max=None,
310 314 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
311 315 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
312 316 server=None, folder=None, username=None, password=None,
313 317 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None,
314 318 xaxis='frequency'):
315 319
316 320 """
317 321
318 322 Input:
319 323 dataOut :
320 324 id :
321 325 wintitle :
322 326 channelList :
323 327 showProfile :
324 328 xmin : None,
325 329 xmax : None,
326 330 ymin : None,
327 331 ymax : None,
328 332 zmin : None,
329 333 zmax : None
330 334 """
331 335
332 336 if pairsList == None:
333 337 pairsIndexList = dataOut.pairsIndexList
334 338 else:
335 339 pairsIndexList = []
336 340 for pair in pairsList:
337 341 if pair not in dataOut.pairsList:
338 342 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
339 343 pairsIndexList.append(dataOut.pairsList.index(pair))
340 344
341 345 if not pairsIndexList:
342 346 return
343 347
344 348 if len(pairsIndexList) > 4:
345 349 pairsIndexList = pairsIndexList[0:4]
346 350
347 351 if normFactor is None:
348 352 factor = dataOut.normFactor
349 353 else:
350 354 factor = normFactor
351 355 x = dataOut.getVelRange(1)
352 356 y = dataOut.getHeiRange()
353 357 z = dataOut.data_spc[:,:,:]/factor
354 358 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
355 359
356 360 noise = dataOut.noise/factor
357 361
358 362 zdB = 10*numpy.log10(z)
359 363 noisedB = 10*numpy.log10(noise)
360 364
361 365 if coh_min == None:
362 366 coh_min = 0.0
363 367 if coh_max == None:
364 368 coh_max = 1.0
365 369
366 370 if phase_min == None:
367 371 phase_min = -180
368 372 if phase_max == None:
369 373 phase_max = 180
370 374
371 375 #thisDatetime = dataOut.datatime
372 376 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
373 377 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
374 378 # xlabel = "Velocity (m/s)"
375 379 ylabel = "Range (Km)"
376 380
377 381 if xaxis == "frequency":
378 382 x = dataOut.getFreqRange(1)/1000.
379 383 xlabel = "Frequency (kHz)"
380 384
381 385 elif xaxis == "time":
382 386 x = dataOut.getAcfRange(1)
383 387 xlabel = "Time (ms)"
384 388
385 389 else:
386 390 x = dataOut.getVelRange(1)
387 391 xlabel = "Velocity (m/s)"
388 392
389 393 if not self.isConfig:
390 394
391 395 nplots = len(pairsIndexList)
392 396
393 397 self.setup(id=id,
394 398 nplots=nplots,
395 399 wintitle=wintitle,
396 400 showprofile=False,
397 401 show=show)
398 402
399 403 avg = numpy.abs(numpy.average(z, axis=1))
400 404 avgdB = 10*numpy.log10(avg)
401 405
402 406 if xmin == None: xmin = numpy.nanmin(x)
403 407 if xmax == None: xmax = numpy.nanmax(x)
404 408 if ymin == None: ymin = numpy.nanmin(y)
405 409 if ymax == None: ymax = numpy.nanmax(y)
406 410 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
407 411 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
408 412
409 413 self.FTP_WEI = ftp_wei
410 414 self.EXP_CODE = exp_code
411 415 self.SUB_EXP_CODE = sub_exp_code
412 416 self.PLOT_POS = plot_pos
413 417
414 418 self.isConfig = True
415 419
416 420 self.setWinTitle(title)
417 421
418 422
419 423 for i in range(self.nplots):
420 424 pair = dataOut.pairsList[pairsIndexList[i]]
421 425
422 426 chan_index0 = dataOut.channelList.index(pair[0])
423 427 chan_index1 = dataOut.channelList.index(pair[1])
424 428
425 429 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
426 430 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[chan_index0], str_datetime)
427 431 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index0,:,:]/factor)
428 432 axes0 = self.axesList[i*self.__nsubplots]
429 433 axes0.pcolor(x, y, zdB,
430 434 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
431 435 xlabel=xlabel, ylabel=ylabel, title=title,
432 436 ticksize=9, colormap=power_cmap, cblabel='')
433 437
434 438 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[chan_index1], str_datetime)
435 439 zdB = 10.*numpy.log10(dataOut.data_spc[chan_index1,:,:]/factor)
436 440 axes0 = self.axesList[i*self.__nsubplots+1]
437 441 axes0.pcolor(x, y, zdB,
438 442 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
439 443 xlabel=xlabel, ylabel=ylabel, title=title,
440 444 ticksize=9, colormap=power_cmap, cblabel='')
441 445
442 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:])
446 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:] / numpy.sqrt( dataOut.data_spc[chan_index0,:,:]*dataOut.data_spc[chan_index1,:,:] )
443 447 coherence = numpy.abs(coherenceComplex)
444 448 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
445 449 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
446 450
447 451
448 # print 'FASE', numpy.shape(phase), y[10]
452
453
454 # #print 'FASE', numpy.shape(phase), y[25]
449 455 # fig = plt.figure(10+self.indice)
450 # plt.plot( x[0:128],phase[:,10] )
456 # #plt.plot( x[0:256],coherence[:,25] )
457 # cohAv = numpy.average(coherence,1)
458 #
459 # plt.plot( x[0:256],cohAv )
451 460 # #plt.axis([-12, 12, 15, 50])
452 461 # plt.title("%s" %( '%s %s, Channel %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S") , i)))
453 462 # plt.ylabel('Desfase [grados]')
454 463 # plt.xlabel('Velocidad [m/s]')
455 464 # fig.savefig('/home/erick/Documents/Pics/to{}.png'.format(self.indice))
456 #
465 #
466 # plt.show()
467 # self.indice=self.indice+1
468
469
470 # print 'FASE', numpy.shape(phase), y[25]
471 # fig = plt.figure(10+self.indice)
472 # plt.plot( x[0:256],phase[:,25] )
473 # #plt.axis([-12, 12, 15, 50])
474 # plt.title("%s" %( '%s %s, Channel %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S") , i)))
475 # plt.ylabel('Desfase [grados]')
476 # plt.xlabel('Velocidad [m/s]')
477 # fig.savefig('/home/erick/Documents/Pics/to{}.png'.format(self.indice))
478 #
457 479 # plt.show()
458 480 # self.indice=self.indice+1
459 481
482
483
484
460 485 title = "Coherence Ch%d * Ch%d" %(pair[0], pair[1])
461 486 axes0 = self.axesList[i*self.__nsubplots+2]
462 487 axes0.pcolor(x, y, coherence,
463 488 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=coh_min, zmax=coh_max,
464 489 xlabel=xlabel, ylabel=ylabel, title=title,
465 490 ticksize=9, colormap=coherence_cmap, cblabel='')
466 491
467 492 title = "Phase Ch%d * Ch%d" %(pair[0], pair[1])
468 493 axes0 = self.axesList[i*self.__nsubplots+3]
469 494 axes0.pcolor(x, y, phase,
470 495 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
471 496 xlabel=xlabel, ylabel=ylabel, title=title,
472 497 ticksize=9, colormap=phase_cmap, cblabel='')
473 498
474 499
475 500
476 501 self.draw()
477 502
478 503 self.save(figpath=figpath,
479 504 figfile=figfile,
480 505 save=save,
481 506 ftp=ftp,
482 507 wr_period=wr_period,
483 508 thisDatetime=thisDatetime)
484 509
485 510
486 511 class RTIPlot(Figure):
487 512
488 513 __isConfig = None
489 514 __nsubplots = None
490 515
491 516 WIDTHPROF = None
492 517 HEIGHTPROF = None
493 518 PREFIX = 'rti'
494 519
495 520 def __init__(self, **kwargs):
496 521
497 522 Figure.__init__(self, **kwargs)
498 523 self.timerange = None
499 524 self.isConfig = False
500 525 self.__nsubplots = 1
501 526
502 527 self.WIDTH = 800
503 self.HEIGHT = 180
528 self.HEIGHT = 250
504 529 self.WIDTHPROF = 120
505 530 self.HEIGHTPROF = 0
506 531 self.counter_imagwr = 0
507 532
508 533 self.PLOT_CODE = RTI_CODE
509 534
510 535 self.FTP_WEI = None
511 536 self.EXP_CODE = None
512 537 self.SUB_EXP_CODE = None
513 538 self.PLOT_POS = None
514 539 self.tmin = None
515 540 self.tmax = None
516 541
517 542 self.xmin = None
518 543 self.xmax = None
519 544
520 545 self.figfile = None
521 546
522 547 def getSubplots(self):
523 548
524 549 ncol = 1
525 550 nrow = self.nplots
526 551
527 552 return nrow, ncol
528 553
529 554 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
530 555
531 556 self.__showprofile = showprofile
532 557 self.nplots = nplots
533 558
534 559 ncolspan = 1
535 560 colspan = 1
536 561 if showprofile:
537 562 ncolspan = 7
538 563 colspan = 6
539 564 self.__nsubplots = 2
540 565
541 566 self.createFigure(id = id,
542 567 wintitle = wintitle,
543 568 widthplot = self.WIDTH + self.WIDTHPROF,
544 569 heightplot = self.HEIGHT + self.HEIGHTPROF,
545 570 show=show)
546 571
547 572 nrow, ncol = self.getSubplots()
548 573
549 574 counter = 0
550 575 for y in range(nrow):
551 576 for x in range(ncol):
552 577
553 578 if counter >= self.nplots:
554 579 break
555 580
556 581 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
557 582
558 583 if showprofile:
559 584 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
560 585
561 586 counter += 1
562 587
563 588 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
564 589 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
565 590 timerange=None, colormap='jet',
566 591 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
567 592 server=None, folder=None, username=None, password=None,
568 593 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, normFactor=None, HEIGHT=None):
569 594
570 595 """
571 596
572 597 Input:
573 598 dataOut :
574 599 id :
575 600 wintitle :
576 601 channelList :
577 602 showProfile :
578 603 xmin : None,
579 604 xmax : None,
580 605 ymin : None,
581 606 ymax : None,
582 607 zmin : None,
583 608 zmax : None
584 609 """
585 610
586 611 #colormap = kwargs.get('colormap', 'jet')
587 612 if HEIGHT is not None:
588 613 self.HEIGHT = HEIGHT
589 614
590 615 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
591 616 return
592 617
593 618 if channelList == None:
594 619 channelIndexList = dataOut.channelIndexList
595 620 else:
596 621 channelIndexList = []
597 622 for channel in channelList:
598 623 if channel not in dataOut.channelList:
599 624 raise ValueError, "Channel %d is not in dataOut.channelList"
600 625 channelIndexList.append(dataOut.channelList.index(channel))
601 626
602 627 if normFactor is None:
603 628 factor = dataOut.normFactor
604 629 else:
605 630 factor = normFactor
606 631
607 632 # factor = dataOut.normFactor
608 633 x = dataOut.getTimeRange()
609 634 y = dataOut.getHeiRange()
610 635
611 636 z = dataOut.data_spc/factor
612 637 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
613 638 avg = numpy.average(z, axis=1)
614 639 avgdB = 10.*numpy.log10(avg)
615 640 # avgdB = dataOut.getPower()
616 641
617 642
618 643 thisDatetime = dataOut.datatime
619 644 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
620 645 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
621 646 xlabel = ""
622 647 ylabel = "Range (Km)"
623 648
624 649 update_figfile = False
625 650
626 651 if dataOut.ltctime >= self.xmax:
627 652 self.counter_imagwr = wr_period
628 653 self.isConfig = False
629 654 update_figfile = True
630 655
631 656 if not self.isConfig:
632 657
633 658 nplots = len(channelIndexList)
634 659
635 660 self.setup(id=id,
636 661 nplots=nplots,
637 662 wintitle=wintitle,
638 663 showprofile=showprofile,
639 664 show=show)
640 665
641 666 if timerange != None:
642 667 self.timerange = timerange
643 668
644 669 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
645 670
646 671 noise = dataOut.noise/factor
647 672 noisedB = 10*numpy.log10(noise)
648 673
649 674 if ymin == None: ymin = numpy.nanmin(y)
650 675 if ymax == None: ymax = numpy.nanmax(y)
651 676 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
652 677 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
653 678
654 679 self.FTP_WEI = ftp_wei
655 680 self.EXP_CODE = exp_code
656 681 self.SUB_EXP_CODE = sub_exp_code
657 682 self.PLOT_POS = plot_pos
658 683
659 684 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
660 685 self.isConfig = True
661 686 self.figfile = figfile
662 687 update_figfile = True
663 688
664 689 self.setWinTitle(title)
665 690
666 691 for i in range(self.nplots):
667 692 index = channelIndexList[i]
668 693 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
669 694 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
670 695 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
671 696 axes = self.axesList[i*self.__nsubplots]
672 697 zdB = avgdB[index].reshape((1,-1))
673 698 axes.pcolorbuffer(x, y, zdB,
674 699 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
675 700 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
676 701 ticksize=9, cblabel='', cbsize="1%", colormap=colormap)
677 702
678 703 if self.__showprofile:
679 704 axes = self.axesList[i*self.__nsubplots +1]
680 705 axes.pline(avgdB[index], y,
681 706 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
682 707 xlabel='dB', ylabel='', title='',
683 708 ytick_visible=False,
684 709 grid='x')
685 710
686 711 self.draw()
687 712
688 713 self.save(figpath=figpath,
689 714 figfile=figfile,
690 715 save=save,
691 716 ftp=ftp,
692 717 wr_period=wr_period,
693 718 thisDatetime=thisDatetime,
694 719 update_figfile=update_figfile)
695 720
696 721 class CoherenceMap(Figure):
697 722 isConfig = None
698 723 __nsubplots = None
699 724
700 725 WIDTHPROF = None
701 726 HEIGHTPROF = None
702 727 PREFIX = 'cmap'
703 728
704 729 def __init__(self, **kwargs):
705 730 Figure.__init__(self, **kwargs)
706 731 self.timerange = 2*60*60
707 732 self.isConfig = False
708 733 self.__nsubplots = 1
709 734
710 735 self.WIDTH = 800
711 736 self.HEIGHT = 180
712 737 self.WIDTHPROF = 120
713 738 self.HEIGHTPROF = 0
714 739 self.counter_imagwr = 0
715 740
716 741 self.PLOT_CODE = COH_CODE
717 742
718 743 self.FTP_WEI = None
719 744 self.EXP_CODE = None
720 745 self.SUB_EXP_CODE = None
721 746 self.PLOT_POS = None
722 747 self.counter_imagwr = 0
723 748
724 749 self.xmin = None
725 750 self.xmax = None
726 751
727 752 def getSubplots(self):
728 753 ncol = 1
729 754 nrow = self.nplots*2
730 755
731 756 return nrow, ncol
732 757
733 758 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
734 759 self.__showprofile = showprofile
735 760 self.nplots = nplots
736 761
737 762 ncolspan = 1
738 763 colspan = 1
739 764 if showprofile:
740 765 ncolspan = 7
741 766 colspan = 6
742 767 self.__nsubplots = 2
743 768
744 769 self.createFigure(id = id,
745 770 wintitle = wintitle,
746 771 widthplot = self.WIDTH + self.WIDTHPROF,
747 772 heightplot = self.HEIGHT + self.HEIGHTPROF,
748 773 show=True)
749 774
750 775 nrow, ncol = self.getSubplots()
751 776
752 777 for y in range(nrow):
753 778 for x in range(ncol):
754 779
755 780 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
756 781
757 782 if showprofile:
758 783 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
759 784
760 785 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
761 786 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
762 787 timerange=None, phase_min=None, phase_max=None,
763 788 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
764 789 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
765 790 server=None, folder=None, username=None, password=None,
766 791 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
767 792
768 793 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
769 794 return
770 795
771 796 if pairsList == None:
772 797 pairsIndexList = dataOut.pairsIndexList
773 798 else:
774 799 pairsIndexList = []
775 800 for pair in pairsList:
776 801 if pair not in dataOut.pairsList:
777 802 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
778 803 pairsIndexList.append(dataOut.pairsList.index(pair))
779 804
780 805 if pairsIndexList == []:
781 806 return
782 807
783 808 if len(pairsIndexList) > 4:
784 809 pairsIndexList = pairsIndexList[0:4]
785 810
786 811 if phase_min == None:
787 812 phase_min = -180
788 813 if phase_max == None:
789 814 phase_max = 180
790 815
791 816 x = dataOut.getTimeRange()
792 817 y = dataOut.getHeiRange()
793 818
794 819 thisDatetime = dataOut.datatime
795 820
796 821 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
797 822 xlabel = ""
798 823 ylabel = "Range (Km)"
799 824 update_figfile = False
800 825
801 826 if not self.isConfig:
802 827 nplots = len(pairsIndexList)
803 828 self.setup(id=id,
804 829 nplots=nplots,
805 830 wintitle=wintitle,
806 831 showprofile=showprofile,
807 832 show=show)
808 833
809 834 if timerange != None:
810 835 self.timerange = timerange
811 836
812 837 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
813 838
814 839 if ymin == None: ymin = numpy.nanmin(y)
815 840 if ymax == None: ymax = numpy.nanmax(y)
816 841 if zmin == None: zmin = 0.
817 842 if zmax == None: zmax = 1.
818 843
819 844 self.FTP_WEI = ftp_wei
820 845 self.EXP_CODE = exp_code
821 846 self.SUB_EXP_CODE = sub_exp_code
822 847 self.PLOT_POS = plot_pos
823 848
824 849 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
825 850
826 851 self.isConfig = True
827 852 update_figfile = True
828 853
829 854 self.setWinTitle(title)
830 855
831 856 for i in range(self.nplots):
832 857
833 858 pair = dataOut.pairsList[pairsIndexList[i]]
834 859
835 860 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
836 861 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
837 862 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
838 863
839 864
840 865 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
841 866 coherence = numpy.abs(avgcoherenceComplex)
842 867
843 868 z = coherence.reshape((1,-1))
844 869
845 870 counter = 0
846 871
847 872 title = "Coherence Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
848 873 axes = self.axesList[i*self.__nsubplots*2]
849 874 axes.pcolorbuffer(x, y, z,
850 875 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
851 876 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
852 877 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
853 878
854 879 if self.__showprofile:
855 880 counter += 1
856 881 axes = self.axesList[i*self.__nsubplots*2 + counter]
857 882 axes.pline(coherence, y,
858 883 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
859 884 xlabel='', ylabel='', title='', ticksize=7,
860 885 ytick_visible=False, nxticks=5,
861 886 grid='x')
862 887
863 888 counter += 1
864 889
865 890 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
866 891
867 892 z = phase.reshape((1,-1))
868 893
869 894 title = "Phase Ch%d * Ch%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
870 895 axes = self.axesList[i*self.__nsubplots*2 + counter]
871 896 axes.pcolorbuffer(x, y, z,
872 897 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=phase_min, zmax=phase_max,
873 898 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
874 899 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
875 900
876 901 if self.__showprofile:
877 902 counter += 1
878 903 axes = self.axesList[i*self.__nsubplots*2 + counter]
879 904 axes.pline(phase, y,
880 905 xmin=phase_min, xmax=phase_max, ymin=ymin, ymax=ymax,
881 906 xlabel='', ylabel='', title='', ticksize=7,
882 907 ytick_visible=False, nxticks=4,
883 908 grid='x')
884 909
885 910 self.draw()
886 911
887 912 if dataOut.ltctime >= self.xmax:
888 913 self.counter_imagwr = wr_period
889 914 self.isConfig = False
890 915 update_figfile = True
891 916
892 917 self.save(figpath=figpath,
893 918 figfile=figfile,
894 919 save=save,
895 920 ftp=ftp,
896 921 wr_period=wr_period,
897 922 thisDatetime=thisDatetime,
898 923 update_figfile=update_figfile)
899 924
900 925 class PowerProfilePlot(Figure):
901 926
902 927 isConfig = None
903 928 __nsubplots = None
904 929
905 930 WIDTHPROF = None
906 931 HEIGHTPROF = None
907 932 PREFIX = 'spcprofile'
908 933
909 934 def __init__(self, **kwargs):
910 935 Figure.__init__(self, **kwargs)
911 936 self.isConfig = False
912 937 self.__nsubplots = 1
913 938
914 939 self.PLOT_CODE = POWER_CODE
915 940
916 941 self.WIDTH = 300
917 942 self.HEIGHT = 500
918 943 self.counter_imagwr = 0
919 944
920 945 def getSubplots(self):
921 946 ncol = 1
922 947 nrow = 1
923 948
924 949 return nrow, ncol
925 950
926 951 def setup(self, id, nplots, wintitle, show):
927 952
928 953 self.nplots = nplots
929 954
930 955 ncolspan = 1
931 956 colspan = 1
932 957
933 958 self.createFigure(id = id,
934 959 wintitle = wintitle,
935 960 widthplot = self.WIDTH,
936 961 heightplot = self.HEIGHT,
937 962 show=show)
938 963
939 964 nrow, ncol = self.getSubplots()
940 965
941 966 counter = 0
942 967 for y in range(nrow):
943 968 for x in range(ncol):
944 969 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
945 970
946 971 def run(self, dataOut, id, wintitle="", channelList=None,
947 972 xmin=None, xmax=None, ymin=None, ymax=None,
948 973 save=False, figpath='./', figfile=None, show=True,
949 974 ftp=False, wr_period=1, server=None,
950 975 folder=None, username=None, password=None):
951 976
952 977
953 978 if channelList == None:
954 979 channelIndexList = dataOut.channelIndexList
955 980 channelList = dataOut.channelList
956 981 else:
957 982 channelIndexList = []
958 983 for channel in channelList:
959 984 if channel not in dataOut.channelList:
960 985 raise ValueError, "Channel %d is not in dataOut.channelList"
961 986 channelIndexList.append(dataOut.channelList.index(channel))
962 987
963 988 factor = dataOut.normFactor
964 989
965 990 y = dataOut.getHeiRange()
966 991
967 992 #for voltage
968 993 if dataOut.type == 'Voltage':
969 994 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
970 995 x = x.real
971 996 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
972 997
973 998 #for spectra
974 999 if dataOut.type == 'Spectra':
975 1000 x = dataOut.data_spc[channelIndexList,:,:]/factor
976 1001 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
977 1002 x = numpy.average(x, axis=1)
978 1003
979 1004
980 1005 xdB = 10*numpy.log10(x)
981 1006
982 1007 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
983 1008 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
984 1009 xlabel = "dB"
985 1010 ylabel = "Range (Km)"
986 1011
987 1012 if not self.isConfig:
988 1013
989 1014 nplots = 1
990 1015
991 1016 self.setup(id=id,
992 1017 nplots=nplots,
993 1018 wintitle=wintitle,
994 1019 show=show)
995 1020
996 1021 if ymin == None: ymin = numpy.nanmin(y)
997 1022 if ymax == None: ymax = numpy.nanmax(y)
998 1023 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
999 1024 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
1000 1025
1001 1026 self.isConfig = True
1002 1027
1003 1028 self.setWinTitle(title)
1004 1029
1005 1030 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1006 1031 axes = self.axesList[0]
1007 1032
1008 1033 legendlabels = ["channel %d"%x for x in channelList]
1009 1034 axes.pmultiline(xdB, y,
1010 1035 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1011 1036 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1012 1037 ytick_visible=True, nxticks=5,
1013 1038 grid='x')
1014 1039
1015 1040 self.draw()
1016 1041
1017 1042 self.save(figpath=figpath,
1018 1043 figfile=figfile,
1019 1044 save=save,
1020 1045 ftp=ftp,
1021 1046 wr_period=wr_period,
1022 1047 thisDatetime=thisDatetime)
1023 1048
1024 1049 class SpectraCutPlot(Figure):
1025 1050
1026 1051 isConfig = None
1027 1052 __nsubplots = None
1028 1053
1029 1054 WIDTHPROF = None
1030 1055 HEIGHTPROF = None
1031 1056 PREFIX = 'spc_cut'
1032 1057
1033 1058 def __init__(self, **kwargs):
1034 1059 Figure.__init__(self, **kwargs)
1035 1060 self.isConfig = False
1036 1061 self.__nsubplots = 1
1037 1062
1038 1063 self.PLOT_CODE = POWER_CODE
1039 1064
1040 1065 self.WIDTH = 700
1041 1066 self.HEIGHT = 500
1042 1067 self.counter_imagwr = 0
1043 1068
1044 1069 def getSubplots(self):
1045 1070 ncol = 1
1046 1071 nrow = 1
1047 1072
1048 1073 return nrow, ncol
1049 1074
1050 1075 def setup(self, id, nplots, wintitle, show):
1051 1076
1052 1077 self.nplots = nplots
1053 1078
1054 1079 ncolspan = 1
1055 1080 colspan = 1
1056 1081
1057 1082 self.createFigure(id = id,
1058 1083 wintitle = wintitle,
1059 1084 widthplot = self.WIDTH,
1060 1085 heightplot = self.HEIGHT,
1061 1086 show=show)
1062 1087
1063 1088 nrow, ncol = self.getSubplots()
1064 1089
1065 1090 counter = 0
1066 1091 for y in range(nrow):
1067 1092 for x in range(ncol):
1068 1093 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1069 1094
1070 1095 def run(self, dataOut, id, wintitle="", channelList=None,
1071 1096 xmin=None, xmax=None, ymin=None, ymax=None,
1072 1097 save=False, figpath='./', figfile=None, show=True,
1073 1098 ftp=False, wr_period=1, server=None,
1074 1099 folder=None, username=None, password=None,
1075 1100 xaxis="frequency"):
1076 1101
1077 1102
1078 1103 if channelList == None:
1079 1104 channelIndexList = dataOut.channelIndexList
1080 1105 channelList = dataOut.channelList
1081 1106 else:
1082 1107 channelIndexList = []
1083 1108 for channel in channelList:
1084 1109 if channel not in dataOut.channelList:
1085 1110 raise ValueError, "Channel %d is not in dataOut.channelList"
1086 1111 channelIndexList.append(dataOut.channelList.index(channel))
1087 1112
1088 1113 factor = dataOut.normFactor
1089 1114
1090 1115 y = dataOut.getHeiRange()
1091 1116
1092 1117 z = dataOut.data_spc/factor
1093 1118 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1094 1119
1095 1120 hei_index = numpy.arange(25)*3 + 20
1096 1121
1097 1122 if xaxis == "frequency":
1098 1123 x = dataOut.getFreqRange()/1000.
1099 1124 zdB = 10*numpy.log10(z[0,:,hei_index])
1100 1125 xlabel = "Frequency (kHz)"
1101 1126 ylabel = "Power (dB)"
1102 1127
1103 1128 elif xaxis == "time":
1104 1129 x = dataOut.getAcfRange()
1105 1130 zdB = z[0,:,hei_index]
1106 1131 xlabel = "Time (ms)"
1107 1132 ylabel = "ACF"
1108 1133
1109 1134 else:
1110 1135 x = dataOut.getVelRange()
1111 1136 zdB = 10*numpy.log10(z[0,:,hei_index])
1112 1137 xlabel = "Velocity (m/s)"
1113 1138 ylabel = "Power (dB)"
1114 1139
1115 1140 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1116 1141 title = wintitle + " Range Cuts %s" %(thisDatetime.strftime("%d-%b-%Y"))
1117 1142
1118 1143 if not self.isConfig:
1119 1144
1120 1145 nplots = 1
1121 1146
1122 1147 self.setup(id=id,
1123 1148 nplots=nplots,
1124 1149 wintitle=wintitle,
1125 1150 show=show)
1126 1151
1127 1152 if xmin == None: xmin = numpy.nanmin(x)*0.9
1128 1153 if xmax == None: xmax = numpy.nanmax(x)*1.1
1129 1154 if ymin == None: ymin = numpy.nanmin(zdB)
1130 1155 if ymax == None: ymax = numpy.nanmax(zdB)
1131 1156
1132 1157 self.isConfig = True
1133 1158
1134 1159 self.setWinTitle(title)
1135 1160
1136 1161 title = "Spectra Cuts: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1137 1162 axes = self.axesList[0]
1138 1163
1139 1164 legendlabels = ["Range = %dKm" %y[i] for i in hei_index]
1140 1165
1141 1166 axes.pmultilineyaxis( x, zdB,
1142 1167 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1143 1168 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
1144 1169 ytick_visible=True, nxticks=5,
1145 1170 grid='x')
1146 1171
1147 1172 self.draw()
1148 1173
1149 1174 self.save(figpath=figpath,
1150 1175 figfile=figfile,
1151 1176 save=save,
1152 1177 ftp=ftp,
1153 1178 wr_period=wr_period,
1154 1179 thisDatetime=thisDatetime)
1155 1180
1156 1181 class Noise(Figure):
1157 1182
1158 1183 isConfig = None
1159 1184 __nsubplots = None
1160 1185
1161 1186 PREFIX = 'noise'
1162 1187
1163 1188
1164 1189 def __init__(self, **kwargs):
1165 1190 Figure.__init__(self, **kwargs)
1166 1191 self.timerange = 24*60*60
1167 1192 self.isConfig = False
1168 1193 self.__nsubplots = 1
1169 1194 self.counter_imagwr = 0
1170 1195 self.WIDTH = 800
1171 1196 self.HEIGHT = 400
1172 1197 self.WIDTHPROF = 120
1173 1198 self.HEIGHTPROF = 0
1174 1199 self.xdata = None
1175 1200 self.ydata = None
1176 1201
1177 1202 self.PLOT_CODE = NOISE_CODE
1178 1203
1179 1204 self.FTP_WEI = None
1180 1205 self.EXP_CODE = None
1181 1206 self.SUB_EXP_CODE = None
1182 1207 self.PLOT_POS = None
1183 1208 self.figfile = None
1184 1209
1185 1210 self.xmin = None
1186 1211 self.xmax = None
1187 1212
1188 1213 def getSubplots(self):
1189 1214
1190 1215 ncol = 1
1191 1216 nrow = 1
1192 1217
1193 1218 return nrow, ncol
1194 1219
1195 1220 def openfile(self, filename):
1196 1221 dirname = os.path.dirname(filename)
1197 1222
1198 1223 if not os.path.exists(dirname):
1199 1224 os.mkdir(dirname)
1200 1225
1201 1226 f = open(filename,'w+')
1202 1227 f.write('\n\n')
1203 1228 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1204 1229 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1205 1230 f.close()
1206 1231
1207 1232 def save_data(self, filename_phase, data, data_datetime):
1208 1233
1209 1234 f=open(filename_phase,'a')
1210 1235
1211 1236 timetuple_data = data_datetime.timetuple()
1212 1237 day = str(timetuple_data.tm_mday)
1213 1238 month = str(timetuple_data.tm_mon)
1214 1239 year = str(timetuple_data.tm_year)
1215 1240 hour = str(timetuple_data.tm_hour)
1216 1241 minute = str(timetuple_data.tm_min)
1217 1242 second = str(timetuple_data.tm_sec)
1218 1243
1219 1244 data_msg = ''
1220 1245 for i in range(len(data)):
1221 1246 data_msg += str(data[i]) + ' '
1222 1247
1223 1248 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' ' + data_msg + '\n')
1224 1249 f.close()
1225 1250
1226 1251
1227 1252 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1228 1253
1229 1254 self.__showprofile = showprofile
1230 1255 self.nplots = nplots
1231 1256
1232 1257 ncolspan = 7
1233 1258 colspan = 6
1234 1259 self.__nsubplots = 2
1235 1260
1236 1261 self.createFigure(id = id,
1237 1262 wintitle = wintitle,
1238 1263 widthplot = self.WIDTH+self.WIDTHPROF,
1239 1264 heightplot = self.HEIGHT+self.HEIGHTPROF,
1240 1265 show=show)
1241 1266
1242 1267 nrow, ncol = self.getSubplots()
1243 1268
1244 1269 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1245 1270
1246 1271
1247 1272 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1248 1273 xmin=None, xmax=None, ymin=None, ymax=None,
1249 1274 timerange=None,
1250 1275 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1251 1276 server=None, folder=None, username=None, password=None,
1252 1277 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1253 1278
1254 1279 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1255 1280 return
1256 1281
1257 1282 if channelList == None:
1258 1283 channelIndexList = dataOut.channelIndexList
1259 1284 channelList = dataOut.channelList
1260 1285 else:
1261 1286 channelIndexList = []
1262 1287 for channel in channelList:
1263 1288 if channel not in dataOut.channelList:
1264 1289 raise ValueError, "Channel %d is not in dataOut.channelList"
1265 1290 channelIndexList.append(dataOut.channelList.index(channel))
1266 1291
1267 1292 x = dataOut.getTimeRange()
1268 1293 #y = dataOut.getHeiRange()
1269 1294 factor = dataOut.normFactor
1270 1295 noise = dataOut.noise[channelIndexList]/factor
1271 1296 noisedB = 10*numpy.log10(noise)
1272 1297
1273 1298 thisDatetime = dataOut.datatime
1274 1299
1275 1300 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1276 1301 xlabel = ""
1277 1302 ylabel = "Intensity (dB)"
1278 1303 update_figfile = False
1279 1304
1280 1305 if not self.isConfig:
1281 1306
1282 1307 nplots = 1
1283 1308
1284 1309 self.setup(id=id,
1285 1310 nplots=nplots,
1286 1311 wintitle=wintitle,
1287 1312 showprofile=showprofile,
1288 1313 show=show)
1289 1314
1290 1315 if timerange != None:
1291 1316 self.timerange = timerange
1292 1317
1293 1318 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1294 1319
1295 1320 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1296 1321 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1297 1322
1298 1323 self.FTP_WEI = ftp_wei
1299 1324 self.EXP_CODE = exp_code
1300 1325 self.SUB_EXP_CODE = sub_exp_code
1301 1326 self.PLOT_POS = plot_pos
1302 1327
1303 1328
1304 1329 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1305 1330 self.isConfig = True
1306 1331 self.figfile = figfile
1307 1332 self.xdata = numpy.array([])
1308 1333 self.ydata = numpy.array([])
1309 1334
1310 1335 update_figfile = True
1311 1336
1312 1337 #open file beacon phase
1313 1338 path = '%s%03d' %(self.PREFIX, self.id)
1314 1339 noise_file = os.path.join(path,'%s.txt'%self.name)
1315 1340 self.filename_noise = os.path.join(figpath,noise_file)
1316 1341
1317 1342 self.setWinTitle(title)
1318 1343
1319 1344 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1320 1345
1321 1346 legendlabels = ["channel %d"%(idchannel) for idchannel in channelList]
1322 1347 axes = self.axesList[0]
1323 1348
1324 1349 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1325 1350
1326 1351 if len(self.ydata)==0:
1327 1352 self.ydata = noisedB.reshape(-1,1)
1328 1353 else:
1329 1354 self.ydata = numpy.hstack((self.ydata, noisedB.reshape(-1,1)))
1330 1355
1331 1356
1332 1357 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1333 1358 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1334 1359 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1335 1360 XAxisAsTime=True, grid='both'
1336 1361 )
1337 1362
1338 1363 self.draw()
1339 1364
1340 1365 if dataOut.ltctime >= self.xmax:
1341 1366 self.counter_imagwr = wr_period
1342 1367 self.isConfig = False
1343 1368 update_figfile = True
1344 1369
1345 1370 self.save(figpath=figpath,
1346 1371 figfile=figfile,
1347 1372 save=save,
1348 1373 ftp=ftp,
1349 1374 wr_period=wr_period,
1350 1375 thisDatetime=thisDatetime,
1351 1376 update_figfile=update_figfile)
1352 1377
1353 1378 #store data beacon phase
1354 1379 if save:
1355 1380 self.save_data(self.filename_noise, noisedB, thisDatetime)
1356 1381
1357 1382 class BeaconPhase(Figure):
1358 1383
1359 1384 __isConfig = None
1360 1385 __nsubplots = None
1361 1386
1362 1387 PREFIX = 'beacon_phase'
1363 1388
1364 1389 def __init__(self, **kwargs):
1365 1390 Figure.__init__(self, **kwargs)
1366 1391 self.timerange = 24*60*60
1367 1392 self.isConfig = False
1368 1393 self.__nsubplots = 1
1369 1394 self.counter_imagwr = 0
1370 1395 self.WIDTH = 800
1371 1396 self.HEIGHT = 400
1372 1397 self.WIDTHPROF = 120
1373 1398 self.HEIGHTPROF = 0
1374 1399 self.xdata = None
1375 1400 self.ydata = None
1376 1401
1377 1402 self.PLOT_CODE = BEACON_CODE
1378 1403
1379 1404 self.FTP_WEI = None
1380 1405 self.EXP_CODE = None
1381 1406 self.SUB_EXP_CODE = None
1382 1407 self.PLOT_POS = None
1383 1408
1384 1409 self.filename_phase = None
1385 1410
1386 1411 self.figfile = None
1387 1412
1388 1413 self.xmin = None
1389 1414 self.xmax = None
1390 1415
1391 1416 def getSubplots(self):
1392 1417
1393 1418 ncol = 1
1394 1419 nrow = 1
1395 1420
1396 1421 return nrow, ncol
1397 1422
1398 1423 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1399 1424
1400 1425 self.__showprofile = showprofile
1401 1426 self.nplots = nplots
1402 1427
1403 1428 ncolspan = 7
1404 1429 colspan = 6
1405 1430 self.__nsubplots = 2
1406 1431
1407 1432 self.createFigure(id = id,
1408 1433 wintitle = wintitle,
1409 1434 widthplot = self.WIDTH+self.WIDTHPROF,
1410 1435 heightplot = self.HEIGHT+self.HEIGHTPROF,
1411 1436 show=show)
1412 1437
1413 1438 nrow, ncol = self.getSubplots()
1414 1439
1415 1440 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1416 1441
1417 1442 def save_phase(self, filename_phase):
1418 1443 f = open(filename_phase,'w+')
1419 1444 f.write('\n\n')
1420 1445 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1421 1446 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1422 1447 f.close()
1423 1448
1424 1449 def save_data(self, filename_phase, data, data_datetime):
1425 1450 f=open(filename_phase,'a')
1426 1451 timetuple_data = data_datetime.timetuple()
1427 1452 day = str(timetuple_data.tm_mday)
1428 1453 month = str(timetuple_data.tm_mon)
1429 1454 year = str(timetuple_data.tm_year)
1430 1455 hour = str(timetuple_data.tm_hour)
1431 1456 minute = str(timetuple_data.tm_min)
1432 1457 second = str(timetuple_data.tm_sec)
1433 1458 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1434 1459 f.close()
1435 1460
1436 1461
1437 1462 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1438 1463 xmin=None, xmax=None, ymin=None, ymax=None, hmin=None, hmax=None,
1439 1464 timerange=None,
1440 1465 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1441 1466 server=None, folder=None, username=None, password=None,
1442 1467 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1443 1468
1444 1469 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
1445 1470 return
1446 1471
1447 1472 if pairsList == None:
1448 1473 pairsIndexList = dataOut.pairsIndexList[:10]
1449 1474 else:
1450 1475 pairsIndexList = []
1451 1476 for pair in pairsList:
1452 1477 if pair not in dataOut.pairsList:
1453 1478 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1454 1479 pairsIndexList.append(dataOut.pairsList.index(pair))
1455 1480
1456 1481 if pairsIndexList == []:
1457 1482 return
1458 1483
1459 1484 # if len(pairsIndexList) > 4:
1460 1485 # pairsIndexList = pairsIndexList[0:4]
1461 1486
1462 1487 hmin_index = None
1463 1488 hmax_index = None
1464 1489
1465 1490 if hmin != None and hmax != None:
1466 1491 indexes = numpy.arange(dataOut.nHeights)
1467 1492 hmin_list = indexes[dataOut.heightList >= hmin]
1468 1493 hmax_list = indexes[dataOut.heightList <= hmax]
1469 1494
1470 1495 if hmin_list.any():
1471 1496 hmin_index = hmin_list[0]
1472 1497
1473 1498 if hmax_list.any():
1474 1499 hmax_index = hmax_list[-1]+1
1475 1500
1476 1501 x = dataOut.getTimeRange()
1477 1502 #y = dataOut.getHeiRange()
1478 1503
1479 1504
1480 1505 thisDatetime = dataOut.datatime
1481 1506
1482 1507 title = wintitle + " Signal Phase" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1483 1508 xlabel = "Local Time"
1484 1509 ylabel = "Phase (degrees)"
1485 1510
1486 1511 update_figfile = False
1487 1512
1488 1513 nplots = len(pairsIndexList)
1489 1514 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1490 1515 phase_beacon = numpy.zeros(len(pairsIndexList))
1491 1516 for i in range(nplots):
1492 1517 pair = dataOut.pairsList[pairsIndexList[i]]
1493 1518 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i], :, hmin_index:hmax_index], axis=0)
1494 1519 powa = numpy.average(dataOut.data_spc[pair[0], :, hmin_index:hmax_index], axis=0)
1495 1520 powb = numpy.average(dataOut.data_spc[pair[1], :, hmin_index:hmax_index], axis=0)
1496 1521 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1497 1522 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1498 1523
1499 1524 #print "Phase %d%d" %(pair[0], pair[1])
1500 1525 #print phase[dataOut.beacon_heiIndexList]
1501 1526
1502 1527 if dataOut.beacon_heiIndexList:
1503 1528 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1504 1529 else:
1505 1530 phase_beacon[i] = numpy.average(phase)
1506 1531
1507 1532 if not self.isConfig:
1508 1533
1509 1534 nplots = len(pairsIndexList)
1510 1535
1511 1536 self.setup(id=id,
1512 1537 nplots=nplots,
1513 1538 wintitle=wintitle,
1514 1539 showprofile=showprofile,
1515 1540 show=show)
1516 1541
1517 1542 if timerange != None:
1518 1543 self.timerange = timerange
1519 1544
1520 1545 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1521 1546
1522 1547 if ymin == None: ymin = 0
1523 1548 if ymax == None: ymax = 360
1524 1549
1525 1550 self.FTP_WEI = ftp_wei
1526 1551 self.EXP_CODE = exp_code
1527 1552 self.SUB_EXP_CODE = sub_exp_code
1528 1553 self.PLOT_POS = plot_pos
1529 1554
1530 1555 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1531 1556 self.isConfig = True
1532 1557 self.figfile = figfile
1533 1558 self.xdata = numpy.array([])
1534 1559 self.ydata = numpy.array([])
1535 1560
1536 1561 update_figfile = True
1537 1562
1538 1563 #open file beacon phase
1539 1564 path = '%s%03d' %(self.PREFIX, self.id)
1540 1565 beacon_file = os.path.join(path,'%s.txt'%self.name)
1541 1566 self.filename_phase = os.path.join(figpath,beacon_file)
1542 1567 #self.save_phase(self.filename_phase)
1543 1568
1544 1569
1545 1570 #store data beacon phase
1546 1571 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1547 1572
1548 1573 self.setWinTitle(title)
1549 1574
1550 1575
1551 1576 title = "Phase Plot %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1552 1577
1553 1578 legendlabels = ["Pair (%d,%d)"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1554 1579
1555 1580 axes = self.axesList[0]
1556 1581
1557 1582 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1558 1583
1559 1584 if len(self.ydata)==0:
1560 1585 self.ydata = phase_beacon.reshape(-1,1)
1561 1586 else:
1562 1587 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1563 1588
1564 1589
1565 1590 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1566 1591 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1567 1592 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1568 1593 XAxisAsTime=True, grid='both'
1569 1594 )
1570 1595
1571 1596 self.draw()
1572 1597
1573 1598 if dataOut.ltctime >= self.xmax:
1574 1599 self.counter_imagwr = wr_period
1575 1600 self.isConfig = False
1576 1601 update_figfile = True
1577 1602
1578 1603 self.save(figpath=figpath,
1579 1604 figfile=figfile,
1580 1605 save=save,
1581 1606 ftp=ftp,
1582 1607 wr_period=wr_period,
1583 1608 thisDatetime=thisDatetime,
1584 1609 update_figfile=update_figfile)
@@ -1,362 +1,365
1 1 '''
2 2 Created on Nov 9, 2016
3 3
4 4 @author: roj- LouVD
5 5 '''
6 6
7 7
8 8 import os
9 9 import sys
10 10 import time
11 11 import glob
12 12 import datetime
13 13
14 14 import numpy
15 15
16 16 from schainpy.model.proc.jroproc_base import ProcessingUnit
17 17 from schainpy.model.data.jrodata import Parameters
18 18 from schainpy.model.io.jroIO_base import JRODataReader, isNumber
19 19
20 20 FILE_HEADER_STRUCTURE = numpy.dtype([
21 21 ('FMN', '<u4'),
22 22 ('nrec', '<u4'),
23 23 ('fr_offset', '<u4'),
24 24 ('id', '<u4'),
25 25 ('site', 'u1', (32,))
26 26 ])
27 27
28 28 REC_HEADER_STRUCTURE = numpy.dtype([
29 29 ('rmn', '<u4'),
30 30 ('rcounter', '<u4'),
31 31 ('nr_offset', '<u4'),
32 32 ('tr_offset', '<u4'),
33 33 ('time', '<u4'),
34 34 ('time_msec', '<u4'),
35 35 ('tag', 'u1', (32,)),
36 36 ('comments', 'u1', (32,)),
37 37 ('lat', '<f4'),
38 38 ('lon', '<f4'),
39 39 ('gps_status', '<u4'),
40 40 ('freq', '<u4'),
41 41 ('freq0', '<u4'),
42 42 ('nchan', '<u4'),
43 43 ('delta_r', '<u4'),
44 44 ('nranges', '<u4'),
45 45 ('r0', '<u4'),
46 46 ('prf', '<u4'),
47 47 ('ncoh', '<u4'),
48 48 ('npoints', '<u4'),
49 49 ('polarization', '<i4'),
50 50 ('rx_filter', '<u4'),
51 51 ('nmodes', '<u4'),
52 52 ('dmode_index', '<u4'),
53 53 ('dmode_rngcorr', '<u4'),
54 54 ('nrxs', '<u4'),
55 55 ('acf_length', '<u4'),
56 56 ('acf_lags', '<u4'),
57 57 ('sea_to_atmos', '<f4'),
58 58 ('sea_notch', '<u4'),
59 59 ('lh_sea', '<u4'),
60 60 ('hh_sea', '<u4'),
61 61 ('nbins_sea', '<u4'),
62 62 ('min_snr', '<f4'),
63 63 ('min_cc', '<f4'),
64 64 ('max_time_diff', '<f4')
65 65 ])
66 66
67 67 DATA_STRUCTURE = numpy.dtype([
68 68 ('range', '<u4'),
69 69 ('status', '<u4'),
70 70 ('zonal', '<f4'),
71 71 ('meridional', '<f4'),
72 72 ('vertical', '<f4'),
73 73 ('zonal_a', '<f4'),
74 74 ('meridional_a', '<f4'),
75 75 ('corrected_fading', '<f4'), # seconds
76 76 ('uncorrected_fading', '<f4'), # seconds
77 77 ('time_diff', '<f4'),
78 78 ('major_axis', '<f4'),
79 79 ('axial_ratio', '<f4'),
80 80 ('orientation', '<f4'),
81 81 ('sea_power', '<u4'),
82 82 ('sea_algorithm', '<u4')
83 83 ])
84 84
85 85 class BLTRParamReader(JRODataReader, ProcessingUnit):
86 86 '''
87 87 Boundary Layer and Tropospheric Radar (BLTR) reader, Wind velocities and SNR from *.sswma files
88 88 '''
89 89
90 90 ext = '.sswma'
91 91
92 92 def __init__(self, **kwargs):
93 93
94 94 ProcessingUnit.__init__(self , **kwargs)
95 95
96 96 self.dataOut = Parameters()
97 97 self.counter_records = 0
98 98 self.flagNoMoreFiles = 0
99 99 self.isConfig = False
100 100 self.filename = None
101 101
102 102 def setup(self,
103 103 path=None,
104 104 startDate=None,
105 105 endDate=None,
106 106 ext=None,
107 107 startTime=datetime.time(0, 0, 0),
108 108 endTime=datetime.time(23, 59, 59),
109 109 timezone=0,
110 110 status_value=0,
111 111 **kwargs):
112 112
113 self.verbose = kwargs.get('verbose', True)
113 114 self.path = path
114 115 self.startTime = startTime
115 116 self.endTime = endTime
116 117 self.status_value = status_value
117 118
118 119 if self.path is None:
119 120 raise ValueError, "The path is not valid"
120 121
121 122 if ext is None:
122 123 ext = self.ext
123 124
124 125 self.search_files(self.path, startDate, endDate, ext)
125 126 self.timezone = timezone
126 127 self.fileIndex = 0
127 128
128 129 if not self.fileList:
129 130 raise Warning, "There is no files matching these date in the folder: %s. \n Check 'startDate' and 'endDate' "%(path)
130 131
131 132 self.setNextFile()
132 133
133 134 def search_files(self, path, startDate, endDate, ext):
134 135 '''
135 136 Searching for BLTR rawdata file in path
136 137 Creating a list of file to proces included in [startDate,endDate]
137 138
138 139 Input:
139 140 path - Path to find BLTR rawdata files
140 141 startDate - Select file from this date
141 142 enDate - Select file until this date
142 143 ext - Extension of the file to read
143 144
144 145 '''
145 146
146 147 print 'Searching file in %s ' % (path)
147 148 foldercounter = 0
148 149 fileList0 = glob.glob1(path, "*%s" % ext)
149 150 fileList0.sort()
150 151
151 152 self.fileList = []
152 153 self.dateFileList = []
153 154
154 155 for thisFile in fileList0:
155 156 year = thisFile[-14:-10]
156 157 if not isNumber(year):
157 158 continue
158 159
159 160 month = thisFile[-10:-8]
160 161 if not isNumber(month):
161 162 continue
162 163
163 164 day = thisFile[-8:-6]
164 165 if not isNumber(day):
165 166 continue
166 167
167 168 year, month, day = int(year), int(month), int(day)
168 169 dateFile = datetime.date(year, month, day)
169 170
170 171 if (startDate > dateFile) or (endDate < dateFile):
171 172 continue
172 173
173 174 self.fileList.append(thisFile)
174 175 self.dateFileList.append(dateFile)
175 176
176 177 return
177 178
178 179 def setNextFile(self):
179 180
180 181 file_id = self.fileIndex
181 182
182 183 if file_id == len(self.fileList):
183 184 print '\nNo more files in the folder'
184 185 print 'Total number of file(s) read : {}'.format(self.fileIndex + 1)
185 186 self.flagNoMoreFiles = 1
186 187 return 0
187 188
188 189 print '\n[Setting file] (%s) ...' % self.fileList[file_id]
189 190 filename = os.path.join(self.path, self.fileList[file_id])
190 191
191 192 dirname, name = os.path.split(filename)
192 193 self.siteFile = name.split('.')[0] # 'peru2' ---> Piura - 'peru1' ---> Huancayo or Porcuya
193 194 if self.filename is not None:
194 195 self.fp.close()
195 196 self.filename = filename
196 197 self.fp = open(self.filename, 'rb')
197 198 self.header_file = numpy.fromfile(self.fp, FILE_HEADER_STRUCTURE, 1)
198 199 self.nrecords = self.header_file['nrec'][0]
199 200 self.sizeOfFile = os.path.getsize(self.filename)
200 201 self.counter_records = 0
201 202 self.flagIsNewFile = 0
202 203 self.fileIndex += 1
203 204
204 205 return 1
205 206
206 207 def readNextBlock(self):
207 208
208 209 while True:
209 210 if self.counter_records == self.nrecords:
210 211 self.flagIsNewFile = 1
211 212 if not self.setNextFile():
212 213 return 0
213 214
214 215 self.readBlock()
215 216
216 217 if (self.datatime.time() < self.startTime) or (self.datatime.time() > self.endTime):
217 print "[Reading] Record No. %d/%d -> %s [Skipping]" %(
218 self.counter_records,
219 self.nrecords,
220 self.datatime.ctime())
218 if self.verbose:
219 print "[Reading] Record No. %d/%d -> %s [Skipping]" %(
220 self.counter_records,
221 self.nrecords,
222 self.datatime.ctime())
221 223 continue
222 224 break
223 225
224 print "[Reading] Record No. %d/%d -> %s" %(
225 self.counter_records,
226 self.nrecords,
227 self.datatime.ctime())
226 if self.verbose:
227 print "[Reading] Record No. %d/%d -> %s" %(
228 self.counter_records,
229 self.nrecords,
230 self.datatime.ctime())
228 231
229 232 return 1
230 233
231 234 def readBlock(self):
232 235
233 236 pointer = self.fp.tell()
234 237 header_rec = numpy.fromfile(self.fp, REC_HEADER_STRUCTURE, 1)
235 238 self.nchannels = header_rec['nchan'][0]/2
236 239 self.kchan = header_rec['nrxs'][0]
237 240 self.nmodes = header_rec['nmodes'][0]
238 241 self.nranges = header_rec['nranges'][0]
239 242 self.fp.seek(pointer)
240 243 self.height = numpy.empty((self.nmodes, self.nranges))
241 244 self.snr = numpy.empty((self.nmodes, self.nchannels, self.nranges))
242 245 self.buffer = numpy.empty((self.nmodes, 3, self.nranges))
243 246
244 247 for mode in range(self.nmodes):
245 248 self.readHeader()
246 249 data = self.readData()
247 250 self.height[mode] = (data[0] - self.correction) / 1000.
248 251 self.buffer[mode] = data[1]
249 252 self.snr[mode] = data[2]
250 253
251 254 self.counter_records = self.counter_records + self.nmodes
252 255
253 256 return
254 257
255 258 def readHeader(self):
256 259 '''
257 260 RecordHeader of BLTR rawdata file
258 261 '''
259 262
260 263 header_structure = numpy.dtype(
261 264 REC_HEADER_STRUCTURE.descr + [
262 265 ('antenna_coord', 'f4', (2, self.nchannels)),
263 266 ('rx_gains', 'u4', (self.nchannels,)),
264 267 ('rx_analysis', 'u4', (self.nchannels,))
265 268 ]
266 269 )
267 270
268 271 self.header_rec = numpy.fromfile(self.fp, header_structure, 1)
269 272 self.lat = self.header_rec['lat'][0]
270 273 self.lon = self.header_rec['lon'][0]
271 274 self.delta = self.header_rec['delta_r'][0]
272 275 self.correction = self.header_rec['dmode_rngcorr'][0]
273 276 self.imode = self.header_rec['dmode_index'][0]
274 277 self.antenna = self.header_rec['antenna_coord']
275 278 self.rx_gains = self.header_rec['rx_gains']
276 279 self.time = self.header_rec['time'][0]
277 280 tseconds = self.header_rec['time'][0]
278 281 local_t1 = time.localtime(tseconds)
279 282 self.year = local_t1.tm_year
280 283 self.month = local_t1.tm_mon
281 284 self.day = local_t1.tm_mday
282 285 self.t = datetime.datetime(self.year, self.month, self.day)
283 286 self.datatime = datetime.datetime.utcfromtimestamp(self.time)
284 287
285 288 def readData(self):
286 289 '''
287 290 Reading and filtering data block record of BLTR rawdata file, filtering is according to status_value.
288 291
289 292 Input:
290 293 status_value - Array data is set to NAN for values that are not equal to status_value
291 294
292 295 '''
293 296
294 297 data_structure = numpy.dtype(
295 298 DATA_STRUCTURE.descr + [
296 299 ('rx_saturation', 'u4', (self.nchannels,)),
297 300 ('chan_offset', 'u4', (2 * self.nchannels,)),
298 301 ('rx_amp', 'u4', (self.nchannels,)),
299 302 ('rx_snr', 'f4', (self.nchannels,)),
300 303 ('cross_snr', 'f4', (self.kchan,)),
301 304 ('sea_power_relative', 'f4', (self.kchan,))]
302 305 )
303 306
304 307 data = numpy.fromfile(self.fp, data_structure, self.nranges)
305 308
306 309 height = data['range']
307 310 winds = numpy.array((data['zonal'], data['meridional'], data['vertical']))
308 311 snr = data['rx_snr'].T
309 312
310 313 winds[numpy.where(winds == -9999.)] = numpy.nan
311 314 winds[:, numpy.where(data['status'] != self.status_value)] = numpy.nan
312 315 snr[numpy.where(snr == -9999.)] = numpy.nan
313 316 snr[:, numpy.where(data['status'] != self.status_value)] = numpy.nan
314 317 snr = numpy.power(10, snr / 10)
315 318
316 319 return height, winds, snr
317 320
318 321 def set_output(self):
319 322 '''
320 323 Storing data from databuffer to dataOut object
321 324 '''
322 325
323 326 self.dataOut.data_SNR = self.snr
324 327 self.dataOut.height = self.height
325 328 self.dataOut.data_output = self.buffer
326 329 self.dataOut.utctimeInit = self.time
327 330 self.dataOut.utctime = self.dataOut.utctimeInit
328 331 self.dataOut.useLocalTime = False
329 332 self.dataOut.paramInterval = 157
330 333 self.dataOut.timezone = self.timezone
331 334 self.dataOut.site = self.siteFile
332 335 self.dataOut.nrecords = self.nrecords/self.nmodes
333 336 self.dataOut.sizeOfFile = self.sizeOfFile
334 337 self.dataOut.lat = self.lat
335 338 self.dataOut.lon = self.lon
336 339 self.dataOut.channelList = range(self.nchannels)
337 340 self.dataOut.kchan = self.kchan
338 341 # self.dataOut.nHeights = self.nranges
339 342 self.dataOut.delta = self.delta
340 343 self.dataOut.correction = self.correction
341 344 self.dataOut.nmodes = self.nmodes
342 345 self.dataOut.imode = self.imode
343 346 self.dataOut.antenna = self.antenna
344 347 self.dataOut.rx_gains = self.rx_gains
345 348 self.dataOut.flagNoData = False
346 349
347 350 def getData(self):
348 351 '''
349 352 Storing data from databuffer to dataOut object
350 353 '''
351 354 if self.flagNoMoreFiles:
352 355 self.dataOut.flagNoData = True
353 356 print 'No file left to process'
354 357 return 0
355 358
356 359 if not self.readNextBlock():
357 360 self.dataOut.flagNoData = True
358 361 return 0
359 362
360 363 self.set_output()
361 364
362 365 return 1
@@ -1,1794 +1,1794
1 1 '''
2 2 Created on Jul 2, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import sys
8 8 import glob
9 9 import time
10 10 import numpy
11 11 import fnmatch
12 12 import inspect
13 13 import time, datetime
14 14 import traceback
15 15
16 16 try:
17 17 from gevent import sleep
18 18 except:
19 19 from time import sleep
20 20
21 21 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
22 22 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
23 23
24 24 LOCALTIME = True
25 25
26 26 def isNumber(cad):
27 27 """
28 28 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
29 29
30 30 Excepciones:
31 31 Si un determinado string no puede ser convertido a numero
32 32 Input:
33 33 str, string al cual se le analiza para determinar si convertible a un numero o no
34 34
35 35 Return:
36 36 True : si el string es uno numerico
37 37 False : no es un string numerico
38 38 """
39 39 try:
40 40 float( cad )
41 41 return True
42 42 except:
43 43 return False
44 44
45 45 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
46 46 """
47 47 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
48 48
49 49 Inputs:
50 50 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
51 51
52 52 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
53 53 segundos contados desde 01/01/1970.
54 54 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
55 55 segundos contados desde 01/01/1970.
56 56
57 57 Return:
58 58 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
59 59 fecha especificado, de lo contrario retorna False.
60 60
61 61 Excepciones:
62 62 Si el archivo no existe o no puede ser abierto
63 63 Si la cabecera no puede ser leida.
64 64
65 65 """
66 66 basicHeaderObj = BasicHeader(LOCALTIME)
67 67
68 68 try:
69 69 fp = open(filename,'rb')
70 70 except IOError:
71 71 print "The file %s can't be opened" %(filename)
72 72 return 0
73 73
74 74 sts = basicHeaderObj.read(fp)
75 75 fp.close()
76 76
77 77 if not(sts):
78 78 print "Skipping the file %s because it has not a valid header" %(filename)
79 79 return 0
80 80
81 81 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
82 82 return 0
83 83
84 84 return 1
85 85
86 86 def isTimeInRange(thisTime, startTime, endTime):
87 87
88 88 if endTime >= startTime:
89 89 if (thisTime < startTime) or (thisTime > endTime):
90 90 return 0
91 91
92 92 return 1
93 93 else:
94 94 if (thisTime < startTime) and (thisTime > endTime):
95 95 return 0
96 96
97 97 return 1
98 98
99 99 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
100 100 """
101 101 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
102 102
103 103 Inputs:
104 104 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
105 105
106 106 startDate : fecha inicial del rango seleccionado en formato datetime.date
107 107
108 108 endDate : fecha final del rango seleccionado en formato datetime.date
109 109
110 110 startTime : tiempo inicial del rango seleccionado en formato datetime.time
111 111
112 112 endTime : tiempo final del rango seleccionado en formato datetime.time
113 113
114 114 Return:
115 115 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
116 116 fecha especificado, de lo contrario retorna False.
117 117
118 118 Excepciones:
119 119 Si el archivo no existe o no puede ser abierto
120 120 Si la cabecera no puede ser leida.
121 121
122 122 """
123 123
124 124
125 125 try:
126 126 fp = open(filename,'rb')
127 127 except IOError:
128 128 print "The file %s can't be opened" %(filename)
129 129 return None
130 130
131 131 firstBasicHeaderObj = BasicHeader(LOCALTIME)
132 132 systemHeaderObj = SystemHeader()
133 133 radarControllerHeaderObj = RadarControllerHeader()
134 134 processingHeaderObj = ProcessingHeader()
135 135
136 136 lastBasicHeaderObj = BasicHeader(LOCALTIME)
137 137
138 138 sts = firstBasicHeaderObj.read(fp)
139 139
140 140 if not(sts):
141 141 print "[Reading] Skipping the file %s because it has not a valid header" %(filename)
142 142 return None
143 143
144 144 if not systemHeaderObj.read(fp):
145 145 return None
146 146
147 147 if not radarControllerHeaderObj.read(fp):
148 148 return None
149 149
150 150 if not processingHeaderObj.read(fp):
151 151 return None
152 152
153 153 filesize = os.path.getsize(filename)
154 154
155 155 offset = processingHeaderObj.blockSize + 24 #header size
156 156
157 157 if filesize <= offset:
158 158 print "[Reading] %s: This file has not enough data" %filename
159 159 return None
160 160
161 161 fp.seek(-offset, 2)
162 162
163 163 sts = lastBasicHeaderObj.read(fp)
164 164
165 165 fp.close()
166 166
167 167 thisDatetime = lastBasicHeaderObj.datatime
168 168 thisTime_last_block = thisDatetime.time()
169 169
170 170 thisDatetime = firstBasicHeaderObj.datatime
171 171 thisDate = thisDatetime.date()
172 172 thisTime_first_block = thisDatetime.time()
173 173
174 174 #General case
175 175 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
176 176 #-----------o----------------------------o-----------
177 177 # startTime endTime
178 178
179 179 if endTime >= startTime:
180 180 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
181 181 return None
182 182
183 183 return thisDatetime
184 184
185 185 #If endTime < startTime then endTime belongs to the next day
186 186
187 187
188 188 #<<<<<<<<<<<o o>>>>>>>>>>>
189 189 #-----------o----------------------------o-----------
190 190 # endTime startTime
191 191
192 192 if (thisDate == startDate) and (thisTime_last_block < startTime):
193 193 return None
194 194
195 195 if (thisDate == endDate) and (thisTime_first_block > endTime):
196 196 return None
197 197
198 198 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
199 199 return None
200 200
201 201 return thisDatetime
202 202
203 203 def isFolderInDateRange(folder, startDate=None, endDate=None):
204 204 """
205 205 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
206 206
207 207 Inputs:
208 208 folder : nombre completo del directorio.
209 209 Su formato deberia ser "/path_root/?YYYYDDD"
210 210
211 211 siendo:
212 212 YYYY : Anio (ejemplo 2015)
213 213 DDD : Dia del anio (ejemplo 305)
214 214
215 215 startDate : fecha inicial del rango seleccionado en formato datetime.date
216 216
217 217 endDate : fecha final del rango seleccionado en formato datetime.date
218 218
219 219 Return:
220 220 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
221 221 fecha especificado, de lo contrario retorna False.
222 222 Excepciones:
223 223 Si el directorio no tiene el formato adecuado
224 224 """
225 225
226 226 basename = os.path.basename(folder)
227 227
228 228 if not isRadarFolder(basename):
229 229 print "The folder %s has not the rigth format" %folder
230 230 return 0
231 231
232 232 if startDate and endDate:
233 233 thisDate = getDateFromRadarFolder(basename)
234 234
235 235 if thisDate < startDate:
236 236 return 0
237 237
238 238 if thisDate > endDate:
239 239 return 0
240 240
241 241 return 1
242 242
243 243 def isFileInDateRange(filename, startDate=None, endDate=None):
244 244 """
245 245 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
246 246
247 247 Inputs:
248 248 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
249 249
250 250 Su formato deberia ser "?YYYYDDDsss"
251 251
252 252 siendo:
253 253 YYYY : Anio (ejemplo 2015)
254 254 DDD : Dia del anio (ejemplo 305)
255 255 sss : set
256 256
257 257 startDate : fecha inicial del rango seleccionado en formato datetime.date
258 258
259 259 endDate : fecha final del rango seleccionado en formato datetime.date
260 260
261 261 Return:
262 262 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
263 263 fecha especificado, de lo contrario retorna False.
264 264 Excepciones:
265 265 Si el archivo no tiene el formato adecuado
266 266 """
267 267
268 268 basename = os.path.basename(filename)
269 269
270 270 if not isRadarFile(basename):
271 271 print "The filename %s has not the rigth format" %filename
272 272 return 0
273 273
274 274 if startDate and endDate:
275 275 thisDate = getDateFromRadarFile(basename)
276 276
277 277 if thisDate < startDate:
278 278 return 0
279 279
280 280 if thisDate > endDate:
281 281 return 0
282 282
283 283 return 1
284 284
285 285 def getFileFromSet(path, ext, set):
286 286 validFilelist = []
287 287 fileList = os.listdir(path)
288 288
289 289 # 0 1234 567 89A BCDE
290 290 # H YYYY DDD SSS .ext
291 291
292 292 for thisFile in fileList:
293 293 try:
294 294 year = int(thisFile[1:5])
295 295 doy = int(thisFile[5:8])
296 296 except:
297 297 continue
298 298
299 299 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
300 300 continue
301 301
302 302 validFilelist.append(thisFile)
303 303
304 304 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
305 305
306 306 if len(myfile)!= 0:
307 307 return myfile[0]
308 308 else:
309 309 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
310 310 print 'the filename %s does not exist'%filename
311 311 print '...going to the last file: '
312 312
313 313 if validFilelist:
314 314 validFilelist = sorted( validFilelist, key=str.lower )
315 315 return validFilelist[-1]
316 316
317 317 return None
318 318
319 319 def getlastFileFromPath(path, ext):
320 320 """
321 321 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
322 322 al final de la depuracion devuelve el ultimo file de la lista que quedo.
323 323
324 324 Input:
325 325 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
326 326 ext : extension de los files contenidos en una carpeta
327 327
328 328 Return:
329 329 El ultimo file de una determinada carpeta, no se considera el path.
330 330 """
331 331 validFilelist = []
332 332 fileList = os.listdir(path)
333 333
334 334 # 0 1234 567 89A BCDE
335 335 # H YYYY DDD SSS .ext
336 336
337 337 for thisFile in fileList:
338 338
339 339 year = thisFile[1:5]
340 340 if not isNumber(year):
341 341 continue
342 342
343 343 doy = thisFile[5:8]
344 344 if not isNumber(doy):
345 345 continue
346 346
347 347 year = int(year)
348 348 doy = int(doy)
349 349
350 350 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
351 351 continue
352 352
353 353 validFilelist.append(thisFile)
354 354
355 355 if validFilelist:
356 356 validFilelist = sorted( validFilelist, key=str.lower )
357 357 return validFilelist[-1]
358 358
359 359 return None
360 360
361 361 def checkForRealPath(path, foldercounter, year, doy, set, ext):
362 362 """
363 363 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
364 364 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
365 365 el path exacto de un determinado file.
366 366
367 367 Example :
368 368 nombre correcto del file es .../.../D2009307/P2009307367.ext
369 369
370 370 Entonces la funcion prueba con las siguientes combinaciones
371 371 .../.../y2009307367.ext
372 372 .../.../Y2009307367.ext
373 373 .../.../x2009307/y2009307367.ext
374 374 .../.../x2009307/Y2009307367.ext
375 375 .../.../X2009307/y2009307367.ext
376 376 .../.../X2009307/Y2009307367.ext
377 377 siendo para este caso, la ultima combinacion de letras, identica al file buscado
378 378
379 379 Return:
380 380 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
381 381 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
382 382 para el filename
383 383 """
384 384 fullfilename = None
385 385 find_flag = False
386 386 filename = None
387 387
388 388 prefixDirList = [None,'d','D']
389 389 if ext.lower() == ".r": #voltage
390 390 prefixFileList = ['d','D']
391 391 elif ext.lower() == ".pdata": #spectra
392 392 prefixFileList = ['p','P']
393 393 else:
394 394 return None, filename
395 395
396 396 #barrido por las combinaciones posibles
397 397 for prefixDir in prefixDirList:
398 398 thispath = path
399 399 if prefixDir != None:
400 400 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
401 401 if foldercounter == 0:
402 402 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
403 403 else:
404 404 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
405 405 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
406 406 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
407 407 fullfilename = os.path.join( thispath, filename ) #formo el path completo
408 408
409 409 if os.path.exists( fullfilename ): #verifico que exista
410 410 find_flag = True
411 411 break
412 412 if find_flag:
413 413 break
414 414
415 415 if not(find_flag):
416 416 return None, filename
417 417
418 418 return fullfilename, filename
419 419
420 420 def isRadarFolder(folder):
421 421 try:
422 422 year = int(folder[1:5])
423 423 doy = int(folder[5:8])
424 424 except:
425 425 return 0
426 426
427 427 return 1
428 428
429 429 def isRadarFile(file):
430 430 try:
431 431 year = int(file[1:5])
432 432 doy = int(file[5:8])
433 433 set = int(file[8:11])
434 434 except:
435 435 return 0
436 436
437 437 return 1
438 438
439 439 def getDateFromRadarFile(file):
440 440 try:
441 441 year = int(file[1:5])
442 442 doy = int(file[5:8])
443 443 set = int(file[8:11])
444 444 except:
445 445 return None
446 446
447 447 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
448 448 return thisDate
449 449
450 450 def getDateFromRadarFolder(folder):
451 451 try:
452 452 year = int(folder[1:5])
453 453 doy = int(folder[5:8])
454 454 except:
455 455 return None
456 456
457 457 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
458 458 return thisDate
459 459
460 460 class JRODataIO:
461 461
462 462 c = 3E8
463 463
464 464 isConfig = False
465 465
466 466 basicHeaderObj = None
467 467
468 468 systemHeaderObj = None
469 469
470 470 radarControllerHeaderObj = None
471 471
472 472 processingHeaderObj = None
473 473
474 474 dtype = None
475 475
476 476 pathList = []
477 477
478 478 filenameList = []
479 479
480 480 filename = None
481 481
482 482 ext = None
483 483
484 484 flagIsNewFile = 1
485 485
486 486 flagDiscontinuousBlock = 0
487 487
488 488 flagIsNewBlock = 0
489 489
490 490 fp = None
491 491
492 492 firstHeaderSize = 0
493 493
494 494 basicHeaderSize = 24
495 495
496 496 versionFile = 1103
497 497
498 498 fileSize = None
499 499
500 500 # ippSeconds = None
501 501
502 502 fileSizeByHeader = None
503 503
504 504 fileIndex = None
505 505
506 506 profileIndex = None
507 507
508 508 blockIndex = None
509 509
510 510 nTotalBlocks = None
511 511
512 512 maxTimeStep = 30
513 513
514 514 lastUTTime = None
515 515
516 516 datablock = None
517 517
518 518 dataOut = None
519 519
520 520 blocksize = None
521 521
522 522 getByBlock = False
523 523
524 524 def __init__(self):
525 525
526 526 raise NotImplementedError
527 527
528 528 def run(self):
529 529
530 530 raise NotImplementedError
531 531
532 532 def getDtypeWidth(self):
533 533
534 534 dtype_index = get_dtype_index(self.dtype)
535 535 dtype_width = get_dtype_width(dtype_index)
536 536
537 537 return dtype_width
538 538
539 539 def getAllowedArgs(self):
540 540 return inspect.getargspec(self.run).args
541 541
542 542 class JRODataReader(JRODataIO):
543 543
544 544
545 545 online = 0
546 546
547 547 realtime = 0
548 548
549 549 nReadBlocks = 0
550 550
551 551 delay = 10 #number of seconds waiting a new file
552 552
553 553 nTries = 3 #quantity tries
554 554
555 555 nFiles = 3 #number of files for searching
556 556
557 557 path = None
558 558
559 559 foldercounter = 0
560 560
561 561 flagNoMoreFiles = 0
562 562
563 563 datetimeList = []
564 564
565 565 __isFirstTimeOnline = 1
566 566
567 567 __printInfo = True
568 568
569 569 profileIndex = None
570 570
571 571 nTxs = 1
572 572
573 573 txIndex = None
574 574
575 575 #Added--------------------
576 576
577 577 selBlocksize = None
578 578
579 579 selBlocktime = None
580 580
581 581
582 582 def __init__(self):
583 583
584 584 """
585 585 This class is used to find data files
586 586
587 587 Example:
588 588 reader = JRODataReader()
589 589 fileList = reader.findDataFiles()
590 590
591 591 """
592 592 pass
593 593
594 594
595 595 def createObjByDefault(self):
596 596 """
597 597
598 598 """
599 599 raise NotImplementedError
600 600
601 601 def getBlockDimension(self):
602 602
603 603 raise NotImplementedError
604 604
605 605 def __searchFilesOffLine(self,
606 606 path,
607 607 startDate=None,
608 608 endDate=None,
609 609 startTime=datetime.time(0,0,0),
610 610 endTime=datetime.time(23,59,59),
611 611 set=None,
612 612 expLabel='',
613 613 ext='.r',
614 614 queue=None,
615 615 cursor=None,
616 616 skip=None,
617 617 walk=True):
618 618
619 619 self.filenameList = []
620 620 self.datetimeList = []
621 621
622 622 pathList = []
623 623
624 624 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
625 625
626 626 if dateList == []:
627 627 # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
628 628 return None, None
629 629
630 630 if len(dateList) > 1:
631 631 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
632 632 else:
633 633 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
634 634
635 635 filenameList = []
636 636 datetimeList = []
637 637
638 638 for thisPath in pathList:
639 639 # thisPath = pathList[pathDict[file]]
640 640
641 641 fileList = glob.glob1(thisPath, "*%s" %ext)
642 642 fileList.sort()
643 643
644 644 skippedFileList = []
645 645
646 646 if cursor is not None and skip is not None:
647 647 # if cursor*skip > len(fileList):
648 648 if skip == 0:
649 649 if queue is not None:
650 650 queue.put(len(fileList))
651 651 skippedFileList = []
652 652 else:
653 653 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
654 654
655 655 else:
656 656 skippedFileList = fileList
657 657
658 658 for file in skippedFileList:
659 659
660 660 filename = os.path.join(thisPath,file)
661 661
662 662 if not isFileInDateRange(filename, startDate, endDate):
663 663 continue
664 664
665 665 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
666 666
667 667 if not(thisDatetime):
668 668 continue
669 669
670 670 filenameList.append(filename)
671 671 datetimeList.append(thisDatetime)
672 672
673 673 if not(filenameList):
674 674 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
675 675 return None, None
676 676
677 677 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
678 678 print
679 679
680 680 for i in range(len(filenameList)):
681 681 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
682 682
683 683 self.filenameList = filenameList
684 684 self.datetimeList = datetimeList
685 685
686 686 return pathList, filenameList
687 687
688 688 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
689 689
690 690 """
691 691 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
692 692 devuelve el archivo encontrado ademas de otros datos.
693 693
694 694 Input:
695 695 path : carpeta donde estan contenidos los files que contiene data
696 696
697 697 expLabel : Nombre del subexperimento (subfolder)
698 698
699 699 ext : extension de los files
700 700
701 701 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
702 702
703 703 Return:
704 704 directory : eL directorio donde esta el file encontrado
705 705 filename : el ultimo file de una determinada carpeta
706 706 year : el anho
707 707 doy : el numero de dia del anho
708 708 set : el set del archivo
709 709
710 710
711 711 """
712 712 if not os.path.isdir(path):
713 713 return None, None, None, None, None, None
714 714
715 715 dirList = []
716 716
717 717 if not walk:
718 718 fullpath = path
719 719 foldercounter = 0
720 720 else:
721 721 #Filtra solo los directorios
722 722 for thisPath in os.listdir(path):
723 723 if not os.path.isdir(os.path.join(path,thisPath)):
724 724 continue
725 725 if not isRadarFolder(thisPath):
726 726 continue
727 727
728 728 dirList.append(thisPath)
729 729
730 730 if not(dirList):
731 731 return None, None, None, None, None, None
732 732
733 733 dirList = sorted( dirList, key=str.lower )
734 734
735 735 doypath = dirList[-1]
736 736 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
737 737 fullpath = os.path.join(path, doypath, expLabel)
738 738
739 739
740 740 print "[Reading] %s folder was found: " %(fullpath )
741 741
742 742 if set == None:
743 743 filename = getlastFileFromPath(fullpath, ext)
744 744 else:
745 745 filename = getFileFromSet(fullpath, ext, set)
746 746
747 747 if not(filename):
748 748 return None, None, None, None, None, None
749 749
750 750 print "[Reading] %s file was found" %(filename)
751 751
752 752 if not(self.__verifyFile(os.path.join(fullpath, filename))):
753 753 return None, None, None, None, None, None
754 754
755 755 year = int( filename[1:5] )
756 756 doy = int( filename[5:8] )
757 757 set = int( filename[8:11] )
758 758
759 759 return fullpath, foldercounter, filename, year, doy, set
760 760
761 761 def __setNextFileOffline(self):
762 762
763 763 idFile = self.fileIndex
764 764
765 765 while (True):
766 766 idFile += 1
767 767 if not(idFile < len(self.filenameList)):
768 768 self.flagNoMoreFiles = 1
769 769 # print "[Reading] No more Files"
770 770 return 0
771 771
772 772 filename = self.filenameList[idFile]
773 773
774 774 if not(self.__verifyFile(filename)):
775 775 continue
776 776
777 777 fileSize = os.path.getsize(filename)
778 778 fp = open(filename,'rb')
779 779 break
780 780
781 781 self.flagIsNewFile = 1
782 782 self.fileIndex = idFile
783 783 self.filename = filename
784 784 self.fileSize = fileSize
785 785 self.fp = fp
786 786
787 787 # print "[Reading] Setting the file: %s"%self.filename
788 788
789 789 return 1
790 790
791 791 def __setNextFileOnline(self):
792 792 """
793 793 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
794 794 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
795 795 siguientes.
796 796
797 797 Affected:
798 798 self.flagIsNewFile
799 799 self.filename
800 800 self.fileSize
801 801 self.fp
802 802 self.set
803 803 self.flagNoMoreFiles
804 804
805 805 Return:
806 806 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
807 807 1 : si el file fue abierto con exito y esta listo a ser leido
808 808
809 809 Excepciones:
810 810 Si un determinado file no puede ser abierto
811 811 """
812 812 nFiles = 0
813 813 fileOk_flag = False
814 814 firstTime_flag = True
815 815
816 816 self.set += 1
817 817
818 818 if self.set > 999:
819 819 self.set = 0
820 820 self.foldercounter += 1
821 821
822 822 #busca el 1er file disponible
823 823 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
824 824 if fullfilename:
825 825 if self.__verifyFile(fullfilename, False):
826 826 fileOk_flag = True
827 827
828 828 #si no encuentra un file entonces espera y vuelve a buscar
829 829 if not(fileOk_flag):
830 830 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
831 831
832 832 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
833 833 tries = self.nTries
834 834 else:
835 835 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
836 836
837 837 for nTries in range( tries ):
838 838 if firstTime_flag:
839 839 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
840 840 sleep( self.delay )
841 841 else:
842 842 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
843 843
844 844 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
845 845 if fullfilename:
846 846 if self.__verifyFile(fullfilename):
847 847 fileOk_flag = True
848 848 break
849 849
850 850 if fileOk_flag:
851 851 break
852 852
853 853 firstTime_flag = False
854 854
855 855 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
856 856 self.set += 1
857 857
858 858 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
859 859 self.set = 0
860 860 self.doy += 1
861 861 self.foldercounter = 0
862 862
863 863 if fileOk_flag:
864 864 self.fileSize = os.path.getsize( fullfilename )
865 865 self.filename = fullfilename
866 866 self.flagIsNewFile = 1
867 867 if self.fp != None: self.fp.close()
868 868 self.fp = open(fullfilename, 'rb')
869 869 self.flagNoMoreFiles = 0
870 870 # print '[Reading] Setting the file: %s' % fullfilename
871 871 else:
872 872 self.fileSize = 0
873 873 self.filename = None
874 874 self.flagIsNewFile = 0
875 875 self.fp = None
876 876 self.flagNoMoreFiles = 1
877 877 # print '[Reading] No more files to read'
878 878
879 879 return fileOk_flag
880 880
881 881 def setNextFile(self):
882 882 if self.fp != None:
883 883 self.fp.close()
884 884
885 885 if self.online:
886 886 newFile = self.__setNextFileOnline()
887 887 else:
888 888 newFile = self.__setNextFileOffline()
889 889
890 890 if not(newFile):
891 891 print '[Reading] No more files to read'
892 892 return 0
893 893
894 894 if self.verbose:
895 895 print '[Reading] Setting the file: %s' % self.filename
896 896
897 897 self.__readFirstHeader()
898 898 self.nReadBlocks = 0
899 899 return 1
900 900
901 901 def __waitNewBlock(self):
902 902 """
903 903 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
904 904
905 905 Si el modo de lectura es OffLine siempre retorn 0
906 906 """
907 907 if not self.online:
908 908 return 0
909 909
910 910 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
911 911 return 0
912 912
913 913 currentPointer = self.fp.tell()
914 914
915 915 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
916 916
917 917 for nTries in range( self.nTries ):
918 918
919 919 self.fp.close()
920 920 self.fp = open( self.filename, 'rb' )
921 921 self.fp.seek( currentPointer )
922 922
923 923 self.fileSize = os.path.getsize( self.filename )
924 924 currentSize = self.fileSize - currentPointer
925 925
926 926 if ( currentSize >= neededSize ):
927 927 self.basicHeaderObj.read(self.fp)
928 928 return 1
929 929
930 930 if self.fileSize == self.fileSizeByHeader:
931 931 # self.flagEoF = True
932 932 return 0
933 933
934 934 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
935 935 sleep( self.delay )
936 936
937 937
938 938 return 0
939 939
940 940 def waitDataBlock(self,pointer_location):
941 941
942 942 currentPointer = pointer_location
943 943
944 944 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
945 945
946 946 for nTries in range( self.nTries ):
947 947 self.fp.close()
948 948 self.fp = open( self.filename, 'rb' )
949 949 self.fp.seek( currentPointer )
950 950
951 951 self.fileSize = os.path.getsize( self.filename )
952 952 currentSize = self.fileSize - currentPointer
953 953
954 954 if ( currentSize >= neededSize ):
955 955 return 1
956 956
957 957 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
958 958 sleep( self.delay )
959 959
960 960 return 0
961 961
962 962 def __jumpToLastBlock(self):
963 963
964 964 if not(self.__isFirstTimeOnline):
965 965 return
966 966
967 967 csize = self.fileSize - self.fp.tell()
968 968 blocksize = self.processingHeaderObj.blockSize
969 969
970 970 #salta el primer bloque de datos
971 971 if csize > self.processingHeaderObj.blockSize:
972 972 self.fp.seek(self.fp.tell() + blocksize)
973 973 else:
974 974 return
975 975
976 976 csize = self.fileSize - self.fp.tell()
977 977 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
978 978 while True:
979 979
980 980 if self.fp.tell()<self.fileSize:
981 981 self.fp.seek(self.fp.tell() + neededsize)
982 982 else:
983 983 self.fp.seek(self.fp.tell() - neededsize)
984 984 break
985 985
986 986 # csize = self.fileSize - self.fp.tell()
987 987 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
988 988 # factor = int(csize/neededsize)
989 989 # if factor > 0:
990 990 # self.fp.seek(self.fp.tell() + factor*neededsize)
991 991
992 992 self.flagIsNewFile = 0
993 993 self.__isFirstTimeOnline = 0
994 994
995 995 def __setNewBlock(self):
996 996
997 997 if self.fp == None:
998 998 return 0
999 999
1000 1000 # if self.online:
1001 1001 # self.__jumpToLastBlock()
1002 1002
1003 1003 if self.flagIsNewFile:
1004 1004 self.lastUTTime = self.basicHeaderObj.utc
1005 1005 return 1
1006 1006
1007 1007 if self.realtime:
1008 1008 self.flagDiscontinuousBlock = 1
1009 1009 if not(self.setNextFile()):
1010 1010 return 0
1011 1011 else:
1012 1012 return 1
1013 1013
1014 1014 currentSize = self.fileSize - self.fp.tell()
1015 1015 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1016 1016
1017 1017 if (currentSize >= neededSize):
1018 1018 self.basicHeaderObj.read(self.fp)
1019 1019 self.lastUTTime = self.basicHeaderObj.utc
1020 1020 return 1
1021 1021
1022 1022 if self.__waitNewBlock():
1023 1023 self.lastUTTime = self.basicHeaderObj.utc
1024 1024 return 1
1025 1025
1026 1026 if not(self.setNextFile()):
1027 1027 return 0
1028 1028
1029 1029 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1030 1030 self.lastUTTime = self.basicHeaderObj.utc
1031 1031
1032 1032 self.flagDiscontinuousBlock = 0
1033 1033
1034 1034 if deltaTime > self.maxTimeStep:
1035 1035 self.flagDiscontinuousBlock = 1
1036 1036
1037 1037 return 1
1038 1038
1039 1039 def readNextBlock(self):
1040 1040
1041 1041 #Skip block out of startTime and endTime
1042 1042 while True:
1043 1043 if not(self.__setNewBlock()):
1044 1044 return 0
1045 1045
1046 1046 if not(self.readBlock()):
1047 1047 return 0
1048 1048
1049 1049 self.getBasicHeader()
1050 1050
1051 1051 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1052 1052
1053 1053 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1054 1054 self.processingHeaderObj.dataBlocksPerFile,
1055 1055 self.dataOut.datatime.ctime())
1056 1056 continue
1057 1057
1058 1058 break
1059 1059
1060 1060 if self.verbose:
1061 1061 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1062 1062 self.processingHeaderObj.dataBlocksPerFile,
1063 1063 self.dataOut.datatime.ctime())
1064 1064 return 1
1065 1065
1066 1066 def __readFirstHeader(self):
1067 1067
1068 1068 self.basicHeaderObj.read(self.fp)
1069 1069 self.systemHeaderObj.read(self.fp)
1070 1070 self.radarControllerHeaderObj.read(self.fp)
1071 1071 self.processingHeaderObj.read(self.fp)
1072 1072
1073 1073 self.firstHeaderSize = self.basicHeaderObj.size
1074 1074
1075 1075 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1076 1076 if datatype == 0:
1077 1077 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1078 1078 elif datatype == 1:
1079 1079 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1080 1080 elif datatype == 2:
1081 1081 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1082 1082 elif datatype == 3:
1083 1083 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1084 1084 elif datatype == 4:
1085 1085 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1086 1086 elif datatype == 5:
1087 1087 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1088 1088 else:
1089 1089 raise ValueError, 'Data type was not defined'
1090 1090
1091 1091 self.dtype = datatype_str
1092 1092 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1093 1093 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1094 1094 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1095 1095 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1096 1096 self.getBlockDimension()
1097 1097
1098 1098 def __verifyFile(self, filename, msgFlag=True):
1099 1099
1100 1100 msg = None
1101 1101
1102 1102 try:
1103 1103 fp = open(filename, 'rb')
1104 1104 except IOError:
1105 1105
1106 1106 if msgFlag:
1107 1107 print "[Reading] File %s can't be opened" % (filename)
1108 1108
1109 1109 return False
1110 1110
1111 1111 currentPosition = fp.tell()
1112 1112 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1113 1113
1114 1114 if neededSize == 0:
1115 1115 basicHeaderObj = BasicHeader(LOCALTIME)
1116 1116 systemHeaderObj = SystemHeader()
1117 1117 radarControllerHeaderObj = RadarControllerHeader()
1118 1118 processingHeaderObj = ProcessingHeader()
1119 1119
1120 1120 if not( basicHeaderObj.read(fp) ):
1121 1121 fp.close()
1122 1122 return False
1123 1123
1124 1124 if not( systemHeaderObj.read(fp) ):
1125 1125 fp.close()
1126 1126 return False
1127 1127
1128 1128 if not( radarControllerHeaderObj.read(fp) ):
1129 1129 fp.close()
1130 1130 return False
1131 1131
1132 1132 if not( processingHeaderObj.read(fp) ):
1133 1133 fp.close()
1134 1134 return False
1135 1135
1136 1136 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1137 1137 else:
1138 1138 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1139 1139
1140 1140 fp.close()
1141 1141
1142 1142 fileSize = os.path.getsize(filename)
1143 1143 currentSize = fileSize - currentPosition
1144 1144
1145 1145 if currentSize < neededSize:
1146 1146 if msgFlag and (msg != None):
1147 1147 print msg
1148 1148 return False
1149 1149
1150 1150 return True
1151 1151
1152 1152 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1153 1153
1154 1154 path_empty = True
1155 1155
1156 1156 dateList = []
1157 1157 pathList = []
1158 1158
1159 1159 multi_path = path.split(',')
1160 1160
1161 1161 if not walk:
1162 1162
1163 1163 for single_path in multi_path:
1164 1164
1165 1165 if not os.path.isdir(single_path):
1166 1166 continue
1167 1167
1168 1168 fileList = glob.glob1(single_path, "*"+ext)
1169 1169
1170 1170 if not fileList:
1171 1171 continue
1172 1172
1173 1173 path_empty = False
1174 1174
1175 1175 fileList.sort()
1176 1176
1177 1177 for thisFile in fileList:
1178 1178
1179 1179 if not os.path.isfile(os.path.join(single_path, thisFile)):
1180 1180 continue
1181 1181
1182 1182 if not isRadarFile(thisFile):
1183 1183 continue
1184 1184
1185 1185 if not isFileInDateRange(thisFile, startDate, endDate):
1186 1186 continue
1187 1187
1188 1188 thisDate = getDateFromRadarFile(thisFile)
1189 1189
1190 1190 if thisDate in dateList:
1191 1191 continue
1192 1192
1193 1193 dateList.append(thisDate)
1194 1194 pathList.append(single_path)
1195 1195
1196 1196 else:
1197 1197 for single_path in multi_path:
1198 1198
1199 1199 if not os.path.isdir(single_path):
1200 1200 continue
1201 1201
1202 1202 dirList = []
1203 1203
1204 1204 for thisPath in os.listdir(single_path):
1205 1205
1206 1206 if not os.path.isdir(os.path.join(single_path,thisPath)):
1207 1207 continue
1208 1208
1209 1209 if not isRadarFolder(thisPath):
1210 1210 continue
1211 1211
1212 1212 if not isFolderInDateRange(thisPath, startDate, endDate):
1213 1213 continue
1214 1214
1215 1215 dirList.append(thisPath)
1216 1216
1217 1217 if not dirList:
1218 1218 continue
1219 1219
1220 1220 dirList.sort()
1221 1221
1222 1222 for thisDir in dirList:
1223 1223
1224 1224 datapath = os.path.join(single_path, thisDir, expLabel)
1225 1225 fileList = glob.glob1(datapath, "*"+ext)
1226 1226
1227 1227 if not fileList:
1228 1228 continue
1229 1229
1230 1230 path_empty = False
1231 1231
1232 1232 thisDate = getDateFromRadarFolder(thisDir)
1233 1233
1234 1234 pathList.append(datapath)
1235 1235 dateList.append(thisDate)
1236 1236
1237 1237 dateList.sort()
1238 1238
1239 1239 if walk:
1240 1240 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1241 1241 else:
1242 1242 pattern_path = multi_path[0]
1243 1243
1244 1244 if path_empty:
1245 1245 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1246 1246 else:
1247 1247 if not dateList:
1248 1248 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1249 1249
1250 1250 if include_path:
1251 1251 return dateList, pathList
1252 1252
1253 1253 return dateList
1254 1254
1255 1255 def setup(self,
1256 1256 path=None,
1257 1257 startDate=None,
1258 1258 endDate=None,
1259 1259 startTime=datetime.time(0,0,0),
1260 1260 endTime=datetime.time(23,59,59),
1261 1261 set=None,
1262 1262 expLabel = "",
1263 1263 ext = None,
1264 1264 online = False,
1265 1265 delay = 60,
1266 1266 walk = True,
1267 1267 getblock = False,
1268 1268 nTxs = 1,
1269 1269 realtime=False,
1270 1270 blocksize=None,
1271 1271 blocktime=None,
1272 1272 queue=None,
1273 1273 skip=None,
1274 1274 cursor=None,
1275 1275 warnings=True,
1276 1276 verbose=True):
1277 1277
1278 1278 if path == None:
1279 1279 raise ValueError, "[Reading] The path is not valid"
1280 1280
1281 1281 if ext == None:
1282 1282 ext = self.ext
1283 1283
1284 1284 if online:
1285 1285 print "[Reading] Searching files in online mode..."
1286 1286
1287 1287 for nTries in range( self.nTries ):
1288 1288 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1289 1289
1290 1290 if fullpath:
1291 1291 break
1292 1292
1293 1293 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1294 1294 sleep( self.delay )
1295 1295
1296 1296 if not(fullpath):
1297 1297 print "[Reading] There 'isn't any valid file in %s" % path
1298 1298 return
1299 1299
1300 1300 self.year = year
1301 1301 self.doy = doy
1302 1302 self.set = set - 1
1303 1303 self.path = path
1304 1304 self.foldercounter = foldercounter
1305 1305 last_set = None
1306 1306
1307 1307 else:
1308 1308 print "[Reading] Searching files in offline mode ..."
1309 1309 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1310 1310 startTime=startTime, endTime=endTime,
1311 1311 set=set, expLabel=expLabel, ext=ext,
1312 1312 walk=walk, cursor=cursor,
1313 1313 skip=skip, queue=queue)
1314 1314
1315 1315 if not(pathList):
1316 1316 # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path,
1317 1317 # datetime.datetime.combine(startDate,startTime).ctime(),
1318 1318 # datetime.datetime.combine(endDate,endTime).ctime())
1319 1319
1320 1320 # sys.exit(-1)
1321 1321
1322 1322 self.fileIndex = -1
1323 1323 self.pathList = []
1324 1324 self.filenameList = []
1325 1325 return
1326 1326
1327 1327 self.fileIndex = -1
1328 1328 self.pathList = pathList
1329 1329 self.filenameList = filenameList
1330 1330 file_name = os.path.basename(filenameList[-1])
1331 1331 basename, ext = os.path.splitext(file_name)
1332 1332 last_set = int(basename[-3:])
1333 1333
1334 1334 self.online = online
1335 1335 self.realtime = realtime
1336 1336 self.delay = delay
1337 1337 ext = ext.lower()
1338 1338 self.ext = ext
1339 1339 self.getByBlock = getblock
1340 1340 self.nTxs = nTxs
1341 1341 self.startTime = startTime
1342 1342 self.endTime = endTime
1343 1343
1344 1344 #Added-----------------
1345 1345 self.selBlocksize = blocksize
1346 1346 self.selBlocktime = blocktime
1347 1347
1348 1348 # Verbose-----------
1349 1349 self.verbose = verbose
1350 1350 self.warnings = warnings
1351 1351
1352 1352 if not(self.setNextFile()):
1353 1353 if (startDate!=None) and (endDate!=None):
1354 1354 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1355 1355 elif startDate != None:
1356 1356 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1357 1357 else:
1358 1358 print "[Reading] No files"
1359 1359
1360 1360 self.fileIndex = -1
1361 1361 self.pathList = []
1362 1362 self.filenameList = []
1363 1363 return
1364 1364
1365 1365 # self.getBasicHeader()
1366 1366
1367 1367 if last_set != None:
1368 1368 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1369 1369 return
1370 1370
1371 1371 def getBasicHeader(self):
1372 1372
1373 1373 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1374 1374
1375 1375 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1376 1376
1377 1377 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1378 1378
1379 1379 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1380 1380
1381 1381 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1382 1382
1383 1383 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1384 1384
1385 1385 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1386 1386
1387 1387 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1388 1388
1389 1389
1390 1390 def getFirstHeader(self):
1391 1391
1392 1392 raise NotImplementedError
1393 1393
1394 1394 def getData(self):
1395 1395
1396 1396 raise NotImplementedError
1397 1397
1398 1398 def hasNotDataInBuffer(self):
1399 1399
1400 1400 raise NotImplementedError
1401 1401
1402 1402 def readBlock(self):
1403 1403
1404 1404 raise NotImplementedError
1405 1405
1406 1406 def isEndProcess(self):
1407 1407
1408 1408 return self.flagNoMoreFiles
1409 1409
1410 1410 def printReadBlocks(self):
1411 1411
1412 1412 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1413 1413
1414 1414 def printTotalBlocks(self):
1415 1415
1416 1416 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1417 1417
1418 1418 def printNumberOfBlock(self):
1419 1419 'SPAM!'
1420 1420
1421 1421 # if self.flagIsNewBlock:
1422 1422 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1423 1423 # self.processingHeaderObj.dataBlocksPerFile,
1424 1424 # self.dataOut.datatime.ctime())
1425 1425
1426 1426 def printInfo(self):
1427 1427
1428 1428 if self.__printInfo == False:
1429 1429 return
1430 1430
1431 1431 self.basicHeaderObj.printInfo()
1432 1432 self.systemHeaderObj.printInfo()
1433 1433 self.radarControllerHeaderObj.printInfo()
1434 1434 self.processingHeaderObj.printInfo()
1435 1435
1436 1436 self.__printInfo = False
1437 1437
1438 1438
1439 1439 def run(self,
1440 1440 path=None,
1441 1441 startDate=None,
1442 1442 endDate=None,
1443 1443 startTime=datetime.time(0,0,0),
1444 1444 endTime=datetime.time(23,59,59),
1445 1445 set=None,
1446 1446 expLabel = "",
1447 1447 ext = None,
1448 1448 online = False,
1449 1449 delay = 60,
1450 1450 walk = True,
1451 1451 getblock = False,
1452 1452 nTxs = 1,
1453 1453 realtime=False,
1454 1454 blocksize=None,
1455 1455 blocktime=None,
1456 1456 queue=None,
1457 1457 skip=None,
1458 1458 cursor=None,
1459 1459 warnings=True,
1460 1460 verbose=True, **kwargs):
1461 1461
1462 1462 if not(self.isConfig):
1463 1463 # self.dataOut = dataOut
1464 1464 self.setup( path=path,
1465 1465 startDate=startDate,
1466 1466 endDate=endDate,
1467 1467 startTime=startTime,
1468 1468 endTime=endTime,
1469 1469 set=set,
1470 1470 expLabel=expLabel,
1471 1471 ext=ext,
1472 1472 online=online,
1473 1473 delay=delay,
1474 1474 walk=walk,
1475 1475 getblock=getblock,
1476 1476 nTxs=nTxs,
1477 1477 realtime=realtime,
1478 1478 blocksize=blocksize,
1479 1479 blocktime=blocktime,
1480 1480 queue=queue,
1481 1481 skip=skip,
1482 1482 cursor=cursor,
1483 1483 warnings=warnings,
1484 1484 verbose=verbose)
1485 1485 self.isConfig = True
1486 1486
1487 1487 self.getData()
1488 1488
1489 1489 class JRODataWriter(JRODataIO):
1490 1490
1491 1491 """
1492 1492 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1493 1493 de los datos siempre se realiza por bloques.
1494 1494 """
1495 1495
1496 1496 blockIndex = 0
1497 1497
1498 1498 path = None
1499 1499
1500 1500 setFile = None
1501 1501
1502 1502 profilesPerBlock = None
1503 1503
1504 1504 blocksPerFile = None
1505 1505
1506 1506 nWriteBlocks = 0
1507 1507
1508 1508 fileDate = None
1509 1509
1510 1510 def __init__(self, dataOut=None):
1511 1511 raise NotImplementedError
1512 1512
1513 1513
1514 1514 def hasAllDataInBuffer(self):
1515 1515 raise NotImplementedError
1516 1516
1517 1517
1518 1518 def setBlockDimension(self):
1519 1519 raise NotImplementedError
1520 1520
1521 1521
1522 1522 def writeBlock(self):
1523 1523 raise NotImplementedError
1524 1524
1525 1525
1526 1526 def putData(self):
1527 1527 raise NotImplementedError
1528 1528
1529 1529
1530 1530 def getProcessFlags(self):
1531 1531
1532 1532 processFlags = 0
1533 1533
1534 1534 dtype_index = get_dtype_index(self.dtype)
1535 1535 procflag_dtype = get_procflag_dtype(dtype_index)
1536 1536
1537 1537 processFlags += procflag_dtype
1538 1538
1539 1539 if self.dataOut.flagDecodeData:
1540 1540 processFlags += PROCFLAG.DECODE_DATA
1541 1541
1542 1542 if self.dataOut.flagDeflipData:
1543 1543 processFlags += PROCFLAG.DEFLIP_DATA
1544 1544
1545 1545 if self.dataOut.code is not None:
1546 1546 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1547 1547
1548 1548 if self.dataOut.nCohInt > 1:
1549 1549 processFlags += PROCFLAG.COHERENT_INTEGRATION
1550 1550
1551 1551 if self.dataOut.type == "Spectra":
1552 1552 if self.dataOut.nIncohInt > 1:
1553 1553 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1554 1554
1555 1555 if self.dataOut.data_dc is not None:
1556 1556 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1557 1557
1558 1558 if self.dataOut.flagShiftFFT:
1559 1559 processFlags += PROCFLAG.SHIFT_FFT_DATA
1560 1560
1561 1561 return processFlags
1562 1562
1563 1563 def setBasicHeader(self):
1564 1564
1565 1565 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1566 1566 self.basicHeaderObj.version = self.versionFile
1567 1567 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1568 1568
1569 1569 utc = numpy.floor(self.dataOut.utctime)
1570 1570 milisecond = (self.dataOut.utctime - utc)* 1000.0
1571 1571
1572 1572 self.basicHeaderObj.utc = utc
1573 1573 self.basicHeaderObj.miliSecond = milisecond
1574 1574 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1575 1575 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1576 1576 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1577 1577
1578 1578 def setFirstHeader(self):
1579 1579 """
1580 1580 Obtiene una copia del First Header
1581 1581
1582 1582 Affected:
1583 1583
1584 1584 self.basicHeaderObj
1585 1585 self.systemHeaderObj
1586 1586 self.radarControllerHeaderObj
1587 1587 self.processingHeaderObj self.
1588 1588
1589 1589 Return:
1590 1590 None
1591 1591 """
1592 1592
1593 1593 raise NotImplementedError
1594 1594
1595 1595 def __writeFirstHeader(self):
1596 1596 """
1597 1597 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1598 1598
1599 1599 Affected:
1600 1600 __dataType
1601 1601
1602 1602 Return:
1603 1603 None
1604 1604 """
1605 1605
1606 1606 # CALCULAR PARAMETROS
1607 1607
1608 1608 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1609 1609 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1610 1610
1611 1611 self.basicHeaderObj.write(self.fp)
1612 1612 self.systemHeaderObj.write(self.fp)
1613 1613 self.radarControllerHeaderObj.write(self.fp)
1614 1614 self.processingHeaderObj.write(self.fp)
1615 1615
1616 1616 def __setNewBlock(self):
1617 1617 """
1618 1618 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1619 1619
1620 1620 Return:
1621 1621 0 : si no pudo escribir nada
1622 1622 1 : Si escribio el Basic el First Header
1623 1623 """
1624 1624 if self.fp == None:
1625 1625 self.setNextFile()
1626 1626
1627 1627 if self.flagIsNewFile:
1628 1628 return 1
1629 1629
1630 1630 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1631 1631 self.basicHeaderObj.write(self.fp)
1632 1632 return 1
1633 1633
1634 1634 if not( self.setNextFile() ):
1635 1635 return 0
1636 1636
1637 1637 return 1
1638 1638
1639 1639
1640 1640 def writeNextBlock(self):
1641 1641 """
1642 1642 Selecciona el bloque siguiente de datos y los escribe en un file
1643 1643
1644 1644 Return:
1645 1645 0 : Si no hizo pudo escribir el bloque de datos
1646 1646 1 : Si no pudo escribir el bloque de datos
1647 1647 """
1648 1648 if not( self.__setNewBlock() ):
1649 1649 return 0
1650 1650
1651 1651 self.writeBlock()
1652 1652
1653 1653 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1654 1654 self.processingHeaderObj.dataBlocksPerFile)
1655 1655
1656 1656 return 1
1657 1657
1658 1658 def setNextFile(self):
1659 1659 """
1660 1660 Determina el siguiente file que sera escrito
1661 1661
1662 1662 Affected:
1663 1663 self.filename
1664 1664 self.subfolder
1665 1665 self.fp
1666 1666 self.setFile
1667 1667 self.flagIsNewFile
1668 1668
1669 1669 Return:
1670 1670 0 : Si el archivo no puede ser escrito
1671 1671 1 : Si el archivo esta listo para ser escrito
1672 1672 """
1673 1673 ext = self.ext
1674 1674 path = self.path
1675 1675
1676 1676 if self.fp != None:
1677 1677 self.fp.close()
1678 1678
1679 1679 timeTuple = time.localtime( self.dataOut.utctime)
1680 1680 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1681 1681
1682 1682 fullpath = os.path.join( path, subfolder )
1683 1683 setFile = self.setFile
1684 1684
1685 1685 if not( os.path.exists(fullpath) ):
1686 1686 os.mkdir(fullpath)
1687 1687 setFile = -1 #inicializo mi contador de seteo
1688 1688 else:
1689 1689 filesList = os.listdir( fullpath )
1690 1690 if len( filesList ) > 0:
1691 1691 filesList = sorted( filesList, key=str.lower )
1692 1692 filen = filesList[-1]
1693 1693 # el filename debera tener el siguiente formato
1694 1694 # 0 1234 567 89A BCDE (hex)
1695 1695 # x YYYY DDD SSS .ext
1696 1696 if isNumber( filen[8:11] ):
1697 1697 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1698 1698 else:
1699 1699 setFile = -1
1700 1700 else:
1701 1701 setFile = -1 #inicializo mi contador de seteo
1702 1702
1703 1703 setFile += 1
1704 1704
1705 1705 #If this is a new day it resets some values
1706 1706 if self.dataOut.datatime.date() > self.fileDate:
1707 1707 setFile = 0
1708 1708 self.nTotalBlocks = 0
1709 1709
1710 1710 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1711 1711
1712 1712 filename = os.path.join( path, subfolder, filen )
1713 1713
1714 1714 fp = open( filename,'wb' )
1715 1715
1716 1716 self.blockIndex = 0
1717 1717
1718 1718 #guardando atributos
1719 1719 self.filename = filename
1720 1720 self.subfolder = subfolder
1721 1721 self.fp = fp
1722 1722 self.setFile = setFile
1723 1723 self.flagIsNewFile = 1
1724 1724 self.fileDate = self.dataOut.datatime.date()
1725 1725
1726 1726 self.setFirstHeader()
1727 1727
1728 1728 print '[Writing] Opening file: %s'%self.filename
1729 1729
1730 1730 self.__writeFirstHeader()
1731 1731
1732 1732 return 1
1733 1733
1734 1734 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1735 1735 """
1736 1736 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1737 1737
1738 1738 Inputs:
1739 1739 path : directory where data will be saved
1740 1740 profilesPerBlock : number of profiles per block
1741 1741 set : initial file set
1742 1742 datatype : An integer number that defines data type:
1743 1743 0 : int8 (1 byte)
1744 1744 1 : int16 (2 bytes)
1745 1745 2 : int32 (4 bytes)
1746 1746 3 : int64 (8 bytes)
1747 1747 4 : float32 (4 bytes)
1748 1748 5 : double64 (8 bytes)
1749 1749
1750 1750 Return:
1751 1751 0 : Si no realizo un buen seteo
1752 1752 1 : Si realizo un buen seteo
1753 1753 """
1754 1754
1755 1755 if ext == None:
1756 1756 ext = self.ext
1757 1757
1758 1758 self.ext = ext.lower()
1759 1759
1760 1760 self.path = path
1761 1761
1762 1762 if set is None:
1763 1763 self.setFile = -1
1764 1764 else:
1765 1765 self.setFile = set - 1
1766 1766
1767 1767 self.blocksPerFile = blocksPerFile
1768 1768
1769 1769 self.profilesPerBlock = profilesPerBlock
1770 1770
1771 1771 self.dataOut = dataOut
1772 1772 self.fileDate = self.dataOut.datatime.date()
1773 1773 #By default
1774 1774 self.dtype = self.dataOut.dtype
1775 1775
1776 1776 if datatype is not None:
1777 1777 self.dtype = get_numpy_dtype(datatype)
1778 1778
1779 1779 if not(self.setNextFile()):
1780 1780 print "[Writing] There isn't a next file"
1781 1781 return 0
1782 1782
1783 1783 self.setBlockDimension()
1784 1784
1785 1785 return 1
1786 1786
1787 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1787 def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1788 1788
1789 1789 if not(self.isConfig):
1790 1790
1791 1791 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs)
1792 1792 self.isConfig = True
1793 1793
1794 1794 self.putData()
@@ -1,707 +1,711
1 1 '''
2 2 Created on Jul 2, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import numpy
7 7
8 8 from jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
10 10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 11 from schainpy.model.data.jrodata import Spectra
12 12
13 13 class SpectraReader(JRODataReader, ProcessingUnit):
14 14
15 15 """
16 16 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
17 17 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
18 18 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
19 19
20 20 paresCanalesIguales * alturas * perfiles (Self Spectra)
21 21 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
22 22 canales * alturas (DC Channels)
23 23
24 24
25 25 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
26 26 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
27 27 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
28 28 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
29 29
30 30 Example:
31 31 dpath = "/home/myuser/data"
32 32
33 33 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
34 34
35 35 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
36 36
37 37 readerObj = SpectraReader()
38 38
39 39 readerObj.setup(dpath, startTime, endTime)
40 40
41 41 while(True):
42 42
43 43 readerObj.getData()
44 44
45 45 print readerObj.data_spc
46 46
47 47 print readerObj.data_cspc
48 48
49 49 print readerObj.data_dc
50 50
51 51 if readerObj.flagNoMoreFiles:
52 52 break
53 53
54 54 """
55 55
56 56 pts2read_SelfSpectra = 0
57 57
58 58 pts2read_CrossSpectra = 0
59 59
60 60 pts2read_DCchannels = 0
61 61
62 62 ext = ".pdata"
63 63
64 64 optchar = "P"
65 65
66 66 dataOut = None
67 67
68 68 nRdChannels = None
69 69
70 70 nRdPairs = None
71 71
72 72 rdPairList = []
73 73
74 74 def __init__(self, **kwargs):
75 75 """
76 76 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
77 77
78 78 Inputs:
79 79
80 80 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
81 81 almacenar un perfil de datos cada vez que se haga un requerimiento
82 82 (getData). El perfil sera obtenido a partir del buffer de datos,
83 83 si el buffer esta vacio se hara un nuevo proceso de lectura de un
84 84 bloque de datos.
85 85 Si este parametro no es pasado se creara uno internamente.
86 86
87 87
88 88 Affected:
89 89
90 90 self.dataOut
91 91
92 92 Return : None
93 93 """
94 94
95 95
96 96 #Eliminar de la base la herencia
97 97 ProcessingUnit.__init__(self, **kwargs)
98 98
99 99 # self.isConfig = False
100 100
101 101 self.pts2read_SelfSpectra = 0
102 102
103 103 self.pts2read_CrossSpectra = 0
104 104
105 105 self.pts2read_DCchannels = 0
106 106
107 107 self.datablock = None
108 108
109 109 self.utc = None
110 110
111 111 self.ext = ".pdata"
112 112
113 113 self.optchar = "P"
114 114
115 115 self.basicHeaderObj = BasicHeader(LOCALTIME)
116 116
117 117 self.systemHeaderObj = SystemHeader()
118 118
119 119 self.radarControllerHeaderObj = RadarControllerHeader()
120 120
121 121 self.processingHeaderObj = ProcessingHeader()
122 122
123 123 self.online = 0
124 124
125 125 self.fp = None
126 126
127 127 self.idFile = None
128 128
129 129 self.dtype = None
130 130
131 131 self.fileSizeByHeader = None
132 132
133 133 self.filenameList = []
134 134
135 135 self.filename = None
136 136
137 137 self.fileSize = None
138 138
139 139 self.firstHeaderSize = 0
140 140
141 141 self.basicHeaderSize = 24
142 142
143 143 self.pathList = []
144 144
145 145 self.lastUTTime = 0
146 146
147 147 self.maxTimeStep = 30
148 148
149 149 self.flagNoMoreFiles = 0
150 150
151 151 self.set = 0
152 152
153 153 self.path = None
154 154
155 155 self.delay = 60 #seconds
156 156
157 157 self.nTries = 3 #quantity tries
158 158
159 159 self.nFiles = 3 #number of files for searching
160 160
161 161 self.nReadBlocks = 0
162 162
163 163 self.flagIsNewFile = 1
164 164
165 165 self.__isFirstTimeOnline = 1
166 166
167 167 # self.ippSeconds = 0
168 168
169 169 self.flagDiscontinuousBlock = 0
170 170
171 171 self.flagIsNewBlock = 0
172 172
173 173 self.nTotalBlocks = 0
174 174
175 175 self.blocksize = 0
176 176
177 177 self.dataOut = self.createObjByDefault()
178 178
179 179 self.profileIndex = 1 #Always
180 180
181 181
182 182 def createObjByDefault(self):
183 183
184 184 dataObj = Spectra()
185 185
186 186 return dataObj
187 187
188 188 def __hasNotDataInBuffer(self):
189 189 return 1
190 190
191 191
192 192 def getBlockDimension(self):
193 193 """
194 194 Obtiene la cantidad de puntos a leer por cada bloque de datos
195 195
196 196 Affected:
197 197 self.nRdChannels
198 198 self.nRdPairs
199 199 self.pts2read_SelfSpectra
200 200 self.pts2read_CrossSpectra
201 201 self.pts2read_DCchannels
202 202 self.blocksize
203 203 self.dataOut.nChannels
204 204 self.dataOut.nPairs
205 205
206 206 Return:
207 207 None
208 208 """
209 209 self.nRdChannels = 0
210 210 self.nRdPairs = 0
211 211 self.rdPairList = []
212 212
213 213 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
214 214 if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]:
215 215 self.nRdChannels = self.nRdChannels + 1 #par de canales iguales
216 216
217 217 else:
218 218 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
219 219 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
220 220
221 221 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
222 222
223 223 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
224 224 self.blocksize = self.pts2read_SelfSpectra
225 225
226 226 if self.processingHeaderObj.flag_cspc:
227 227 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
228 228 self.blocksize += self.pts2read_CrossSpectra
229 229
230 230 if self.processingHeaderObj.flag_dc:
231 231 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
232 232 self.blocksize += self.pts2read_DCchannels
233 233
234 234 # self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels
235 235
236 236
237 237 def readBlock(self):
238 238 """
239 239 Lee el bloque de datos desde la posicion actual del puntero del archivo
240 240 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
241 241 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
242 242 es seteado a 0
243 243
244 244 Return: None
245 245
246 246 Variables afectadas:
247 247
248 248
249 249 self.flagIsNewFile
250 250 self.flagIsNewBlock
251 251 self.nTotalBlocks
252 252 self.data_spc
253 253 self.data_cspc
254 254 self.data_dc
255 255
256 256 Exceptions:
257 257 Si un bloque leido no es un bloque valido
258 258 """
259 259 print ' ======================================================== '
260 260 print ' '
261 261 print ' '
262 262 print self.processingHeaderObj.totalSpectra, 'TotalSpectra', type(self.processingHeaderObj.totalSpectra)
263 263 print self.processingHeaderObj.spectraComb, 'SpectraComb', type(self.processingHeaderObj.spectraComb)
264 264 print ' '
265 265 print ' '
266 266 print ' ======================================================== '
267 267
268 268
269 269 blockOk_flag = False
270 270 fpointer = self.fp.tell()
271 271
272 272 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
273 273 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
274 274
275 275 if self.processingHeaderObj.flag_cspc:
276 276 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
277 277 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
278 278
279 279 if self.processingHeaderObj.flag_dc:
280 280 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
281 281 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
282 282
283 283
284 284 if not(self.processingHeaderObj.shif_fft):
285 285 #desplaza a la derecha en el eje 2 determinadas posiciones
286 286 shift = int(self.processingHeaderObj.profilesPerBlock/2)
287 287 spc = numpy.roll( spc, shift , axis=2 )
288 288
289 289 if self.processingHeaderObj.flag_cspc:
290 290 #desplaza a la derecha en el eje 2 determinadas posiciones
291 291 cspc = numpy.roll( cspc, shift, axis=2 )
292 292
293 293 #Dimensions : nChannels, nProfiles, nSamples
294 294 spc = numpy.transpose( spc, (0,2,1) )
295 295 self.data_spc = spc
296 296
297 297 if self.processingHeaderObj.flag_cspc:
298 298
299 299 cspc = numpy.transpose( cspc, (0,2,1) )
300 300 self.data_cspc = cspc['real'] + cspc['imag']*1j
301 301 else:
302 302 self.data_cspc = None
303 print 'SALE NONE ***********************************************************'
303 304
304 305
305 306 if self.processingHeaderObj.flag_dc:
306 307 self.data_dc = dc['real'] + dc['imag']*1j
307 308 else:
308 309 self.data_dc = None
309 310
310 311 self.flagIsNewFile = 0
311 312 self.flagIsNewBlock = 1
312 313
313 314 self.nTotalBlocks += 1
314 315 self.nReadBlocks += 1
315 316
316 317 return 1
317 318
318 319 def getFirstHeader(self):
319 320
320 321 self.getBasicHeader()
321 322
322 323 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
323 324
324 325 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
325 326
326 327 # self.dataOut.ippSeconds = self.ippSeconds
327 328
328 329 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
329 330
330 331 self.dataOut.dtype = self.dtype
331 332
332 333 # self.dataOut.nPairs = self.nPairs
333 334
334 335 self.dataOut.pairsList = self.rdPairList
335 336
336 337 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
337 338
338 339 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
339 340
340 341 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
341 342
342 343 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
343 344
344 345 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
345 346
346 347 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
347 348
348 349 self.dataOut.channelList = range(self.systemHeaderObj.nChannels)
349 350
350 351 self.dataOut.flagShiftFFT = True #Data is always shifted
351 352
352 353 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
353 354
354 355 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
355 356
356 357 def getData(self):
357 358 """
358 359 First method to execute before "RUN" is called.
359 360
360 361 Copia el buffer de lectura a la clase "Spectra",
361 362 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
362 363 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
363 364
364 365 Return:
365 366 0 : Si no hay mas archivos disponibles
366 367 1 : Si hizo una buena copia del buffer
367 368
368 369 Affected:
369 370 self.dataOut
370 371
371 372 self.flagDiscontinuousBlock
372 373 self.flagIsNewBlock
373 374 """
374 375
375 376 if self.flagNoMoreFiles:
376 377 self.dataOut.flagNoData = True
377 378 print 'Process finished'
378 379 return 0
379 380
380 381 self.flagDiscontinuousBlock = 0
381 382 self.flagIsNewBlock = 0
382 383
383 384 if self.__hasNotDataInBuffer():
384 385
385 386 if not( self.readNextBlock() ):
386 387 self.dataOut.flagNoData = True
387 388 return 0
388 389
389 390
390 391 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
391 392
392 393 if self.data_spc is None:
393 394 self.dataOut.flagNoData = True
394 395 return 0
395 396
396 397 self.getBasicHeader()
397 398
398 399 self.getFirstHeader()
399 400
400 401 self.dataOut.data_spc = self.data_spc
401 402
402 403 self.dataOut.data_cspc = self.data_cspc
403 404
404 405 self.dataOut.data_dc = self.data_dc
405 406
406 407 self.dataOut.flagNoData = False
407 408
408 409 self.dataOut.realtime = self.online
409 410
410 411 return self.dataOut.data_spc
411 412
412 413 class SpectraWriter(JRODataWriter, Operation):
413 414
414 415 """
415 416 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
416 417 de los datos siempre se realiza por bloques.
417 418 """
418 419
419 420 ext = ".pdata"
420 421
421 422 optchar = "P"
422 423
423 424 shape_spc_Buffer = None
424 425
425 426 shape_cspc_Buffer = None
426 427
427 428 shape_dc_Buffer = None
428 429
429 430 data_spc = None
430 431
431 432 data_cspc = None
432 433
433 434 data_dc = None
434 435
435 436 # dataOut = None
436 437
437 def __init__(self):
438 def __init__(self, **kwargs):
438 439 """
439 440 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
440 441
441 442 Affected:
442 443
443 444 self.dataOut
444 445 self.basicHeaderObj
445 446 self.systemHeaderObj
446 447 self.radarControllerHeaderObj
447 448 self.processingHeaderObj
448 449
449 450 Return: None
450 451 """
451 452
452 Operation.__init__(self)
453 Operation.__init__(self, **kwargs)
453 454
454 455 self.isConfig = False
455 456
456 457 self.nTotalBlocks = 0
457 458
458 459 self.data_spc = None
459 460
460 461 self.data_cspc = None
461 462
462 463
463 464 self.data_dc = None
464 465
465 466 self.fp = None
466 467
467 468 self.flagIsNewFile = 1
468 469
469 470 self.nTotalBlocks = 0
470 471
471 472 self.flagIsNewBlock = 0
472 473
473 474 self.setFile = None
474 475
475 476 self.dtype = None
476 477
477 478 self.path = None
478 479
479 480 self.noMoreFiles = 0
480 481
481 482 self.filename = None
482 483
483 484 self.basicHeaderObj = BasicHeader(LOCALTIME)
484 485
485 486 self.systemHeaderObj = SystemHeader()
486 487
487 488 self.radarControllerHeaderObj = RadarControllerHeader()
488 489
489 490 self.processingHeaderObj = ProcessingHeader()
490 491
491 492
492 493 def hasAllDataInBuffer(self):
493 494 return 1
494 495
495 496
496 497
497 498 def setBlockDimension(self):
498 499 """
499 500 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
500 501
501 502 Affected:
502 503 self.shape_spc_Buffer
503 504 self.shape_cspc_Buffer
504 505 self.shape_dc_Buffer
505 506
506 507 Return: None
507 508 """
508 509 self.shape_spc_Buffer = (self.dataOut.nChannels,
509 510 self.processingHeaderObj.nHeights,
510 511 self.processingHeaderObj.profilesPerBlock)
511 512
512 513 self.shape_cspc_Buffer = (self.dataOut.nPairs,
513 514 self.processingHeaderObj.nHeights,
514 515 self.processingHeaderObj.profilesPerBlock)
515 516
516 517 self.shape_dc_Buffer = (self.dataOut.nChannels,
517 518 self.processingHeaderObj.nHeights)
518 519
519 520
520 521 def writeBlock(self):
521 """
522 """processingHeaderObj
522 523 Escribe el buffer en el file designado
523 524
524 525
525 526 Affected:
526 527 self.data_spc
527 528 self.data_cspc
528 529 self.data_dc
529 530 self.flagIsNewFile
530 531 self.flagIsNewBlock
531 532 self.nTotalBlocks
532 533 self.nWriteBlocks
533 534
534 535 Return: None
535 536 """
536 537
537 538 spc = numpy.transpose( self.data_spc, (0,2,1) )
538 539 if not( self.processingHeaderObj.shif_fft ):
539 540 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
540 541 data = spc.reshape((-1))
541 542 data = data.astype(self.dtype[0])
542 543 data.tofile(self.fp)
543 544
544 545 if self.data_cspc is not None:
545 data = numpy.zeros( self.shape_cspc_Buffer, self.dtype )
546
546 547 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
548 data = numpy.zeros( numpy.shape(cspc), self.dtype )
549 print 'data.shape', self.shape_cspc_Buffer
547 550 if not( self.processingHeaderObj.shif_fft ):
548 551 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
549 552 data['real'] = cspc.real
550 553 data['imag'] = cspc.imag
551 554 data = data.reshape((-1))
552 555 data.tofile(self.fp)
553 556
554 557
555 558 if self.data_dc is not None:
556 data = numpy.zeros( self.shape_dc_Buffer, self.dtype )
559
557 560 dc = self.data_dc
561 data = numpy.zeros( numpy.shape(dc), self.dtype )
558 562 data['real'] = dc.real
559 563 data['imag'] = dc.imag
560 564 data = data.reshape((-1))
561 565 data.tofile(self.fp)
562 566
563 567 # self.data_spc.fill(0)
564 568 #
565 569 # if self.data_dc is not None:
566 570 # self.data_dc.fill(0)
567 571 #
568 572 # if self.data_cspc is not None:
569 573 # self.data_cspc.fill(0)
570 574
571 575
572 576 self.flagIsNewFile = 0
573 577 self.flagIsNewBlock = 1
574 578 self.nTotalBlocks += 1
575 579 self.nWriteBlocks += 1
576 580 self.blockIndex += 1
577 581
578 582 # print "[Writing] Block = %d04" %self.blockIndex
579 583
580 584 def putData(self):
581 585 """
582 586 Setea un bloque de datos y luego los escribe en un file
583 587
584 588
585 589 Affected:
586 590 self.data_spc
587 591 self.data_cspc
588 592 self.data_dc
589 593
590 594 Return:
591 595 0 : Si no hay data o no hay mas files que puedan escribirse
592 596 1 : Si se escribio la data de un bloque en un file
593 597 """
594 598
595 599 if self.dataOut.flagNoData:
596 600 return 0
597 601
598 602 self.flagIsNewBlock = 0
599 603
600 604 if self.dataOut.flagDiscontinuousBlock:
601 605 self.data_spc.fill(0)
602 606 self.data_cspc.fill(0)
603 607 self.data_dc.fill(0)
604 608 self.setNextFile()
605 609
606 610 if self.flagIsNewFile == 0:
607 611 self.setBasicHeader()
608 612
609 613 self.data_spc = self.dataOut.data_spc.copy()
610 614
611 615 if self.dataOut.data_cspc is not None:
612 616 self.data_cspc = self.dataOut.data_cspc.copy()
613 617
614 618 if self.dataOut.data_dc is not None:
615 619 self.data_dc = self.dataOut.data_dc.copy()
616 620
617 621 # #self.processingHeaderObj.dataBlocksPerFile)
618 622 if self.hasAllDataInBuffer():
619 623 # self.setFirstHeader()
620 624 self.writeNextBlock()
621 625
622 626 return 1
623 627
624 628
625 629 def __getBlockSize(self):
626 630 '''
627 631 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
628 632 '''
629 633
630 634 dtype_width = self.getDtypeWidth()
631 635
632 636 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
633 637
634 638 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
635 639 blocksize = (pts2write_SelfSpectra*dtype_width)
636 640
637 641 if self.dataOut.data_cspc is not None:
638 642 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
639 643 blocksize += (pts2write_CrossSpectra*dtype_width*2)
640 644
641 645 if self.dataOut.data_dc is not None:
642 646 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
643 647 blocksize += (pts2write_DCchannels*dtype_width*2)
644 648
645 649 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
646 650
647 651 return blocksize
648 652
649 653 def setFirstHeader(self):
650 654
651 655 """
652 656 Obtiene una copia del First Header
653 657
654 658 Affected:
655 659 self.systemHeaderObj
656 660 self.radarControllerHeaderObj
657 661 self.dtype
658 662
659 663 Return:
660 664 None
661 665 """
662 666
663 667 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
664 668 self.systemHeaderObj.nChannels = self.dataOut.nChannels
665 669 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
666 670
667 671 self.processingHeaderObj.dtype = 1 # Spectra
668 672 self.processingHeaderObj.blockSize = self.__getBlockSize()
669 673 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
670 674 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
671 675 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
672 676 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
673 677 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
674 678 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
675 679 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
676 680
677 681
678 682 if self.processingHeaderObj.totalSpectra > 0:
679 683 channelList = []
680 684 for channel in range(self.dataOut.nChannels):
681 685 channelList.append(channel)
682 686 channelList.append(channel)
683 687
684 688 pairsList = []
685 689 if self.dataOut.nPairs > 0:
686 690 for pair in self.dataOut.pairsList:
687 691 pairsList.append(pair[0])
688 692 pairsList.append(pair[1])
689 693
690 694 spectraComb = channelList + pairsList
691 695 spectraComb = numpy.array(spectraComb, dtype="u1")
692 696 self.processingHeaderObj.spectraComb = spectraComb
693 697
694 698 if self.dataOut.code is not None:
695 699 self.processingHeaderObj.code = self.dataOut.code
696 700 self.processingHeaderObj.nCode = self.dataOut.nCode
697 701 self.processingHeaderObj.nBaud = self.dataOut.nBaud
698 702
699 703 if self.processingHeaderObj.nWindows != 0:
700 704 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
701 705 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
702 706 self.processingHeaderObj.nHeights = self.dataOut.nHeights
703 707 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
704 708
705 709 self.processingHeaderObj.processFlags = self.getProcessFlags()
706 710
707 711 self.setBasicHeader()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,905 +1,1064
1 1 import numpy
2 2
3 3 from jroproc_base import ProcessingUnit, Operation
4 4 from schainpy.model.data.jrodata import Spectra
5 5 from schainpy.model.data.jrodata import hildebrand_sekhon
6 6
7 import matplotlib.pyplot as plt
8
7 9 class SpectraProc(ProcessingUnit):
8 10
9 11 def __init__(self, **kwargs):
10 12
11 13 ProcessingUnit.__init__(self, **kwargs)
12 14
13 15 self.buffer = None
14 16 self.firstdatatime = None
15 17 self.profIndex = 0
16 18 self.dataOut = Spectra()
17 19 self.id_min = None
18 20 self.id_max = None
19 21
20 22 def __updateSpecFromVoltage(self):
21 23
22 24 self.dataOut.timeZone = self.dataIn.timeZone
23 25 self.dataOut.dstFlag = self.dataIn.dstFlag
24 26 self.dataOut.errorCount = self.dataIn.errorCount
25 27 self.dataOut.useLocalTime = self.dataIn.useLocalTime
26 28
27 29 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
28 30 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
29 31 self.dataOut.channelList = self.dataIn.channelList
30 32 self.dataOut.heightList = self.dataIn.heightList
31 33 self.dataOut.dtype = numpy.dtype([('real','<f4'),('imag','<f4')])
32 34
33 35 self.dataOut.nBaud = self.dataIn.nBaud
34 36 self.dataOut.nCode = self.dataIn.nCode
35 37 self.dataOut.code = self.dataIn.code
36 38 self.dataOut.nProfiles = self.dataOut.nFFTPoints
37 39
38 40 self.dataOut.flagDiscontinuousBlock = self.dataIn.flagDiscontinuousBlock
39 41 self.dataOut.utctime = self.firstdatatime
40 42 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
41 43 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
42 44 self.dataOut.flagShiftFFT = False
43 45
44 46 self.dataOut.nCohInt = self.dataIn.nCohInt
45 47 self.dataOut.nIncohInt = 1
46 48
47 49 self.dataOut.windowOfFilter = self.dataIn.windowOfFilter
48 50
49 51 self.dataOut.frequency = self.dataIn.frequency
50 52 self.dataOut.realtime = self.dataIn.realtime
51 53
52 54 self.dataOut.azimuth = self.dataIn.azimuth
53 55 self.dataOut.zenith = self.dataIn.zenith
54 56
55 57 self.dataOut.beam.codeList = self.dataIn.beam.codeList
56 58 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
57 59 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
58 60
59 61 def __getFft(self):
60 62 """
61 63 Convierte valores de Voltaje a Spectra
62 64
63 65 Affected:
64 66 self.dataOut.data_spc
65 67 self.dataOut.data_cspc
66 68 self.dataOut.data_dc
67 69 self.dataOut.heightList
68 70 self.profIndex
69 71 self.buffer
70 72 self.dataOut.flagNoData
71 73 """
72 74 fft_volt = numpy.fft.fft(self.buffer,n=self.dataOut.nFFTPoints,axis=1)
73 75 fft_volt = fft_volt.astype(numpy.dtype('complex'))
74 76 dc = fft_volt[:,0,:]
75 77
76 78 #calculo de self-spectra
77 79 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
78 80 spc = fft_volt * numpy.conjugate(fft_volt)
79 81 spc = spc.real
80 82
81 83 blocksize = 0
82 84 blocksize += dc.size
83 85 blocksize += spc.size
84 86
85 87 cspc = None
86 88 pairIndex = 0
87 89 if self.dataOut.pairsList != None:
88 90 #calculo de cross-spectra
89 91 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
90 92 for pair in self.dataOut.pairsList:
91 93 if pair[0] not in self.dataOut.channelList:
92 94 raise ValueError, "Error getting CrossSpectra: pair 0 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
93 95 if pair[1] not in self.dataOut.channelList:
94 96 raise ValueError, "Error getting CrossSpectra: pair 1 of %s is not in channelList = %s" %(str(pair), str(self.dataOut.channelList))
95 97
96 98 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
97 99 pairIndex += 1
98 100 blocksize += cspc.size
99 101
100 102 self.dataOut.data_spc = spc
101 103 self.dataOut.data_cspc = cspc
102 104 self.dataOut.data_dc = dc
103 105 self.dataOut.blockSize = blocksize
104 106 self.dataOut.flagShiftFFT = True
105 107
106 108 def run(self, nProfiles=None, nFFTPoints=None, pairsList=[], ippFactor=None):
107 109
108 110 self.dataOut.flagNoData = True
109 111
110 112 if self.dataIn.type == "Spectra":
111 113 self.dataOut.copy(self.dataIn)
112 114 # self.__selectPairs(pairsList)
113 115 return True
114 116
115 117 if self.dataIn.type == "Voltage":
116 118
117 119 if nFFTPoints == None:
118 120 raise ValueError, "This SpectraProc.run() need nFFTPoints input variable"
119 121
120 122 if nProfiles == None:
121 123 nProfiles = nFFTPoints
122 124
123 125 if ippFactor == None:
124 126 ippFactor = 1
125 127
126 128 self.dataOut.ippFactor = ippFactor
127 129
128 130 self.dataOut.nFFTPoints = nFFTPoints
129 131 self.dataOut.pairsList = pairsList
130 132
131 133 if self.buffer is None:
132 134 self.buffer = numpy.zeros( (self.dataIn.nChannels,
133 135 nProfiles,
134 136 self.dataIn.nHeights),
135 137 dtype='complex')
136 138
137 139 if self.dataIn.flagDataAsBlock:
138 140 #data dimension: [nChannels, nProfiles, nSamples]
139 141 nVoltProfiles = self.dataIn.data.shape[1]
140 142 # nVoltProfiles = self.dataIn.nProfiles
141 143
142 144 if nVoltProfiles == nProfiles:
143 145 self.buffer = self.dataIn.data.copy()
144 146 self.profIndex = nVoltProfiles
145 147
146 148 elif nVoltProfiles < nProfiles:
147 149
148 150 if self.profIndex == 0:
149 151 self.id_min = 0
150 152 self.id_max = nVoltProfiles
151 153
152 154 self.buffer[:,self.id_min:self.id_max,:] = self.dataIn.data
153 155 self.profIndex += nVoltProfiles
154 156 self.id_min += nVoltProfiles
155 157 self.id_max += nVoltProfiles
156 158 else:
157 159 raise ValueError, "The type object %s has %d profiles, it should just has %d profiles"%(self.dataIn.type,self.dataIn.data.shape[1],nProfiles)
158 160 self.dataOut.flagNoData = True
159 161 return 0
160 162 else:
161 163 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
162 164 self.profIndex += 1
163 165
164 166 if self.firstdatatime == None:
165 167 self.firstdatatime = self.dataIn.utctime
166 168
167 169 if self.profIndex == nProfiles:
168 170 self.__updateSpecFromVoltage()
169 171 self.__getFft()
170 172
171 173 self.dataOut.flagNoData = False
172 174 self.firstdatatime = None
173 175 self.profIndex = 0
174 176
175 177 return True
176 178
177 179 raise ValueError, "The type of input object '%s' is not valid"%(self.dataIn.type)
178 180
179 181 def __selectPairs(self, pairsList):
180 182
181 183 if channelList == None:
182 184 return
183 185
184 186 pairsIndexListSelected = []
185 187
186 188 for thisPair in pairsList:
187 189
188 190 if thisPair not in self.dataOut.pairsList:
189 191 continue
190 192
191 193 pairIndex = self.dataOut.pairsList.index(thisPair)
192 194
193 195 pairsIndexListSelected.append(pairIndex)
194 196
195 197 if not pairsIndexListSelected:
196 198 self.dataOut.data_cspc = None
197 199 self.dataOut.pairsList = []
198 200 return
199 201
200 202 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
201 203 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
202 204
203 205 return
204 206
205 207 def __selectPairsByChannel(self, channelList=None):
206 208
207 209 if channelList == None:
208 210 return
209 211
210 212 pairsIndexListSelected = []
211 213 for pairIndex in self.dataOut.pairsIndexList:
212 214 #First pair
213 215 if self.dataOut.pairsList[pairIndex][0] not in channelList:
214 216 continue
215 217 #Second pair
216 218 if self.dataOut.pairsList[pairIndex][1] not in channelList:
217 219 continue
218 220
219 221 pairsIndexListSelected.append(pairIndex)
220 222
221 223 if not pairsIndexListSelected:
222 224 self.dataOut.data_cspc = None
223 225 self.dataOut.pairsList = []
224 226 return
225 227
226 228 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
227 229 self.dataOut.pairsList = [self.dataOut.pairsList[i] for i in pairsIndexListSelected]
228 230
229 231 return
230 232
231 233 def selectChannels(self, channelList):
232 234
233 235 channelIndexList = []
234 236
235 237 for channel in channelList:
236 238 if channel not in self.dataOut.channelList:
237 239 raise ValueError, "Error selecting channels, Channel %d is not valid.\nAvailable channels = %s" %(channel, str(self.dataOut.channelList))
238 240
239 241 index = self.dataOut.channelList.index(channel)
240 242 channelIndexList.append(index)
241 243
242 244 self.selectChannelsByIndex(channelIndexList)
243 245
244 246 def selectChannelsByIndex(self, channelIndexList):
245 247 """
246 248 Selecciona un bloque de datos en base a canales segun el channelIndexList
247 249
248 250 Input:
249 251 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
250 252
251 253 Affected:
252 254 self.dataOut.data_spc
253 255 self.dataOut.channelIndexList
254 256 self.dataOut.nChannels
255 257
256 258 Return:
257 259 None
258 260 """
259 261
260 262 for channelIndex in channelIndexList:
261 263 if channelIndex not in self.dataOut.channelIndexList:
262 264 raise ValueError, "Error selecting channels: The value %d in channelIndexList is not valid.\nAvailable channel indexes = " %(channelIndex, self.dataOut.channelIndexList)
263 265
264 266 # nChannels = len(channelIndexList)
265 267
266 268 data_spc = self.dataOut.data_spc[channelIndexList,:]
267 269 data_dc = self.dataOut.data_dc[channelIndexList,:]
268 270
269 271 self.dataOut.data_spc = data_spc
270 272 self.dataOut.data_dc = data_dc
271 273
272 274 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
273 275 # self.dataOut.nChannels = nChannels
274 276
275 277 self.__selectPairsByChannel(self.dataOut.channelList)
276 278
277 279 return 1
280
281
282 def selectFFTs(self, minFFT, maxFFT ):
283 """
284 Selecciona un bloque de datos en base a un grupo de valores de puntos FFTs segun el rango
285 minFFT<= FFT <= maxFFT
286 """
287
288 if (minFFT > maxFFT):
289 raise ValueError, "Error selecting heights: Height range (%d,%d) is not valid" % (minFFT, maxFFT)
290
291 if (minFFT < self.dataOut.getFreqRange()[0]):
292 minFFT = self.dataOut.getFreqRange()[0]
293
294 if (maxFFT > self.dataOut.getFreqRange()[-1]):
295 maxFFT = self.dataOut.getFreqRange()[-1]
296
297 minIndex = 0
298 maxIndex = 0
299 FFTs = self.dataOut.getFreqRange()
300
301 inda = numpy.where(FFTs >= minFFT)
302 indb = numpy.where(FFTs <= maxFFT)
278 303
304 try:
305 minIndex = inda[0][0]
306 except:
307 minIndex = 0
308
309 try:
310 maxIndex = indb[0][-1]
311 except:
312 maxIndex = len(FFTs)
313
314 self.selectFFTsByIndex(minIndex, maxIndex)
315
316 return 1
317
318
319
279 320 def selectHeights(self, minHei, maxHei):
280 321 """
281 322 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
282 323 minHei <= height <= maxHei
283 324
284 325 Input:
285 326 minHei : valor minimo de altura a considerar
286 327 maxHei : valor maximo de altura a considerar
287 328
288 329 Affected:
289 330 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
290 331
291 332 Return:
292 333 1 si el metodo se ejecuto con exito caso contrario devuelve 0
293 334 """
294 335
336
295 337 if (minHei > maxHei):
296 338 raise ValueError, "Error selecting heights: Height range (%d,%d) is not valid" % (minHei, maxHei)
297 339
298 340 if (minHei < self.dataOut.heightList[0]):
299 341 minHei = self.dataOut.heightList[0]
300 342
301 343 if (maxHei > self.dataOut.heightList[-1]):
302 344 maxHei = self.dataOut.heightList[-1]
303 345
304 346 minIndex = 0
305 347 maxIndex = 0
306 348 heights = self.dataOut.heightList
307 349
308 350 inda = numpy.where(heights >= minHei)
309 351 indb = numpy.where(heights <= maxHei)
310 352
311 353 try:
312 354 minIndex = inda[0][0]
313 355 except:
314 356 minIndex = 0
315 357
316 358 try:
317 359 maxIndex = indb[0][-1]
318 360 except:
319 361 maxIndex = len(heights)
320 362
321 363 self.selectHeightsByIndex(minIndex, maxIndex)
364
322 365
323 366 return 1
324 367
325 368 def getBeaconSignal(self, tauindex = 0, channelindex = 0, hei_ref=None):
326 369 newheis = numpy.where(self.dataOut.heightList>self.dataOut.radarControllerHeaderObj.Taus[tauindex])
327 370
328 371 if hei_ref != None:
329 372 newheis = numpy.where(self.dataOut.heightList>hei_ref)
330 373
331 374 minIndex = min(newheis[0])
332 375 maxIndex = max(newheis[0])
333 376 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
334 377 heightList = self.dataOut.heightList[minIndex:maxIndex+1]
335 378
336 379 # determina indices
337 380 nheis = int(self.dataOut.radarControllerHeaderObj.txB/(self.dataOut.heightList[1]-self.dataOut.heightList[0]))
338 381 avg_dB = 10*numpy.log10(numpy.sum(data_spc[channelindex,:,:],axis=0))
339 382 beacon_dB = numpy.sort(avg_dB)[-nheis:]
340 383 beacon_heiIndexList = []
341 384 for val in avg_dB.tolist():
342 385 if val >= beacon_dB[0]:
343 386 beacon_heiIndexList.append(avg_dB.tolist().index(val))
344 387
345 388 #data_spc = data_spc[:,:,beacon_heiIndexList]
346 389 data_cspc = None
347 390 if self.dataOut.data_cspc is not None:
348 391 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
349 392 #data_cspc = data_cspc[:,:,beacon_heiIndexList]
350 393
351 394 data_dc = None
352 395 if self.dataOut.data_dc is not None:
353 396 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
354 397 #data_dc = data_dc[:,beacon_heiIndexList]
355 398
356 399 self.dataOut.data_spc = data_spc
357 400 self.dataOut.data_cspc = data_cspc
358 401 self.dataOut.data_dc = data_dc
359 402 self.dataOut.heightList = heightList
360 403 self.dataOut.beacon_heiIndexList = beacon_heiIndexList
361 404
362 405 return 1
363 406
407 def selectFFTsByIndex(self, minIndex, maxIndex):
408 """
409
410 """
411
412 if (minIndex < 0) or (minIndex > maxIndex):
413 raise ValueError, "Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex)
414
415 if (maxIndex >= self.dataOut.nProfiles):
416 maxIndex = self.dataOut.nProfiles-1
417
418 #Spectra
419 data_spc = self.dataOut.data_spc[:,minIndex:maxIndex+1,:]
420
421 data_cspc = None
422 if self.dataOut.data_cspc is not None:
423 data_cspc = self.dataOut.data_cspc[:,minIndex:maxIndex+1,:]
424
425 data_dc = None
426 if self.dataOut.data_dc is not None:
427 data_dc = self.dataOut.data_dc[minIndex:maxIndex+1,:]
428
429 self.dataOut.data_spc = data_spc
430 self.dataOut.data_cspc = data_cspc
431 self.dataOut.data_dc = data_dc
432
433 self.dataOut.ippSeconds = self.dataOut.ippSeconds*(self.dataOut.nFFTPoints / numpy.shape(data_cspc)[1])
434 self.dataOut.nFFTPoints = numpy.shape(data_cspc)[1]
435 self.dataOut.profilesPerBlock = numpy.shape(data_cspc)[1]
436
437 #self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
438
439 return 1
440
441
364 442
365 443 def selectHeightsByIndex(self, minIndex, maxIndex):
366 444 """
367 445 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
368 446 minIndex <= index <= maxIndex
369 447
370 448 Input:
371 449 minIndex : valor de indice minimo de altura a considerar
372 450 maxIndex : valor de indice maximo de altura a considerar
373 451
374 452 Affected:
375 453 self.dataOut.data_spc
376 454 self.dataOut.data_cspc
377 455 self.dataOut.data_dc
378 456 self.dataOut.heightList
379 457
380 458 Return:
381 459 1 si el metodo se ejecuto con exito caso contrario devuelve 0
382 460 """
383 461
384 462 if (minIndex < 0) or (minIndex > maxIndex):
385 463 raise ValueError, "Error selecting heights: Index range (%d,%d) is not valid" % (minIndex, maxIndex)
386 464
387 465 if (maxIndex >= self.dataOut.nHeights):
388 466 maxIndex = self.dataOut.nHeights-1
389 467
390 468 #Spectra
391 469 data_spc = self.dataOut.data_spc[:,:,minIndex:maxIndex+1]
392 470
393 471 data_cspc = None
394 472 if self.dataOut.data_cspc is not None:
395 473 data_cspc = self.dataOut.data_cspc[:,:,minIndex:maxIndex+1]
396 474
397 475 data_dc = None
398 476 if self.dataOut.data_dc is not None:
399 477 data_dc = self.dataOut.data_dc[:,minIndex:maxIndex+1]
400 478
401 479 self.dataOut.data_spc = data_spc
402 480 self.dataOut.data_cspc = data_cspc
403 481 self.dataOut.data_dc = data_dc
404 482
405 483 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
406 484
407 485 return 1
408
486
487
409 488 def removeDC(self, mode = 2):
410 489 jspectra = self.dataOut.data_spc
411 490 jcspectra = self.dataOut.data_cspc
412 491
413 492
414 493 num_chan = jspectra.shape[0]
415 494 num_hei = jspectra.shape[2]
416 495
417 496 if jcspectra is not None:
418 497 jcspectraExist = True
419 498 num_pairs = jcspectra.shape[0]
420 499 else: jcspectraExist = False
421 500
422 501 freq_dc = jspectra.shape[1]/2
423 502 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
424 503
425 504 if ind_vel[0]<0:
426 505 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
427 506
428 507 if mode == 1:
429 508 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
430 509
431 510 if jcspectraExist:
432 511 jcspectra[:,freq_dc,:] = (jcspectra[:,ind_vel[1],:] + jcspectra[:,ind_vel[2],:])/2
433 512
434 513 if mode == 2:
435 514
436 515 vel = numpy.array([-2,-1,1,2])
437 516 xx = numpy.zeros([4,4])
438 517
439 518 for fil in range(4):
440 519 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
441 520
442 521 xx_inv = numpy.linalg.inv(xx)
443 522 xx_aux = xx_inv[0,:]
444 523
445 524 for ich in range(num_chan):
446 525 yy = jspectra[ich,ind_vel,:]
447 526 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
448 527
449 528 junkid = jspectra[ich,freq_dc,:]<=0
450 529 cjunkid = sum(junkid)
451 530
452 531 if cjunkid.any():
453 532 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
454 533
455 534 if jcspectraExist:
456 535 for ip in range(num_pairs):
457 536 yy = jcspectra[ip,ind_vel,:]
458 537 jcspectra[ip,freq_dc,:] = numpy.dot(xx_aux,yy)
459 538
460 539
461 540 self.dataOut.data_spc = jspectra
462 541 self.dataOut.data_cspc = jcspectra
463 542
464 543 return 1
465 544
545 def removeInterference2(self):
546
547 cspc = self.dataOut.data_cspc
548 spc = self.dataOut.data_spc
549 print numpy.shape(spc)
550 Heights = numpy.arange(cspc.shape[2])
551 realCspc = numpy.abs(cspc)
552
553 for i in range(cspc.shape[0]):
554 LinePower= numpy.sum(realCspc[i], axis=0)
555 Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
556 SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
557 #print numpy.shape(realCspc)
558 #print '',SelectedHeights, '', numpy.shape(realCspc[i,:,SelectedHeights])
559 InterferenceSum = numpy.sum( realCspc[i,:,SelectedHeights], axis=0 )
560 print SelectedHeights
561 InterferenceThresholdMin = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
562 InterferenceThresholdMax = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.99)]
563
564
565 InterferenceRange = numpy.where( ([InterferenceSum > InterferenceThresholdMin]))# , InterferenceSum < InterferenceThresholdMax]) )
566 #InterferenceRange = numpy.where( ([InterferenceRange < InterferenceThresholdMax]))
567 if len(InterferenceRange)<int(cspc.shape[1]*0.3):
568 cspc[i,InterferenceRange,:] = numpy.NaN
569
570 print '########################################################################################'
571 print 'Len interference sum',len(InterferenceSum)
572 print 'InterferenceThresholdMin', InterferenceThresholdMin, 'InterferenceThresholdMax', InterferenceThresholdMax
573 print 'InterferenceRange',InterferenceRange
574 print '########################################################################################'
575
576 ''' Ploteo '''
577
578 #for i in range(3):
579 #print 'FASE', numpy.shape(phase), y[25]
580 #print numpy.shape(coherence)
581 #fig = plt.figure(10+ int(numpy.random.rand()*100))
582 #plt.plot( x[0:256],coherence[:,25] )
583 #cohAv = numpy.average(coherence[i],1)
584 #Pendiente = FrecRange * PhaseSlope[i]
585 #plt.plot( InterferenceSum)
586 #plt.plot( numpy.sort(InterferenceSum))
587 #plt.plot( LinePower )
588 #plt.plot( xFrec,phase[i])
589
590 #CSPCmean = numpy.mean(numpy.abs(CSPCSamples),0)
591 #plt.plot(xFrec, FitGauss01)
592 #plt.plot(xFrec, CSPCmean)
593 #plt.plot(xFrec, numpy.abs(CSPCSamples[0]))
594 #plt.plot(xFrec, FitGauss)
595 #plt.plot(xFrec, yMean)
596 #plt.plot(xFrec, numpy.abs(coherence[0]))
597
598 #plt.axis([-12, 12, 15, 50])
599 #plt.title("%s" %( '%s %s, Channel %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S") , i)))
600
601
602 #fig.savefig('/home/erick/Documents/Pics/nom{}.png'.format(int(numpy.random.rand()*100)))
603
604 #plt.show()
605 #self.indice=self.indice+1
606 #raise
607
608
609 self.dataOut.data_cspc = cspc
610
611 # for i in range(spc.shape[0]):
612 # LinePower= numpy.sum(spc[i], axis=0)
613 # Threshold = numpy.amax(LinePower)-numpy.sort(LinePower)[len(Heights)-int(len(Heights)*0.1)]
614 # SelectedHeights = Heights[ numpy.where( LinePower < Threshold ) ]
615 # #print numpy.shape(realCspc)
616 # #print '',SelectedHeights, '', numpy.shape(realCspc[i,:,SelectedHeights])
617 # InterferenceSum = numpy.sum( spc[i,:,SelectedHeights], axis=0 )
618 # InterferenceThreshold = numpy.sort(InterferenceSum)[int(len(InterferenceSum)*0.98)]
619 # InterferenceRange = numpy.where( InterferenceSum > InterferenceThreshold )
620 # if len(InterferenceRange)<int(spc.shape[1]*0.03):
621 # spc[i,InterferenceRange,:] = numpy.NaN
622
623 #self.dataOut.data_spc = spc
624
466 625 def removeInterference(self, interf = 2,hei_interf = None, nhei_interf = None, offhei_interf = None):
467 626
468 627 jspectra = self.dataOut.data_spc
469 628 jcspectra = self.dataOut.data_cspc
470 629 jnoise = self.dataOut.getNoise()
471 630 num_incoh = self.dataOut.nIncohInt
472 631
473 632 num_channel = jspectra.shape[0]
474 633 num_prof = jspectra.shape[1]
475 634 num_hei = jspectra.shape[2]
476 635
477 636 #hei_interf
478 637 if hei_interf is None:
479 638 count_hei = num_hei/2 #Como es entero no importa
480 639 hei_interf = numpy.asmatrix(range(count_hei)) + num_hei - count_hei
481 640 hei_interf = numpy.asarray(hei_interf)[0]
482 641 #nhei_interf
483 642 if (nhei_interf == None):
484 643 nhei_interf = 5
485 644 if (nhei_interf < 1):
486 645 nhei_interf = 1
487 646 if (nhei_interf > count_hei):
488 647 nhei_interf = count_hei
489 648 if (offhei_interf == None):
490 649 offhei_interf = 0
491 650
492 651 ind_hei = range(num_hei)
493 652 # mask_prof = numpy.asarray(range(num_prof - 2)) + 1
494 653 # mask_prof[range(num_prof/2 - 1,len(mask_prof))] += 1
495 654 mask_prof = numpy.asarray(range(num_prof))
496 655 num_mask_prof = mask_prof.size
497 656 comp_mask_prof = [0, num_prof/2]
498 657
499 658
500 659 #noise_exist: Determina si la variable jnoise ha sido definida y contiene la informacion del ruido de cada canal
501 660 if (jnoise.size < num_channel or numpy.isnan(jnoise).any()):
502 661 jnoise = numpy.nan
503 662 noise_exist = jnoise[0] < numpy.Inf
504 663
505 664 #Subrutina de Remocion de la Interferencia
506 665 for ich in range(num_channel):
507 666 #Se ordena los espectros segun su potencia (menor a mayor)
508 667 power = jspectra[ich,mask_prof,:]
509 668 power = power[:,hei_interf]
510 669 power = power.sum(axis = 0)
511 670 psort = power.ravel().argsort()
512 671
513 672 #Se estima la interferencia promedio en los Espectros de Potencia empleando
514 673 junkspc_interf = jspectra[ich,:,hei_interf[psort[range(offhei_interf, nhei_interf + offhei_interf)]]]
515 674
516 675 if noise_exist:
517 676 # tmp_noise = jnoise[ich] / num_prof
518 677 tmp_noise = jnoise[ich]
519 678 junkspc_interf = junkspc_interf - tmp_noise
520 679 #junkspc_interf[:,comp_mask_prof] = 0
521 680
522 681 jspc_interf = junkspc_interf.sum(axis = 0) / nhei_interf
523 682 jspc_interf = jspc_interf.transpose()
524 683 #Calculando el espectro de interferencia promedio
525 684 noiseid = numpy.where(jspc_interf <= tmp_noise/ numpy.sqrt(num_incoh))
526 685 noiseid = noiseid[0]
527 686 cnoiseid = noiseid.size
528 687 interfid = numpy.where(jspc_interf > tmp_noise/ numpy.sqrt(num_incoh))
529 688 interfid = interfid[0]
530 689 cinterfid = interfid.size
531 690
532 691 if (cnoiseid > 0): jspc_interf[noiseid] = 0
533 692
534 693 #Expandiendo los perfiles a limpiar
535 694 if (cinterfid > 0):
536 695 new_interfid = (numpy.r_[interfid - 1, interfid, interfid + 1] + num_prof)%num_prof
537 696 new_interfid = numpy.asarray(new_interfid)
538 697 new_interfid = {x for x in new_interfid}
539 698 new_interfid = numpy.array(list(new_interfid))
540 699 new_cinterfid = new_interfid.size
541 700 else: new_cinterfid = 0
542 701
543 702 for ip in range(new_cinterfid):
544 703 ind = junkspc_interf[:,new_interfid[ip]].ravel().argsort()
545 704 jspc_interf[new_interfid[ip]] = junkspc_interf[ind[nhei_interf/2],new_interfid[ip]]
546 705
547 706
548 707 jspectra[ich,:,ind_hei] = jspectra[ich,:,ind_hei] - jspc_interf #Corregir indices
549 708
550 709 #Removiendo la interferencia del punto de mayor interferencia
551 710 ListAux = jspc_interf[mask_prof].tolist()
552 711 maxid = ListAux.index(max(ListAux))
553 712
554 713
555 714 if cinterfid > 0:
556 715 for ip in range(cinterfid*(interf == 2) - 1):
557 716 ind = (jspectra[ich,interfid[ip],:] < tmp_noise*(1 + 1/numpy.sqrt(num_incoh))).nonzero()
558 717 cind = len(ind)
559 718
560 719 if (cind > 0):
561 720 jspectra[ich,interfid[ip],ind] = tmp_noise*(1 + (numpy.random.uniform(cind) - 0.5)/numpy.sqrt(num_incoh))
562 721
563 722 ind = numpy.array([-2,-1,1,2])
564 723 xx = numpy.zeros([4,4])
565 724
566 725 for id1 in range(4):
567 726 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
568 727
569 728 xx_inv = numpy.linalg.inv(xx)
570 729 xx = xx_inv[:,0]
571 730 ind = (ind + maxid + num_mask_prof)%num_mask_prof
572 731 yy = jspectra[ich,mask_prof[ind],:]
573 732 jspectra[ich,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
574 733
575 734
576 735 indAux = (jspectra[ich,:,:] < tmp_noise*(1-1/numpy.sqrt(num_incoh))).nonzero()
577 736 jspectra[ich,indAux[0],indAux[1]] = tmp_noise * (1 - 1/numpy.sqrt(num_incoh))
578 737
579 738 #Remocion de Interferencia en el Cross Spectra
580 739 if jcspectra is None: return jspectra, jcspectra
581 740 num_pairs = jcspectra.size/(num_prof*num_hei)
582 741 jcspectra = jcspectra.reshape(num_pairs, num_prof, num_hei)
583 742
584 743 for ip in range(num_pairs):
585 744
586 745 #-------------------------------------------
587 746
588 747 cspower = numpy.abs(jcspectra[ip,mask_prof,:])
589 748 cspower = cspower[:,hei_interf]
590 749 cspower = cspower.sum(axis = 0)
591 750
592 751 cspsort = cspower.ravel().argsort()
593 752 junkcspc_interf = jcspectra[ip,:,hei_interf[cspsort[range(offhei_interf, nhei_interf + offhei_interf)]]]
594 753 junkcspc_interf = junkcspc_interf.transpose()
595 754 jcspc_interf = junkcspc_interf.sum(axis = 1)/nhei_interf
596 755
597 756 ind = numpy.abs(jcspc_interf[mask_prof]).ravel().argsort()
598 757
599 758 median_real = numpy.median(numpy.real(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
600 759 median_imag = numpy.median(numpy.imag(junkcspc_interf[mask_prof[ind[range(3*num_prof/4)]],:]))
601 760 junkcspc_interf[comp_mask_prof,:] = numpy.complex(median_real, median_imag)
602 761
603 762 for iprof in range(num_prof):
604 763 ind = numpy.abs(junkcspc_interf[iprof,:]).ravel().argsort()
605 764 jcspc_interf[iprof] = junkcspc_interf[iprof, ind[nhei_interf/2]]
606 765
607 766 #Removiendo la Interferencia
608 767 jcspectra[ip,:,ind_hei] = jcspectra[ip,:,ind_hei] - jcspc_interf
609 768
610 769 ListAux = numpy.abs(jcspc_interf[mask_prof]).tolist()
611 770 maxid = ListAux.index(max(ListAux))
612 771
613 772 ind = numpy.array([-2,-1,1,2])
614 773 xx = numpy.zeros([4,4])
615 774
616 775 for id1 in range(4):
617 776 xx[:,id1] = ind[id1]**numpy.asarray(range(4))
618 777
619 778 xx_inv = numpy.linalg.inv(xx)
620 779 xx = xx_inv[:,0]
621 780
622 781 ind = (ind + maxid + num_mask_prof)%num_mask_prof
623 782 yy = jcspectra[ip,mask_prof[ind],:]
624 783 jcspectra[ip,mask_prof[maxid],:] = numpy.dot(yy.transpose(),xx)
625 784
626 785 #Guardar Resultados
627 786 self.dataOut.data_spc = jspectra
628 787 self.dataOut.data_cspc = jcspectra
629 788
630 789 return 1
631 790
632 791 def setRadarFrequency(self, frequency=None):
633 792
634 793 if frequency != None:
635 794 self.dataOut.frequency = frequency
636 795
637 796 return 1
638 797
639 798 def getNoise(self, minHei=None, maxHei=None, minVel=None, maxVel=None):
640 799 #validacion de rango
641 800 if minHei == None:
642 801 minHei = self.dataOut.heightList[0]
643 802
644 803 if maxHei == None:
645 804 maxHei = self.dataOut.heightList[-1]
646 805
647 806 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
648 807 print 'minHei: %.2f is out of the heights range'%(minHei)
649 808 print 'minHei is setting to %.2f'%(self.dataOut.heightList[0])
650 809 minHei = self.dataOut.heightList[0]
651 810
652 811 if (maxHei > self.dataOut.heightList[-1]) or (maxHei < minHei):
653 812 print 'maxHei: %.2f is out of the heights range'%(maxHei)
654 813 print 'maxHei is setting to %.2f'%(self.dataOut.heightList[-1])
655 814 maxHei = self.dataOut.heightList[-1]
656 815
657 816 # validacion de velocidades
658 817 velrange = self.dataOut.getVelRange(1)
659 818
660 819 if minVel == None:
661 820 minVel = velrange[0]
662 821
663 822 if maxVel == None:
664 823 maxVel = velrange[-1]
665 824
666 825 if (minVel < velrange[0]) or (minVel > maxVel):
667 826 print 'minVel: %.2f is out of the velocity range'%(minVel)
668 827 print 'minVel is setting to %.2f'%(velrange[0])
669 828 minVel = velrange[0]
670 829
671 830 if (maxVel > velrange[-1]) or (maxVel < minVel):
672 831 print 'maxVel: %.2f is out of the velocity range'%(maxVel)
673 832 print 'maxVel is setting to %.2f'%(velrange[-1])
674 833 maxVel = velrange[-1]
675 834
676 835 # seleccion de indices para rango
677 836 minIndex = 0
678 837 maxIndex = 0
679 838 heights = self.dataOut.heightList
680 839
681 840 inda = numpy.where(heights >= minHei)
682 841 indb = numpy.where(heights <= maxHei)
683 842
684 843 try:
685 844 minIndex = inda[0][0]
686 845 except:
687 846 minIndex = 0
688 847
689 848 try:
690 849 maxIndex = indb[0][-1]
691 850 except:
692 851 maxIndex = len(heights)
693 852
694 853 if (minIndex < 0) or (minIndex > maxIndex):
695 854 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
696 855
697 856 if (maxIndex >= self.dataOut.nHeights):
698 857 maxIndex = self.dataOut.nHeights-1
699 858
700 859 # seleccion de indices para velocidades
701 860 indminvel = numpy.where(velrange >= minVel)
702 861 indmaxvel = numpy.where(velrange <= maxVel)
703 862 try:
704 863 minIndexVel = indminvel[0][0]
705 864 except:
706 865 minIndexVel = 0
707 866
708 867 try:
709 868 maxIndexVel = indmaxvel[0][-1]
710 869 except:
711 870 maxIndexVel = len(velrange)
712 871
713 872 #seleccion del espectro
714 873 data_spc = self.dataOut.data_spc[:,minIndexVel:maxIndexVel+1,minIndex:maxIndex+1]
715 874 #estimacion de ruido
716 875 noise = numpy.zeros(self.dataOut.nChannels)
717 876
718 877 for channel in range(self.dataOut.nChannels):
719 878 daux = data_spc[channel,:,:]
720 879 noise[channel] = hildebrand_sekhon(daux, self.dataOut.nIncohInt)
721 880
722 881 self.dataOut.noise_estimation = noise.copy()
723 882
724 883 return 1
725 884
726 885 class IncohInt(Operation):
727 886
728 887
729 888 __profIndex = 0
730 889 __withOverapping = False
731 890
732 891 __byTime = False
733 892 __initime = None
734 893 __lastdatatime = None
735 894 __integrationtime = None
736 895
737 896 __buffer_spc = None
738 897 __buffer_cspc = None
739 898 __buffer_dc = None
740 899
741 900 __dataReady = False
742 901
743 902 __timeInterval = None
744 903
745 904 n = None
746 905
747 906
748 907
749 908 def __init__(self, **kwargs):
750 909
751 910 Operation.__init__(self, **kwargs)
752 911 # self.isConfig = False
753 912
754 913 def setup(self, n=None, timeInterval=None, overlapping=False):
755 914 """
756 915 Set the parameters of the integration class.
757 916
758 917 Inputs:
759 918
760 919 n : Number of coherent integrations
761 920 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
762 921 overlapping :
763 922
764 923 """
765 924
766 925 self.__initime = None
767 926 self.__lastdatatime = 0
768 927
769 928 self.__buffer_spc = 0
770 929 self.__buffer_cspc = 0
771 930 self.__buffer_dc = 0
772 931
773 932 self.__profIndex = 0
774 933 self.__dataReady = False
775 934 self.__byTime = False
776 935
777 936 if n is None and timeInterval is None:
778 937 raise ValueError, "n or timeInterval should be specified ..."
779 938
780 939 if n is not None:
781 940 self.n = int(n)
782 941 else:
783 942 self.__integrationtime = int(timeInterval) #if (type(timeInterval)!=integer) -> change this line
784 943 self.n = None
785 944 self.__byTime = True
786 945
787 946 def putData(self, data_spc, data_cspc, data_dc):
788 947
789 948 """
790 949 Add a profile to the __buffer_spc and increase in one the __profileIndex
791 950
792 951 """
793 952
794 953 self.__buffer_spc += data_spc
795 954
796 955 if data_cspc is None:
797 956 self.__buffer_cspc = None
798 957 else:
799 958 self.__buffer_cspc += data_cspc
800 959
801 960 if data_dc is None:
802 961 self.__buffer_dc = None
803 962 else:
804 963 self.__buffer_dc += data_dc
805 964
806 965 self.__profIndex += 1
807 966
808 967 return
809 968
810 969 def pushData(self):
811 970 """
812 971 Return the sum of the last profiles and the profiles used in the sum.
813 972
814 973 Affected:
815 974
816 975 self.__profileIndex
817 976
818 977 """
819 978
820 979 data_spc = self.__buffer_spc
821 980 data_cspc = self.__buffer_cspc
822 981 data_dc = self.__buffer_dc
823 982 n = self.__profIndex
824 983
825 984 self.__buffer_spc = 0
826 985 self.__buffer_cspc = 0
827 986 self.__buffer_dc = 0
828 987 self.__profIndex = 0
829 988
830 989 return data_spc, data_cspc, data_dc, n
831 990
832 991 def byProfiles(self, *args):
833 992
834 993 self.__dataReady = False
835 994 avgdata_spc = None
836 995 avgdata_cspc = None
837 996 avgdata_dc = None
838 997
839 998 self.putData(*args)
840 999
841 1000 if self.__profIndex == self.n:
842 1001
843 1002 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
844 1003 self.n = n
845 1004 self.__dataReady = True
846 1005
847 1006 return avgdata_spc, avgdata_cspc, avgdata_dc
848 1007
849 1008 def byTime(self, datatime, *args):
850 1009
851 1010 self.__dataReady = False
852 1011 avgdata_spc = None
853 1012 avgdata_cspc = None
854 1013 avgdata_dc = None
855 1014
856 1015 self.putData(*args)
857 1016
858 1017 if (datatime - self.__initime) >= self.__integrationtime:
859 1018 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
860 1019 self.n = n
861 1020 self.__dataReady = True
862 1021
863 1022 return avgdata_spc, avgdata_cspc, avgdata_dc
864 1023
865 1024 def integrate(self, datatime, *args):
866 1025
867 1026 if self.__profIndex == 0:
868 1027 self.__initime = datatime
869 1028
870 1029 if self.__byTime:
871 1030 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
872 1031 else:
873 1032 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
874 1033
875 1034 if not self.__dataReady:
876 1035 return None, None, None, None
877 1036
878 1037 return self.__initime, avgdata_spc, avgdata_cspc, avgdata_dc
879 1038
880 1039 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
881 1040
882 1041 if n==1:
883 1042 return
884 1043
885 1044 dataOut.flagNoData = True
886 1045
887 1046 if not self.isConfig:
888 1047 self.setup(n, timeInterval, overlapping)
889 1048 self.isConfig = True
890 1049
891 1050 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
892 1051 dataOut.data_spc,
893 1052 dataOut.data_cspc,
894 1053 dataOut.data_dc)
895 1054
896 1055 if self.__dataReady:
897 1056
898 1057 dataOut.data_spc = avgdata_spc
899 1058 dataOut.data_cspc = avgdata_cspc
900 1059 dataOut.data_dc = avgdata_dc
901 1060
902 1061 dataOut.nIncohInt *= self.n
903 1062 dataOut.utctime = avgdatatime
904 1063 dataOut.flagNoData = False
905 1064
General Comments 0
You need to be logged in to leave comments. Login now